waves/public/assets/g/flappybird/playcanvas-stable.min.js
2025-04-09 17:11:14 -05:00

2 lines
1.3 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).pc={})}(this,(function(e){"use strict";function t(e,t,i){e.prototype[t]||Object.defineProperty(e.prototype,t,{value:i,configurable:!0,enumerable:!1,writable:!0})}t(Array,"fill",(function(e){if(null==this)throw new TypeError("this is null or not defined");for(var t=Object(this),i=t.length>>>0,n=arguments[1],s=n>>0,r=s<0?Math.max(i+s,0):Math.min(s,i),a=arguments[2],o=void 0===a?i:a>>0,h=o<0?Math.max(i+o,0):Math.min(o,i);r<h;)t[r]=e,r++;return t})),t(Array,"find",(function(e){if(null==this)throw TypeError('"this" is null or not defined');var t=Object(this),i=t.length>>>0;if("function"!=typeof e)throw TypeError("predicate must be a function");for(var n=arguments[1],s=0;s<i;){var r=t[s];if(e.call(n,r,s,t))return r;s++}})),t(Array,"findIndex",(function(e){if(null==this)throw new TypeError('"this" is null or not defined');var t=Object(this),i=t.length>>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");for(var n=arguments[1],s=0;s<i;){var r=t[s];if(e.call(n,r,s,t))return s;s++}return-1})),Math.log2=Math.log2||function(e){return Math.log(e)*Math.LOG2E},Math.sign||(Math.sign=function(e){return(e>0)-(e<0)||+e}),void 0===Number.isFinite&&(Number.isFinite=function(e){return"number"==typeof e&&isFinite(e)}),"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var i=Object(e),n=1;n<arguments.length;n++){var s=arguments[n];if(null!=s)for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&(i[r]=s[r])}return i},writable:!0,configurable:!0}),Object.values=Object.values||function(e){return Object.keys(e).map((function(t){return e[t]}))},function(){if("undefined"!=typeof navigator&&"undefined"!=typeof document){navigator.pointer=navigator.pointer||navigator.webkitPointer||navigator.mozPointer;var e=function(){var e=document.createEvent("CustomEvent");e.initCustomEvent("pointerlockchange",!0,!1,null),document.dispatchEvent(e)},t=function(){var e=document.createEvent("CustomEvent");e.initCustomEvent("pointerlockerror",!0,!1,null),document.dispatchEvent(e)};document.addEventListener("webkitpointerlockchange",e,!1),document.addEventListener("webkitpointerlocklost",e,!1),document.addEventListener("mozpointerlockchange",e,!1),document.addEventListener("mozpointerlocklost",e,!1),document.addEventListener("webkitpointerlockerror",t,!1),document.addEventListener("mozpointerlockerror",t,!1),Element.prototype.mozRequestPointerLock?Element.prototype.requestPointerLock=function(){this.mozRequestPointerLock()}:Element.prototype.requestPointerLock=Element.prototype.requestPointerLock||Element.prototype.webkitRequestPointerLock||Element.prototype.mozRequestPointerLock,!Element.prototype.requestPointerLock&&navigator.pointer&&(Element.prototype.requestPointerLock=function(){document.pointerLockElement=this,navigator.pointer.lock(this,e,t)}),document.exitPointerLock=document.exitPointerLock||document.webkitExitPointerLock||document.mozExitPointerLock,document.exitPointerLock||(document.exitPointerLock=function(){navigator.pointer&&(document.pointerLockElement=null,navigator.pointer.unlock())})}}(),function(){if("undefined"!=typeof window){for(var e=0,t=["ms","moz","webkit","o"],i=0;i<t.length&&!window.requestAnimationFrame;++i)window.requestAnimationFrame=window[t[i]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[t[i]+"CancelAnimationFrame"]||window[t[i]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(t,i){var n=(new Date).getTime(),s=Math.max(0,16-(n-e)),r=window.setTimeout((function(){t(n+s)}),s);return e=n+s,r}),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(e){clearTimeout(e)})}}(),t(String,"endsWith",(function(e,t){return(void 0===t||t>this.length)&&(t=this.length),this.substring(t-e.length,t)===e})),t(String,"includes",(function(e,t){return"number"!=typeof t&&(t=0),!(t+e.length>this.length)&&-1!==this.indexOf(e,t)})),t(String,"startsWith",(function(e,t){var i=t>0?0|t:0;return this.substring(i,i+e.length)===e})),t(String,"trimEnd",(function(){return this.replace(new RegExp(/[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/.source+"$","g"),"")}));for(var i=0,n=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array];i<n.length;i++){var s=n[i];t(s,"fill",Array.prototype.fill),t(s,"join",Array.prototype.join)}var r={};function a(e,t){var i;r[e]=!0,void 0!==t&&(i=t,window.console&&window.console.error&&window.console.error(i))}var o=function e(t){var i=t.gl;this.ext=t,this.isAlive=!0,this.hasBeenBound=!1,this.elementArrayBuffer=null,this.attribs=new Array(t.maxVertexAttribs);for(var n=0;n<this.attribs.length;n++){var s=new e.VertexAttrib(i);this.attribs[n]=s}this.maxAttrib=0};(o.VertexAttrib=function(e){this.enabled=!1,this.buffer=null,this.size=4,this.type=e.FLOAT,this.normalized=!1,this.stride=16,this.offset=0,this.cached="",this.recache()}).prototype.recache=function(){this.cached=[this.size,this.type,this.normalized,this.stride,this.offset].join(":")};var h=function(e){var t=this;this.gl=e,function(e){var t=e.getError;e.getError=function(){do{(i=t.apply(e))!=e.NO_ERROR&&(r[i]=!0)}while(i!=e.NO_ERROR);for(var i in r)if(r[i])return delete r[i],parseInt(i);return e.NO_ERROR}}(e);var i=this.original={getParameter:e.getParameter,enableVertexAttribArray:e.enableVertexAttribArray,disableVertexAttribArray:e.disableVertexAttribArray,bindBuffer:e.bindBuffer,getVertexAttrib:e.getVertexAttrib,vertexAttribPointer:e.vertexAttribPointer};e.getParameter=function(e){return e==t.VERTEX_ARRAY_BINDING_OES?t.currentVertexArrayObject==t.defaultVertexArrayObject?null:t.currentVertexArrayObject:i.getParameter.apply(this,arguments)},e.enableVertexAttribArray=function(e){var n=t.currentVertexArrayObject;n.maxAttrib=Math.max(n.maxAttrib,e);var s=n.attribs[e];return s.enabled=!0,i.enableVertexAttribArray.apply(this,arguments)},e.disableVertexAttribArray=function(e){var n=t.currentVertexArrayObject;n.maxAttrib=Math.max(n.maxAttrib,e);var s=n.attribs[e];return s.enabled=!1,i.disableVertexAttribArray.apply(this,arguments)},e.bindBuffer=function(n,s){switch(n){case e.ARRAY_BUFFER:t.currentArrayBuffer=s;break;case e.ELEMENT_ARRAY_BUFFER:t.currentVertexArrayObject.elementArrayBuffer=s}return i.bindBuffer.apply(this,arguments)},e.getVertexAttrib=function(n,s){var r=t.currentVertexArrayObject,a=r.attribs[n];switch(s){case e.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING:return a.buffer;case e.VERTEX_ATTRIB_ARRAY_ENABLED:return a.enabled;case e.VERTEX_ATTRIB_ARRAY_SIZE:return a.size;case e.VERTEX_ATTRIB_ARRAY_STRIDE:return a.stride;case e.VERTEX_ATTRIB_ARRAY_TYPE:return a.type;case e.VERTEX_ATTRIB_ARRAY_NORMALIZED:return a.normalized;default:return i.getVertexAttrib.apply(this,arguments)}},e.vertexAttribPointer=function(e,n,s,r,a,o){var h=t.currentVertexArrayObject;h.maxAttrib=Math.max(h.maxAttrib,e);var l=h.attribs[e];return l.buffer=t.currentArrayBuffer,l.size=n,l.type=s,l.normalized=r,l.stride=a,l.offset=o,l.recache(),i.vertexAttribPointer.apply(this,arguments)},e.instrumentExtension&&e.instrumentExtension(this,"OES_vertex_array_object"),e.canvas.addEventListener("webglcontextrestored",(function(){var e;e="OESVertexArrayObject emulation library context restored",window.console&&window.console.log&&window.console.log(e),t.reset_()}),!0),this.reset_()};h.prototype.VERTEX_ARRAY_BINDING_OES=34229,h.prototype.reset_=function(){if(void 0!==this.vertexArrayObjects)for(var e=0;e<this.vertexArrayObjects.length;++e)this.vertexArrayObjects.isAlive=!1;var t=this.gl;this.maxVertexAttribs=t.getParameter(t.MAX_VERTEX_ATTRIBS),this.defaultVertexArrayObject=new o(this),this.currentVertexArrayObject=null,this.currentArrayBuffer=null,this.vertexArrayObjects=[this.defaultVertexArrayObject],this.bindVertexArrayOES(null)},h.prototype.createVertexArrayOES=function(){var e=new o(this);return this.vertexArrayObjects.push(e),e},h.prototype.deleteVertexArrayOES=function(e){e.isAlive=!1,this.vertexArrayObjects.splice(this.vertexArrayObjects.indexOf(e),1),this.currentVertexArrayObject==e&&this.bindVertexArrayOES(null)},h.prototype.isVertexArrayOES=function(e){return!!(e&&e instanceof o&&e.hasBeenBound&&e.ext==this)},h.prototype.bindVertexArrayOES=function(e){var t=this.gl;if(!e||e.isAlive){var i=this.original,n=this.currentVertexArrayObject;this.currentVertexArrayObject=e||this.defaultVertexArrayObject,this.currentVertexArrayObject.hasBeenBound=!0;var s=this.currentVertexArrayObject;if(n!=s){n&&s.elementArrayBuffer==n.elementArrayBuffer||i.bindBuffer.call(t,t.ELEMENT_ARRAY_BUFFER,s.elementArrayBuffer);for(var r=this.currentArrayBuffer,o=Math.max(n?n.maxAttrib:0,s.maxAttrib),h=0;h<=o;h++){var l=s.attribs[h],c=n?n.attribs[h]:null;if(n&&l.enabled==c.enabled||(l.enabled?i.enableVertexAttribArray.call(t,h):i.disableVertexAttribArray.call(t,h)),l.enabled){var u=!1;n&&l.buffer==c.buffer||(r!=l.buffer&&(i.bindBuffer.call(t,t.ARRAY_BUFFER,l.buffer),r=l.buffer),u=!0),(u||l.cached!=c.cached)&&i.vertexAttribPointer.call(t,h,l.size,l.type,l.normalized,l.stride,l.offset)}}this.currentArrayBuffer!=r&&i.bindBuffer.call(t,t.ARRAY_BUFFER,this.currentArrayBuffer)}}else a(t.INVALID_OPERATION,"bindVertexArrayOES: attempt to bind deleted arrayObject")};var l="1.57.1",c="256dd83c2",u=function(){for(var e={},t=["Array","Object","Function","Date","RegExp","Float32Array"],i=0;i<t.length;i++)e["[object "+t[i]+"]"]=t[i].toLowerCase();return e}();function d(e){if(null===e)return"null";var t=typeof e;return"undefined"===t||"number"===t||"string"===t||"boolean"===t?t:u[Object.prototype.toString.call(e)]}function f(e,t){for(var i in t){var n=t[i];"object"===d(n)?e[i]=f({},n):"array"===d(n)?e[i]=f([],n):e[i]=n}return e}function p(e){return undefined!==e}var m=function(){function e(){this._callbacks={},this._callbackActive={}}var t=e.prototype;return t.initEventHandler=function(){this._callbacks={},this._callbackActive={}},t._addCallback=function(e,t,i,n){void 0===n&&(n=!1),e&&"string"==typeof e&&t&&(this._callbacks[e]||(this._callbacks[e]=[]),this._callbackActive[e]&&this._callbackActive[e]===this._callbacks[e]&&(this._callbackActive[e]=this._callbackActive[e].slice()),this._callbacks[e].push({callback:t,scope:i||this,once:n}))},t.on=function(e,t,i){return this._addCallback(e,t,i,!1),this},t.off=function(e,t,i){if(e)this._callbackActive[e]&&this._callbackActive[e]===this._callbacks[e]&&(this._callbackActive[e]=this._callbackActive[e].slice());else for(var n in this._callbackActive)this._callbacks[n]&&this._callbacks[n]===this._callbackActive[n]&&(this._callbackActive[n]=this._callbackActive[n].slice());if(e)if(t){var s=this._callbacks[e];if(!s)return this;for(var r=s.length,a=0;a<r;a++)s[a].callback===t&&(i&&s[a].scope!==i||(s[a--]=s[--r]));s.length=r}else this._callbacks[e]&&(this._callbacks[e]=[]);else this._callbacks={};return this},t.fire=function(e,t,i,n,s,r,a,o,h){if(!e||!this._callbacks[e])return this;var l;this._callbackActive[e]?(this._callbackActive[e]===this._callbacks[e]&&(this._callbackActive[e]=this._callbackActive[e].slice()),l=this._callbacks[e].slice()):this._callbackActive[e]=this._callbacks[e];for(var c=0;(l||this._callbackActive[e])&&c<(l||this._callbackActive[e]).length;c++){var u=(l||this._callbackActive[e])[c];if(u.callback.call(u.scope,t,i,n,s,r,a,o,h),u.once){var d=this._callbacks[e],f=d?d.indexOf(u):-1;-1!==f&&(this._callbackActive[e]===d&&(this._callbackActive[e]=this._callbackActive[e].slice()),this._callbacks[e].splice(f,1))}}return l||(this._callbackActive[e]=null),this},t.once=function(e,t,i){return this._addCallback(e,t,i,!0),this},t.hasEvent=function(e){return this._callbacks[e]&&0!==this._callbacks[e].length||!1},e}(),_={attach:function(e){var t=_;return e._addCallback=t._addCallback,e.on=t.on,e.off=t.off,e.fire=t.fire,e.once=t.once,e.hasEvent=t.hasEvent,e._callbacks={},e._callbackActive={},e},_addCallback:m.prototype._addCallback,on:m.prototype.on,off:m.prototype.off,fire:m.prototype.fire,once:m.prototype.once,hasEvent:m.prototype.hasEvent},g={create:function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}},v={delimiter:"/",join:function(){for(var e=arguments.length,t=arguments[0],i=0;i<e-1;++i){var n=arguments[i],s=arguments[i+1];if(!p(n)||!p(s))throw new Error("undefined argument to pc.path.join");s[0]!==v.delimiter?n&&s&&n[n.length-1]!==v.delimiter&&s[0]!==v.delimiter?t+=v.delimiter+s:t+=s:t=s}return t},normalize:function(e){for(var t=e.startsWith(v.delimiter),i=e.endsWith(v.delimiter),n=e.split("/"),s="",r=[],a=0;a<n.length;a++)""!==n[a]&&"."!==n[a]&&(".."===n[a]&&r.length>0?r=r.slice(0,r.length-2):(a>0&&r.push(v.delimiter),r.push(n[a])));return s=r.join(""),t||s[0]!==v.delimiter||(s=s.slice(1)),i&&s[s.length-1]!==v.delimiter&&(s+=v.delimiter),s},split:function(e){var t=e.split(v.delimiter),i=t.slice(t.length-1)[0];return[t.slice(0,t.length-1).join(v.delimiter),i]},getBasename:function(e){return v.split(e)[1]},getDirectory:function(e){var t=e.split(v.delimiter);return t.slice(0,t.length-1).join(v.delimiter)},getExtension:function(e){var t=e.split("?")[0].split(".").pop();return t!==e?"."+t:""},isRelativePath:function(e){return"/"!==e.charAt(0)&&null===e.match(/:\/\//)},extractPath:function(e){var t="",i=e.split("/"),n=0;if(i.length>1)if(v.isRelativePath(e))if("."===i[0])for(n=0;n<i.length-1;++n)t+=0===n?i[n]:"/"+i[n];else if(".."===i[0])for(n=0;n<i.length-1;++n)t+=0===n?i[n]:"/"+i[n];else for(t=".",n=0;n<i.length-1;++n)t+="/"+i[n];else for(n=0;n<i.length-1;++n)t+=0===n?i[n]:"/"+i[n];return t}},y=!1,x=!1,b=!1,S=!1,w=!1,T=!1,A=!1,M=!1,C=!1,E=!1;if("undefined"!=typeof navigator){var P=navigator.userAgent;/(windows|mac os|linux|cros)/i.test(P)&&(y=!0),/xbox/i.test(P)&&(S=!0),/(windows phone|iemobile|wpdesktop)/i.test(P)?(y=!1,x=!0,b=!0):/android/i.test(P)?(y=!1,x=!0,w=!0):/ip([ao]d|hone)/i.test(P)&&(y=!1,x=!0,T=!0),"undefined"!=typeof window&&(A="ontouchstart"in window||"maxTouchPoints"in navigator&&navigator.maxTouchPoints>0),M="getGamepads"in navigator,C="undefined"!=typeof Worker;try{var R=Object.defineProperty({},"passive",{get:function(){return E=!0,!1}});window.addEventListener("testpassive",null,R),window.removeEventListener("testpassive",null,R)}catch(e){}}var I="undefined"!=typeof window?"browser":"node",L={environment:I,global:"browser"===I?window:global,browser:"browser"===I,desktop:y,mobile:x,ios:T,android:w,windows:b,xbox:S,gamepads:M,touch:A,workers:C,passiveEvents:E},D="abcdefghijklmnopqrstuvwxyz",k="ABCDEFGHIJKLMNOPQRSTUVWXYZ",O=55296,F=127462,B=127487,N=65024,U=65039;function z(e,t){void 0===t&&(t=0);var i=e.length;if(t<0||t>=i)return null;var n=e.charCodeAt(t);if(i>1&&n>=O&&n<=56319){var s=e.charCodeAt(t+1);if(s>=56320&&s<=57343)return{code:1024*(n-O)+s-56320+65536,long:!0}}return{code:n,long:!1}}function V(e,t,i){if(!e)return!1;var n=z(e);if(n){var s=n.code;return s>=t&&s<=i}return!1}function G(e,t){if(t===e.length-1)return 1;if(V(e[t],O,56319)){var i=e.substring(t,t+2),n=e.substring(t+2,t+4);return V(n,127995,127999)||V(i,F,B)&&V(n,F,B)?4:V(n,N,U)?3:2}return V(e[t+1],N,U)?2:1}var W,H,X,q={ASCII_LOWERCASE:D,ASCII_UPPERCASE:k,ASCII_LETTERS:"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",format:function(e){for(var t=1;t<arguments.length;t++)e=e.replace("{"+(t-1)+"}",arguments[t]);return e},toBool:function(e,t){if(void 0===t&&(t=!1),"true"===e)return!0;if(t){if("false"===e)return!1;throw new TypeError("Not a boolean string")}return!1},getCodePoint:function(e,t){var i=z(e,t);return i&&i.code},getCodePoints:function(e){if("string"!=typeof e)throw new TypeError("Not a string");for(var t,i=0,n=[];t=z(e,i);)n.push(t.code),i+=t.long?2:1;return n},getSymbols:function(e){if("string"!=typeof e)throw new TypeError("Not a string");for(var t,i=0,n=e.length,s=[],r=0;i<n;)if(V(t=e[i+(r+=G(e,i+r))],8400,8447)&&(t=e[i+r++]),V(t,N,U)&&(t=e[i+r++]),t&&8205===t.charCodeAt(0))t=e[i+r++];else{var a=e.substring(i,i+r);s.push(a),i+=r,r=0}return s},fromCodePoint:function(){for(var e,t,i,n=[],s=0;s<arguments.length;++s)t=(e=Number(arguments[s]))-65536,i=e>65535?[55296+(t>>10),t%1024+56320]:[e],n.push(String.fromCharCode.apply(null,i));return n.join("")}},j=function(){function e(){this._list=[],this._index={}}var t=e.prototype;return t.push=function(e,t){if(this._index[e])throw Error("Key already in index "+e);var i=this._list.push(t)-1;this._index[e]=i},t.has=function(e){return void 0!==this._index[e]},t.get=function(e){var t=this._index[e];return void 0!==t?this._list[t]:null},t.remove=function(e){var t=this._index[e];if(void 0!==t){for(e in this._list.splice(t,1),delete this._index[e],this._index){var i=this._index[e];i>t&&(this._index[e]=i-1)}return!0}return!1},t.list=function(){return this._list},t.clear=function(){for(var e in this._list.length=0,this._index)delete this._index[e]},e}(),Y=function(){function e(){}return e.loadScript=function(e,t){var i=document.createElement("script");i.setAttribute("src",e),i.onload=function(){t(null)},i.onerror=function(){t("Failed to load script='"+e+"'")},document.body.appendChild(i)},e.loadWasm=function(t,i,n){var s=e.wasmSupported()&&i.glueUrl&&i.wasmUrl?i.glueUrl:i.fallbackUrl;s?e.loadScript(s,(function(e){if(e)n(e,null);else{var s=window[t];window[t]=void 0,s({locateFile:function(){return i.wasmUrl},onAbort:function(){n("wasm module aborted.")}}).then((function(e){n(null,e)}))}})):n("No supported wasm modules found.",null)},e.getModule=function(t){return e.modules.hasOwnProperty(t)||(e.modules[t]={config:null,initializing:!1,instance:null,callbacks:[]}),e.modules[t]},e.initialize=function(t,i){if(!i.initializing){var n=i.config;(n.glueUrl||n.wasmUrl||n.fallbackUrl)&&(i.initializing=!0,e.loadWasm(t,n,(function(e,s){e?n.errorHandler?n.errorHandler(e):console.error("failed to initialize module="+t+" error="+e):(i.instance=s,i.callbacks.forEach((function(e){e(s)})))})))}},e}();Y.modules={},Y.wasmSupported=(W=function(){try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){var e=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(e instanceof WebAssembly.Module)return new WebAssembly.Instance(e)instanceof WebAssembly.Instance}}catch(e){}return!1},X=H={},function(){return X===H&&(X=W()),X});var K=function(){function e(){}return e.setConfig=function(e,t){var i=Y.getModule(e);i.config=t,i.callbacks.length>0&&Y.initialize(e,i)},e.getInstance=function(e,t){var i=Y.getModule(e);i.instance?t(i.instance):(i.callbacks.push(t),i.config&&Y.initialize(e,i))},e}();function Z(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function $(e,t,i){return t&&Z(e.prototype,t),i&&Z(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}function Q(){return Q=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n])}return e},Q.apply(this,arguments)}function J(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,ee(e,t)}function ee(e,t){return ee=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},ee(e,t)}function te(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function ie(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i<t;i++)n[i]=e[i];return n}function ne(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(i)return(i=i.call(e)).next.bind(i);if(Array.isArray(e)||(i=function(e,t){if(e){if("string"==typeof e)return ie(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?ie(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var se=function(){function e(e){this.arraybuffer=e,this.dataView=new DataView(e),this.offset=0,this.stack=[]}var t=e.prototype;return t.reset=function(e){void 0===e&&(e=0),this.offset=e},t.skip=function(e){this.offset+=e},t.align=function(e){this.offset=this.offset+e-1&~(e-1)},t._inc=function(e){return this.offset+=e,this.offset-e},t.readChar=function(){return String.fromCharCode(this.dataView.getUint8(this.offset++))},t.readChars=function(e){for(var t="",i=0;i<e;++i)t+=this.readChar();return t},t.readU8=function(){return this.dataView.getUint8(this.offset++)},t.readU16=function(){return this.dataView.getUint16(this._inc(2),!0)},t.readU32=function(){return this.dataView.getUint32(this._inc(4),!0)},t.readU64=function(){return this.readU32()+Math.pow(2,32)*this.readU32()},t.readU32be=function(){return this.dataView.getUint32(this._inc(4),!1)},t.readArray=function(e){for(var t=0;t<e.length;++t)e[t]=this.readU8()},t.readLine=function(){for(var e=this.dataView,t="";!(this.offset>=e.byteLength);){var i=String.fromCharCode(this.readU8());if("\n"===i)break;t+=i}return t},$(e,[{key:"remainingBytes",get:function(){return this.dataView.byteLength-this.offset}}]),e}(),re=function(){function e(e){this.items=[],this.length=0,this.loopIndex=-1,this._sortBy=e.sortBy,this._sortHandler=this._doSort.bind(this)}var t=e.prototype;return t._binarySearch=function(e){for(var t,i,n=0,s=this.items.length-1,r=e[this._sortBy];n<=s;)t=Math.floor((n+s)/2),(i=this.items[t][this._sortBy])<=r?n=t+1:i>r&&(s=t-1);return n},t._doSort=function(e,t){var i=this._sortBy;return e[i]-t[i]},t.insert=function(e){var t=this._binarySearch(e);this.items.splice(t,0,e),this.length++,this.loopIndex>=t&&this.loopIndex++},t.append=function(e){this.items.push(e),this.length++},t.remove=function(e){var t=this.items.indexOf(e);t<0||(this.items.splice(t,1),this.length--,this.loopIndex>=t&&this.loopIndex--)},t.sort=function(){var e=this.loopIndex>=0?this.items[this.loopIndex]:null;this.items.sort(this._sortHandler),null!==e&&(this.loopIndex=this.items.indexOf(e))},e}(),ae=function(e){function t(t){var i;return(i=e.call(this)||this)._index={},i._list=[],i._parent=t,i}J(t,e);var i=t.prototype;return i.add=function(){var e=!1,t=this._processArguments(arguments,!0);if(!t.length)return e;for(var i=0;i<t.length;i++)this._index[t[i]]||(e=!0,this._index[t[i]]=!0,this._list.push(t[i]),this.fire("add",t[i],this._parent));return e&&this.fire("change",this._parent),e},i.remove=function(){var e=!1;if(!this._list.length)return e;var t=this._processArguments(arguments,!0);if(!t.length)return e;for(var i=0;i<t.length;i++)this._index[t[i]]&&(e=!0,delete this._index[t[i]],this._list.splice(this._list.indexOf(t[i]),1),this.fire("remove",t[i],this._parent));return e&&this.fire("change",this._parent),e},i.clear=function(){if(this._list.length){var e=this._list.slice(0);this._list=[],this._index={};for(var t=0;t<e.length;t++)this.fire("remove",e[t],this._parent);this.fire("change",this._parent)}},i.has=function(){return!!this._list.length&&this._has(this._processArguments(arguments))},i._has=function(e){if(!this._list.length||!e.length)return!1;for(var t=0;t<e.length;t++)if(1===e[t].length){if(this._index[e[t][0]])return!0}else{for(var i=!0,n=0;n<e[t].length;n++)if(!this._index[e[t][n]]){i=!1;break}if(i)return!0}return!1},i.list=function(){return this._list.slice(0)},i._processArguments=function(e,t){var i=[],n=[];if(!e||!e.length)return i;for(var s=0;s<e.length;s++)if(e[s]instanceof Array){t||(n=[]);for(var r=0;r<e[s].length;r++)"string"==typeof e[s][r]&&(t?i.push(e[s][r]):n.push(e[s][r]));!t&&n.length&&i.push(n)}else"string"==typeof e[s]&&(t?i.push(e[s]):i.push([e[s]]));return i},$(t,[{key:"size",get:function(){return this._list.length}}]),t}(m),oe="undefined"!=typeof window&&window.performance&&window.performance.now&&window.performance.timing?performance.now.bind(performance):Date.now,he=function(){function e(){this._isRunning=!1,this._a=0,this._b=0}var t=e.prototype;return t.start=function(){this._isRunning=!0,this._a=oe()},t.stop=function(){this._isRunning=!1,this._b=oe()},t.getMilliseconds=function(){return this._b-this._a},e}();var le=/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,ce=function(){function e(e){var t=e.match(le);this.scheme=t[2],this.authority=t[4],this.path=t[5],this.query=t[7],this.fragment=t[9]}var t=e.prototype;return t.toString=function(){var e="";return this.scheme&&(e+=this.scheme+":"),this.authority&&(e+="//"+this.authority),e+=this.path,this.query&&(e+="?"+this.query),this.fragment&&(e+="#"+this.fragment),e},t.getQuery=function(){var e={};if(this.query)for(var t,i=ne(decodeURIComponent(this.query).split("&"));!(t=i()).done;){var n=t.value.split("=");e[n[0]]=n[1]}return e},t.setQuery=function(e){var t="";for(var i in e)e.hasOwnProperty(i)&&(""!==t&&(t+="&"),t+=encodeURIComponent(i)+"="+encodeURIComponent(e[i]));this.query=t},e}(),ue=function(){function e(){}return e.set=function(e,t){},e.get=function(t){return e._traceChannels.has(t)},e}();ue._traceChannels=new Set;var de={DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,clamp:function(e,t,i){return e>=i?i:e<=t?t:e},intToBytes24:function(e){return[e>>16&255,e>>8&255,255&e]},intToBytes32:function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]},bytesToInt24:function(e,t,i){return e.length&&(i=e[2],t=e[1],e=e[0]),e<<16|t<<8|i},bytesToInt32:function(e,t,i,n){return e.length&&(n=e[3],i=e[2],t=e[1],e=e[0]),(e<<24|t<<16|i<<8|n)>>>0},lerp:function(e,t,i){return e+(t-e)*de.clamp(i,0,1)},lerpAngle:function(e,t,i){return t-e>180&&(t-=360),t-e<-180&&(t+=360),de.lerp(e,t,de.clamp(i,0,1))},powerOfTwo:function(e){return 0!==e&&!(e&e-1)},nextPowerOfTwo:function(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e},random:function(e,t){var i=t-e;return Math.random()*i+e},smoothstep:function(e,t,i){return i<=e?0:i>=t?1:(i=(i-e)/(t-e))*i*(3-2*i)},smootherstep:function(e,t,i){return i<=e?0:i>=t?1:(i=(i-e)/(t-e))*i*i*(i*(6*i-15)+10)},roundUp:function(e,t){return 0===t?e:Math.ceil(e/t)*t},between:function(e,t,i,n){var s=Math.min(t,i),r=Math.max(t,i);return n?e>=s&&e<=r:e>s&&e<r}},fe=function(){function e(){}var t=e.prototype;return t.get=function(e,t,i){return"function"==typeof t&&(i=t,t={}),this.request("GET",e,t,i)},t.post=function(e,t,i,n){return"function"==typeof i&&(n=i,i={}),i.postdata=t,this.request("POST",e,i,n)},t.put=function(e,t,i,n){return"function"==typeof i&&(n=i,i={}),i.postdata=t,this.request("PUT",e,i,n)},t.del=function(e,t,i){return"function"==typeof t&&(i=t,t={}),this.request("DELETE",e,t,i)},t.request=function(t,i,n,s){var r,a,o,h=this,l=!1;if("function"==typeof n&&(s=n,n={}),n.retry&&(n=Object.assign({retries:0,maxRetries:5},n)),n.callback=s,null==n.async&&(n.async=!0),null==n.headers&&(n.headers={}),null!=n.postdata)if(n.postdata instanceof Document)o=n.postdata;else if(n.postdata instanceof FormData)o=n.postdata;else if(n.postdata instanceof Object){var c=n.headers["Content-Type"];switch(void 0===c&&(n.headers["Content-Type"]=e.ContentType.FORM_URLENCODED,c=n.headers["Content-Type"]),c){case e.ContentType.FORM_URLENCODED:o="";var u=!0;for(var d in n.postdata){if(n.postdata.hasOwnProperty(d))u?u=!1:o+="&",o+=encodeURIComponent(d)+"="+encodeURIComponent(n.postdata[d])}break;default:case e.ContentType.JSON:null==c&&(n.headers["Content-Type"]=e.ContentType.JSON),o=JSON.stringify(n.postdata)}}else o=n.postdata;if(!1===n.cache){var p=oe();(r=new ce(i)).query?r.query=r.query+"&ts="+p:r.query="ts="+p,i=r.toString()}n.query&&(a=f((r=new ce(i)).getQuery(),n.query),r.setQuery(a),i=r.toString());var m=new XMLHttpRequest;for(var _ in m.open(t,i,n.async),m.withCredentials=void 0!==n.withCredentials&&n.withCredentials,m.responseType=n.responseType||this._guessResponseType(i),n.headers)n.headers.hasOwnProperty(_)&&m.setRequestHeader(_,n.headers[_]);m.onreadystatechange=function(){h._onReadyStateChange(t,i,n,m)},m.onerror=function(){h._onError(t,i,n,m),l=!0};try{m.send(o)}catch(e){l||n.error(m.status,m,e)}return m},t._guessResponseType=function(t){var i=new ce(t),n=v.getExtension(i.path);return e.binaryExtensions.indexOf(n)>=0?e.ResponseType.ARRAY_BUFFER:".xml"===n?e.ResponseType.DOCUMENT:e.ResponseType.TEXT},t._isBinaryContentType=function(t){return[e.ContentType.MP4,e.ContentType.WAV,e.ContentType.OGG,e.ContentType.MP3,e.ContentType.BIN,e.ContentType.DDS,e.ContentType.BASIS,e.ContentType.GLB,e.ContentType.OPUS].indexOf(t)>=0},t._onReadyStateChange=function(e,t,i,n){if(4===n.readyState)switch(n.status){case 0:n.responseURL&&n.responseURL.startsWith("file:///")?this._onSuccess(e,t,i,n):this._onError(e,t,i,n);break;case 200:case 201:case 206:case 304:this._onSuccess(e,t,i,n);break;default:this._onError(e,t,i,n)}},t._onSuccess=function(t,i,n,s){var r,a,o=s.getResponseHeader("Content-Type");o&&(a=o.split(";")[0].trim());try{r=a===e.ContentType.JSON||i.split("?")[0].endsWith(".json")?JSON.parse(s.responseText):this._isBinaryContentType(a)||s.responseType===e.ResponseType.ARRAY_BUFFER||s.responseType===e.ResponseType.BLOB||s.responseType===e.ResponseType.JSON?s.response:s.responseType===e.ResponseType.DOCUMENT||a===e.ContentType.XML?s.responseXML:s.responseText,n.callback(null,r)}catch(e){n.callback(e)}},t._onError=function(t,i,n,s){var r=this;if(!n.retrying)if(n.retry&&n.retries<n.maxRetries){n.retries++,n.retrying=!0;var a=de.clamp(Math.pow(2,n.retries)*e.retryDelay,0,n.maxRetryDelay||5e3);console.log(t+": "+i+" - Error "+s.status+". Retrying in "+a+" ms"),setTimeout((function(){n.retrying=!1,r.request(t,i,n,n.callback)}),a)}else n.callback(0===s.status?"Network error":s.status,null)},e}();fe.ContentType={FORM_URLENCODED:"application/x-www-form-urlencoded",GIF:"image/gif",JPEG:"image/jpeg",DDS:"image/dds",JSON:"application/json",PNG:"image/png",TEXT:"text/plain",XML:"application/xml",WAV:"audio/x-wav",OGG:"audio/ogg",MP3:"audio/mpeg",MP4:"audio/mp4",AAC:"audio/aac",BIN:"application/octet-stream",BASIS:"image/basis",GLB:"model/gltf-binary",OPUS:'audio/ogg; codecs="opus"'},fe.ResponseType={TEXT:"text",ARRAY_BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json"},fe.binaryExtensions=[".model",".wav",".ogg",".mp3",".mp4",".m4a",".aac",".dds",".basis",".glb",".opus"],fe.retryDelay=100;var pe=new fe,me=function(){function e(e,t,i,n){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=1);var s=e.length;3===s||4===s?(this.r=e[0],this.g=e[1],this.b=e[2],this.a=void 0!==e[3]?e[3]:1):(this.r=e,this.g=t,this.b=i,this.a=n)}var t=e.prototype;return t.clone=function(){return new(0,this.constructor)(this.r,this.g,this.b,this.a)},t.copy=function(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this},t.equals=function(e){return this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a},t.set=function(e,t,i,n){return void 0===n&&(n=1),this.r=e,this.g=t,this.b=i,this.a=n,this},t.lerp=function(e,t,i){return this.r=e.r+i*(t.r-e.r),this.g=e.g+i*(t.g-e.g),this.b=e.b+i*(t.b-e.b),this.a=e.a+i*(t.a-e.a),this},t.fromString=function(e){var t,i=parseInt(e.replace("#","0x"),16);return e.length>7?t=de.intToBytes32(i):(t=de.intToBytes24(i))[3]=255,this.set(t[0]/255,t[1]/255,t[2]/255,t[3]/255),this},t.toString=function(e){var t="#"+((1<<24)+(Math.round(255*this.r)<<16)+(Math.round(255*this.g)<<8)+Math.round(255*this.b)).toString(16).slice(1);if(!0===e){var i=Math.round(255*this.a).toString(16);this.a<16/255?t+="0"+i:t+=i}return t},e}();me.BLACK=Object.freeze(new me(0,0,0,1)),me.BLUE=Object.freeze(new me(0,0,1,1)),me.CYAN=Object.freeze(new me(0,1,1,1)),me.GRAY=Object.freeze(new me(.5,.5,.5,1)),me.GREEN=Object.freeze(new me(0,1,0,1)),me.MAGENTA=Object.freeze(new me(1,0,1,1)),me.RED=Object.freeze(new me(1,0,0,1)),me.WHITE=Object.freeze(new me(1,1,1,1)),me.YELLOW=Object.freeze(new me(1,1,0,1));var _e=function(){function e(e,t){void 0===t&&(t=0),this._curve=e,this._left=-1/0,this._right=1/0,this._recip=0,this._p0=0,this._p1=0,this._m0=0,this._m1=0,this._reset(t)}var t=e.prototype;return t.evaluate=function(e,t){var i;void 0===t&&(t=!1),(t||e<this._left||e>=this._right)&&this._reset(e);var n=this._curve.type;if(5===n)i=this._p0;else{var s=0===this._recip?0:(e-this._left)*this._recip;i=0===n?de.lerp(this._p0,this._p1,s):1===n?de.lerp(this._p0,this._p1,s*s*(3-2*s)):this._evaluateHermite(this._p0,this._p1,this._m0,this._m1,s)}return i},t._reset=function(e){var t=this._curve.keys,i=t.length;if(i)if(e<t[0][0])this._left=-1/0,this._right=t[0][0],this._recip=0,this._p0=this._p1=t[0][1],this._m0=this._m1=0;else if(e>=t[i-1][0])this._left=t[i-1][0],this._right=1/0,this._recip=0,this._p0=this._p1=t[i-1][1],this._m0=this._m1=0;else{for(var n=0;e>=t[n+1][0];)n++;this._left=t[n][0],this._right=t[n+1][0];var s=1/(this._right-this._left);this._recip=isFinite(s)?s:0,this._p0=t[n][1],this._p1=t[n+1][1],this._isHermite()&&this._calcTangents(t,n)}else this._left=-1/0,this._right=1/0,this._recip=0,this._p0=this._p1=this._m0=this._m1=0},t._isHermite=function(){return 2===this._curve.type||3===this._curve.type||4===this._curve.type},t._calcTangents=function(e,t){var i,n,s=e[t],r=e[t+1];if(i=0===t?[e[0][0]+(e[0][0]-e[1][0]),e[0][1]+(e[0][1]-e[1][1])]:e[t-1],n=t===e.length-2?[e[t+1][0]+(e[t+1][0]-e[t][0]),e[t+1][1]+(e[t+1][1]-e[t][1])]:e[t+2],4===this._curve.type){var a=2*(r[0]-s[0])/(r[0]-i[0]),o=2*(r[0]-s[0])/(n[0]-s[0]);this._m0=this._curve.tension*(isFinite(a)?a:0)*(r[1]-i[1]),this._m1=this._curve.tension*(isFinite(o)?o:0)*(n[1]-s[1])}else{var h=(r[0]-s[0])/(s[0]-i[0]),l=(r[0]-s[0])/(n[0]-r[0]),c=s[1]+(i[1]-s[1])*(isFinite(h)?h:0),u=r[1]+(n[1]-r[1])*(isFinite(l)?l:0),d=2===this._curve.type?.5:this._curve.tension;this._m0=d*(r[1]-c),this._m1=d*(u-s[1])}},t._evaluateHermite=function(e,t,i,n,s){var r=s*s,a=s+s,o=1-s,h=o*o;return e*((1+a)*h)+i*(s*h)+t*(r*(3-a))+n*(r*(s-1))},e}(),ge=function(){function e(e){if(this.keys=[],this.type=1,this.tension=.5,this._eval=new _e(this),e)for(var t=0;t<e.length-1;t+=2)this.keys.push([e[t],e[t+1]]);this.sort()}var t=e.prototype;return t.add=function(e,t){for(var i=this.keys,n=i.length,s=0;s<n&&!(i[s][0]>e);s++);var r=[e,t];return this.keys.splice(s,0,r),r},t.get=function(e){return this.keys[e]},t.sort=function(){this.keys.sort((function(e,t){return e[0]-t[0]}))},t.value=function(e){return this._eval.evaluate(e,!0)},t.closest=function(e){for(var t=this.keys,i=t.length,n=2,s=null,r=0;r<i;r++){var a=Math.abs(e-t[r][0]);if(!(n>=a))break;n=a,s=t[r]}return s},t.clone=function(){var e=new this.constructor;return e.keys=f(e.keys,this.keys),e.type=this.type,e.tension=this.tension,e},t.quantize=function(e){e=Math.max(e,2);var t=new Float32Array(e),i=1/(e-1);t[0]=this._eval.evaluate(0,!0);for(var n=1;n<e;n++)t[n]=this._eval.evaluate(i*n);return t},t.quantizeClamped=function(e,t,i){for(var n=this.quantize(e),s=0;s<n.length;++s)n[s]=Math.min(i,Math.max(t,n[s]));return n},$(e,[{key:"length",get:function(){return this.keys.length}}]),e}(),ve=function(){function e(){if(this.curves=[],this._type=1,arguments.length>1)for(var e=0;e<arguments.length;e++)this.curves.push(new ge(arguments[e]));else if(0===arguments.length)this.curves.push(new ge);else{var t=arguments[0];if("number"==typeof t)for(var i=0;i<t;i++)this.curves.push(new ge);else for(var n=0;n<t.length;n++)this.curves.push(new ge(t[n]))}}var t=e.prototype;return t.get=function(e){return this.curves[e]},t.value=function(e,t){void 0===t&&(t=[]);var i=this.curves.length;t.length=i;for(var n=0;n<i;n++)t[n]=this.curves[n].value(e);return t},t.clone=function(){var e=new this.constructor;e.curves=[];for(var t=0;t<this.curves.length;t++)e.curves.push(this.curves[t].clone());return e._type=this._type,e},t.quantize=function(e){e=Math.max(e,2);for(var t=this.curves.length,i=new Float32Array(e*t),n=1/(e-1),s=0;s<t;s++)for(var r=new _e(this.curves[s]),a=0;a<e;a++)i[a*t+s]=r.evaluate(n*a);return i},t.quantizeClamped=function(e,t,i){for(var n=this.quantize(e),s=0;s<n.length;++s)n[s]=Math.min(i,Math.max(t,n[s]));return n},$(e,[{key:"length",get:function(){return this.curves.length}},{key:"type",get:function(){return this._type},set:function(e){this._type=e;for(var t=0;t<this.curves.length;t++)this.curves[t].type=e}}]),e}(),ye=function(){function e(e,t,i){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),3===e.length?(this.x=e[0],this.y=e[1],this.z=e[2]):(this.x=e,this.y=t,this.z=i)}var t=e.prototype;return t.add=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this},t.add2=function(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this},t.addScalar=function(e){return this.x+=e,this.y+=e,this.z+=e,this},t.clone=function(){return new(0,this.constructor)(this.x,this.y,this.z)},t.copy=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this},t.cross=function(e,t){var i=e.x,n=e.y,s=e.z,r=t.x,a=t.y,o=t.z;return this.x=n*o-a*s,this.y=s*r-o*i,this.z=i*a-r*n,this},t.distance=function(e){var t=this.x-e.x,i=this.y-e.y,n=this.z-e.z;return Math.sqrt(t*t+i*i+n*n)},t.div=function(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this},t.div2=function(e,t){return this.x=e.x/t.x,this.y=e.y/t.y,this.z=e.z/t.z,this},t.divScalar=function(e){return this.x/=e,this.y/=e,this.z/=e,this},t.dot=function(e){return this.x*e.x+this.y*e.y+this.z*e.z},t.equals=function(e){return this.x===e.x&&this.y===e.y&&this.z===e.z},t.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},t.lengthSq=function(){return this.x*this.x+this.y*this.y+this.z*this.z},t.lerp=function(e,t,i){return this.x=e.x+i*(t.x-e.x),this.y=e.y+i*(t.y-e.y),this.z=e.z+i*(t.z-e.z),this},t.mul=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this},t.mul2=function(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this},t.mulScalar=function(e){return this.x*=e,this.y*=e,this.z*=e,this},t.normalize=function(){var e=this.x*this.x+this.y*this.y+this.z*this.z;if(e>0){var t=1/Math.sqrt(e);this.x*=t,this.y*=t,this.z*=t}return this},t.floor=function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this},t.ceil=function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this},t.round=function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this},t.min=function(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),this},t.max=function(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),this},t.project=function(e){var t=(this.x*e.x+this.y*e.y+this.z*e.z)/(e.x*e.x+e.y*e.y+e.z*e.z);return this.x=e.x*t,this.y=e.y*t,this.z=e.z*t,this},t.set=function(e,t,i){return this.x=e,this.y=t,this.z=i,this},t.sub=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this},t.sub2=function(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this},t.subScalar=function(e){return this.x-=e,this.y-=e,this.z-=e,this},t.toString=function(){return"["+this.x+", "+this.y+", "+this.z+"]"},e}();ye.ZERO=Object.freeze(new ye(0,0,0)),ye.ONE=Object.freeze(new ye(1,1,1)),ye.UP=Object.freeze(new ye(0,1,0)),ye.DOWN=Object.freeze(new ye(0,-1,0)),ye.RIGHT=Object.freeze(new ye(1,0,0)),ye.LEFT=Object.freeze(new ye(-1,0,0)),ye.FORWARD=Object.freeze(new ye(0,0,-1)),ye.BACK=Object.freeze(new ye(0,0,1));var xe=function(){function e(){var e=new Float32Array(9);e[0]=e[4]=e[8]=1,this.data=e}var t=e.prototype;return t.clone=function(){return(new(0,this.constructor)).copy(this)},t.copy=function(e){var t=e.data,i=this.data;return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[3],i[4]=t[4],i[5]=t[5],i[6]=t[6],i[7]=t[7],i[8]=t[8],this},t.set=function(e){var t=this.data;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],this},t.equals=function(e){var t=this.data,i=e.data;return t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]&&t[4]===i[4]&&t[5]===i[5]&&t[6]===i[6]&&t[7]===i[7]&&t[8]===i[8]},t.isIdentity=function(){var e=this.data;return 1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&1===e[4]&&0===e[5]&&0===e[6]&&0===e[7]&&1===e[8]},t.setIdentity=function(){var e=this.data;return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,this},t.toString=function(){return"["+this.data.join(", ")+"]"},t.transpose=function(){var e,t=this.data;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this},t.setFromMat4=function(e){var t=e.data,i=this.data;return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[4],i[4]=t[5],i[5]=t[6],i[6]=t[8],i[7]=t[9],i[8]=t[10],this},t.transformVector=function(e,t){void 0===t&&(t=new ye);var i=this.data,n=e.x,s=e.y,r=e.z;return t.x=n*i[0]+s*i[3]+r*i[6],t.y=n*i[1]+s*i[4]+r*i[7],t.z=n*i[2]+s*i[5]+r*i[8],t},e}();xe.IDENTITY=Object.freeze(new xe),xe.ZERO=Object.freeze((new xe).set([0,0,0,0,0,0,0,0,0]));var be=function(){function e(e,t){void 0===e&&(e=0),void 0===t&&(t=0),2===e.length?(this.x=e[0],this.y=e[1]):(this.x=e,this.y=t)}var t=e.prototype;return t.add=function(e){return this.x+=e.x,this.y+=e.y,this},t.add2=function(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this},t.addScalar=function(e){return this.x+=e,this.y+=e,this},t.clone=function(){return new(0,this.constructor)(this.x,this.y)},t.copy=function(e){return this.x=e.x,this.y=e.y,this},t.cross=function(e){return this.x*e.y-this.y*e.x},t.distance=function(e){var t=this.x-e.x,i=this.y-e.y;return Math.sqrt(t*t+i*i)},t.div=function(e){return this.x/=e.x,this.y/=e.y,this},t.div2=function(e,t){return this.x=e.x/t.x,this.y=e.y/t.y,this},t.divScalar=function(e){return this.x/=e,this.y/=e,this},t.dot=function(e){return this.x*e.x+this.y*e.y},t.equals=function(e){return this.x===e.x&&this.y===e.y},t.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},t.lengthSq=function(){return this.x*this.x+this.y*this.y},t.lerp=function(e,t,i){return this.x=e.x+i*(t.x-e.x),this.y=e.y+i*(t.y-e.y),this},t.mul=function(e){return this.x*=e.x,this.y*=e.y,this},t.mul2=function(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this},t.mulScalar=function(e){return this.x*=e,this.y*=e,this},t.normalize=function(){var e=this.x*this.x+this.y*this.y;if(e>0){var t=1/Math.sqrt(e);this.x*=t,this.y*=t}return this},t.floor=function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},t.ceil=function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},t.round=function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},t.min=function(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),this},t.max=function(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),this},t.set=function(e,t){return this.x=e,this.y=t,this},t.sub=function(e){return this.x-=e.x,this.y-=e.y,this},t.sub2=function(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this},t.subScalar=function(e){return this.x-=e,this.y-=e,this},t.toString=function(){return"["+this.x+", "+this.y+"]"},e.angleRad=function(e,t){return Math.atan2(e.x*t.y-e.y*t.x,e.x*t.x+e.y*t.y)},e}();be.ZERO=Object.freeze(new be(0,0)),be.ONE=Object.freeze(new be(1,1)),be.UP=Object.freeze(new be(0,1)),be.DOWN=Object.freeze(new be(0,-1)),be.RIGHT=Object.freeze(new be(1,0)),be.LEFT=Object.freeze(new be(-1,0));var Se=function(){function e(e,t,i,n){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),4===e.length?(this.x=e[0],this.y=e[1],this.z=e[2],this.w=e[3]):(this.x=e,this.y=t,this.z=i,this.w=n)}var t=e.prototype;return t.add=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this},t.add2=function(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this},t.addScalar=function(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this},t.clone=function(){return new(0,this.constructor)(this.x,this.y,this.z,this.w)},t.copy=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},t.div=function(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this},t.div2=function(e,t){return this.x=e.x/t.x,this.y=e.y/t.y,this.z=e.z/t.z,this.w=e.w/t.w,this},t.divScalar=function(e){return this.x/=e,this.y/=e,this.z/=e,this.w/=e,this},t.dot=function(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w},t.equals=function(e){return this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},t.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.lengthSq=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},t.lerp=function(e,t,i){return this.x=e.x+i*(t.x-e.x),this.y=e.y+i*(t.y-e.y),this.z=e.z+i*(t.z-e.z),this.w=e.w+i*(t.w-e.w),this},t.mul=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this},t.mul2=function(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this.w=e.w*t.w,this},t.mulScalar=function(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},t.normalize=function(){var e=this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w;if(e>0){var t=1/Math.sqrt(e);this.x*=t,this.y*=t,this.z*=t,this.w*=t}return this},t.floor=function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this},t.ceil=function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this},t.round=function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this},t.min=function(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),e.w<this.w&&(this.w=e.w),this},t.max=function(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this},t.set=function(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this},t.sub=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this},t.sub2=function(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this},t.subScalar=function(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this},t.toString=function(){return"["+this.x+", "+this.y+", "+this.z+", "+this.w+"]"},e}();Se.ZERO=Object.freeze(new Se(0,0,0,0)),Se.ONE=Object.freeze(new Se(1,1,1,1));var we=new be,Te=new ye,Ae=new ye,Me=new ye,Ce=new ye,Ee=function(){function e(){var e=new Float32Array(16);e[0]=e[5]=e[10]=e[15]=1,this.data=e}e._getPerspectiveHalfSize=function(e,t,i,n,s){s?(e.x=n*Math.tan(t*Math.PI/360),e.y=e.x/i):(e.y=n*Math.tan(t*Math.PI/360),e.x=e.y*i)};var t=e.prototype;return t.add2=function(e,t){var i=e.data,n=t.data,s=this.data;return s[0]=i[0]+n[0],s[1]=i[1]+n[1],s[2]=i[2]+n[2],s[3]=i[3]+n[3],s[4]=i[4]+n[4],s[5]=i[5]+n[5],s[6]=i[6]+n[6],s[7]=i[7]+n[7],s[8]=i[8]+n[8],s[9]=i[9]+n[9],s[10]=i[10]+n[10],s[11]=i[11]+n[11],s[12]=i[12]+n[12],s[13]=i[13]+n[13],s[14]=i[14]+n[14],s[15]=i[15]+n[15],this},t.add=function(e){return this.add2(this,e)},t.clone=function(){return(new(0,this.constructor)).copy(this)},t.copy=function(e){var t=e.data,i=this.data;return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[3],i[4]=t[4],i[5]=t[5],i[6]=t[6],i[7]=t[7],i[8]=t[8],i[9]=t[9],i[10]=t[10],i[11]=t[11],i[12]=t[12],i[13]=t[13],i[14]=t[14],i[15]=t[15],this},t.equals=function(e){var t=this.data,i=e.data;return t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]&&t[4]===i[4]&&t[5]===i[5]&&t[6]===i[6]&&t[7]===i[7]&&t[8]===i[8]&&t[9]===i[9]&&t[10]===i[10]&&t[11]===i[11]&&t[12]===i[12]&&t[13]===i[13]&&t[14]===i[14]&&t[15]===i[15]},t.isIdentity=function(){var e=this.data;return 1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]},t.mul2=function(e,t){var i,n,s,r,a=e.data,o=t.data,h=this.data,l=a[0],c=a[1],u=a[2],d=a[3],f=a[4],p=a[5],m=a[6],_=a[7],g=a[8],v=a[9],y=a[10],x=a[11],b=a[12],S=a[13],w=a[14],T=a[15];return i=o[0],n=o[1],s=o[2],r=o[3],h[0]=l*i+f*n+g*s+b*r,h[1]=c*i+p*n+v*s+S*r,h[2]=u*i+m*n+y*s+w*r,h[3]=d*i+_*n+x*s+T*r,i=o[4],n=o[5],s=o[6],r=o[7],h[4]=l*i+f*n+g*s+b*r,h[5]=c*i+p*n+v*s+S*r,h[6]=u*i+m*n+y*s+w*r,h[7]=d*i+_*n+x*s+T*r,i=o[8],n=o[9],s=o[10],r=o[11],h[8]=l*i+f*n+g*s+b*r,h[9]=c*i+p*n+v*s+S*r,h[10]=u*i+m*n+y*s+w*r,h[11]=d*i+_*n+x*s+T*r,i=o[12],n=o[13],s=o[14],r=o[15],h[12]=l*i+f*n+g*s+b*r,h[13]=c*i+p*n+v*s+S*r,h[14]=u*i+m*n+y*s+w*r,h[15]=d*i+_*n+x*s+T*r,this},t.mulAffine2=function(e,t){var i,n,s,r=e.data,a=t.data,o=this.data,h=r[0],l=r[1],c=r[2],u=r[4],d=r[5],f=r[6],p=r[8],m=r[9],_=r[10],g=r[12],v=r[13],y=r[14];return i=a[0],n=a[1],s=a[2],o[0]=h*i+u*n+p*s,o[1]=l*i+d*n+m*s,o[2]=c*i+f*n+_*s,o[3]=0,i=a[4],n=a[5],s=a[6],o[4]=h*i+u*n+p*s,o[5]=l*i+d*n+m*s,o[6]=c*i+f*n+_*s,o[7]=0,i=a[8],n=a[9],s=a[10],o[8]=h*i+u*n+p*s,o[9]=l*i+d*n+m*s,o[10]=c*i+f*n+_*s,o[11]=0,i=a[12],n=a[13],s=a[14],o[12]=h*i+u*n+p*s+g,o[13]=l*i+d*n+m*s+v,o[14]=c*i+f*n+_*s+y,o[15]=1,this},t.mul=function(e){return this.mul2(this,e)},t.transformPoint=function(e,t){void 0===t&&(t=new ye);var i=this.data,n=e.x,s=e.y,r=e.z;return t.x=n*i[0]+s*i[4]+r*i[8]+i[12],t.y=n*i[1]+s*i[5]+r*i[9]+i[13],t.z=n*i[2]+s*i[6]+r*i[10]+i[14],t},t.transformVector=function(e,t){void 0===t&&(t=new ye);var i=this.data,n=e.x,s=e.y,r=e.z;return t.x=n*i[0]+s*i[4]+r*i[8],t.y=n*i[1]+s*i[5]+r*i[9],t.z=n*i[2]+s*i[6]+r*i[10],t},t.transformVec4=function(e,t){void 0===t&&(t=new Se);var i=this.data,n=e.x,s=e.y,r=e.z,a=e.w;return t.x=n*i[0]+s*i[4]+r*i[8]+a*i[12],t.y=n*i[1]+s*i[5]+r*i[9]+a*i[13],t.z=n*i[2]+s*i[6]+r*i[10]+a*i[14],t.w=n*i[3]+s*i[7]+r*i[11]+a*i[15],t},t.setLookAt=function(e,t,i){Me.sub2(e,t).normalize(),Ae.copy(i).normalize(),Te.cross(Ae,Me).normalize(),Ae.cross(Me,Te);var n=this.data;return n[0]=Te.x,n[1]=Te.y,n[2]=Te.z,n[3]=0,n[4]=Ae.x,n[5]=Ae.y,n[6]=Ae.z,n[7]=0,n[8]=Me.x,n[9]=Me.y,n[10]=Me.z,n[11]=0,n[12]=e.x,n[13]=e.y,n[14]=e.z,n[15]=1,this},t.setFrustum=function(e,t,i,n,s,r){var a=2*s,o=t-e,h=n-i,l=r-s,c=this.data;return c[0]=a/o,c[1]=0,c[2]=0,c[3]=0,c[4]=0,c[5]=a/h,c[6]=0,c[7]=0,c[8]=(t+e)/o,c[9]=(n+i)/h,c[10]=(-r-s)/l,c[11]=-1,c[12]=0,c[13]=0,c[14]=-a*r/l,c[15]=0,this},t.setPerspective=function(t,i,n,s,r){return e._getPerspectiveHalfSize(we,t,i,n,r),this.setFrustum(-we.x,we.x,-we.y,we.y,n,s)},t.setOrtho=function(e,t,i,n,s,r){var a=this.data;return a[0]=2/(t-e),a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=2/(n-i),a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=-2/(r-s),a[11]=0,a[12]=-(t+e)/(t-e),a[13]=-(n+i)/(n-i),a[14]=-(r+s)/(r-s),a[15]=1,this},t.setFromAxisAngle=function(e,t){t*=de.DEG_TO_RAD;var i=e.x,n=e.y,s=e.z,r=Math.cos(t),a=Math.sin(t),o=1-r,h=o*i,l=o*n,c=this.data;return c[0]=h*i+r,c[1]=h*n+a*s,c[2]=h*s-a*n,c[3]=0,c[4]=h*n-a*s,c[5]=l*n+r,c[6]=l*s+a*i,c[7]=0,c[8]=h*s+a*n,c[9]=l*s-i*a,c[10]=o*s*s+r,c[11]=0,c[12]=0,c[13]=0,c[14]=0,c[15]=1,this},t.setTranslate=function(e,t,i){var n=this.data;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=e,n[13]=t,n[14]=i,n[15]=1,this},t.setScale=function(e,t,i){var n=this.data;return n[0]=e,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=t,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=i,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this},t.setViewport=function(e,t,i,n){var s=this.data;return s[0]=.5*i,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=.5*n,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=.5,s[11]=0,s[12]=e+.5*i,s[13]=t+.5*n,s[14]=.5,s[15]=1,this},t.invert=function(){var e=this.data,t=e[0],i=e[1],n=e[2],s=e[3],r=e[4],a=e[5],o=e[6],h=e[7],l=e[8],c=e[9],u=e[10],d=e[11],f=e[12],p=e[13],m=e[14],_=e[15],g=t*a-i*r,v=t*o-n*r,y=t*h-s*r,x=i*o-n*a,b=i*h-s*a,S=n*h-s*o,w=l*p-c*f,T=l*m-u*f,A=l*_-d*f,M=c*m-u*p,C=c*_-d*p,E=u*_-d*m,P=g*E-v*C+y*M+x*A-b*T+S*w;if(0===P)this.setIdentity();else{var R=1/P;e[0]=(a*E-o*C+h*M)*R,e[1]=(-i*E+n*C-s*M)*R,e[2]=(p*S-m*b+_*x)*R,e[3]=(-c*S+u*b-d*x)*R,e[4]=(-r*E+o*A-h*T)*R,e[5]=(t*E-n*A+s*T)*R,e[6]=(-f*S+m*y-_*v)*R,e[7]=(l*S-u*y+d*v)*R,e[8]=(r*C-a*A+h*w)*R,e[9]=(-t*C+i*A-s*w)*R,e[10]=(f*b-p*y+_*g)*R,e[11]=(-l*b+c*y-d*g)*R,e[12]=(-r*M+a*T-o*w)*R,e[13]=(t*M-i*T+n*w)*R,e[14]=(-f*x+p*v-m*g)*R,e[15]=(l*x-c*v+u*g)*R}return this},t.set=function(e){var t=this.data;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],this},t.setIdentity=function(){var e=this.data;return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},t.setTRS=function(e,t,i){var n=t.x,s=t.y,r=t.z,a=t.w,o=i.x,h=i.y,l=i.z,c=n+n,u=s+s,d=r+r,f=n*c,p=n*u,m=n*d,_=s*u,g=s*d,v=r*d,y=a*c,x=a*u,b=a*d,S=this.data;return S[0]=(1-(_+v))*o,S[1]=(p+b)*o,S[2]=(m-x)*o,S[3]=0,S[4]=(p-b)*h,S[5]=(1-(f+v))*h,S[6]=(g+y)*h,S[7]=0,S[8]=(m+x)*l,S[9]=(g-y)*l,S[10]=(1-(f+_))*l,S[11]=0,S[12]=e.x,S[13]=e.y,S[14]=e.z,S[15]=1,this},t.transpose=function(){var e,t=this.data;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this},t.invertTo3x3=function(e){var t=this.data,i=e.data,n=t[0],s=t[1],r=t[2],a=t[4],o=t[5],h=t[6],l=t[8],c=t[9],u=t[10],d=u*o-h*c,f=-u*s+r*c,p=h*s-r*o,m=-u*a+h*l,_=u*n-r*l,g=-h*n+r*a,v=c*a-o*l,y=-c*n+s*l,x=o*n-s*a,b=n*d+s*m+r*v;if(0===b)return this;var S=1/b;return i[0]=S*d,i[1]=S*f,i[2]=S*p,i[3]=S*m,i[4]=S*_,i[5]=S*g,i[6]=S*v,i[7]=S*y,i[8]=S*x,this},t.getTranslation=function(e){return void 0===e&&(e=new ye),e.set(this.data[12],this.data[13],this.data[14])},t.getX=function(e){return void 0===e&&(e=new ye),e.set(this.data[0],this.data[1],this.data[2])},t.getY=function(e){return void 0===e&&(e=new ye),e.set(this.data[4],this.data[5],this.data[6])},t.getZ=function(e){return void 0===e&&(e=new ye),e.set(this.data[8],this.data[9],this.data[10])},t.getScale=function(e){return void 0===e&&(e=new ye),this.getX(Te),this.getY(Ae),this.getZ(Me),e.set(Te.length(),Ae.length(),Me.length()),e},t.setFromEulerAngles=function(e,t,i){e*=de.DEG_TO_RAD,t*=de.DEG_TO_RAD,i*=de.DEG_TO_RAD;var n=Math.sin(-e),s=Math.cos(-e),r=Math.sin(-t),a=Math.cos(-t),o=Math.sin(-i),h=Math.cos(-i),l=this.data;return l[0]=a*h,l[1]=-a*o,l[2]=r,l[3]=0,l[4]=s*o+h*n*r,l[5]=s*h-n*r*o,l[6]=-a*n,l[7]=0,l[8]=n*o-s*h*r,l[9]=h*n+s*r*o,l[10]=s*a,l[11]=0,l[12]=0,l[13]=0,l[14]=0,l[15]=1,this},t.getEulerAngles=function(e){void 0===e&&(e=new ye),this.getScale(Ce);var t=Ce.x,i=Ce.y,n=Ce.z;if(0===t||0===i||0===n)return e.set(0,0,0);var s,r,a=this.data,o=Math.asin(-a[2]/t),h=.5*Math.PI;return o<h?o>-h?(s=Math.atan2(a[6]/i,a[10]/n),r=Math.atan2(a[1]/t,a[0]/t)):(r=0,s=-Math.atan2(a[4]/i,a[5]/i)):(r=0,s=Math.atan2(a[4]/i,a[5]/i)),e.set(s,o,r).mulScalar(de.RAD_TO_DEG)},t.toString=function(){return"["+this.data.join(", ")+"]"},e}();Ee.IDENTITY=Object.freeze(new Ee),Ee.ZERO=Object.freeze((new Ee).set([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]));var Pe=function(){function e(e,t,i,n){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=1),4===e.length?(this.x=e[0],this.y=e[1],this.z=e[2],this.w=e[3]):(this.x=e,this.y=t,this.z=i,this.w=n)}var t=e.prototype;return t.clone=function(){return new(0,this.constructor)(this.x,this.y,this.z,this.w)},t.conjugate=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.copy=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},t.equals=function(e){return this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},t.getAxisAngle=function(e){var t=2*Math.acos(this.w),i=Math.sin(t/2);return 0!==i?(e.x=this.x/i,e.y=this.y/i,e.z=this.z/i,(e.x<0||e.y<0||e.z<0)&&(e.x*=-1,e.y*=-1,e.z*=-1,t*=-1)):(e.x=1,e.y=0,e.z=0),t*de.RAD_TO_DEG},t.getEulerAngles=function(e){var t,i,n;void 0===e&&(e=new ye);var s=this.x,r=this.y,a=this.z,o=this.w,h=2*(o*r-s*a);return h<=-.99999?(t=2*Math.atan2(s,o),i=-Math.PI/2,n=0):h>=.99999?(t=2*Math.atan2(s,o),i=Math.PI/2,n=0):(t=Math.atan2(2*(o*s+r*a),1-2*(s*s+r*r)),i=Math.asin(h),n=Math.atan2(2*(o*a+s*r),1-2*(r*r+a*a))),e.set(t,i,n).mulScalar(de.RAD_TO_DEG)},t.invert=function(){return this.conjugate().normalize()},t.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.lengthSq=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},t.mul=function(e){var t=this.x,i=this.y,n=this.z,s=this.w,r=e.x,a=e.y,o=e.z,h=e.w;return this.x=s*r+t*h+i*o-n*a,this.y=s*a+i*h+n*r-t*o,this.z=s*o+n*h+t*a-i*r,this.w=s*h-t*r-i*a-n*o,this},t.mul2=function(e,t){var i=e.x,n=e.y,s=e.z,r=e.w,a=t.x,o=t.y,h=t.z,l=t.w;return this.x=r*a+i*l+n*h-s*o,this.y=r*o+n*l+s*a-i*h,this.z=r*h+s*l+i*o-n*a,this.w=r*l-i*a-n*o-s*h,this},t.normalize=function(){var e=this.length();return 0===e?(this.x=this.y=this.z=0,this.w=1):(e=1/e,this.x*=e,this.y*=e,this.z*=e,this.w*=e),this},t.set=function(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this},t.setFromAxisAngle=function(e,t){t*=.5*de.DEG_TO_RAD;var i=Math.sin(t),n=Math.cos(t);return this.x=i*e.x,this.y=i*e.y,this.z=i*e.z,this.w=n,this},t.setFromEulerAngles=function(e,t,i){if(e instanceof ye){var n=e;e=n.x,t=n.y,i=n.z}var s=.5*de.DEG_TO_RAD;e*=s,t*=s,i*=s;var r=Math.sin(e),a=Math.cos(e),o=Math.sin(t),h=Math.cos(t),l=Math.sin(i),c=Math.cos(i);return this.x=r*h*c-a*o*l,this.y=a*o*c+r*h*l,this.z=a*h*l-r*o*c,this.w=a*h*c+r*o*l,this},t.setFromMat4=function(e){var t,i,n,s,r,a,o,h,l,c,u,d,f,p;if(t=(e=e.data)[0],i=e[1],n=e[2],s=e[4],r=e[5],a=e[6],o=e[8],h=e[9],l=e[10],0===(d=t*t+i*i+n*n))return this;if(d=1/Math.sqrt(d),0===(f=s*s+r*r+a*a))return this;if(f=1/Math.sqrt(f),0===(p=o*o+h*h+l*l))return this;i*=d,n*=d,s*=f,a*=f,o*=p=1/Math.sqrt(p),h*=p;var m=(t*=d)+(r*=f)+(l*=p);return m>=0?(c=Math.sqrt(m+1),this.w=.5*c,c=.5/c,this.x=(a-h)*c,this.y=(o-n)*c,this.z=(i-s)*c):t>r?t>l?(u=t-(r+l)+1,u=Math.sqrt(u),this.x=.5*u,u=.5/u,this.w=(a-h)*u,this.y=(i+s)*u,this.z=(n+o)*u):(u=l-(t+r)+1,u=Math.sqrt(u),this.z=.5*u,u=.5/u,this.w=(i-s)*u,this.x=(o+n)*u,this.y=(h+a)*u):r>l?(u=r-(l+t)+1,u=Math.sqrt(u),this.y=.5*u,u=.5/u,this.w=(o-n)*u,this.z=(a+h)*u,this.x=(s+i)*u):(u=l-(t+r)+1,u=Math.sqrt(u),this.z=.5*u,u=.5/u,this.w=(i-s)*u,this.x=(o+n)*u,this.y=(h+a)*u),this},t.slerp=function(e,t,i){var n=e.x,s=e.y,r=e.z,a=e.w,o=t.x,h=t.y,l=t.z,c=t.w,u=a*c+n*o+s*h+r*l;if(u<0&&(c=-c,o=-o,h=-h,l=-l,u=-u),Math.abs(u)>=1)return this.w=a,this.x=n,this.y=s,this.z=r,this;var d=Math.acos(u),f=Math.sqrt(1-u*u);if(Math.abs(f)<.001)return this.w=.5*a+.5*c,this.x=.5*n+.5*o,this.y=.5*s+.5*h,this.z=.5*r+.5*l,this;var p=Math.sin((1-i)*d)/f,m=Math.sin(i*d)/f;return this.w=a*p+c*m,this.x=n*p+o*m,this.y=s*p+h*m,this.z=r*p+l*m,this},t.transformVector=function(e,t){void 0===t&&(t=new ye);var i=e.x,n=e.y,s=e.z,r=this.x,a=this.y,o=this.z,h=this.w,l=h*i+a*s-o*n,c=h*n+o*i-r*s,u=h*s+r*n-a*i,d=-r*i-a*n-o*s;return t.x=l*h+d*-r+c*-o-u*-a,t.y=c*h+d*-a+u*-r-l*-o,t.z=u*h+d*-o+l*-a-c*-r,t},t.toString=function(){return"["+this.x+", "+this.y+", "+this.z+", "+this.w+"]"},e}();Pe.IDENTITY=Object.freeze(new Pe(0,0,0,1)),Pe.ZERO=Object.freeze(new Pe(0,0,0,0));var Re=new ye,Ie=new ye,Le=new ye,De=new ye,ke=new ye,Oe=function(){function e(e,t){void 0===e&&(e=new ye),void 0===t&&(t=new ye(.5,.5,.5)),this.center=e,this.halfExtents=t,this._min=new ye,this._max=new ye}var t=e.prototype;return t.add=function(e){var t=this.center,i=t.x,n=t.y,s=t.z,r=this.halfExtents,a=r.x,o=r.y,h=r.z,l=i-a,c=i+a,u=n-o,d=n+o,f=s-h,p=s+h,m=e.center,_=m.x,g=m.y,v=m.z,y=e.halfExtents,x=y.x,b=y.y,S=y.z,w=_-x,T=_+x,A=g-b,M=g+b,C=v-S,E=v+S;w<l&&(l=w),T>c&&(c=T),A<u&&(u=A),M>d&&(d=M),C<f&&(f=C),E>p&&(p=E),t.x=.5*(l+c),t.y=.5*(u+d),t.z=.5*(f+p),r.x=.5*(c-l),r.y=.5*(d-u),r.z=.5*(p-f)},t.copy=function(e){this.center.copy(e.center),this.halfExtents.copy(e.halfExtents)},t.clone=function(){return new e(this.center.clone(),this.halfExtents.clone())},t.intersects=function(e){var t=this.getMax(),i=this.getMin(),n=e.getMax(),s=e.getMin();return i.x<=n.x&&t.x>=s.x&&i.y<=n.y&&t.y>=s.y&&i.z<=n.z&&t.z>=s.z},t._intersectsRay=function(e,t){var i=Re.copy(this.getMin()).sub(e.origin),n=Ie.copy(this.getMax()).sub(e.origin),s=e.direction;0===s.x?(i.x=i.x<0?-Number.MAX_VALUE:Number.MAX_VALUE,n.x=n.x<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.x/=s.x,n.x/=s.x),0===s.y?(i.y=i.y<0?-Number.MAX_VALUE:Number.MAX_VALUE,n.y=n.y<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.y/=s.y,n.y/=s.y),0===s.z?(i.z=i.z<0?-Number.MAX_VALUE:Number.MAX_VALUE,n.z=n.z<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.z/=s.z,n.z/=s.z);var r=Le.set(Math.min(i.x,n.x),Math.min(i.y,n.y),Math.min(i.z,n.z)),a=De.set(Math.max(i.x,n.x),Math.max(i.y,n.y),Math.max(i.z,n.z)),o=Math.min(Math.min(a.x,a.y),a.z),h=Math.max(Math.max(r.x,r.y),r.z),l=o>=h&&h>=0;return l&&t.copy(e.direction).mulScalar(h).add(e.origin),l},t._fastIntersectsRay=function(e){var t=Re,i=Ie,n=Le,s=De,r=ke,a=e.direction;return t.sub2(e.origin,this.center),s.set(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z)),n.mul2(t,a),!(s.x>this.halfExtents.x&&n.x>=0)&&(!(s.y>this.halfExtents.y&&n.y>=0)&&(!(s.z>this.halfExtents.z&&n.z>=0)&&(r.set(Math.abs(a.x),Math.abs(a.y),Math.abs(a.z)),i.cross(a,t),i.set(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z)),!(i.x>this.halfExtents.y*r.z+this.halfExtents.z*r.y)&&(!(i.y>this.halfExtents.x*r.z+this.halfExtents.z*r.x)&&!(i.z>this.halfExtents.x*r.y+this.halfExtents.y*r.x)))))},t.intersectsRay=function(e,t){return t?this._intersectsRay(e,t):this._fastIntersectsRay(e)},t.setMinMax=function(e,t){this.center.add2(t,e).mulScalar(.5),this.halfExtents.sub2(t,e).mulScalar(.5)},t.getMin=function(){return this._min.copy(this.center).sub(this.halfExtents)},t.getMax=function(){return this._max.copy(this.center).add(this.halfExtents)},t.containsPoint=function(e){var t=this.getMin(),i=this.getMax();return!(e.x<t.x||e.x>i.x||e.y<t.y||e.y>i.y||e.z<t.z||e.z>i.z)},t.setFromTransformedAabb=function(e,t,i){void 0===i&&(i=!1);var n=e.center,s=e.halfExtents,r=t.data,a=r[0],o=r[4],h=r[8],l=r[1],c=r[5],u=r[9],d=r[2],f=r[6],p=r[10];if(i){var m=a*a+o*o+h*h;if(m>0){var _=1/Math.sqrt(m);a*=_,o*=_,h*=_}if((m=l*l+c*c+u*u)>0){var g=1/Math.sqrt(m);l*=g,c*=g,u*=g}if((m=d*d+f*f+p*p)>0){var v=1/Math.sqrt(m);d*=v,f*=v,p*=v}}this.center.set(r[12]+a*n.x+o*n.y+h*n.z,r[13]+l*n.x+c*n.y+u*n.z,r[14]+d*n.x+f*n.y+p*n.z),this.halfExtents.set(Math.abs(a)*s.x+Math.abs(o)*s.y+Math.abs(h)*s.z,Math.abs(l)*s.x+Math.abs(c)*s.y+Math.abs(u)*s.z,Math.abs(d)*s.x+Math.abs(f)*s.y+Math.abs(p)*s.z)},e.computeMinMax=function(e,t,i,n){if(void 0===n&&(n=e.length/3),n>0){t.set(e[0],e[1],e[2]),i.set(e[0],e[1],e[2]);for(var s=1;s<n;s++){var r=e[3*s+0],a=e[3*s+1],o=e[3*s+2];r<t.x&&(t.x=r),a<t.y&&(t.y=a),o<t.z&&(t.z=o),r>i.x&&(i.x=r),a>i.y&&(i.y=a),o>i.z&&(i.z=o)}}},t.compute=function(t,i){e.computeMinMax(t,Re,Ie,i),this.setMinMax(Re,Ie)},t.intersectsBoundingSphere=function(e){return this._distanceToBoundingSphereSq(e)<=e.radius*e.radius},t._distanceToBoundingSphereSq=function(e){for(var t=this.getMin(),i=this.getMax(),n=0,s=["x","y","z"],r=0;r<3;++r){var a=0,o=e.center[s[r]],h=t[s[r]],l=i[s[r]],c=0;o<h&&(a+=(c=h-o)*c),o>l&&(a+=(c=o-l)*c),n+=a}return n},t._expand=function(e,t){Re.add2(this.getMin(),e),Ie.add2(this.getMax(),t),this.setMinMax(Re,Ie)},e}(),Fe=new ye,Be=new ye,Ne=function(){function e(e,t){void 0===e&&(e=new ye),void 0===t&&(t=.5),this.center=e,this.radius=t}var t=e.prototype;return t.containsPoint=function(e){var t=Fe.sub2(e,this.center).lengthSq(),i=this.radius;return t<i*i},t.intersectsRay=function(e,t){var i=Fe.copy(e.origin).sub(this.center),n=i.dot(Be.copy(e.direction).normalize()),s=i.dot(i)-this.radius*this.radius;if(s>0&&n>0)return!1;var r=n*n-s;if(r<0)return!1;var a=Math.abs(-n-Math.sqrt(r));return t&&t.copy(e.direction).mulScalar(a).add(e.origin),!0},t.intersectsBoundingSphere=function(e){Fe.sub2(e.center,this.center);var t=e.radius+this.radius;return Fe.lengthSq()<=t*t},e}(),Ue="none",ze="linear",Ve={0:"PCF3",1:"VSM8",2:"VSM16",3:"VSM32",4:"PCF5",5:"PCF1"},Ge=128,We=256,He=1024,Xe=2048,qe=4096,je=8192,Ye="forward",Ke="depth",Ze="pick",$e="shadow",Qe=[new ye,new ye,new ye,new ye,new ye,new ye,new ye,new ye],Je=function(){function e(){this.planes=[];for(var e=0;e<6;e++)this.planes[e]=[]}var t=e.prototype;return t.setFromMat4=function(e){var t,i=e.data,n=this.planes;(t=n[0])[0]=i[3]-i[0],t[1]=i[7]-i[4],t[2]=i[11]-i[8],t[3]=i[15]-i[12];var s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s,(t=n[1])[0]=i[3]+i[0],t[1]=i[7]+i[4],t[2]=i[11]+i[8],t[3]=i[15]+i[12],s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s,(t=n[2])[0]=i[3]+i[1],t[1]=i[7]+i[5],t[2]=i[11]+i[9],t[3]=i[15]+i[13],s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s,(t=n[3])[0]=i[3]-i[1],t[1]=i[7]-i[5],t[2]=i[11]-i[9],t[3]=i[15]-i[13],s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s,(t=n[4])[0]=i[3]-i[2],t[1]=i[7]-i[6],t[2]=i[11]-i[10],t[3]=i[15]-i[14],s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s,(t=n[5])[0]=i[3]+i[2],t[1]=i[7]+i[6],t[2]=i[11]+i[10],t[3]=i[15]+i[14],s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s},t.containsPoint=function(e){var t,i;for(t=0;t<6;t++)if((i=this.planes[t])[0]*e.x+i[1]*e.y+i[2]*e.z+i[3]<=0)return!1;return!0},t.containsSphere=function(e){var t,i,n,s=0,r=e.radius,a=e.center,o=a.x,h=a.y,l=a.z,c=this.planes;for(i=0;i<6;i++){if((t=(n=c[i])[0]*o+n[1]*h+n[2]*l+n[3])<=-r)return 0;t>r&&s++}return 6===s?2:1},e.getPoints=function(e,t,i){t=t||e._nearClip,i=i||e._farClip;var n=e._fov*Math.PI/180,s=0===e._projection?Math.tan(n/2)*t:e._orthoHeight,r=s*e._aspectRatio,a=Qe;return a[0].x=r,a[0].y=-s,a[0].z=-t,a[1].x=r,a[1].y=s,a[1].z=-t,a[2].x=-r,a[2].y=s,a[2].z=-t,a[3].x=-r,a[3].y=-s,a[3].z=-t,0===e._projection&&(r=(s=Math.tan(n/2)*i)*e._aspectRatio),a[4].x=r,a[4].y=-s,a[4].z=-i,a[5].x=r,a[5].y=s,a[5].z=-i,a[6].x=-r,a[6].y=s,a[6].z=-i,a[7].x=-r,a[7].y=-s,a[7].z=-i,a},e}(),et=function(){function e(e,t){void 0===e&&(e=new ye),void 0===t&&(t=new ye(0,0,-1)),this.origin=e,this.direction=t}return e.prototype.set=function(e,t){return this.origin.copy(e),this.direction.copy(t),this},e}(),tt=new et,it=new ye,nt=new Ne,st=new Ee,rt=function(){function e(e,t){void 0===e&&(e=new Ee),void 0===t&&(t=new ye(.5,.5,.5)),this.halfExtents=t,this._modelTransform=e.clone().invert(),this._worldTransform=e.clone(),this._aabb=new Oe(new ye,this.halfExtents)}var t=e.prototype;return t.intersectsRay=function(e,t){if(this._modelTransform.transformPoint(e.origin,tt.origin),this._modelTransform.transformVector(e.direction,tt.direction),t){var i=this._aabb._intersectsRay(tt,t);return st.copy(this._modelTransform).invert().transformPoint(t,t),i}return this._aabb._fastIntersectsRay(tt)},t.containsPoint=function(e){return this._modelTransform.transformPoint(e,it),this._aabb.containsPoint(it)},t.intersectsBoundingSphere=function(e){return this._modelTransform.transformPoint(e.center,nt.center),nt.radius=e.radius,!!this._aabb.intersectsBoundingSphere(nt)},$(e,[{key:"worldTransform",get:function(){return this._worldTransform},set:function(e){this._worldTransform.copy(e),this._modelTransform.copy(e).invert()}}]),e}(),at=new ye,ot=function(){function e(e,t){void 0===e&&(e=new ye),void 0===t&&(t=new ye(0,0,1)),this.point=e,this.normal=t}var t=e.prototype;return t.intersectsLine=function(e,t,i){var n=-this.normal.dot(this.point),s=this.normal.dot(e)+n,r=s/(s-(this.normal.dot(t)+n)),a=r>=0&&r<=1;return a&&i&&i.lerp(e,t,r),a},t.intersectsRay=function(e,t){var i=at.sub2(this.point,e.origin),n=this.normal.dot(i)/this.normal.dot(e.direction),s=n>=0;return s&&t&&t.copy(e.direction).mulScalar(n).add(e.origin),s},e}(),ht=10,lt=11,ct=12,ut=13,dt=14,ft=16,pt=17,mt=21,_t=24,gt=25,vt="POSITION",yt="NORMAL",xt="TANGENT",bt="BLENDWEIGHT",St="BLENDINDICES",wt="COLOR",Tt="TEXCOORD",At="TEXCOORD0",Mt="TEXCOORD1",Ct="TEXCOORD2",Et="TEXCOORD3",Pt="TEXCOORD4",Rt="TEXCOORD5",It="TEXCOORD6",Lt="TEXCOORD7",Dt="ATTR",kt="ATTR0",Ot="ATTR1",Ft="ATTR2",Bt="ATTR3",Nt="ATTR4",Ut="ATTR5",zt="ATTR6",Vt="ATTR7",Gt="ATTR8",Wt="ATTR9",Ht="ATTR10",Xt="ATTR11",qt="ATTR12",jt="ATTR13",Yt="ATTR14",Kt="ATTR15",Zt="default",$t="rgbm",Qt="rgbe",Jt="rgbp",ei="swizzleGGGR",ti="2d",ii="float",ni="unfilterable-float",si="none",ri="cube",ai="equirect",oi="octahedral",hi=["bool","int","float","vec2","vec3","vec4","ivec2","ivec3","ivec4","bec2","bec3","bec4","mat2","mat3","mat4","sampler2D","samplerCube","","sampler2DShadow","samplerCubeShadow","sampler3D","","",""],li="webgl",ci="webgpu",ui="default",di=["view","mesh"],fi=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array],pi=[1,1,2,2,4,4,4],mi={Int8Array:0,Uint8Array:1,Int16Array:2,Uint16Array:3,Int32Array:4,Uint32Array:5,Float32Array:6},_i=[Uint8Array,Uint16Array,Uint32Array],gi=[1,2,4],vi={POSITION:0,NORMAL:1,BLENDWEIGHT:2,BLENDINDICES:3,COLOR:4,TEXCOORD0:5,TEXCOORD1:6,TEXCOORD2:7,TEXCOORD3:8,TEXCOORD4:9,TEXCOORD5:10,TEXCOORD6:11,TEXCOORD7:12,TANGENT:13,ATTR0:0,ATTR1:1,ATTR2:2,ATTR3:3,ATTR4:4,ATTR5:5,ATTR6:6,ATTR7:7,ATTR8:8,ATTR9:9,ATTR10:10,ATTR11:11,ATTR12:12,ATTR13:13,ATTR14:14,ATTR15:15},yi="1.55",xi="1.57",bi=0,Si=function(){function e(e,t,i,n,s){void 0===n&&(n=0),this.device=e,this.format=t,this.numVertices=i,this.usage=n,this.id=bi++,this.impl=e.createVertexBufferImpl(this,t),this.instancing=!1,this.numBytes=t.verticesByteSize?t.verticesByteSize:t.size*i,this.adjustVramSizeTracking(e._vram,this.numBytes),s?this.setData(s):this.storage=new ArrayBuffer(this.numBytes),this.device.buffers.push(this)}var t=e.prototype;return t.destroy=function(){var e=this.device,t=e.buffers.indexOf(this);-1!==t&&e.buffers.splice(t,1),this.impl.initialized&&(this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this.storage.byteLength))},t.adjustVramSizeTracking=function(e,t){e.vb+=t},t.loseContext=function(){this.impl.loseContext()},t.getFormat=function(){return this.format},t.getUsage=function(){return this.usage},t.getNumVertices=function(){return this.numVertices},t.lock=function(){return this.storage},t.unlock=function(){this.impl.unlock(this)},t.setData=function(e){return e.byteLength===this.numBytes&&(this.storage=e,this.unlock(),!0)},e}();function wi(e){for(var t=0,i=0,n=e.length;i<n;i++)t=(t<<5)-t+e.charCodeAt(i),t|=0;return t}var Ti=function(){function e(e,t,i){this._elements=[],this.hasUv0=!1,this.hasUv1=!1,this.hasColor=!1,this.hasTangents=!1,this.verticesByteSize=0,this.vertexCount=i,this.interleaved=void 0===i,this.size=t.reduce((function(e,t){return e+4*Math.ceil(t.components*pi[t.type]/4)}),0);for(var n,s=0,r=0,a=t.length;r<a;r++){var o=t[r];n=o.components*pi[o.type],i&&(s=de.roundUp(s,n));var h={name:o.semantic,offset:i?s:o.hasOwnProperty("offset")?o.offset:s,stride:i?n:o.hasOwnProperty("stride")?o.stride:this.size,dataType:o.type,numComponents:o.components,normalize:void 0!==o.normalize&&o.normalize,size:n};this._elements.push(h),s+=i?n*i:4*Math.ceil(n/4),o.semantic===At?this.hasUv0=!0:o.semantic===Mt?this.hasUv1=!0:o.semantic===wt?this.hasColor=!0:o.semantic===xt&&(this.hasTangents=!0)}i&&(this.verticesByteSize=s),this._evaluateHash()}return e.prototype._evaluateHash=function(){for(var e,t,i=[],n=[],s=this._elements.length,r=0;r<s;r++){var a=this._elements[r];e=a.name,e+=a.dataType,e+=a.numComponents,e+=a.normalize,i.push(e),t=e,t+=a.offset,t+=a.stride,t+=a.size,n.push(t)}i.sort(),this.batchingHash=wi(i.join()),this.renderingingHashString=n.join("_"),this.renderingingHash=wi(this.renderingingHashString)},$(e,[{key:"elements",get:function(){return this._elements}}],[{key:"defaultInstancingFormat",get:function(){return e._defaultInstancingFormat||(e._defaultInstancingFormat=new e(null,[{semantic:qt,components:4,type:6},{semantic:jt,components:4,type:6},{semantic:Yt,components:4,type:6},{semantic:Kt,components:4,type:6}])),e._defaultInstancingFormat}}]),e}();Ti._defaultInstancingFormat=null;var Ai=function(){function e(){this._cache=new Map}var t=e.prototype;return t.get=function(e,t){var i=this;return this._cache.has(e)||(this._cache.set(e,t()),e.on("destroy",(function(){i.remove(e)}))),this._cache.get(e)},t.remove=function(e){var t;null==(t=this._cache.get(e))||t.destroy(),this._cache.delete(e)},e}(),Mi={type:5,base:0,count:4,indexed:!1},Ci=new Ai;function Ei(e,t,i,n,s,r){void 0===r&&(r=!1);var a,o,h,l,c,u,d,f,p=e.renderTarget;e.setRenderTarget(t),e.updateBegin(),n?(a=n.x,o=n.y,h=n.z,l=n.w):(h=t?t.width:e.width,l=t?t.height:e.height,a=0,o=0),s?(c=s.x,u=s.y,d=s.z,f=s.w):(c=a,u=o,d=h,f=l);var m=e.vx,_=e.vy,g=e.vw,v=e.vh;e.setViewport(a,o,h,l);var y=e.sx,x=e.sy,b=e.sw,S=e.sh;e.setScissor(c,u,d,f);var w=e.getDepthTest(),T=e.getDepthWrite(),A=e.getCullMode(),M=e.writeRed,C=e.writeGreen,E=e.writeBlue,P=e.writeAlpha;e.setDepthTest(!1),e.setDepthWrite(!1),e.setCullMode(0),e.setColorWrite(!0,!0,!0,!0),r||e.setBlending(!1),e.setVertexBuffer(function(e){return Ci.get(e,(function(){var t=new Ti(e,[{semantic:vt,components:2,type:6}]),i=new Float32Array(8);return i.set([-1,-1,1,-1,-1,1,1,1]),new Si(e,t,4,0,i)}))}(e),0),e.setShader(i),e.draw(Mi),e.setDepthTest(w),e.setDepthWrite(T),e.setCullMode(A),e.setColorWrite(M,C,E,P),e.updateEnd(),e.setRenderTarget(p),e.updateBegin(),e.setViewport(m,_,g,v),e.setScissor(y,x,b,S)}var Pi=/[ \t]*#(ifn?def|if|endif|else|elif|define|undef|extension)/g,Ri=/define[ \t]+([^\n]+)\r?(?:\n|$)/g,Ii=/extension[ \t]+([\w-]+)[ \t]*:[ \t]*enable/g,Li=/undef[ \t]+([^\n]+)\r?(?:\n|$)/g,Di=/(ifdef|ifndef|if)[ \t]*([^\r\n]+)\r?\n/g,ki=/(endif|else|elif)([ \t]+[^\r\n]+)?\r?(?:\n|$)/g,Oi=/([\w-]+)/,Fi=/(!|\s)?defined\(([\w-]+)\)/,Bi=/[><=|&+-]/g,Ni=function(){function e(){}return e.run=function(e){return e=(e=e.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm,"$1")).split(/\r?\n/).map((function(e){return e.trimEnd()})).join("\n"),null!==(e=this._preprocess(e))&&(e=(e=e.split(/\r?\n/).map((function(e){return""===e.trim()?"":e})).join("\n")).replace(/(\n\n){3,}/gm,"\n\n")),e},e._preprocess=function(t){for(var i,n=t,s=[],r=!1,a=new Map;null!==(i=Pi.exec(t));){var o=i[1];switch(o){case"define":Ri.lastIndex=i.index;var h=Ri.exec(t);r||(r=null===h);var l=h[1];Oi.lastIndex=h.index;var c=Oi.exec(l)[1],u=l.substring(c.length).trim();""===u&&(u="true"),e._keep(s)&&a.set(c,u),Pi.lastIndex=h.index+h[0].length;break;case"undef":Li.lastIndex=i.index;var d=Li.exec(t),f=d[1].trim();e._keep(s)&&a.delete(f),Pi.lastIndex=d.index+d[0].length;break;case"extension":Ii.lastIndex=i.index;var p=Ii.exec(t);if(r||(r=null===p),p){var m=p[1];e._keep(s)&&a.set(m,"true")}Pi.lastIndex=p.index+p[0].length;break;case"ifdef":case"ifndef":case"if":Di.lastIndex=i.index;var _=Di.exec(t),g=_[2],v=e.evaluate(g,a);r||(r=v.error);var y=v.result;"ifndef"===o&&(y=!y),s.push({anyKeep:y,keep:y,start:i.index,end:Di.lastIndex}),Pi.lastIndex=_.index+_[0].length;break;case"endif":case"else":case"elif":ki.lastIndex=i.index;var x=ki.exec(t),b=s.pop(),S=b.keep?t.substring(b.end,i.index):"";t=t.substring(0,b.start)+S+t.substring(ki.lastIndex),Pi.lastIndex=b.start+S.length;var w=x[1];if("else"===w||"elif"===w){var T=!1;if(!b.anyKeep)if("else"===w)T=!b.keep;else{var A=e.evaluate(x[2],a);T=A.result,r||(r=A.error)}s.push({anyKeep:b.anyKeep||T,keep:T,start:Pi.lastIndex,end:Pi.lastIndex})}}}return r?(console.warn("Failed to preprocess shader: ",{source:n}),n):t},e._keep=function(e){for(var t=0;t<e.length;t++)if(!e[t].keep)return!1;return!0},e.evaluate=function(e,t){var i=null===Bi.exec(e),n=!1,s=Fi.exec(e);s&&(n="!"===s[1],e=s[2]),e=e.trim();var r=t.has(e);return n&&(r=!r),{result:r,error:!i}},e}(),Ui=0,zi=function(){function e(e,t){this.meshUniformBufferFormat=void 0,this.meshBindGroupFormat=void 0,this.id=Ui++,this.device=e,this.definition=t,this.name=t.name||"Untitled",t.vshader=Ni.run(t.vshader),t.fshader=Ni.run(t.fshader),this.init(),this.impl=e.createShaderImpl(this)}var t=e.prototype;return t.init=function(){this.ready=!1,this.failed=!1},t.destroy=function(){this.impl.destroy(this)},t.loseContext=function(){this.init(),this.impl.loseContext()},t.restoreContext=function(){this.impl.restoreContext(this.device,this)},e}(),Vi="\nvec3 decodeLinear(vec4 raw) {\n return raw.rgb;\n}\n\nfloat decodeGamma(float raw) {\n return pow(raw, 2.2);\n}\n\nvec3 decodeGamma(vec3 raw) {\n return pow(raw, vec3(2.2));\n}\n\nvec3 decodeGamma(vec4 raw) {\n return pow(raw.xyz, vec3(2.2));\n}\n\nvec3 decodeRGBM(vec4 raw) {\n vec3 color = (8.0 * raw.a) * raw.rgb;\n return color * color;\n}\n\nvec3 decodeRGBP(vec4 raw) {\n vec3 color = raw.rgb * (-raw.a * 7.0 + 8.0);\n return color * color;\n}\n\nvec3 decodeRGBE(vec4 raw) {\n if (raw.a == 0.0) {\n return vec3(0.0, 0.0, 0.0);\n } else {\n return raw.xyz * pow(2.0, raw.w * 255.0 - 128.0);\n }\n}\n\nvec4 passThrough(vec4 raw) {\n return raw;\n}\n",Gi="\nvec4 encodeLinear(vec3 source) {\n return vec4(source, 1.0);\n}\n\nvec4 encodeGamma(vec3 source) {\n return vec4(pow(source + 0.0000001, vec3(1.0 / 2.2)), 1.0);\n}\n\nvec4 encodeRGBM(vec3 source) { // modified RGBM\n vec4 result;\n result.rgb = pow(source.rgb, vec3(0.5));\n result.rgb *= 1.0 / 8.0;\n\n result.a = saturate( max( max( result.r, result.g ), max( result.b, 1.0 / 255.0 ) ) );\n result.a = ceil(result.a * 255.0) / 255.0;\n\n result.rgb /= result.a;\n return result;\n}\n\nvec4 encodeRGBP(vec3 source) {\n // convert incoming linear to gamma(ish)\n vec3 gamma = pow(source, vec3(0.5));\n\n // calculate the maximum component clamped to 1..8\n float maxVal = min(8.0, max(1.0, max(gamma.x, max(gamma.y, gamma.z))));\n\n // calculate storage factor\n float v = 1.0 - ((maxVal - 1.0) / 7.0);\n\n // round the value for storage in 8bit channel\n v = ceil(v * 255.0) / 255.0;\n\n return vec4(gamma / (-v * 7.0 + 8.0), v); \n}\n\nvec4 encodeRGBE(vec3 source) {\n float maxVal = max(source.x, max(source.y, source.z));\n if (maxVal < 1e-32) {\n return vec4(0, 0, 0, 0);\n } else {\n float e = ceil(log2(maxVal));\n return vec4(source / pow(2.0, e), (e + 128.0) / 255.0);\n }\n}\n",Wi={alphaTestPS:"\nuniform float alpha_ref;\n\nvoid alphaTest(float a) {\n if (a < alpha_ref) discard;\n}\n",ambientConstantPS:"\nvoid addAmbient() {\n dDiffuseLight += light_globalAmbient;\n}\n",ambientEnvPS:"\n#ifndef ENV_ATLAS\n#define ENV_ATLAS\nuniform sampler2D texture_envAtlas;\n#endif\n\nvoid addAmbient() {\n vec3 dir = normalize(cubeMapRotate(dNormalW) * vec3(-1.0, 1.0, 1.0));\n vec2 uv = mapUv(toSphericalUv(dir), vec4(128.0, 256.0 + 128.0, 64.0, 32.0) / atlasSize);\n\n vec4 raw = texture2D(texture_envAtlas, uv);\n vec3 linear = $DECODE(raw);\n dDiffuseLight += processEnvironment(linear);\n}\n",ambientSHPS:"\nuniform vec3 ambientSH[9];\n\nvoid addAmbient() {\n vec3 n = cubeMapRotate(dNormalW);\n\n vec3 color =\n ambientSH[0] +\n ambientSH[1] * n.x +\n ambientSH[2] * n.y +\n ambientSH[3] * n.z +\n ambientSH[4] * n.x * n.z +\n ambientSH[5] * n.z * n.y +\n ambientSH[6] * n.y * n.x +\n ambientSH[7] * (3.0 * n.z * n.z - 1.0) +\n ambientSH[8] * (n.x * n.x - n.y * n.y);\n\n dDiffuseLight += processEnvironment(max(color, vec3(0.0)));\n}\n",aoPS:"\n\nvoid getAO() {\n dAo = 1.0;\n\n #ifdef MAPTEXTURE\n dAo *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n dAo *= saturate(vVertexColor.$VC);\n #endif\n}\n",aoDiffuseOccPS:"\nvoid occludeDiffuse() {\n dDiffuseLight *= dAo;\n}\n",aoSpecOccPS:"\nuniform float material_occludeSpecularIntensity;\n\nvoid occludeSpecular() {\n // approximated specular occlusion from AO\n float specPow = exp2(dGlossiness * 11.0);\n // http://research.tri-ace.com/Data/cedec2011_RealtimePBR_Implementation_e.pptx\n float specOcc = saturate(pow(dot(dNormalW, dViewDirW) + dAo, 0.01*specPow) - 1.0 + dAo);\n specOcc = mix(1.0, specOcc, material_occludeSpecularIntensity);\n\n dSpecularLight *= specOcc;\n dReflection *= specOcc;\n}\n",aoSpecOccConstPS:"\nvoid occludeSpecular() {\n // approximated specular occlusion from AO\n float specPow = exp2(dGlossiness * 11.0);\n // http://research.tri-ace.com/Data/cedec2011_RealtimePBR_Implementation_e.pptx\n float specOcc = saturate(pow(dot(dNormalW, dViewDirW) + dAo, 0.01*specPow) - 1.0 + dAo);\n\n dSpecularLight *= specOcc;\n dReflection *= specOcc;\n}\n",aoSpecOccConstSimplePS:"\nvoid occludeSpecular() {\n dSpecularLight *= dAo;\n dReflection *= dAo;\n}\n",aoSpecOccSimplePS:"\nuniform float material_occludeSpecularIntensity;\n\nvoid occludeSpecular() {\n float specOcc = mix(1.0, dAo, material_occludeSpecularIntensity);\n dSpecularLight *= specOcc;\n dReflection *= specOcc;\n}\n",basePS:"\nuniform vec3 view_position;\n\nuniform vec3 light_globalAmbient;\n\nfloat square(float x) {\n return x*x;\n}\n\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n\nvec3 saturate(vec3 x) {\n return clamp(x, vec3(0.0), vec3(1.0));\n}\n",baseVS:"\nattribute vec3 vertex_position;\nattribute vec3 vertex_normal;\nattribute vec4 vertex_tangent;\nattribute vec2 vertex_texCoord0;\nattribute vec2 vertex_texCoord1;\nattribute vec4 vertex_color;\n\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\nuniform mat3 matrix_normal;\n\nvec3 dPositionW;\nmat4 dModelMatrix;\nmat3 dNormalMatrix;\n",baseNineSlicedPS:"\n#define NINESLICED\n\nvarying vec2 vMask;\nvarying vec2 vTiledUv;\n\nuniform mediump vec4 innerOffset;\nuniform mediump vec2 outerScale;\nuniform mediump vec4 atlasRect;\n\nvec2 nineSlicedUv;\n",baseNineSlicedVS:"\n#define NINESLICED\n\nvarying vec2 vMask;\nvarying vec2 vTiledUv;\n\nuniform mediump vec4 innerOffset;\nuniform mediump vec2 outerScale;\nuniform mediump vec4 atlasRect;\n",baseNineSlicedTiledPS:"\n#define NINESLICED\n#define NINESLICETILED\n\nvarying vec2 vMask;\nvarying vec2 vTiledUv;\n\nuniform mediump vec4 innerOffset;\nuniform mediump vec2 outerScale;\nuniform mediump vec4 atlasRect;\n\nvec2 nineSlicedUv;\n",biasConstPS:"\n#define SHADOWBIAS\n\nfloat getShadowBias(float resolution, float maxBias) {\n return maxBias;\n}\n",blurVSMPS:"\nvarying vec2 vUv0;\n\nuniform sampler2D source;\nuniform vec2 pixelOffset;\n\n#ifdef GAUSS\nuniform float weight[SAMPLES];\n#endif\n\n#ifdef PACKED\nfloat decodeFloatRG(vec2 rg) {\n return rg.y*(1.0/255.0) + rg.x;\n}\n\nvec2 encodeFloatRG( float v ) {\n vec2 enc = vec2(1.0, 255.0) * v;\n enc = fract(enc);\n enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n return enc;\n}\n#endif\n\nvoid main(void) {\n vec3 moments = vec3(0.0);\n vec2 uv = vUv0 - pixelOffset * (float(SAMPLES) * 0.5);\n for (int i=0; i<SAMPLES; i++) {\n vec4 c = texture2D(source, uv + pixelOffset * float(i));\n\n #ifdef PACKED\n c.xy = vec2(decodeFloatRG(c.xy), decodeFloatRG(c.zw));\n #endif\n\n #ifdef GAUSS\n moments += c.xyz * weight[i];\n #else\n moments += c.xyz;\n #endif\n }\n\n #ifndef GAUSS\n moments /= float(SAMPLES);\n #endif\n\n #ifdef PACKED\n gl_FragColor = vec4(encodeFloatRG(moments.x), encodeFloatRG(moments.y));\n #else\n gl_FragColor = vec4(moments.x, moments.y, moments.z, 1.0);\n #endif\n}\n",clearCoatPS:"\n#ifdef MAPFLOAT\nuniform float material_clearCoat;\n#endif\n\nvoid getClearCoat() {\n ccSpecularity = 1.0;\n\n #ifdef MAPFLOAT\n ccSpecularity *= material_clearCoat;\n #endif\n\n #ifdef MAPTEXTURE\n ccSpecularity *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n ccSpecularity *= saturate(vVertexColor.$VC);\n #endif\n}\n",clearCoatGlossPS:"\n#ifdef MAPFLOAT\nuniform float material_clearCoatGlossiness;\n#endif\n\nvoid getClearCoatGlossiness() {\n ccGlossiness = 1.0;\n\n #ifdef MAPFLOAT\n ccGlossiness *= material_clearCoatGlossiness;\n #endif\n\n #ifdef MAPTEXTURE\n ccGlossiness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n ccGlossiness *= saturate(vVertexColor.$VC);\n #endif\n\n ccGlossiness += 0.0000001;\n}\n",clearCoatNormalPS:"\n#ifdef MAPTEXTURE\nuniform float material_clearCoatBumpiness;\n#endif\n\nvoid getClearCoatNormal() {\n#ifdef MAPTEXTURE\n vec3 normalMap = unpackNormal(texture2DBias($SAMPLER, $UV, textureBias));\n normalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, material_clearCoatBumpiness);\n ccNormalW = normalize(dTBN * normalMap);\n#else\n ccNormalW = dVertexNormalW;\n#endif\n}\n",clusteredLightCookiesPS:"\nvec3 _getCookieClustered(sampler2D tex, vec2 uv, float intensity, bool isRgb, vec4 cookieChannel) {\n vec4 pixel = mix(vec4(1.0), texture2D(tex, uv), intensity);\n return isRgb == true ? pixel.rgb : vec3(dot(pixel, cookieChannel));\n}\n\n// getCookie2D for clustered lighting including channel selector\nvec3 getCookie2DClustered(sampler2D tex, mat4 transform, vec3 worldPosition, float intensity, bool isRgb, vec4 cookieChannel) {\n vec4 projPos = transform * vec4(worldPosition, 1.0);\n return _getCookieClustered(tex, projPos.xy / projPos.w, intensity, isRgb, cookieChannel);\n}\n\n// getCookie for clustered omni light with the cookie texture being stored in the cookie atlas\nvec3 getCookieCubeClustered(sampler2D tex, vec3 dir, float intensity, bool isRgb, vec4 cookieChannel, float shadowTextureResolution, float shadowEdgePixels, vec3 omniAtlasViewport) {\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);\n return _getCookieClustered(tex, uv, intensity, isRgb, cookieChannel);\n}\n",clusteredLightShadowsPS:"\n// Clustered Omni Sampling using atlas\n\n#ifdef GL2\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\n float getShadowOmniClusteredPCF1(sampler2DShadow shadowMap, vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 dir) {\n\n float shadowTextureResolution = shadowParams.x;\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);\n\n float shadowZ = length(dir) * shadowParams.w + shadowParams.z;\n return texture(shadowMap, vec3(uv, shadowZ));\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\n float getShadowOmniClusteredPCF3(sampler2DShadow shadowMap, vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 dir) {\n\n float shadowTextureResolution = shadowParams.x;\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);\n\n float shadowZ = length(dir) * shadowParams.w + shadowParams.z;\n dShadowCoord = vec3(uv, shadowZ);\n return getShadowPCF3x3(shadowMap, shadowParams.xyz);\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\n float getShadowOmniClusteredPCF5(sampler2DShadow shadowMap, vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 dir) {\n\n float shadowTextureResolution = shadowParams.x;\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);\n\n float shadowZ = length(dir) * shadowParams.w + shadowParams.z;\n dShadowCoord = vec3(uv, shadowZ);\n return getShadowPCF5x5(shadowMap, shadowParams.xyz);\n }\n\n #endif\n\n#else\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\n float getShadowOmniClusteredPCF1(sampler2D shadowMap, vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 dir) {\n\n float shadowTextureResolution = shadowParams.x;\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);\n\n // no filter shadow sampling\n float depth = unpackFloat(texture2D(shadowMap, uv));\n float shadowZ = length(dir) * shadowParams.w + shadowParams.z;\n return depth > shadowZ ? 1.0 : 0.0;\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\n float getShadowOmniClusteredPCF3(sampler2D shadowMap, vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 dir) {\n\n float shadowTextureResolution = shadowParams.x;\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);\n\n // pcf3\n float shadowZ = length(dir) * shadowParams.w + shadowParams.z;\n dShadowCoord = vec3(uv, shadowZ);\n return getShadowPCF3x3(shadowMap, shadowParams.xyz);\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\n // we don't have PCF5 implementation for webgl1, use PCF3\n float getShadowOmniClusteredPCF5(sampler2D shadowMap, vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 dir) {\n\n float shadowTextureResolution = shadowParams.x;\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);\n\n // pcf3\n float shadowZ = length(dir) * shadowParams.w + shadowParams.z;\n dShadowCoord = vec3(uv, shadowZ);\n return getShadowPCF3x3(shadowMap, shadowParams.xyz);\n }\n\n #endif\n\n#endif\n\n\n// Clustered Spot Sampling using atlas\n\n#ifdef GL2\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\n float getShadowSpotClusteredPCF1(sampler2DShadow shadowMap, vec4 shadowParams) {\n return texture(shadowMap, dShadowCoord);\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\n float getShadowSpotClusteredPCF3(sampler2DShadow shadowMap, vec4 shadowParams) {\n return getShadowSpotPCF3x3(shadowMap, shadowParams);\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\n float getShadowSpotClusteredPCF5(sampler2DShadow shadowMap, vec4 shadowParams) {\n return getShadowPCF5x5(shadowMap, shadowParams.xyz);\n }\n #endif\n\n#else\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\n float getShadowSpotClusteredPCF1(sampler2D shadowMap, vec4 shadowParams) {\n\n float depth = unpackFloat(texture2D(shadowMap, dShadowCoord.xy));\n\n return depth > dShadowCoord.z ? 1.0 : 0.0;\n\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\n float getShadowSpotClusteredPCF3(sampler2D shadowMap, vec4 shadowParams) {\n return getShadowSpotPCF3x3(shadowMap, shadowParams);\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\n // we don't have PCF5 implementation for webgl1, use PCF3\n float getShadowSpotClusteredPCF5(sampler2D shadowMap, vec4 shadowParams) {\n return getShadowSpotPCF3x3(shadowMap, shadowParams);\n }\n\n #endif\n\n#endif\n",clusteredLightUtilsPS:"\n// Converts unnormalized direction vector to a cubemap face index [0..5] and uv coordinates within the face in [0..1] range.\n// Additionally offset to a tile in atlas within 3x3 subdivision is provided\nvec2 getCubemapFaceCoordinates(const vec3 dir, out float faceIndex, out vec2 tileOffset)\n{\n vec3 vAbs = abs(dir);\n float ma;\n vec2 uv;\n if (vAbs.z >= vAbs.x && vAbs.z >= vAbs.y) { // front / back\n\n faceIndex = dir.z < 0.0 ? 5.0 : 4.0;\n ma = 0.5 / vAbs.z;\n uv = vec2(dir.z < 0.0 ? -dir.x : dir.x, -dir.y);\n\n tileOffset.x = 2.0;\n tileOffset.y = dir.z < 0.0 ? 1.0 : 0.0;\n\n } else if(vAbs.y >= vAbs.x) { // top index 2, bottom index 3\n\n faceIndex = dir.y < 0.0 ? 3.0 : 2.0;\n ma = 0.5 / vAbs.y;\n uv = vec2(dir.x, dir.y < 0.0 ? -dir.z : dir.z);\n\n tileOffset.x = 1.0;\n tileOffset.y = dir.y < 0.0 ? 1.0 : 0.0;\n\n } else { // left / right\n\n faceIndex = dir.x < 0.0 ? 1.0 : 0.0;\n ma = 0.5 / vAbs.x;\n uv = vec2(dir.x < 0.0 ? dir.z : -dir.z, -dir.y);\n\n tileOffset.x = 0.0;\n tileOffset.y = dir.x < 0.0 ? 1.0 : 0.0;\n\n }\n return uv * ma + 0.5;\n}\n\n// converts unnormalized direction vector to a texture coordinate for a cubemap face stored within texture atlas described by the viewport\nvec2 getCubemapAtlasCoordinates(const vec3 omniAtlasViewport, float shadowEdgePixels, float shadowTextureResolution, const vec3 dir) {\n\n float faceIndex;\n vec2 tileOffset;\n vec2 uv = getCubemapFaceCoordinates(dir, faceIndex, tileOffset);\n\n // move uv coordinates inwards inside to compensate for larger fov when rendering shadow into atlas\n float atlasFaceSize = omniAtlasViewport.z;\n float tileSize = shadowTextureResolution * atlasFaceSize;\n float offset = shadowEdgePixels / tileSize;\n uv = uv * vec2(1.0 - offset * 2.0) + vec2(offset * 1.0);\n\n // scale uv coordinates to cube face area within the viewport\n uv *= atlasFaceSize;\n\n // offset into face of the atlas (3x3 grid)\n uv += tileOffset * atlasFaceSize;\n\n // offset into the atlas viewport\n uv += omniAtlasViewport.xy;\n\n return uv;\n}\n",clusteredLightPS:"\nuniform sampler2D clusterWorldTexture;\nuniform sampler2D lightsTexture8;\nuniform highp sampler2D lightsTextureFloat;\n\n// complex ifdef expression are not supported, handle it here\n// defined(CLUSTER_COOKIES) || defined(CLUSTER_SHADOWS)\n#if defined(CLUSTER_COOKIES)\n #define CLUSTER_COOKIES_OR_SHADOWS\n#endif\n#if defined(CLUSTER_SHADOWS)\n #define CLUSTER_COOKIES_OR_SHADOWS\n#endif\n\n#ifdef CLUSTER_SHADOWS\n #ifdef GL2\n // TODO: when VSM shadow is supported, it needs to use sampler2D in webgl2\n uniform sampler2DShadow shadowAtlasTexture;\n #else\n uniform sampler2D shadowAtlasTexture;\n #endif\n#endif\n\n#ifdef CLUSTER_COOKIES\n uniform sampler2D cookieAtlasTexture;\n#endif\n\nuniform float clusterPixelsPerCell;\nuniform vec3 clusterCellsCountByBoundsSize;\nuniform vec4 lightsTextureInvSize;\nuniform vec3 clusterTextureSize;\nuniform vec3 clusterBoundsMin;\nuniform vec3 clusterBoundsDelta;\nuniform vec3 clusterCellsDot;\nuniform vec3 clusterCellsMax;\nuniform vec2 clusterCompressionLimit0;\nuniform vec2 shadowAtlasParams;\n\n// structure storing light properties of a clustered light\nstruct ClusterLightData {\n\n // v coordinate to look up the light textures\n float lightV;\n\n // type of the light (spot or omni)\n float type;\n\n // area light shape\n float shape;\n\n // area light sizes / orientation\n vec3 halfWidth;\n vec3 halfHeight;\n\n // light follow mode\n float falloffMode;\n\n // 0.0 if the light doesn't cast shadows\n float shadowIntensity;\n\n // shadow bias values\n float shadowBias;\n float shadowNormalBias;\n\n // world space position\n vec3 position;\n\n // world space direction (spot light only)\n vec3 direction;\n\n // range of the light\n float range;\n\n // spot light inner and outer angle cosine\n float innerConeAngleCos;\n float outerConeAngleCos;\n\n // color\n vec3 color;\n\n // atlas viewport for omni light shadow and cookie (.xy is offset to the viewport slot, .z is size of the face in the atlas)\n vec3 omniAtlasViewport;\n\n // 1.0 if the light has a cookie texture\n float cookie;\n\n // 1.0 if cookie texture is rgb, otherwise it is using a single channel selectable by cookieChannelMask\n float cookieRgb;\n\n // intensity of the cookie\n float cookieIntensity;\n\n // channel mask - one of the channels has 1, the others are 0\n vec4 cookieChannelMask;\n\n // light mask\n float mask;\n};\n\n// Note: on some devices (tested on Pixel 3A XL), this matrix when stored inside the light struct has lower precision compared to\n// when stored outside, so we store it outside to avoid spot shadow flickering. This might need to be done to other / all members\n// of the structure if further similar issues are observed.\n\n// shadow (spot light only) / cookie projection matrix\nmat4 lightProjectionMatrix;\n\n// macros for light properties\n#define isClusteredLightCastShadow(light) ( light.shadowIntensity > 0.0 )\n#define isClusteredLightCookie(light) (light.cookie > 0.5 )\n#define isClusteredLightCookieRgb(light) (light.cookieRgb > 0.5 )\n#define isClusteredLightSpot(light) ( light.type > 0.5 )\n#define isClusteredLightFalloffLinear(light) ( light.falloffMode < 0.5 )\n\n// macros to test light shape\n// Note: Following functions need to be called serially in listed order as they do not test both '>' and '<'\n#define isClusteredLightArea(light) ( light.shape > 0.1 )\n#define isClusteredLightRect(light) ( light.shape < 0.3 )\n#define isClusteredLightDisk(light) ( light.shape < 0.6 )\n\n// macro to test light mask (mesh accepts dynamic vs lightmapped lights)\n#ifdef CLUSTER_MESH_DYNAMIC_LIGHTS\n // accept lights marked as dynamic or both dynamic and lightmapped\n #define acceptLightMask(light) ( light.mask < 0.75)\n#else\n // accept lights marked as lightmapped or both dynamic and lightmapped\n #define acceptLightMask(light) ( light.mask > 0.25)\n#endif\n\nvec4 decodeClusterLowRange4Vec4(vec4 d0, vec4 d1, vec4 d2, vec4 d3) {\n return vec4(\n bytes2floatRange4(d0, -2.0, 2.0),\n bytes2floatRange4(d1, -2.0, 2.0),\n bytes2floatRange4(d2, -2.0, 2.0),\n bytes2floatRange4(d3, -2.0, 2.0)\n );\n}\n\n// use LOD sampling if supported to sample data textures as it has better chance of getting skipped inside dynamic branches\n#ifdef SUPPORTS_TEXLOD\n #define textureData(texture, uv) texture2DLodEXT(texture, uv, 0.0)\n#else\n #define textureData(texture, uv) texture2D(texture, uv)\n#endif\n\nvec4 sampleLightsTexture8(const ClusterLightData clusterLightData, float index) {\n return textureData(lightsTexture8, vec2(index * lightsTextureInvSize.z, clusterLightData.lightV));\n}\n\nvec4 sampleLightTextureF(const ClusterLightData clusterLightData, float index) {\n return textureData(lightsTextureFloat, vec2(index * lightsTextureInvSize.x, clusterLightData.lightV));\n}\n\nvoid decodeClusterLightCore(inout ClusterLightData clusterLightData, float lightIndex) {\n\n // read omni light properties\n clusterLightData.lightV = (lightIndex + 0.5) * lightsTextureInvSize.w;\n\n // shared data from 8bit texture\n vec4 lightInfo = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_FLAGS);\n clusterLightData.type = lightInfo.x;\n clusterLightData.shape = lightInfo.y;\n clusterLightData.falloffMode = lightInfo.z;\n clusterLightData.shadowIntensity = lightInfo.w;\n\n // color\n vec4 colorA = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COLOR_A);\n vec4 colorB = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COLOR_B);\n clusterLightData.color = vec3(bytes2float2(colorA.xy), bytes2float2(colorA.zw), bytes2float2(colorB.xy)) * clusterCompressionLimit0.y;\n\n // cookie\n clusterLightData.cookie = colorB.z;\n\n // light mask\n clusterLightData.mask = colorB.w;\n\n #ifdef CLUSTER_TEXTURE_FLOAT\n\n vec4 lightPosRange = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_POSITION_RANGE);\n clusterLightData.position = lightPosRange.xyz;\n clusterLightData.range = lightPosRange.w;\n\n // spot light direction\n vec4 lightDir_Unused = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_SPOT_DIRECTION);\n clusterLightData.direction = lightDir_Unused.xyz;\n\n #else // 8bit\n\n vec4 encPosX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_POSITION_X);\n vec4 encPosY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_POSITION_Y);\n vec4 encPosZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_POSITION_Z);\n clusterLightData.position = vec3(bytes2float4(encPosX), bytes2float4(encPosY), bytes2float4(encPosZ)) * clusterBoundsDelta + clusterBoundsMin;\n\n vec4 encRange = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_RANGE);\n clusterLightData.range = bytes2float4(encRange) * clusterCompressionLimit0.x;\n\n // spot light direction\n vec4 encDirX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_DIRECTION_X);\n vec4 encDirY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_DIRECTION_Y);\n vec4 encDirZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_DIRECTION_Z);\n clusterLightData.direction = vec3(bytes2float4(encDirX), bytes2float4(encDirY), bytes2float4(encDirZ)) * 2.0 - 1.0;\n\n #endif\n}\n\nvoid decodeClusterLightSpot(inout ClusterLightData clusterLightData) {\n\n // spot light cos angles\n vec4 coneAngle = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_ANGLES);\n clusterLightData.innerConeAngleCos = bytes2float2(coneAngle.xy) * 2.0 - 1.0;\n clusterLightData.outerConeAngleCos = bytes2float2(coneAngle.zw) * 2.0 - 1.0;\n}\n\nvoid decodeClusterLightOmniAtlasViewport(inout ClusterLightData clusterLightData) {\n #ifdef CLUSTER_TEXTURE_FLOAT\n clusterLightData.omniAtlasViewport = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_0).xyz;\n #else\n vec4 viewportA = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_ATLAS_VIEWPORT_A);\n vec4 viewportB = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_ATLAS_VIEWPORT_B);\n clusterLightData.omniAtlasViewport = vec3(bytes2float2(viewportA.xy), bytes2float2(viewportA.zw), bytes2float2(viewportB.xy));\n #endif\n}\n\nvoid decodeClusterLightAreaData(inout ClusterLightData clusterLightData) {\n #ifdef CLUSTER_TEXTURE_FLOAT\n clusterLightData.halfWidth = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_AREA_DATA_WIDTH).xyz;\n clusterLightData.halfHeight = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_AREA_DATA_HEIGHT).xyz;\n #else\n vec4 areaWidthX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_WIDTH_X);\n vec4 areaWidthY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_WIDTH_Y);\n vec4 areaWidthZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_WIDTH_Z);\n clusterLightData.halfWidth = vec3(mantissaExponent2Float(areaWidthX), mantissaExponent2Float(areaWidthY), mantissaExponent2Float(areaWidthZ));\n\n vec4 areaHeightX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_HEIGHT_X);\n vec4 areaHeightY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_HEIGHT_Y);\n vec4 areaHeightZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_HEIGHT_Z);\n clusterLightData.halfHeight = vec3(mantissaExponent2Float(areaHeightX), mantissaExponent2Float(areaHeightY), mantissaExponent2Float(areaHeightZ));\n #endif\n}\n\nvoid decodeClusterLightProjectionMatrixData(inout ClusterLightData clusterLightData) {\n \n // shadow matrix\n #ifdef CLUSTER_TEXTURE_FLOAT\n vec4 m0 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_0);\n vec4 m1 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_1);\n vec4 m2 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_2);\n vec4 m3 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_3);\n #else\n vec4 m00 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_00);\n vec4 m01 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_01);\n vec4 m02 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_02);\n vec4 m03 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_03);\n vec4 m0 = decodeClusterLowRange4Vec4(m00, m01, m02, m03);\n\n vec4 m10 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_10);\n vec4 m11 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_11);\n vec4 m12 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_12);\n vec4 m13 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_13);\n vec4 m1 = decodeClusterLowRange4Vec4(m10, m11, m12, m13);\n\n vec4 m20 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_20);\n vec4 m21 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_21);\n vec4 m22 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_22);\n vec4 m23 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_23);\n vec4 m2 = decodeClusterLowRange4Vec4(m20, m21, m22, m23);\n\n vec4 m30 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_30);\n vec4 m31 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_31);\n vec4 m32 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_32);\n vec4 m33 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_33);\n vec4 m3 = vec4(mantissaExponent2Float(m30), mantissaExponent2Float(m31), mantissaExponent2Float(m32), mantissaExponent2Float(m33));\n #endif\n \n lightProjectionMatrix = mat4(m0, m1, m2, m3);\n}\n\nvoid decodeClusterLightShadowData(inout ClusterLightData clusterLightData) {\n \n // shadow biases\n vec4 biases = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SHADOW_BIAS);\n clusterLightData.shadowBias = bytes2floatRange2(biases.xy, -1.0, 20.0),\n clusterLightData.shadowNormalBias = bytes2float2(biases.zw);\n}\n\nvoid decodeClusterLightCookieData(inout ClusterLightData clusterLightData) {\n\n vec4 cookieA = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COOKIE_A);\n clusterLightData.cookieIntensity = cookieA.x;\n clusterLightData.cookieRgb = cookieA.y;\n\n clusterLightData.cookieChannelMask = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COOKIE_B);\n}\n\nvoid evaluateLight(ClusterLightData light) {\n\n dAtten3 = vec3(1.0);\n\n // evaluate omni part of the light\n getLightDirPoint(light.position);\n\n #ifdef CLUSTER_AREALIGHTS\n\n // distance attenuation\n if (isClusteredLightArea(light)) { // area light\n\n // area lights\n decodeClusterLightAreaData(light);\n\n // handle light shape\n if (isClusteredLightRect(light)) {\n calcRectLightValues(light.position, light.halfWidth, light.halfHeight);\n } else if (isClusteredLightDisk(light)) {\n calcDiskLightValues(light.position, light.halfWidth, light.halfHeight);\n } else { // sphere\n calcSphereLightValues(light.position, light.halfWidth, light.halfHeight);\n }\n\n dAtten = getFalloffWindow(light.range);\n\n } else\n\n #endif\n\n { // punctual light\n\n if (isClusteredLightFalloffLinear(light))\n dAtten = getFalloffLinear(light.range);\n else\n dAtten = getFalloffInvSquared(light.range);\n }\n\n if (dAtten > 0.00001) {\n\n #ifdef CLUSTER_AREALIGHTS\n\n if (isClusteredLightArea(light)) { // area light\n\n // handle light shape\n if (isClusteredLightRect(light)) {\n dAttenD = getRectLightDiffuse() * 16.0;\n } else if (isClusteredLightDisk(light)) {\n dAttenD = getDiskLightDiffuse() * 16.0;\n } else { // sphere\n dAttenD = getSphereLightDiffuse() * 16.0;\n }\n\n } else\n\n #endif\n\n {\n dAtten *= getLightDiffuse();\n }\n\n // spot light falloff\n if (isClusteredLightSpot(light)) {\n decodeClusterLightSpot(light);\n dAtten *= getSpotEffect(light.direction, light.innerConeAngleCos, light.outerConeAngleCos);\n }\n\n #if defined(CLUSTER_COOKIES_OR_SHADOWS)\n\n if (dAtten > 0.00001) {\n\n // shadow / cookie\n if (isClusteredLightCastShadow(light) || isClusteredLightCookie(light)) {\n\n // shared shadow / cookie data depends on light type\n if (isClusteredLightSpot(light)) {\n decodeClusterLightProjectionMatrixData(light);\n } else {\n decodeClusterLightOmniAtlasViewport(light);\n }\n\n float shadowTextureResolution = shadowAtlasParams.x;\n float shadowEdgePixels = shadowAtlasParams.y;\n\n #ifdef CLUSTER_COOKIES\n\n // cookie\n if (isClusteredLightCookie(light)) {\n decodeClusterLightCookieData(light);\n\n if (isClusteredLightSpot(light)) {\n dAtten3 = getCookie2DClustered(cookieAtlasTexture, lightProjectionMatrix, vPositionW, light.cookieIntensity, isClusteredLightCookieRgb(light), light.cookieChannelMask);\n } else {\n dAtten3 = getCookieCubeClustered(cookieAtlasTexture, dLightDirW, light.cookieIntensity, isClusteredLightCookieRgb(light), light.cookieChannelMask, shadowTextureResolution, shadowEdgePixels, light.omniAtlasViewport);\n }\n }\n\n #endif\n\n #ifdef CLUSTER_SHADOWS\n\n // shadow\n if (isClusteredLightCastShadow(light)) {\n decodeClusterLightShadowData(light);\n\n vec4 shadowParams = vec4(shadowTextureResolution, light.shadowNormalBias, light.shadowBias, 1.0 / light.range);\n\n if (isClusteredLightSpot(light)) {\n\n // spot shadow\n getShadowCoordPerspZbufferNormalOffset(lightProjectionMatrix, shadowParams);\n \n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n float shadow = getShadowSpotClusteredPCF1(shadowAtlasTexture, shadowParams);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF3)\n float shadow = getShadowSpotClusteredPCF3(shadowAtlasTexture, shadowParams);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF5)\n float shadow = getShadowSpotClusteredPCF5(shadowAtlasTexture, shadowParams);\n #endif\n dAtten *= mix(1.0, shadow, light.shadowIntensity);\n\n } else {\n\n // omni shadow\n normalOffsetPointShadow(shadowParams); // normalBias adjusted for distance\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n float shadow = getShadowOmniClusteredPCF1(shadowAtlasTexture, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dLightDirW);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF3)\n float shadow = getShadowOmniClusteredPCF3(shadowAtlasTexture, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dLightDirW);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF5)\n float shadow = getShadowOmniClusteredPCF5(shadowAtlasTexture, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dLightDirW);\n #endif\n dAtten *= mix(1.0, shadow, light.shadowIntensity);\n }\n }\n\n #endif\n }\n }\n\n #endif\n\n // diffuse / specular / clearcoat\n #ifdef CLUSTER_AREALIGHTS\n\n if (isClusteredLightArea(light)) { // area light\n\n // area light diffuse\n {\n vec3 areaDiffuse = (dAttenD * dAtten) * light.color * dAtten3;\n\n #if defined(LIT_SPECULAR)\n #if defined(LIT_CONSERVE_ENERGY)\n areaDiffuse = mix(areaDiffuse, vec3(0), dLTCSpecFres);\n #endif\n #endif\n\n // area light diffuse - it does not mix diffuse lighting into specular attenuation\n dDiffuseLight += areaDiffuse;\n }\n\n // specular and clear coat are material settings and get included by a define based on the material\n #ifdef LIT_SPECULAR\n\n // area light specular\n float areaLightSpecular;\n\n if (isClusteredLightRect(light)) {\n areaLightSpecular = getRectLightSpecular();\n } else if (isClusteredLightDisk(light)) {\n areaLightSpecular = getDiskLightSpecular();\n } else { // sphere\n areaLightSpecular = getSphereLightSpecular();\n }\n\n dSpecularLight += dLTCSpecFres * areaLightSpecular * dAtten * light.color * dAtten3;\n\n #ifdef LIT_CLEARCOAT\n\n // area light specular clear coat\n float areaLightSpecularCC;\n\n if (isClusteredLightRect(light)) {\n areaLightSpecularCC = getRectLightSpecularCC();\n } else if (isClusteredLightDisk(light)) {\n areaLightSpecularCC = getDiskLightSpecularCC();\n } else { // sphere\n areaLightSpecularCC = getSphereLightSpecularCC();\n }\n\n ccSpecularLight += ccLTCSpecFres * areaLightSpecularCC * dAtten * light.color * dAtten3;\n\n #endif\n\n #endif\n\n } else\n\n #endif\n\n { // punctual light\n\n // punctual light diffuse\n {\n vec3 punctualDiffuse = dAtten * light.color * dAtten3;\n\n #if defined(CLUSTER_AREALIGHTS)\n #if defined(LIT_SPECULAR)\n #if defined(LIT_CONSERVE_ENERGY)\n punctualDiffuse = mix(punctualDiffuse, vec3(0), dSpecularity);\n #endif\n #endif\n #endif\n\n dDiffuseLight += punctualDiffuse;\n }\n \n // specular and clear coat are material settings and get included by a define based on the material\n #ifdef LIT_SPECULAR\n\n vec3 halfDir = normalize(-dLightDirNormW + dViewDirW);\n \n // specular\n #ifdef LIT_SPECULAR_FRESNEL\n dSpecularLight += getLightSpecular(halfDir) * dAtten * light.color * dAtten3 * getFresnel(dot(dViewDirW, halfDir), dSpecularity);\n #else\n dSpecularLight += getLightSpecular(halfDir) * dAtten * light.color * dAtten3 * dSpecularity;\n #endif\n\n #ifdef LIT_CLEARCOAT\n #ifdef LIT_SPECULAR_FRESNEL\n ccSpecularLight += getLightSpecularCC(halfDir) * dAtten * light.color * dAtten3 * getFresnelCC(dot(dViewDirW, halfDir));\n #else\n ccSpecularLight += getLightSpecularCC(halfDir) * dAtten * light.color * dAtten3;\n #endif\n #endif\n\n #ifdef LIT_SHEEN\n sSpecularLight += getLightSpecularSheen(halfDir) * dAtten * light.color * dAtten3;\n #endif\n\n #endif\n }\n }\n}\n\nvoid evaluateClusterLight(float lightIndex) {\n\n // decode core light data from textures\n ClusterLightData clusterLightData;\n decodeClusterLightCore(clusterLightData, lightIndex);\n\n // evaluate light if it uses accepted light mask\n if (acceptLightMask(clusterLightData))\n evaluateLight(clusterLightData);\n}\n\nvoid addClusteredLights() {\n // world space position to 3d integer cell cordinates in the cluster structure\n vec3 cellCoords = floor((vPositionW - clusterBoundsMin) * clusterCellsCountByBoundsSize);\n\n // no lighting when cell coordinate is out of range\n if (!(any(lessThan(cellCoords, vec3(0.0))) || any(greaterThanEqual(cellCoords, clusterCellsMax)))) {\n\n // cell index (mapping from 3d cell coordinates to linear memory)\n float cellIndex = dot(clusterCellsDot, cellCoords);\n\n // convert cell index to uv coordinates\n float clusterV = floor(cellIndex * clusterTextureSize.y);\n float clusterU = cellIndex - (clusterV * clusterTextureSize.x);\n clusterV = (clusterV + 0.5) * clusterTextureSize.z;\n\n // loop over maximum possible number of supported light cells\n const float maxLightCells = 256.0 / 4.0; // 8 bit index, each stores 4 lights\n for (float lightCellIndex = 0.5; lightCellIndex < maxLightCells; lightCellIndex++) {\n\n vec4 lightIndices = textureData(clusterWorldTexture, vec2(clusterTextureSize.y * (clusterU + lightCellIndex), clusterV));\n vec4 indices = lightIndices * 255.0;\n\n // evaluate up to 4 lights. This is written using a loop instead of manually unrolling to keep shader compile time smaller\n for (int i = 0; i < 4; i++) {\n \n if (indices.x <= 0.0)\n return;\n\n evaluateClusterLight(indices.x); \n indices = indices.yzwx;\n }\n\n // end of the cell array\n if (lightCellIndex > clusterPixelsPerCell) {\n break;\n }\n }\n }\n}\n",combinePS:"\nvec3 combineColor() {\n vec3 ret = vec3(0);\n#ifdef LIT_OLD_AMBIENT\n ret += (dDiffuseLight - light_globalAmbient) * dAlbedo + material_ambient * light_globalAmbient;\n#else\n ret += dAlbedo * dDiffuseLight;\n#endif\n#ifdef LIT_SPECULAR\n ret += dSpecularLight;\n#endif\n#ifdef LIT_REFLECTIONS\n ret += dReflection.rgb * dReflection.a;\n#endif\n\n#ifdef LIT_SHEEN\n float sheenScaling = 1.0 - max(max(sSpecularity.r, sSpecularity.g), sSpecularity.b) * 0.157;\n ret = ret * sheenScaling + (sSpecularLight + sReflection.rgb) * sSpecularity;\n#endif\n#ifdef LIT_CLEARCOAT\n float clearCoatScaling = 1.0 - ccFresnel * ccSpecularity;\n ret = ret * clearCoatScaling + (ccSpecularLight + ccReflection.rgb) * ccSpecularity;\n#endif\n\n return ret;\n}\n",cookiePS:"\n// light cookie functionality for non-clustered lights\nvec4 getCookie2D(sampler2D tex, mat4 transform, float intensity) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n return mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);\n}\n\nvec4 getCookie2DClip(sampler2D tex, mat4 transform, float intensity) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n if (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0);\n return mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);\n}\n\nvec4 getCookie2DXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n projPos.xy += cookieOffset;\n vec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);\n return mix(vec4(1.0), texture2D(tex, uv), intensity);\n}\n\nvec4 getCookie2DClipXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n projPos.xy += cookieOffset;\n if (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0);\n vec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);\n return mix(vec4(1.0), texture2D(tex, uv), intensity);\n}\n\nvec4 getCookieCube(samplerCube tex, mat4 transform, float intensity) {\n return mix(vec4(1.0), textureCube(tex, dLightDirNormW * mat3(transform)), intensity);\n}\n",cubeMapProjectBoxPS:"\nuniform vec3 envBoxMin, envBoxMax;\n\nvec3 cubeMapProject(vec3 nrdir) {\n nrdir = cubeMapRotate(nrdir);\n\n vec3 rbmax = (envBoxMax - vPositionW) / nrdir;\n vec3 rbmin = (envBoxMin - vPositionW) / nrdir;\n\n vec3 rbminmax;\n rbminmax.x = nrdir.x>0.0? rbmax.x : rbmin.x;\n rbminmax.y = nrdir.y>0.0? rbmax.y : rbmin.y;\n rbminmax.z = nrdir.z>0.0? rbmax.z : rbmin.z;\n\n float fa = min(min(rbminmax.x, rbminmax.y), rbminmax.z);\n\n vec3 posonbox = vPositionW + nrdir * fa;\n vec3 envBoxPos = (envBoxMin + envBoxMax) * 0.5;\n return normalize(posonbox - envBoxPos);\n}\n",cubeMapProjectNonePS:"\nvec3 cubeMapProject(vec3 dir) {\n return cubeMapRotate(dir);\n}\n",cubeMapRotatePS:"\n#ifdef CUBEMAP_ROTATION\nuniform mat3 cubeMapRotationMatrix;\n#endif\n\nvec3 cubeMapRotate(vec3 refDir) {\n#ifdef CUBEMAP_ROTATION\n return refDir * cubeMapRotationMatrix;\n#else\n return refDir;\n#endif\n}\n",detailModesPS:"\nvec3 detailMode_mul(vec3 c1, vec3 c2) {\n return c1 * c2;\n}\n\nvec3 detailMode_add(vec3 c1, vec3 c2) {\n return c1 + c2;\n}\n\n// https://en.wikipedia.org/wiki/Blend_modes#Screen\nvec3 detailMode_screen(vec3 c1, vec3 c2) {\n return 1.0 - (1.0 - c1)*(1.0 - c2);\n}\n\n// https://en.wikipedia.org/wiki/Blend_modes#Overlay\nvec3 detailMode_overlay(vec3 c1, vec3 c2) {\n return mix(1.0 - 2.0*(1.0 - c1)*(1.0 - c2), 2.0*c1*c2, step(c1, vec3(0.5)));\n}\n\nvec3 detailMode_min(vec3 c1, vec3 c2) {\n return min(c1, c2);\n}\n\nvec3 detailMode_max(vec3 c1, vec3 c2) {\n return max(c1, c2);\n}\n",diffusePS:"\n#ifdef MAPCOLOR\nuniform vec3 material_diffuse;\n#endif\n\nvoid getAlbedo() {\n dAlbedo = vec3(1.0);\n\n#ifdef MAPCOLOR\n dAlbedo *= material_diffuse.rgb;\n#endif\n\n#ifdef MAPTEXTURE\n vec3 albedoBase = $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n dAlbedo *= addAlbedoDetail(albedoBase);\n#endif\n\n#ifdef MAPVERTEX\n dAlbedo *= gammaCorrectInput(saturate(vVertexColor.$VC));\n#endif\n}\n",diffuseDetailMapPS:"\nvec3 addAlbedoDetail(vec3 albedo) {\n#ifdef MAPTEXTURE\n vec3 albedoDetail = $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n return detailMode_$DETAILMODE(albedo, albedoDetail);\n#else\n return albedo;\n#endif\n}\n",decodePS:Vi,emissivePS:"\n#ifdef MAPCOLOR\nuniform vec3 material_emissive;\n#endif\n\n#ifdef MAPFLOAT\nuniform float material_emissiveIntensity;\n#endif\n\nvoid getEmission() {\n dEmission = vec3(1.0);\n\n #ifdef MAPFLOAT\n dEmission *= material_emissiveIntensity;\n #endif\n\n #ifdef MAPCOLOR\n dEmission *= material_emissive;\n #endif\n\n #ifdef MAPTEXTURE\n dEmission *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n #endif\n\n #ifdef MAPVERTEX\n dEmission *= gammaCorrectInput(saturate(vVertexColor.$VC));\n #endif\n}\n",encodePS:Gi,endPS:"\n gl_FragColor.rgb = combineColor();\n\n gl_FragColor.rgb += dEmission;\n gl_FragColor.rgb = addFog(gl_FragColor.rgb);\n\n #ifndef HDR\n gl_FragColor.rgb = toneMap(gl_FragColor.rgb);\n gl_FragColor.rgb = gammaCorrectOutput(gl_FragColor.rgb);\n #endif\n",endVS:"\n",envAtlasPS:"\n// the envAtlas is fixed at 512 pixels. every equirect is generated with 1 pixel boundary.\nconst float atlasSize = 512.0;\nconst float seamSize = 1.0 / atlasSize;\n\n// map a normalized equirect UV to the given rectangle (taking 1 pixel seam into account).\nvec2 mapUv(vec2 uv, vec4 rect) {\n return vec2(mix(rect.x + seamSize, rect.x + rect.z - seamSize, uv.x),\n mix(rect.y + seamSize, rect.y + rect.w - seamSize, uv.y));\n}\n\n// map a normalized equirect UV and roughness level to the correct atlas rect.\nvec2 mapRoughnessUv(vec2 uv, float level) {\n float t = 1.0 / exp2(level);\n return mapUv(uv, vec4(0, 1.0 - t, t, t * 0.5));\n}\n\n// map shiny level UV\nvec2 mapShinyUv(vec2 uv, float level) {\n float t = 1.0 / exp2(level);\n return mapUv(uv, vec4(1.0 - t, 1.0 - t, t, t * 0.5));\n}\n",envConstPS:"\nvec3 processEnvironment(vec3 color) {\n return color;\n}\n",envMultiplyPS:"\nuniform float skyboxIntensity;\n\nvec3 processEnvironment(vec3 color) {\n return color * skyboxIntensity;\n}\n",extensionPS:"\n",extensionVS:"\n",falloffInvSquaredPS:"\nfloat getFalloffWindow(float lightRadius) {\n float sqrDist = dot(dLightDirW, dLightDirW);\n float invRadius = 1.0 / lightRadius;\n return square( saturate( 1.0 - square( sqrDist * square(invRadius) ) ) );\n}\n\nfloat getFalloffInvSquared(float lightRadius) {\n float sqrDist = dot(dLightDirW, dLightDirW);\n float falloff = 1.0 / (sqrDist + 1.0);\n float invRadius = 1.0 / lightRadius;\n\n falloff *= 16.0;\n falloff *= square( saturate( 1.0 - square( sqrDist * square(invRadius) ) ) );\n\n return falloff;\n}\n",falloffLinearPS:"\nfloat getFalloffLinear(float lightRadius) {\n float d = length(dLightDirW);\n return max(((lightRadius - d) / lightRadius), 0.0);\n}\n",fixCubemapSeamsNonePS:"\nvec3 fixSeams(vec3 vec, float mipmapIndex) {\n return vec;\n}\n\nvec3 fixSeams(vec3 vec) {\n return vec;\n}\n\nvec3 fixSeamsStatic(vec3 vec, float invRecMipSize) {\n return vec;\n}\n\nvec3 calcSeam(vec3 vec) {\n return vec3(0);\n}\n\nvec3 applySeam(vec3 vec, vec3 seam, float scale) {\n return vec;\n}\n",fixCubemapSeamsStretchPS:"\nvec3 fixSeams(vec3 vec, float mipmapIndex) {\n vec3 avec = abs(vec);\n float scale = 1.0 - exp2(mipmapIndex) / 128.0;\n float M = max(max(avec.x, avec.y), avec.z);\n if (avec.x != M) vec.x *= scale;\n if (avec.y != M) vec.y *= scale;\n if (avec.z != M) vec.z *= scale;\n return vec;\n}\n\nvec3 fixSeams(vec3 vec) {\n vec3 avec = abs(vec);\n float scale = 1.0 - 1.0 / 128.0;\n float M = max(max(avec.x, avec.y), avec.z);\n if (avec.x != M) vec.x *= scale;\n if (avec.y != M) vec.y *= scale;\n if (avec.z != M) vec.z *= scale;\n return vec;\n}\n\nvec3 fixSeamsStatic(vec3 vec, float invRecMipSize) {\n vec3 avec = abs(vec);\n float scale = invRecMipSize;\n float M = max(max(avec.x, avec.y), avec.z);\n if (avec.x != M) vec.x *= scale;\n if (avec.y != M) vec.y *= scale;\n if (avec.z != M) vec.z *= scale;\n return vec;\n}\n\nvec3 calcSeam(vec3 vec) {\n vec3 avec = abs(vec);\n float M = max(avec.x, max(avec.y, avec.z));\n return vec3(avec.x != M ? 1.0 : 0.0,\n avec.y != M ? 1.0 : 0.0,\n avec.z != M ? 1.0 : 0.0);\n}\n\nvec3 applySeam(vec3 vec, vec3 seam, float scale) {\n return vec * (seam * -scale + vec3(1.0));\n}\n",floatUnpackingPS:"\n// float unpacking functionality, complimentary to float-packing.js\nfloat bytes2float2(vec2 data) {\n return dot(data, vec2(1.0, 1.0 / 255.0));\n}\n\nfloat bytes2float3(vec3 data) {\n return dot(data, vec3(1.0, 1.0 / 255.0, 1.0 / 65025.0));\n}\n\nfloat bytes2float4(vec4 data) {\n return dot(data, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n}\n\nfloat bytes2floatRange2(vec2 data, float min, float max) {\n return mix(min, max, bytes2float2(data));\n}\n\nfloat bytes2floatRange3(vec3 data, float min, float max) {\n return mix(min, max, bytes2float3(data));\n}\n\nfloat bytes2floatRange4(vec4 data, float min, float max) {\n return mix(min, max, bytes2float4(data));\n}\n\nfloat mantissaExponent2Float(vec4 pack)\n{\n float value = bytes2floatRange3(pack.xyz, -1.0, 1.0);\n float exponent = floor(pack.w * 255.0 - 127.0);\n return value * exp2(exponent);\n}\n",fogExpPS:"\nuniform vec3 fog_color;\nuniform float fog_density;\nfloat dBlendModeFogFactor = 1.0;\n\nvec3 addFog(vec3 color) {\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n float fogFactor = exp(-depth * fog_density);\n fogFactor = clamp(fogFactor, 0.0, 1.0);\n return mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogExp2PS:"\nuniform vec3 fog_color;\nuniform float fog_density;\nfloat dBlendModeFogFactor = 1.0;\n\nvec3 addFog(vec3 color) {\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n float fogFactor = exp(-depth * depth * fog_density * fog_density);\n fogFactor = clamp(fogFactor, 0.0, 1.0);\n return mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogLinearPS:"\nuniform vec3 fog_color;\nuniform float fog_start;\nuniform float fog_end;\nfloat dBlendModeFogFactor = 1.0;\n\nvec3 addFog(vec3 color) {\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n float fogFactor = (fog_end - depth) / (fog_end - fog_start);\n fogFactor = clamp(fogFactor, 0.0, 1.0);\n return mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogNonePS:"\nfloat dBlendModeFogFactor = 1.0;\n\nvec3 addFog(vec3 color) {\n return color;\n}\n",fresnelSchlickPS:"\n// Schlick's approximation\nvec3 getFresnel(float cosTheta, vec3 f0) {\n float fresnel = pow(1.0 - max(cosTheta, 0.0), 5.0);\n float glossSq = dGlossiness * dGlossiness;\n vec3 ret = f0 + (max(vec3(glossSq), f0) - f0) * fresnel;\n #ifdef LIT_IRIDESCENCE\n return mix(ret, dIridescenceFresnel, vec3(dIridescence));\n #else\n return ret;\n #endif \n}\n\nfloat getFresnelCC(float cosTheta) {\n float fresnel = pow(1.0 - max(cosTheta, 0.0), 5.0);\n return 0.04 + (1.0 - 0.04) * fresnel;\n}\n",fullscreenQuadPS:"\nvarying vec2 vUv0;\n\nuniform sampler2D source;\n\nvoid main(void) {\n gl_FragColor = texture2D(source, vUv0);\n}\n",fullscreenQuadVS:"\nattribute vec2 vertex_position;\n\nvarying vec2 vUv0;\n\nvoid main(void)\n{\n gl_Position = vec4(vertex_position, 0.5, 1.0);\n vUv0 = vertex_position.xy*0.5+0.5;\n}\n",gamma1_0PS:"\nfloat gammaCorrectInput(float color) {\n return color;\n}\n\nvec3 gammaCorrectInput(vec3 color) {\n return color;\n}\n\nvec4 gammaCorrectInput(vec4 color) {\n return color;\n}\n\nvec3 gammaCorrectOutput(vec3 color) {\n return color;\n}\n",gamma2_2PS:"\nfloat gammaCorrectInput(float color) {\n return decodeGamma(color);\n}\n\nvec3 gammaCorrectInput(vec3 color) {\n return decodeGamma(color);\n}\n\nvec4 gammaCorrectInput(vec4 color) {\n return vec4(decodeGamma(color.xyz), color.w);\n}\n\nvec3 gammaCorrectOutput(vec3 color) {\n#ifdef HDR\n return color;\n#else\n return pow(color + 0.0000001, vec3(1.0 / 2.2));\n#endif\n}\n",gles2PS:"\n#define texture2DBias texture2D\n",gles3PS:"\n#define varying in\nout highp vec4 pc_fragColor;\n#define gl_FragColor pc_fragColor\n#define texture2D texture\n#define texture2DBias texture\n#define textureCube texture\n#define texture2DProj textureProj\n#define texture2DLodEXT textureLod\n#define texture2DProjLodEXT textureProjLod\n#define textureCubeLodEXT textureLod\n#define texture2DGradEXT textureGrad\n#define texture2DProjGradEXT textureProjGrad\n#define textureCubeGradEXT textureGrad\n#define GL2\n#define SUPPORTS_TEXLOD\n",gles3VS:"\n#define attribute in\n#define varying out\n#define texture2D texture\n#define GL2\n#define VERTEXSHADER\n",glossPS:"\n#ifdef MAPFLOAT\nuniform float material_shininess;\n#endif\n\nvoid getGlossiness() {\n dGlossiness = 1.0;\n\n #ifdef MAPFLOAT\n dGlossiness *= material_shininess;\n #endif\n\n #ifdef MAPTEXTURE\n dGlossiness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n dGlossiness *= saturate(vVertexColor.$VC);\n #endif\n\n dGlossiness += 0.0000001;\n}\n",iridescenceDiffractionPS:"\nuniform float material_iridescenceRefractionIndex;\n\n#ifndef PI\n#define PI 3.14159265\n#endif\n\nfloat iridescence_iorToFresnel(float transmittedIor, float incidentIor) {\n return pow((transmittedIor - incidentIor) / (transmittedIor + incidentIor), 2.0);\n}\n\nvec3 iridescence_iorToFresnel(vec3 transmittedIor, float incidentIor) {\n return pow((transmittedIor - vec3(incidentIor)) / (transmittedIor + vec3(incidentIor)), vec3(2.0));\n}\n\nvec3 iridescence_fresnelToIor(vec3 f0) {\n vec3 sqrtF0 = sqrt(f0);\n return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0);\n}\n\nvec3 iridescence_sensitivity(float opd, vec3 shift) {\n float phase = 2.0 * PI * opd * 1.0e-9;\n const vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13);\n const vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06);\n const vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09);\n\n vec3 xyz = val * sqrt(2.0 * PI * var) * cos(pos * phase + shift) * exp(-pow(phase, 2.0) * var);\n xyz.x += 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift[0]) * exp(-4.5282e+09 * pow(phase, 2.0));\n xyz /= vec3(1.0685e-07);\n\n const mat3 XYZ_TO_REC709 = mat3(\n 3.2404542, -0.9692660, 0.0556434,\n -1.5371385, 1.8760108, -0.2040259,\n -0.4985314, 0.0415560, 1.0572252\n );\n\n return XYZ_TO_REC709 * xyz;\n}\n\nfloat iridescence_fresnel(float cosTheta, float f0) {\n float x = clamp(1.0 - cosTheta, 0.0, 1.0);\n float x2 = x * x;\n float x5 = x * x2 * x2;\n return f0 + (1.0 - f0) * x5;\n} \n\nvec3 iridescence_fresnel(float cosTheta, vec3 f0) {\n float x = clamp(1.0 - cosTheta, 0.0, 1.0);\n float x2 = x * x;\n float x5 = x * x2 * x2; \n return f0 + (vec3(1.0) - f0) * x5;\n}\n\nvec3 calcIridescence(float outsideIor, float cosTheta, vec3 base_f0) {\n\n float iridescenceIor = mix(outsideIor, material_iridescenceRefractionIndex, smoothstep(0.0, 0.03, dIridescenceThickness));\n float sinTheta2Sq = pow(outsideIor / iridescenceIor, 2.0) * (1.0 - pow(cosTheta, 2.0));\n float cosTheta2Sq = 1.0 - sinTheta2Sq;\n\n if (cosTheta2Sq < 0.0) {\n return vec3(1.0);\n }\n\n float cosTheta2 = sqrt(cosTheta2Sq);\n\n float r0 = iridescence_iorToFresnel(iridescenceIor, outsideIor);\n float r12 = iridescence_fresnel(cosTheta, r0);\n float r21 = r12;\n float t121 = 1.0 - r12;\n\n float phi12 = iridescenceIor < outsideIor ? PI : 0.0;\n float phi21 = PI - phi12;\n\n vec3 baseIor = iridescence_fresnelToIor(base_f0 + vec3(0.0001));\n vec3 r1 = iridescence_iorToFresnel(baseIor, iridescenceIor);\n vec3 r23 = iridescence_fresnel(cosTheta2, r1);\n\n vec3 phi23 = vec3(0.0);\n if (baseIor[0] < iridescenceIor) phi23[0] = PI;\n if (baseIor[1] < iridescenceIor) phi23[1] = PI;\n if (baseIor[2] < iridescenceIor) phi23[2] = PI;\n float opd = 2.0 * iridescenceIor * dIridescenceThickness * cosTheta2;\n vec3 phi = vec3(phi21) + phi23; \n\n vec3 r123Sq = clamp(r12 * r23, 1e-5, 0.9999);\n vec3 r123 = sqrt(r123Sq);\n vec3 rs = pow(t121, 2.0) * r23 / (1.0 - r123Sq);\n\n vec3 c0 = r12 + rs;\n vec3 i = c0;\n\n vec3 cm = rs - t121;\n for (int m = 1; m <= 2; m++) {\n cm *= r123;\n vec3 sm = 2.0 * iridescence_sensitivity(float(m) * opd, float(m) * phi);\n i += cm * sm;\n }\n return max(i, vec3(0.0));\n}\n\nvoid getIridescence(float cosTheta) {\n dIridescenceFresnel = calcIridescence(1.0, cosTheta, dSpecularity);\n}\n",iridescencePS:"\n#ifdef MAPFLOAT\nuniform float material_iridescence;\n#endif\n\nvoid getIridescence() {\n float iridescence = 1.0;\n\n #ifdef MAPFLOAT\n iridescence *= material_iridescence;\n #endif\n\n #ifdef MAPTEXTURE\n iridescence *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n dIridescence = iridescence; \n}\n",iridescenceThicknessPS:"\nuniform float material_iridescenceThicknessMax;\n\n#ifdef MAPTEXTURE\nuniform float material_iridescenceThicknessMin;\n#endif\n\nvoid getIridescenceThickness() {\n\n #ifdef MAPTEXTURE\n float blend = texture2DBias($SAMPLER, $UV, textureBias).$CH;\n float iridescenceThickness = mix(material_iridescenceThicknessMin, material_iridescenceThicknessMax, blend);\n #else\n float iridescenceThickness = material_iridescenceThicknessMax;\n #endif\n\n dIridescenceThickness = iridescenceThickness; \n}\n",instancingVS:"\nattribute vec4 instance_line1;\nattribute vec4 instance_line2;\nattribute vec4 instance_line3;\nattribute vec4 instance_line4;\n",lightDiffuseLambertPS:"\nfloat getLightDiffuse() {\n return max(dot(dNormalW, -dLightDirNormW), 0.0);\n}\n",lightDirPointPS:"\nvoid getLightDirPoint(vec3 lightPosW) {\n dLightDirW = vPositionW - lightPosW;\n dLightDirNormW = normalize(dLightDirW);\n dLightPosW = lightPosW;\n}\n",lightmapAddPS:"\nvoid addLightMap() {\n dDiffuseLight += dLightmap;\n}\n",lightmapDirAddPS:"\nvoid addLightMap() {\n if (dot(dLightmapDir, dLightmapDir) < 0.0001) {\n dDiffuseLight += dLightmap;\n } else {\n dLightDirNormW = dLightmapDir;\n\n float vlight = saturate(dot(dLightDirNormW, -dVertexNormalW));\n float flight = saturate(dot(dLightDirNormW, -dNormalW));\n float nlight = (flight / max(vlight, 0.01)) * 0.5;\n\n dDiffuseLight += dLightmap * nlight * 2.0;\n\n vec3 halfDirW = normalize(-dLightmapDir + dViewDirW);\n vec3 specularLight = dLightmap * getLightSpecular(halfDirW);\n\n #ifdef LIT_SPECULAR_FRESNEL\n specularLight *= getFresnel(dot(dViewDirW, halfDirW), dSpecularity);\n #endif\n\n dSpecularLight += specularLight;\n }\n}\n",lightmapDirPS:"\nuniform sampler2D texture_lightMap;\nuniform sampler2D texture_dirLightMap;\n\nvoid getLightMap() {\n dLightmap = $DECODE(texture2DBias(texture_lightMap, $UV, textureBias)).$CH;\n\n vec3 dir = texture2DBias(texture_dirLightMap, $UV, textureBias).xyz * 2.0 - 1.0;\n float dirDot = dot(dir, dir);\n dLightmapDir = (dirDot > 0.001) ? dir / sqrt(dirDot) : vec3(0.0);\n}\n",lightmapSinglePS:"\nvoid getLightMap() {\n dLightmap = vec3(1.0);\n\n #ifdef MAPTEXTURE\n dLightmap *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n #endif\n\n #ifdef MAPVERTEX\n dLightmap *= saturate(vVertexColor.$VC);\n #endif\n}\n",lightSpecularAnisoGGXPS:"\n// Anisotropic GGX\nfloat calcLightSpecular(float tGlossiness, vec3 tNormalW, vec3 h) {\n float PI = 3.141592653589793;\n float roughness = max((1.0 - tGlossiness) * (1.0 - tGlossiness), 0.001);\n float anisotropy = material_anisotropy * roughness;\n \n float at = max((roughness + anisotropy), roughness / 4.0);\n float ab = max((roughness - anisotropy), roughness / 4.0);\n\n float NoH = dot(tNormalW, h);\n float ToH = dot(dTBN[0], h);\n float BoH = dot(dTBN[1], h);\n\n float a2 = at * ab;\n vec3 v = vec3(ab * ToH, at * BoH, a2 * NoH);\n float v2 = dot(v, v);\n float w2 = a2 / v2;\n float D = a2 * w2 * w2 * (1.0 / PI);\n\n float ToV = dot(dTBN[0], dViewDirW);\n float BoV = dot(dTBN[1], dViewDirW);\n float ToL = dot(dTBN[0], -dLightDirNormW);\n float BoL = dot(dTBN[1], -dLightDirNormW);\n float NoV = dot(tNormalW, dViewDirW);\n float NoL = dot(tNormalW, -dLightDirNormW);\n\n float lambdaV = NoL * length(vec3(at * ToV, ab * BoV, NoV));\n float lambdaL = NoV * length(vec3(at * ToL, ab * BoL, NoL));\n float G = 0.5 / (lambdaV + lambdaL);\n\n return D * G;\n}\n\nfloat getLightSpecular(vec3 h) {\n return calcLightSpecular(dGlossiness, dNormalW, h);\n}\n\n#ifdef LIT_CLEARCOAT\nfloat getLightSpecularCC(vec3 h) {\n return calcLightSpecular(ccGlossiness, ccNormalW, h);\n}\n#endif\n",lightSpecularBlinnPS:"\n// Energy-conserving (hopefully) Blinn-Phong\nfloat calcLightSpecular(float tGlossiness, vec3 tNormalW, vec3 h) {\n float nh = max( dot( h, tNormalW ), 0.0 );\n\n float specPow = exp2(tGlossiness * 11.0); // glossiness is linear, power is not; 0 - 2048\n\n // Hack: On Mac OS X, calling pow with zero for the exponent generates hideous artifacts so bias up a little\n specPow = max(specPow, 0.0001);\n\n return pow(nh, specPow) * (specPow + 2.0) / 8.0;\n}\n\nfloat getLightSpecular(vec3 h) {\n return calcLightSpecular(dGlossiness, dNormalW, h);\n}\n\n#ifdef LIT_CLEARCOAT\nfloat getLightSpecularCC(vec3 h) {\n return calcLightSpecular(ccGlossiness, ccNormalW, h);\n}\n#endif\n",lightSpecularPhongPS:"\nfloat calcLightSpecular(float tGlossiness, vec3 tReflDirW, vec3 h) {\n float specPow = tGlossiness;\n\n // Hack: On Mac OS X, calling pow with zero for the exponent generates hideous artifacts so bias up a little\n return pow(max(dot(tReflDirW, -dLightDirNormW), 0.0), specPow + 0.0001);\n}\n\nfloat getLightSpecular(vec3 h) {\n return calcLightSpecular(dGlossiness, dReflDirW, h);\n}\n\n#ifdef LIT_CLEARCOAT\nfloat getLightSpecularCC(vec3 h) {\n return calcLightSpecular(ccGlossiness, ccReflDirW,h );\n}\n#endif\n",lightSheenPS:"\n\nfloat sheenD(vec3 normal, vec3 h, float roughness) {\n float invR = 1.0 / (roughness * roughness);\n float cos2h = max(dot(normal, h), 0.0);\n cos2h *= cos2h;\n float sin2h = max(1.0 - cos2h, 0.0078125);\n return (2.0 + invR) * pow(sin2h, invR * 0.5) / (2.0 * PI);\n}\n\nfloat sheenV(vec3 normal, vec3 view, vec3 light) {\n float NoV = max(dot(normal, view), 0.000001);\n float NoL = max(dot(normal, light), 0.000001);\n return 1.0 / (4.0 * (NoL + NoV - NoL * NoV));\n}\n\nfloat getLightSpecularSheen(vec3 h) {\n float D = sheenD(dNormalW, h, sGlossiness);\n float V = sheenV(dNormalW, dViewDirW, -dLightDirNormW);\n return D * V;\n}\n",ltc:'\n// Real-Time Polygonal-Light Shading with Linearly Transformed Cosines\n// by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt\n// code: https://github.com/selfshadow/ltc_code/\n\nmat3 transposeMat3( const in mat3 m ) {\n mat3 tmp;\n tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n return tmp;\n}\n\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n const float LUT_SIZE = 64.0;\n const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n const float LUT_BIAS = 0.5 / LUT_SIZE;\n float dotNV = saturate( dot( N, V ) );\n // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )\n vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n uv = uv * LUT_SCALE + LUT_BIAS;\n return uv;\n}\n\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n // Real-Time Area Lighting: a Journey from Research to Production (p.102)\n // An approximation of the form factor of a horizon-clipped rectangle.\n float l = length( f );\n return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\n\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n float x = dot( v1, v2 );\n float y = abs( x );\n // rational polynomial approximation to theta / sin( theta ) / 2PI\n float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n float b = 3.4175940 + ( 4.1616724 + y ) * y;\n float v = a / b;\n float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n return cross( v1, v2 ) * theta_sintheta;\n}\n\nstruct Coords {\n vec3 coord0;\n vec3 coord1;\n vec3 coord2;\n vec3 coord3;\n};\n\nfloat LTC_EvaluateRect( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in Coords rectCoords) {\n // bail if point is on back side of plane of light\n // assumes ccw winding order of light vertices\n vec3 v1 = rectCoords.coord1 - rectCoords.coord0;\n vec3 v2 = rectCoords.coord3 - rectCoords.coord0;\n \n vec3 lightNormal = cross( v1, v2 );\n // if( dot( lightNormal, P - rectCoords.coord0 ) < 0.0 ) return 0.0;\n float factor = sign(-dot( lightNormal, P - rectCoords.coord0 ));\n\n // construct orthonormal basis around N\n vec3 T1, T2;\n T1 = normalize( V - N * dot( V, N ) );\n T2 = factor * cross( N, T1 ); // negated from paper; possibly due to a different handedness of world coordinate system\n // compute transform\n mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n // transform rect\n vec3 coords[ 4 ];\n coords[ 0 ] = mat * ( rectCoords.coord0 - P );\n coords[ 1 ] = mat * ( rectCoords.coord1 - P );\n coords[ 2 ] = mat * ( rectCoords.coord2 - P );\n coords[ 3 ] = mat * ( rectCoords.coord3 - P );\n // project rect onto sphere\n coords[ 0 ] = normalize( coords[ 0 ] );\n coords[ 1 ] = normalize( coords[ 1 ] );\n coords[ 2 ] = normalize( coords[ 2 ] );\n coords[ 3 ] = normalize( coords[ 3 ] );\n // calculate vector form factor\n vec3 vectorFormFactor = vec3( 0.0 );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n // adjust for horizon clipping\n float result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\n return result;\n}\n\nCoords dLTCCoords;\nCoords getLTCLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){\n Coords coords;\n coords.coord0 = lightPos + halfWidth - halfHeight;\n coords.coord1 = lightPos - halfWidth - halfHeight;\n coords.coord2 = lightPos - halfWidth + halfHeight;\n coords.coord3 = lightPos + halfWidth + halfHeight;\n return coords;\n}\n\nfloat dSphereRadius;\nCoords getSphereLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){\n // used for simple sphere light falloff\n // also, the code only handles a spherical light, it cannot be non-uniformly scaled in world space, and so we enforce it here\n dSphereRadius = max(length(halfWidth), length(halfHeight));\n\n // Billboard the 2d light quad to reflection vector, as it\'s used for specular. This allows us to use disk math for the sphere.\n vec3 f = reflect(normalize(lightPos - view_position), vNormalW);\n vec3 w = normalize(cross(f, halfHeight));\n vec3 h = normalize(cross(f, w));\n\n return getLTCLightCoords(lightPos, w * dSphereRadius, h * dSphereRadius);\n}\n\n// used for LTC LUT texture lookup\nvec2 dLTCUV;\n#ifdef LIT_CLEARCOAT\nvec2 ccLTCUV;\n#endif\nvec2 getLTCLightUV(float tGlossiness, vec3 tNormalW)\n{\n float roughness = max((1.0 - tGlossiness) * (1.0 - tGlossiness), 0.001);\n return LTC_Uv( tNormalW, dViewDirW, roughness );\n}\n\n//used for energy conservation and to modulate specular\nvec3 dLTCSpecFres;\n#ifdef LIT_CLEARCOAT\nvec3 ccLTCSpecFres;\n#endif\nvec3 getLTCLightSpecFres(vec2 uv, vec3 tSpecularity)\n{\n vec4 t2 = texture2D( areaLightsLutTex2, uv );\n\n #ifdef AREA_R8_G8_B8_A8_LUTS\n t2 *= vec4(0.693103,1,1,1);\n t2 += vec4(0.306897,0,0,0);\n #endif\n\n return tSpecularity * t2.x + ( vec3( 1.0 ) - tSpecularity) * t2.y;\n}\n\nvoid calcLTCLightValues()\n{\n dLTCUV = getLTCLightUV(dGlossiness, dNormalW);\n dLTCSpecFres = getLTCLightSpecFres(dLTCUV, dSpecularity); \n\n#ifdef LIT_CLEARCOAT\n ccLTCUV = getLTCLightUV(ccGlossiness, ccNormalW);\n ccLTCSpecFres = getLTCLightSpecFres(ccLTCUV, vec3(ccSpecularity));\n#endif\n}\n\nvoid calcRectLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n dLTCCoords = getLTCLightCoords(lightPos, halfWidth, halfHeight);\n}\nvoid calcDiskLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n calcRectLightValues(lightPos, halfWidth, halfHeight);\n}\nvoid calcSphereLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n dLTCCoords = getSphereLightCoords(lightPos, halfWidth, halfHeight);\n}\n\n// An extended version of the implementation from\n// "How to solve a cubic equation, revisited"\n// http://momentsingraphics.de/?p=105\nvec3 SolveCubic(vec4 Coefficient)\n{\n float pi = 3.14159;\n // Normalize the polynomial\n Coefficient.xyz /= Coefficient.w;\n // Divide middle coefficients by three\n Coefficient.yz /= 3.0;\n\n float A = Coefficient.w;\n float B = Coefficient.z;\n float C = Coefficient.y;\n float D = Coefficient.x;\n\n // Compute the Hessian and the discriminant\n vec3 Delta = vec3(\n -Coefficient.z * Coefficient.z + Coefficient.y,\n -Coefficient.y * Coefficient.z + Coefficient.x,\n dot(vec2(Coefficient.z, -Coefficient.y), Coefficient.xy)\n );\n\n float Discriminant = dot(vec2(4.0 * Delta.x, -Delta.y), Delta.zy);\n\n vec3 RootsA, RootsD;\n\n vec2 xlc, xsc;\n\n // Algorithm A\n {\n float A_a = 1.0;\n float C_a = Delta.x;\n float D_a = -2.0 * B * Delta.x + Delta.y;\n\n // Take the cubic root of a normalized complex number\n float Theta = atan(sqrt(Discriminant), -D_a) / 3.0;\n\n float x_1a = 2.0 * sqrt(-C_a) * cos(Theta);\n float x_3a = 2.0 * sqrt(-C_a) * cos(Theta + (2.0 / 3.0) * pi);\n\n float xl;\n if ((x_1a + x_3a) > 2.0 * B)\n xl = x_1a;\n else\n xl = x_3a;\n\n xlc = vec2(xl - B, A);\n }\n\n // Algorithm D\n {\n float A_d = D;\n float C_d = Delta.z;\n float D_d = -D * Delta.y + 2.0 * C * Delta.z;\n\n // Take the cubic root of a normalized complex number\n float Theta = atan(D * sqrt(Discriminant), -D_d) / 3.0;\n\n float x_1d = 2.0 * sqrt(-C_d) * cos(Theta);\n float x_3d = 2.0 * sqrt(-C_d) * cos(Theta + (2.0 / 3.0) * pi);\n\n float xs;\n if (x_1d + x_3d < 2.0 * C)\n xs = x_1d;\n else\n xs = x_3d;\n\n xsc = vec2(-D, xs + C);\n }\n\n float E = xlc.y * xsc.y;\n float F = -xlc.x * xsc.y - xlc.y * xsc.x;\n float G = xlc.x * xsc.x;\n\n vec2 xmc = vec2(C * F - B * G, -B * F + C * E);\n\n vec3 Root = vec3(xsc.x / xsc.y, xmc.x / xmc.y, xlc.x / xlc.y);\n\n if (Root.x < Root.y && Root.x < Root.z)\n Root.xyz = Root.yxz;\n else if (Root.z < Root.x && Root.z < Root.y)\n Root.xyz = Root.xzy;\n\n return Root;\n}\n\nfloat LTC_EvaluateDisk(vec3 N, vec3 V, vec3 P, mat3 Minv, Coords points)\n{\n // construct orthonormal basis around N\n vec3 T1, T2;\n T1 = normalize(V - N * dot(V, N));\n T2 = cross(N, T1);\n\n // rotate area light in (T1, T2, N) basis\n //mat3 R = transpose(mat3(T1, T2, N));\n mat3 R = transposeMat3( mat3( T1, T2, N ) );\n // polygon (allocate 5 vertices for clipping)\n vec3 L_[ 3 ];\n L_[ 0 ] = R * ( points.coord0 - P );\n L_[ 1 ] = R * ( points.coord1 - P );\n L_[ 2 ] = R * ( points.coord2 - P );\n\n vec3 Lo_i = vec3(0);\n\n // init ellipse\n vec3 C = 0.5 * (L_[0] + L_[2]);\n vec3 V1 = 0.5 * (L_[1] - L_[2]);\n vec3 V2 = 0.5 * (L_[1] - L_[0]);\n\n C = Minv * C;\n V1 = Minv * V1;\n V2 = Minv * V2;\n\n //if(dot(cross(V1, V2), C) > 0.0)\n // return 0.0;\n\n // compute eigenvectors of ellipse\n float a, b;\n float d11 = dot(V1, V1);\n float d22 = dot(V2, V2);\n float d12 = dot(V1, V2);\n if (abs(d12) / sqrt(d11 * d22) > 0.0001)\n {\n float tr = d11 + d22;\n float det = -d12 * d12 + d11 * d22;\n\n // use sqrt matrix to solve for eigenvalues\n det = sqrt(det);\n float u = 0.5 * sqrt(tr - 2.0 * det);\n float v = 0.5 * sqrt(tr + 2.0 * det);\n float e_max = (u + v) * (u + v);\n float e_min = (u - v) * (u - v);\n\n vec3 V1_, V2_;\n\n if (d11 > d22)\n {\n V1_ = d12 * V1 + (e_max - d11) * V2;\n V2_ = d12 * V1 + (e_min - d11) * V2;\n }\n else\n {\n V1_ = d12*V2 + (e_max - d22)*V1;\n V2_ = d12*V2 + (e_min - d22)*V1;\n }\n\n a = 1.0 / e_max;\n b = 1.0 / e_min;\n V1 = normalize(V1_);\n V2 = normalize(V2_);\n }\n else\n {\n a = 1.0 / dot(V1, V1);\n b = 1.0 / dot(V2, V2);\n V1 *= sqrt(a);\n V2 *= sqrt(b);\n }\n\n vec3 V3 = cross(V1, V2);\n if (dot(C, V3) < 0.0)\n V3 *= -1.0;\n\n float L = dot(V3, C);\n float x0 = dot(V1, C) / L;\n float y0 = dot(V2, C) / L;\n\n float E1 = inversesqrt(a);\n float E2 = inversesqrt(b);\n\n a *= L * L;\n b *= L * L;\n\n float c0 = a * b;\n float c1 = a * b * (1.0 + x0 * x0 + y0 * y0) - a - b;\n float c2 = 1.0 - a * (1.0 + x0 * x0) - b * (1.0 + y0 * y0);\n float c3 = 1.0;\n\n vec3 roots = SolveCubic(vec4(c0, c1, c2, c3));\n float e1 = roots.x;\n float e2 = roots.y;\n float e3 = roots.z;\n\n vec3 avgDir = vec3(a * x0 / (a - e2), b * y0 / (b - e2), 1.0);\n\n mat3 rotate = mat3(V1, V2, V3);\n\n avgDir = rotate * avgDir;\n avgDir = normalize(avgDir);\n\n float L1 = sqrt(-e2 / e3);\n float L2 = sqrt(-e2 / e1);\n\n float formFactor = L1 * L2 * inversesqrt((1.0 + L1 * L1) * (1.0 + L2 * L2));\n \n const float LUT_SIZE = 64.0;\n const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n const float LUT_BIAS = 0.5 / LUT_SIZE;\n\n // use tabulated horizon-clipped sphere\n vec2 uv = vec2(avgDir.z * 0.5 + 0.5, formFactor);\n uv = uv*LUT_SCALE + LUT_BIAS;\n\n float scale = texture2D( areaLightsLutTex2, uv ).w;\n\n return formFactor*scale;\n}\n\nfloat getRectLightDiffuse() {\n return LTC_EvaluateRect( dNormalW, dViewDirW, vPositionW, mat3( 1.0 ), dLTCCoords );\n}\n\nfloat getDiskLightDiffuse() {\n return LTC_EvaluateDisk( dNormalW, dViewDirW, vPositionW, mat3( 1.0 ), dLTCCoords );\n}\n\nfloat getSphereLightDiffuse() {\n // NB: this could be improved further with distance based wrap lighting\n float falloff = dSphereRadius / (dot(dLightDirW, dLightDirW) + dSphereRadius);\n return getLightDiffuse()*falloff;\n}\n\nmat3 getLTCLightInvMat(vec2 uv)\n{\n vec4 t1 = texture2D( areaLightsLutTex1, uv );\n\n #ifdef AREA_R8_G8_B8_A8_LUTS\n t1 *= vec4(1.001, 0.3239, 0.60437568, 1.0);\n t1 += vec4(0.0, -0.2976, -0.01381, 0.0);\n #endif\n\n return mat3(\n vec3( t1.x, 0, t1.y ),\n vec3( 0, 1, 0 ),\n vec3( t1.z, 0, t1.w )\n );\n}\n\nfloat calcRectLightSpecular(vec3 tNormalW, vec2 uv) {\n mat3 mInv = getLTCLightInvMat(uv);\n return LTC_EvaluateRect( tNormalW, dViewDirW, vPositionW, mInv, dLTCCoords );\n}\n\nfloat getRectLightSpecular() {\n return calcRectLightSpecular(dNormalW, dLTCUV);\n}\n\n#ifdef LIT_CLEARCOAT\nfloat getRectLightSpecularCC() {\n return calcRectLightSpecular(ccNormalW, ccLTCUV);\n}\n#endif\n\nfloat calcDiskLightSpecular(vec3 tNormalW, vec2 uv) {\n mat3 mInv = getLTCLightInvMat(uv);\n return LTC_EvaluateDisk( tNormalW, dViewDirW, vPositionW, mInv, dLTCCoords );\n}\n\nfloat getDiskLightSpecular() {\n return calcDiskLightSpecular(dNormalW, dLTCUV);\n}\n\n#ifdef LIT_CLEARCOAT\nfloat getDiskLightSpecularCC() {\n return calcDiskLightSpecular(ccNormalW, ccLTCUV);\n}\n#endif\n\nfloat getSphereLightSpecular() {\n return calcDiskLightSpecular(dNormalW, dLTCUV);\n}\n\n#ifdef LIT_CLEARCOAT\nfloat getSphereLightSpecularCC() {\n return calcDiskLightSpecular(ccNormalW, ccLTCUV);\n}\n#endif\n',metalnessPS:"\n#ifdef MAPFLOAT\nuniform float material_metalness;\n#endif\n\nvoid getMetalness() {\n float metalness = 1.0;\n\n #ifdef MAPFLOAT\n metalness *= material_metalness;\n #endif\n\n #ifdef MAPTEXTURE\n metalness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n metalness *= saturate(vVertexColor.$VC);\n #endif\n\n dMetalness = metalness;\n}\n",metalnessModulatePS:"\n\nuniform float material_f0;\n\nvoid getMetalnessModulate() {\n vec3 dielectricF0 = material_f0 * dSpecularity;\n dSpecularity = mix(dielectricF0, dAlbedo, dMetalness);\n dAlbedo *= 1.0 - dMetalness;\n}\n",msdfPS:"\nuniform sampler2D texture_msdfMap;\n\n#ifdef GL_OES_standard_derivatives\n#define USE_FWIDTH\n#endif\n\n#ifdef GL2\n#define USE_FWIDTH\n#endif\n\nfloat median(float r, float g, float b) {\n return max(min(r, g), min(max(r, g), b));\n}\n\nfloat map (float min, float max, float v) {\n return (v - min) / (max - min);\n}\n\nuniform float font_sdfIntensity; // intensity is used to boost the value read from the SDF, 0 is no boost, 1.0 is max boost\nuniform float font_pxrange; // the number of pixels between inside and outside the font in SDF\nuniform float font_textureWidth; // the width of the texture atlas\n\n#ifdef UNIFORM_TEXT_PARAMETERS\nuniform vec4 outline_color;\nuniform float outline_thickness;\nuniform vec4 shadow_color;\nuniform vec2 shadow_offset;\n#else\nvarying vec4 outline_color;\nvarying float outline_thickness;\nvarying vec4 shadow_color;\nvarying vec2 shadow_offset;\n#endif\n\nvec4 applyMsdf(vec4 color) {\n // sample the field\n vec3 tsample = texture2D(texture_msdfMap, vUv0).rgb;\n vec2 uvShdw = vUv0 - shadow_offset;\n vec3 ssample = texture2D(texture_msdfMap, uvShdw).rgb;\n // get the signed distance value\n float sigDist = median(tsample.r, tsample.g, tsample.b);\n float sigDistShdw = median(ssample.r, ssample.g, ssample.b);\n\n // smoothing limit - smaller value makes for sharper but more aliased text, especially on angles\n // too large value (0.5) creates a dark glow around the letters\n float smoothingMax = 0.2;\n\n #ifdef USE_FWIDTH\n // smoothing depends on size of texture on screen\n vec2 w = fwidth(vUv0);\n float smoothing = clamp(w.x * font_textureWidth / font_pxrange, 0.0, smoothingMax);\n #else\n float font_size = 16.0; // TODO fix this\n // smoothing gets smaller as the font size gets bigger\n // don't have fwidth we can approximate from font size, this doesn't account for scaling\n // so a big font scaled down will be wrong...\n float smoothing = clamp(font_pxrange / font_size, 0.0, smoothingMax);\n #endif\n\n float mapMin = 0.05;\n float mapMax = clamp(1.0 - font_sdfIntensity, mapMin, 1.0);\n\n // remap to a smaller range (used on smaller font sizes)\n float sigDistInner = map(mapMin, mapMax, sigDist);\n float sigDistOutline = map(mapMin, mapMax, sigDist + outline_thickness);\n sigDistShdw = map(mapMin, mapMax, sigDistShdw + outline_thickness);\n\n float center = 0.5;\n // calculate smoothing and use to generate opacity\n float inside = smoothstep(center-smoothing, center+smoothing, sigDistInner);\n float outline = smoothstep(center-smoothing, center+smoothing, sigDistOutline);\n float shadow = smoothstep(center-smoothing, center+smoothing, sigDistShdw);\n\n vec4 tcolor = (outline > inside) ? outline * vec4(outline_color.a * outline_color.rgb, outline_color.a) : vec4(0.0);\n tcolor = mix(tcolor, color, inside);\n\n vec4 scolor = (shadow > outline) ? shadow * vec4(shadow_color.a * shadow_color.rgb, shadow_color.a) : tcolor;\n tcolor = mix(scolor, tcolor, outline);\n \n return tcolor;\n}\n",msdfVS:"\nattribute vec3 vertex_outlineParameters;\nattribute vec3 vertex_shadowParameters;\n\nvarying vec4 outline_color;\nvarying float outline_thickness;\nvarying vec4 shadow_color;\nvarying vec2 shadow_offset;\n\nvoid unpackMsdfParams() {\n vec3 little = mod(vertex_outlineParameters, 256.);\n vec3 big = (vertex_outlineParameters - little) / 256.;\n\n outline_color.rb = little.xy / 255.;\n outline_color.ga = big.xy / 255.;\n\n // _outlineThicknessScale === 0.2\n outline_thickness = little.z / 255. * 0.2;\n\n little = mod(vertex_shadowParameters, 256.);\n big = (vertex_shadowParameters - little) / 256.;\n\n shadow_color.rb = little.xy / 255.;\n shadow_color.ga = big.xy / 255.;\n\n // vec2(little.z, big.z) / 127. - 1. remaps shadow offset from [0, 254] to [-1, 1]\n // _shadowOffsetScale === 0.005\n shadow_offset = (vec2(little.z, big.z) / 127. - 1.) * 0.005;\n}\n",normalVS:"\n#ifdef MORPHING_TEXTURE_BASED_NORMAL\nuniform highp sampler2D morphNormalTex;\n#endif\n\nvec3 getNormal() {\n #ifdef SKIN\n dNormalMatrix = mat3(dModelMatrix[0].xyz, dModelMatrix[1].xyz, dModelMatrix[2].xyz);\n #elif defined(INSTANCING)\n dNormalMatrix = mat3(instance_line1.xyz, instance_line2.xyz, instance_line3.xyz);\n #else\n dNormalMatrix = matrix_normal;\n #endif\n\n vec3 tempNormal = vertex_normal;\n\n #ifdef MORPHING\n #ifdef MORPHING_NRM03\n tempNormal += morph_weights_a[0] * morph_nrm0;\n tempNormal += morph_weights_a[1] * morph_nrm1;\n tempNormal += morph_weights_a[2] * morph_nrm2;\n tempNormal += morph_weights_a[3] * morph_nrm3;\n #endif\n #ifdef MORPHING_NRM47\n tempNormal += morph_weights_b[0] * morph_nrm4;\n tempNormal += morph_weights_b[1] * morph_nrm5;\n tempNormal += morph_weights_b[2] * morph_nrm6;\n tempNormal += morph_weights_b[3] * morph_nrm7;\n #endif\n #endif\n\n #ifdef MORPHING_TEXTURE_BASED_NORMAL\n // apply morph offset from texture\n vec2 morphUV = getTextureMorphCoords();\n vec3 morphNormal = texture2D(morphNormalTex, morphUV).xyz;\n tempNormal += morphNormal;\n #endif\n\n return normalize(dNormalMatrix * tempNormal);\n}\n",normalDetailMapPS:"\n#ifdef MAPTEXTURE\nuniform float material_normalDetailMapBumpiness;\n\nvec3 blendNormals(vec3 n1, vec3 n2) {\n // https://blog.selfshadow.com/publications/blending-in-detail/#detail-oriented\n n1 += vec3(0, 0, 1);\n n2 *= vec3(-1, -1, 1);\n return n1 * dot(n1, n2) / n1.z - n2;\n}\n#endif\n\nvec3 addNormalDetail(vec3 normalMap) {\n#ifdef MAPTEXTURE\n vec3 normalDetailMap = unpackNormal(texture2DBias($SAMPLER, $UV, textureBias));\n normalDetailMap = mix(vec3(0.0, 0.0, 1.0), normalDetailMap, material_normalDetailMapBumpiness);\n return blendNormals(normalMap, normalDetailMap);\n#else\n return normalMap;\n#endif\n}\n",normalInstancedVS:"\nvec3 getNormal() {\n dNormalMatrix = mat3(instance_line1.xyz, instance_line2.xyz, instance_line3.xyz);\n return normalize(dNormalMatrix * vertex_normal);\n}\n",normalMapPS:"\n#ifdef MAPTEXTURE\nuniform float material_bumpiness;\n#endif\n\nvoid getNormal() {\n#ifdef MAPTEXTURE\n vec3 normalMap = unpackNormal(texture2DBias($SAMPLER, $UV, textureBias));\n normalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, material_bumpiness);\n dNormalW = normalize(dTBN * addNormalDetail(normalMap));\n#else\n dNormalW = dVertexNormalW;\n#endif\n}\n",normalSkinnedVS:"\nvec3 getNormal() {\n dNormalMatrix = mat3(dModelMatrix[0].xyz, dModelMatrix[1].xyz, dModelMatrix[2].xyz);\n return normalize(dNormalMatrix * vertex_normal);\n}\n",normalXYPS:"\nvec3 unpackNormal(vec4 nmap) {\n vec3 normal;\n normal.xy = nmap.wy * 2.0 - 1.0;\n normal.z = sqrt(1.0 - saturate(dot(normal.xy, normal.xy)));\n return normal;\n}\n",normalXYZPS:"\nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\n",opacityPS:"\n#ifdef MAPFLOAT\nuniform float material_opacity;\n#endif\n\nvoid getOpacity() {\n dAlpha = 1.0;\n\n #ifdef MAPFLOAT\n dAlpha *= material_opacity;\n #endif\n\n #ifdef MAPTEXTURE\n dAlpha *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n dAlpha *= clamp(vVertexColor.$VC, 0.0, 1.0);\n #endif\n}\n",outputAlphaPS:"\ngl_FragColor.a = dAlpha;\n",outputAlphaOpaquePS:"\n gl_FragColor.a = 1.0;\n",outputAlphaPremulPS:"\ngl_FragColor.rgb *= dAlpha;\ngl_FragColor.a = dAlpha;\n",outputTex2DPS:"\nvarying vec2 vUv0;\n\nuniform sampler2D source;\n\nvoid main(void) {\n gl_FragColor = texture2D(source, vUv0);\n}\n",packDepthPS:"\n// Packing a float in GLSL with multiplication and mod\n// http://blog.gradientstudios.com/2012/08/23/shadow-map-improvement\nvec4 packFloat(float depth) {\n const vec4 bit_shift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);\n\n // combination of mod and multiplication and division works better\n vec4 res = mod(depth * bit_shift * vec4(255), vec4(256) ) / vec4(255);\n res -= res.xxyz * bit_mask;\n return res;\n}\n",sheenPS:"\n\n#ifdef MAPCOLOR\nuniform vec3 material_sheen;\n#endif\n\nvoid getSheen() {\n vec3 sheenColor = vec3(1, 1, 1);\n\n #ifdef MAPCOLOR\n sheenColor *= material_sheen;\n #endif\n\n #ifdef MAPTEXTURE\n sheenColor *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n #endif\n\n #ifdef MAPVERTEX\n sheenColor *= saturate(vVertexColor.$VC);\n #endif\n\n sSpecularity = sheenColor;\n}\n",sheenGlossPS:"\n#ifdef MAPFLOAT\nuniform float material_sheenGlossiness;\n#endif\n\nvoid getSheenGlossiness() {\n float sheenGlossiness = 1.0;\n\n #ifdef MAPFLOAT\n sheenGlossiness *= material_sheenGlossiness;\n #endif\n\n #ifdef MAPTEXTURE\n sheenGlossiness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n sheenGlossiness *= saturate(vVertexColor.$VC);\n #endif\n\n sheenGlossiness += 0.0000001;\n sGlossiness = sheenGlossiness;\n}\n",parallaxPS:"\nuniform float material_heightMapFactor;\n\nvoid getParallax() {\n float parallaxScale = material_heightMapFactor;\n\n float height = texture2DBias($SAMPLER, $UV, textureBias).$CH;\n height = height * parallaxScale - parallaxScale*0.5;\n vec3 viewDirT = dViewDirW * dTBN;\n\n viewDirT.z += 0.42;\n dUvOffset = height * (viewDirT.xy / viewDirT.z);\n}\n",particlePS:"\nvarying vec4 texCoordsAlphaLife;\n\nuniform sampler2D colorMap;\nuniform sampler2D colorParam;\nuniform float graphSampleSize;\nuniform float graphNumSamples;\n\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n#endif\n\nuniform float softening;\nuniform float colorMult;\n\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n const vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n float depth = dot(rgbaDepth, bitShift);\n return depth;\n}\n#endif\n\nvoid main(void) {\n vec4 tex = gammaCorrectInput(texture2D(colorMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y)));\n vec4 ramp = gammaCorrectInput(texture2D(colorParam, vec2(texCoordsAlphaLife.w, 0.0)));\n ramp.rgb *= colorMult;\n\n ramp.a += texCoordsAlphaLife.z;\n\n vec3 rgb = tex.rgb * ramp.rgb;\n float a = tex.a * ramp.a;\n",particleVS:"\nvec3 unpack3NFloats(float src) {\n float r = fract(src);\n float g = fract(src * 256.0);\n float b = fract(src * 65536.0);\n return vec3(r, g, b);\n}\n\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n\nvec4 tex1Dlod_lerp(highp sampler2D tex, vec2 tc) {\n return mix( texture2D(tex,tc), texture2D(tex,tc + graphSampleSize), fract(tc.x*graphNumSamples) );\n}\n\nvec4 tex1Dlod_lerp(highp sampler2D tex, vec2 tc, out vec3 w) {\n vec4 a = texture2D(tex,tc);\n vec4 b = texture2D(tex,tc + graphSampleSize);\n float c = fract(tc.x*graphNumSamples);\n\n vec3 unpackedA = unpack3NFloats(a.w);\n vec3 unpackedB = unpack3NFloats(b.w);\n w = mix(unpackedA, unpackedB, c);\n\n return mix(a, b, c);\n}\n\nvec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix) {\n float c = cos(pRotation);\n float s = sin(pRotation);\n\n mat2 m = mat2(c, -s, s, c);\n rotMatrix = m;\n\n return m * quadXY;\n}\n\nvec3 billboard(vec3 InstanceCoords, vec2 quadXY) {\n #ifdef SCREEN_SPACE\n vec3 pos = vec3(-1, 0, 0) * quadXY.x + vec3(0, -1, 0) * quadXY.y;\n #else\n vec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;\n #endif\n\n return pos;\n}\n\nvec3 customFace(vec3 InstanceCoords, vec2 quadXY) {\n vec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;\n return pos;\n}\n\nvec2 safeNormalize(vec2 v) {\n float l = length(v);\n return (l > 1e-06) ? v / l : v;\n}\n\nvoid main(void) {\n vec3 meshLocalPos = particle_vertexData.xyz;\n float id = floor(particle_vertexData.w);\n\n float rndFactor = fract(sin(id + 1.0 + seed));\n vec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));\n\n float uv = id / numParticlesPot;\n readInput(uv);\n\n#ifdef LOCAL_SPACE\n inVel = mat3(matrix_model) * inVel;\n#endif\n vec2 velocityV = safeNormalize((mat3(matrix_view) * inVel).xy); // should be removed by compiler if align/stretch is not used\n\n float particleLifetime = lifetime;\n\n if (inLife <= 0.0 || inLife > particleLifetime || !inShow) meshLocalPos = vec3(0.0);\n vec2 quadXY = meshLocalPos.xy;\n float nlife = clamp(inLife / particleLifetime, 0.0, 1.0);\n\n vec3 paramDiv;\n vec4 params = tex1Dlod_lerp(internalTex2, vec2(nlife, 0), paramDiv);\n float scale = params.y;\n float scaleDiv = paramDiv.x;\n float alphaDiv = paramDiv.z;\n\n scale += (scaleDiv * 2.0 - 1.0) * scaleDivMult * fract(rndFactor*10000.0);\n\n#ifndef USE_MESH\n texCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);\n#else\n texCoordsAlphaLife = vec4(particle_uv, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);\n#endif\n\n vec3 particlePos = inPos;\n vec3 particlePosMoved = vec3(0.0);\n\n mat2 rotMatrix;\n",particleAnimFrameClampVS:"\n float animFrame = min(floor(texCoordsAlphaLife.w * animTexParams.y) + animTexParams.x, animTexParams.z);\n",particleAnimFrameLoopVS:"\n float animFrame = floor(mod(texCoordsAlphaLife.w * animTexParams.y + animTexParams.x, animTexParams.z + 1.0));\n",particleAnimTexVS:"\n float animationIndex;\n\n if (animTexIndexParams.y == 1.0) {\n animationIndex = floor((animTexParams.w + 1.0) * rndFactor3.z) * (animTexParams.z + 1.0);\n } else {\n animationIndex = animTexIndexParams.x * (animTexParams.z + 1.0);\n }\n\n float atlasX = (animationIndex + animFrame) * animTexTilesParams.x;\n float atlasY = 1.0 - floor(atlasX + 1.0) * animTexTilesParams.y;\n atlasX = fract(atlasX);\n\n texCoordsAlphaLife.xy *= animTexTilesParams.xy;\n texCoordsAlphaLife.xy += vec2(atlasX, atlasY);\n",particleInputFloatPS:"\nvoid readInput(float uv) {\n vec4 tex = texture2D(particleTexIN, vec2(uv, 0.25));\n vec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.75));\n\n inPos = tex.xyz;\n inVel = tex2.xyz;\n inAngle = (tex.w < 0.0? -tex.w : tex.w) - 1000.0;\n inShow = tex.w >= 0.0;\n inLife = tex2.w;\n}\n",particleInputRgba8PS:"\n//RG=X, BA=Y\n//RG=Z, BA=A\n//RGB=V, A=visMode\n//RGBA=life\n\n#define PI2 6.283185307179586\n\nuniform vec3 inBoundsSize;\nuniform vec3 inBoundsCenter;\n\nuniform float maxVel;\n\nfloat decodeFloatRG(vec2 rg) {\n return rg.y*(1.0/255.0) + rg.x;\n}\n\nfloat decodeFloatRGBA( vec4 rgba ) {\n return dot( rgba, vec4(1.0, 1.0/255.0, 1.0/65025.0, 1.0/160581375.0) );\n}\n\nvoid readInput(float uv) {\n vec4 tex0 = texture2D(particleTexIN, vec2(uv, 0.125));\n vec4 tex1 = texture2D(particleTexIN, vec2(uv, 0.375));\n vec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.625));\n vec4 tex3 = texture2D(particleTexIN, vec2(uv, 0.875));\n\n inPos = vec3(decodeFloatRG(tex0.rg), decodeFloatRG(tex0.ba), decodeFloatRG(tex1.rg));\n inPos = (inPos - vec3(0.5)) * inBoundsSize + inBoundsCenter;\n\n inVel = tex2.xyz;\n inVel = (inVel - vec3(0.5)) * maxVel;\n\n inAngle = decodeFloatRG(tex1.ba) * PI2;\n inShow = tex2.a > 0.5;\n\n inLife = decodeFloatRGBA(tex3);\n float maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));\n float maxPosLife = lifetime+1.0;\n inLife = inLife * (maxNegLife + maxPosLife) - maxNegLife;\n}\n",particleOutputFloatPS:"\nvoid writeOutput() {\n if (gl_FragCoord.y<1.0) {\n gl_FragColor = vec4(outPos, (outAngle + 1000.0) * visMode);\n } else {\n gl_FragColor = vec4(outVel, outLife);\n }\n}\n",particleOutputRgba8PS:"\nuniform vec3 outBoundsMul;\nuniform vec3 outBoundsAdd;\n\nvec2 encodeFloatRG( float v ) {\n vec2 enc = vec2(1.0, 255.0) * v;\n enc = fract(enc);\n enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n return enc;\n}\n\nvec4 encodeFloatRGBA( float v ) {\n vec4 enc = vec4(1.0, 255.0, 65025.0, 160581375.0) * v;\n enc = fract(enc);\n enc -= enc.yzww * vec4(1.0/255.0,1.0/255.0,1.0/255.0,0.0);\n return enc;\n}\n\nvoid writeOutput() {\n outPos = outPos * outBoundsMul + outBoundsAdd;\n outAngle = fract(outAngle / PI2);\n\n outVel = (outVel / maxVel) + vec3(0.5); // TODO: mul\n\n float maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));\n float maxPosLife = lifetime+1.0;\n outLife = (outLife + maxNegLife) / (maxNegLife + maxPosLife);\n\n if (gl_FragCoord.y < 1.0) {\n gl_FragColor = vec4(encodeFloatRG(outPos.x), encodeFloatRG(outPos.y));\n } else if (gl_FragCoord.y < 2.0) {\n gl_FragColor = vec4(encodeFloatRG(outPos.z), encodeFloatRG(outAngle));\n } else if (gl_FragCoord.y < 3.0) {\n gl_FragColor = vec4(outVel, visMode*0.5+0.5);\n } else {\n gl_FragColor = encodeFloatRGBA(outLife);\n }\n}\n",particleUpdaterAABBPS:"\nuniform mat3 spawnBounds;\nuniform vec3 spawnPosInnerRatio;\n\nvec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {\n vec3 pos = inBounds - vec3(0.5);\n\n vec3 posAbs = abs(pos);\n vec3 maxPos = vec3(max(posAbs.x, max(posAbs.y, posAbs.z)));\n\n vec3 edge = maxPos + (vec3(0.5) - maxPos) * spawnPosInnerRatio;\n\n pos.x = edge.x * (maxPos.x == posAbs.x ? sign(pos.x) : 2.0 * pos.x);\n pos.y = edge.y * (maxPos.y == posAbs.y ? sign(pos.y) : 2.0 * pos.y);\n pos.z = edge.z * (maxPos.z == posAbs.z ? sign(pos.z) : 2.0 * pos.z);\n\n#ifndef LOCAL_SPACE\n return emitterPos + spawnBounds * pos;\n#else\n return spawnBounds * pos;\n#endif\n}\n\nvoid addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {\n localVelocity -= vec3(0, 0, initialVelocity);\n}\n",particleUpdaterEndPS:"\n writeOutput();\n}\n",particleUpdaterInitPS:"\nvarying vec2 vUv0;\n\nuniform highp sampler2D particleTexIN;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\nuniform highp sampler2D internalTex3;\n\nuniform mat3 emitterMatrix, emitterMatrixInv;\nuniform vec3 emitterScale;\n\nuniform vec3 emitterPos, frameRandom, localVelocityDivMult, velocityDivMult;\nuniform float delta, rate, rateDiv, lifetime, numParticles, rotSpeedDivMult, radialSpeedDivMult, seed;\nuniform float startAngle, startAngle2;\nuniform float initialVelocity;\n\nuniform float graphSampleSize;\nuniform float graphNumSamples;\n\nvec3 inPos;\nvec3 inVel;\nfloat inAngle;\nbool inShow;\nfloat inLife;\nfloat visMode;\n\nvec3 outPos;\nvec3 outVel;\nfloat outAngle;\nbool outShow;\nfloat outLife;\n",particleUpdaterNoRespawnPS:"\n if (outLife >= lifetime) {\n outLife -= max(lifetime, (numParticles - 1.0) * particleRate);\n visMode = -1.0;\n }\n",particleUpdaterOnStopPS:"\n visMode = outLife < 0.0? -1.0: visMode;\n",particleUpdaterRespawnPS:"\n if (outLife >= lifetime) {\n outLife -= max(lifetime, (numParticles - 1.0) * particleRate);\n visMode = 1.0;\n }\n visMode = outLife < 0.0? 1.0: visMode;\n",particleUpdaterSpherePS:"\nuniform float spawnBoundsSphere;\nuniform float spawnBoundsSphereInnerRatio;\n\nvec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {\n float rnd4 = fract(rndFactor * 1000.0);\n vec3 norm = normalize(inBounds.xyz - vec3(0.5));\n float r = rnd4 * (1.0 - spawnBoundsSphereInnerRatio) + spawnBoundsSphereInnerRatio;\n#ifndef LOCAL_SPACE\n return emitterPos + norm * r * spawnBoundsSphere;\n#else\n return norm * r * spawnBoundsSphere;\n#endif\n}\n\nvoid addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {\n localVelocity += normalize(inBounds - vec3(0.5)) * initialVelocity;\n}\n",particleUpdaterStartPS:"\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n\nvec3 unpack3NFloats(float src) {\n float r = fract(src);\n float g = fract(src * 256.0);\n float b = fract(src * 65536.0);\n return vec3(r, g, b);\n}\n\nvec3 tex1Dlod_lerp(highp sampler2D tex, vec2 tc, out vec3 w) {\n vec4 a = texture2D(tex, tc);\n vec4 b = texture2D(tex, tc + graphSampleSize);\n float c = fract(tc.x * graphNumSamples);\n\n vec3 unpackedA = unpack3NFloats(a.w);\n vec3 unpackedB = unpack3NFloats(b.w);\n w = mix(unpackedA, unpackedB, c);\n\n return mix(a.xyz, b.xyz, c);\n}\n\n#define HASHSCALE4 vec4(1031, .1030, .0973, .1099)\nvec4 hash41(float p) {\n vec4 p4 = fract(vec4(p) * HASHSCALE4);\n p4 += dot(p4, p4.wzxy+19.19);\n return fract(vec4((p4.x + p4.y)*p4.z, (p4.x + p4.z)*p4.y, (p4.y + p4.z)*p4.w, (p4.z + p4.w)*p4.x));\n}\n\nvoid main(void) {\n if (gl_FragCoord.x > numParticles) discard;\n\n readInput(vUv0.x);\n visMode = inShow? 1.0 : -1.0;\n\n vec4 rndFactor = hash41(gl_FragCoord.x + seed);\n\n float particleRate = rate + rateDiv * rndFactor.x;\n\n outLife = inLife + delta;\n float nlife = clamp(outLife / lifetime, 0.0, 1.0);\n\n vec3 localVelocityDiv;\n vec3 velocityDiv;\n vec3 paramDiv;\n vec3 localVelocity = tex1Dlod_lerp(internalTex0, vec2(nlife, 0), localVelocityDiv);\n vec3 velocity = tex1Dlod_lerp(internalTex1, vec2(nlife, 0), velocityDiv);\n vec3 params = tex1Dlod_lerp(internalTex2, vec2(nlife, 0), paramDiv);\n float rotSpeed = params.x;\n float rotSpeedDiv = paramDiv.y;\n\n vec3 radialParams = tex1Dlod_lerp(internalTex3, vec2(nlife, 0), paramDiv);\n float radialSpeed = radialParams.x;\n float radialSpeedDiv = radialParams.y;\n\n bool respawn = inLife <= 0.0 || outLife >= lifetime;\n inPos = respawn ? calcSpawnPosition(rndFactor.xyz, rndFactor.x) : inPos;\n inAngle = respawn ? mix(startAngle, startAngle2, rndFactor.x) : inAngle;\n\n#ifndef LOCAL_SPACE\n vec3 radialVel = inPos - emitterPos;\n#else\n vec3 radialVel = inPos;\n#endif\n radialVel = (dot(radialVel, radialVel) > 1.0E-8) ? radialSpeed * normalize(radialVel) : vec3(0.0);\n radialVel += (radialSpeedDiv * vec3(2.0) - vec3(1.0)) * radialSpeedDivMult * rndFactor.xyz;\n\n localVelocity += (localVelocityDiv * vec3(2.0) - vec3(1.0)) * localVelocityDivMult * rndFactor.xyz;\n velocity += (velocityDiv * vec3(2.0) - vec3(1.0)) * velocityDivMult * rndFactor.xyz;\n rotSpeed += (rotSpeedDiv * 2.0 - 1.0) * rotSpeedDivMult * rndFactor.y;\n\n addInitialVelocity(localVelocity, rndFactor.xyz);\n\n#ifndef LOCAL_SPACE\n outVel = emitterMatrix * localVelocity + (radialVel + velocity) * emitterScale;\n#else\n outVel = (localVelocity + radialVel) / emitterScale + emitterMatrixInv * velocity;\n#endif\n\n outPos = inPos + outVel * delta;\n outAngle = inAngle + rotSpeed * delta;\n",particle_billboardVS:"\n quadXY = rotate(quadXY, inAngle, rotMatrix);\n vec3 localPos = billboard(particlePos, quadXY);\n",particle_blendAddPS:"\n dBlendModeFogFactor = 0.0;\n rgb *= saturate(gammaCorrectInput(max(a, 0.0)));\n if ((rgb.r + rgb.g + rgb.b) < 0.000001) discard;\n",particle_blendMultiplyPS:"\n rgb = mix(vec3(1.0), rgb, vec3(a));\n if (rgb.r + rgb.g + rgb.b > 2.99) discard;\n",particle_blendNormalPS:"\n if (a < 0.01) discard;\n",particle_cpuVS:"\nattribute vec4 particle_vertexData; // XYZ = world pos, W = life\nattribute vec4 particle_vertexData2; // X = angle, Y = scale, Z = alpha, W = velocity.x\nattribute vec4 particle_vertexData3; // XYZ = particle local pos, W = velocity.y\nattribute float particle_vertexData4; // particle id\n#ifndef USE_MESH\n#define VDATA5TYPE vec2\n#else\n#define VDATA5TYPE vec4\n#endif\nattribute VDATA5TYPE particle_vertexData5; // VDATA4TYPE depends on useMesh property. Start with X = velocity.z, Y = particle ID and for mesh particles proceeds with Z = mesh UV.x, W = mesh UV.y\n\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\n\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n\nuniform mat3 matrix_normal;\nuniform mat4 matrix_viewInverse;\n\nuniform float numParticles;\nuniform float lifetime;\nuniform float stretch;\nuniform float seed;\nuniform vec3 wrapBounds, emitterScale, faceTangent, faceBinorm;\nuniform sampler2D texLifeAndSourcePosOUT;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\nuniform vec3 emitterPos;\n\nvarying vec4 texCoordsAlphaLife;\n\nvec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix)\n{\n float c = cos(pRotation);\n float s = sin(pRotation);\n //vec4 rotationMatrix = vec4(c, -s, s, c);\n\n mat2 m = mat2(c, -s, s, c);\n rotMatrix = m;\n\n return m * quadXY;\n}\n\nvec3 billboard(vec3 InstanceCoords, vec2 quadXY)\n{\n vec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;\n return pos;\n}\n\nvec3 customFace(vec3 InstanceCoords, vec2 quadXY)\n{\n vec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;\n return pos;\n}\n\nvoid main(void)\n{\n vec3 particlePos = particle_vertexData.xyz;\n vec3 inPos = particlePos;\n vec3 vertPos = particle_vertexData3.xyz;\n vec3 inVel = vec3(particle_vertexData2.w, particle_vertexData3.w, particle_vertexData5.x);\n\n float id = floor(particle_vertexData4);\n float rndFactor = fract(sin(id + 1.0 + seed));\n vec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));\n\n#ifdef LOCAL_SPACE\n inVel = mat3(matrix_model) * inVel;\n#endif\n vec2 velocityV = normalize((mat3(matrix_view) * inVel).xy); // should be removed by compiler if align/stretch is not used\n\n vec2 quadXY = vertPos.xy;\n\n#ifdef USE_MESH\n texCoordsAlphaLife = vec4(particle_vertexData5.zw, particle_vertexData2.z, particle_vertexData.w);\n#else\n texCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, particle_vertexData2.z, particle_vertexData.w);\n#endif\n mat2 rotMatrix;\n\n float inAngle = particle_vertexData2.x;\n vec3 particlePosMoved = vec3(0.0);\n vec3 meshLocalPos = particle_vertexData3.xyz;\n",particle_cpu_endVS:"\n localPos *= particle_vertexData2.y * emitterScale;\n localPos += particlePos;\n\n gl_Position = matrix_viewProjection * vec4(localPos, 1.0);\n",particle_customFaceVS:"\n quadXY = rotate(quadXY, inAngle, rotMatrix);\n vec3 localPos = customFace(particlePos, quadXY);\n",particle_endPS:"\n rgb = addFog(rgb);\n rgb = toneMap(rgb);\n rgb = gammaCorrectOutput(rgb);\n gl_FragColor = vec4(rgb, a);\n}\n",particle_endVS:"\n localPos *= scale * emitterScale;\n localPos += particlePos;\n\n #ifdef SCREEN_SPACE\n gl_Position = vec4(localPos.x, localPos.y, 0.0, 1.0);\n #else\n gl_Position = matrix_viewProjection * vec4(localPos.xyz, 1.0);\n #endif\n",particle_halflambertPS:"\n vec3 negNormal = normal*0.5+0.5;\n vec3 posNormal = -normal*0.5+0.5;\n negNormal *= negNormal;\n posNormal *= posNormal;\n",particle_initVS:"\nattribute vec4 particle_vertexData; // XYZ = particle position, W = particle ID + random factor\n#ifdef USE_MESH\nattribute vec2 particle_uv; // mesh UV\n#endif\n\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\nuniform mat3 matrix_normal;\nuniform mat4 matrix_viewInverse;\n\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n\nuniform float numParticles, numParticlesPot;\nuniform float graphSampleSize;\nuniform float graphNumSamples;\nuniform float stretch;\nuniform vec3 wrapBounds;\nuniform vec3 emitterScale, emitterPos, faceTangent, faceBinorm;\nuniform float rate, rateDiv, lifetime, deltaRandomnessStatic, scaleDivMult, alphaDivMult, seed, delta;\nuniform sampler2D particleTexOUT, particleTexIN;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\n\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n#endif\n\nvarying vec4 texCoordsAlphaLife;\n\nvec3 inPos;\nvec3 inVel;\nfloat inAngle;\nbool inShow;\nfloat inLife;\n",particle_lambertPS:"\n vec3 negNormal = max(normal, vec3(0.0));\n vec3 posNormal = max(-normal, vec3(0.0));\n",particle_lightingPS:"\n vec3 light = negNormal.x*lightCube[0] + posNormal.x*lightCube[1] +\n negNormal.y*lightCube[2] + posNormal.y*lightCube[3] +\n negNormal.z*lightCube[4] + posNormal.z*lightCube[5];\n\n rgb *= light;\n",particle_localShiftVS:"\n particlePos = (matrix_model * vec4(particlePos, 1.0)).xyz;\n",particle_meshVS:"\n vec3 localPos = meshLocalPos;\n localPos.xy = rotate(localPos.xy, inAngle, rotMatrix);\n localPos.yz = rotate(localPos.yz, inAngle, rotMatrix);\n\n billboard(particlePos, quadXY);\n",particle_normalVS:"\n Normal = normalize(localPos + matrix_viewInverse[2].xyz);\n",particle_normalMapPS:"\n vec3 normalMap = normalize(texture2D(normalMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y)).xyz * 2.0 - 1.0);\n vec3 normal = ParticleMat * normalMap;\n",particle_pointAlongVS:"\n inAngle = atan(velocityV.x, velocityV.y); // not the fastest way, but easier to plug in; TODO: create rot matrix right from vectors\n\n",particle_softPS:"\n float depth = getLinearScreenDepth();\n float particleDepth = vDepth;\n float depthDiff = saturate(abs(particleDepth - depth) * softening);\n a *= depthDiff;\n",particle_softVS:"\n vDepth = getLinearDepth(localPos);\n",particle_stretchVS:"\n vec3 moveDir = inVel * stretch;\n vec3 posPrev = particlePos - moveDir;\n posPrev += particlePosMoved;\n\n vec2 centerToVertexV = normalize((mat3(matrix_view) * localPos).xy);\n\n float interpolation = dot(-velocityV, centerToVertexV) * 0.5 + 0.5;\n\n particlePos = mix(particlePos, posPrev, interpolation);\n",particle_TBNVS:"\n mat3 rot3 = mat3(rotMatrix[0][0], rotMatrix[0][1], 0.0, rotMatrix[1][0], rotMatrix[1][1], 0.0, 0.0, 0.0, 1.0);\n ParticleMat = mat3(-matrix_viewInverse[0].xyz, -matrix_viewInverse[1].xyz, matrix_viewInverse[2].xyz) * rot3;\n",particle_wrapVS:"\n vec3 origParticlePos = particlePos;\n particlePos -= matrix_model[3].xyz;\n particlePos = mod(particlePos, wrapBounds) - wrapBounds * 0.5;\n particlePos += matrix_model[3].xyz;\n particlePosMoved = particlePos - origParticlePos;\n",precisionTestPS:"\nvoid main(void) {\n gl_FragColor = vec4(2147483648.0);\n}\n",precisionTest2PS:"\nuniform sampler2D source;\n\nvec4 packFloat(float depth) {\n const vec4 bit_shift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);\n\n vec4 res = mod(depth * bit_shift * vec4(255), vec4(256) ) / vec4(255);\n res -= res.xxyz * bit_mask;\n return res;\n}\n\nvoid main(void) {\n float c = texture2D(source, vec2(0.0)).r;\n float diff = abs(c - 2147483648.0) / 2147483648.0;\n gl_FragColor = packFloat(diff);\n}\n",reflDirPS:"\nvoid getReflDir() {\n dReflDirW = normalize(-reflect(dViewDirW, dNormalW));\n}\n",reflDirAnisoPS:"\nvoid getReflDir() {\n float roughness = sqrt(1.0 - min(dGlossiness, 1.0));\n float anisotropy = material_anisotropy * roughness;\n vec3 anisotropicDirection = anisotropy >= 0.0 ? dTBN[1] : dTBN[0];\n vec3 anisotropicTangent = cross(anisotropicDirection, dViewDirW);\n vec3 anisotropicNormal = cross(anisotropicTangent, anisotropicDirection);\n vec3 bentNormal = normalize(mix(normalize(dNormalW), normalize(anisotropicNormal), anisotropy));\n dReflDirW = reflect(-dViewDirW, bentNormal);\n}\n",reflectionCCPS:"\n#ifdef LIT_CLEARCOAT\nvoid addReflectionCC() {\n ccReflection += calcReflection(ccReflDirW, ccGlossiness);\n}\n#endif\n",reflectionCubePS:"\nuniform samplerCube texture_cubeMap;\nuniform float material_reflectivity;\n\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n vec3 lookupVec = fixSeams(cubeMapProject(tReflDirW));\n lookupVec.x *= -1.0;\n return $DECODE(textureCube(texture_cubeMap, lookupVec));\n}\n\nvoid addReflection() { \n dReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionEnvHQPS:"\n#ifndef ENV_ATLAS\n#define ENV_ATLAS\nuniform sampler2D texture_envAtlas;\n#endif\nuniform samplerCube texture_cubeMap;\nuniform float material_reflectivity;\n\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n vec3 dir = cubeMapProject(tReflDirW) * vec3(-1.0, 1.0, 1.0);\n vec2 uv = toSphericalUv(dir);\n\n // calculate roughness level\n float level = saturate(1.0 - tGlossiness) * 5.0;\n float ilevel = floor(level);\n float flevel = level - ilevel;\n\n vec3 sharp = $DECODE(textureCube(texture_cubeMap, fixSeams(dir)));\n vec3 roughA = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel)));\n vec3 roughB = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0)));\n\n return processEnvironment(mix(sharp, mix(roughA, roughB, flevel), min(level, 1.0)));\n}\n\nvoid addReflection() { \n dReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionEnvPS:"\n#ifndef ENV_ATLAS\n#define ENV_ATLAS\nuniform sampler2D texture_envAtlas;\n#endif\nuniform float material_reflectivity;\n\n// calculate mip level for shiny reflection given equirect coords uv.\nfloat shinyMipLevel(vec2 uv) {\n vec2 dx = dFdx(uv);\n vec2 dy = dFdy(uv);\n\n // calculate second dF at 180 degrees\n vec2 uv2 = vec2(fract(uv.x + 0.5), uv.y);\n vec2 dx2 = dFdx(uv2);\n vec2 dy2 = dFdy(uv2);\n\n // calculate min of both sets of dF to handle discontinuity at the azim edge\n float maxd = min(max(dot(dx, dx), dot(dy, dy)), max(dot(dx2, dx2), dot(dy2, dy2)));\n\n return clamp(0.5 * log2(maxd) - 1.0 + textureBias, 0.0, 5.0);\n}\n\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n vec3 dir = cubeMapProject(tReflDirW) * vec3(-1.0, 1.0, 1.0);\n vec2 uv = toSphericalUv(dir);\n\n // calculate roughness level\n float level = saturate(1.0 - tGlossiness) * 5.0;\n float ilevel = floor(level);\n\n // accessing the shiny (top level) reflection - perform manual mipmap lookup\n float level2 = shinyMipLevel(uv * atlasSize);\n float ilevel2 = floor(level2);\n\n vec2 uv0, uv1;\n float weight;\n if (ilevel == 0.0) {\n uv0 = mapShinyUv(uv, ilevel2);\n uv1 = mapShinyUv(uv, ilevel2 + 1.0);\n weight = level2 - ilevel2;\n } else {\n // accessing rough reflection - just sample the same part twice\n uv0 = uv1 = mapRoughnessUv(uv, ilevel);\n weight = 0.0;\n }\n\n vec3 linearA = $DECODE(texture2D(texture_envAtlas, uv0));\n vec3 linearB = $DECODE(texture2D(texture_envAtlas, uv1));\n vec3 linear0 = mix(linearA, linearB, weight);\n vec3 linear1 = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0)));\n\n return processEnvironment(mix(linear0, linear1, level - ilevel));\n}\n\nvoid addReflection() { \n dReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionSpherePS:"\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nuniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\n\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n vec3 reflDirV = (mat3(matrix_view) * tReflDirW).xyz;\n\n float m = 2.0 * sqrt( dot(reflDirV.xy, reflDirV.xy) + (reflDirV.z+1.0)*(reflDirV.z+1.0) );\n vec2 sphereMapUv = reflDirV.xy / m + 0.5;\n\n return $DECODE(texture2D(texture_sphereMap, sphereMapUv));\n}\n\nvoid addReflection() { \n dReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionSphereLowPS:"\nuniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\n\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n vec3 reflDirV = vNormalV;\n\n vec2 sphereMapUv = reflDirV.xy * 0.5 + 0.5;\n return $DECODE(texture2D(texture_sphereMap, sphereMapUv));\n}\n\nvoid addReflection() { \n dReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionSheenPS:"\n\nvoid addReflectionSheen() {\n float NoV = dot(dNormalW, dViewDirW);\n float alphaG = sGlossiness * sGlossiness;\n\n // Avoid using a LUT and approximate the values analytically\n float a = sGlossiness < 0.25 ? -339.2 * alphaG + 161.4 * sGlossiness - 25.9 : -8.48 * alphaG + 14.3 * sGlossiness - 9.95;\n float b = sGlossiness < 0.25 ? 44.0 * alphaG - 23.7 * sGlossiness + 3.26 : 1.97 * alphaG - 3.27 * sGlossiness + 0.72;\n float DG = exp( a * NoV + b ) + ( sGlossiness < 0.25 ? 0.0 : 0.1 * ( sGlossiness - 0.25 ) );\n sReflection += calcReflection(dNormalW, 0.0) * saturate(DG);\n}\n",refractionCubePS:"\nuniform float material_refractionIndex;\n\nvec3 refract2(vec3 viewVec, vec3 Normal, float IOR) {\n float vn = dot(viewVec, Normal);\n float k = 1.0 - IOR * IOR * (1.0 - vn * vn);\n vec3 refrVec = IOR * viewVec - (IOR * vn + sqrt(k)) * Normal;\n return refrVec;\n}\n\nvoid addRefraction() {\n // use same reflection code with refraction vector\n vec3 tmpDir = dReflDirW;\n vec4 tmpRefl = dReflection;\n dReflDirW = refract2(-dViewDirW, dNormalW, material_refractionIndex);\n dReflection = vec4(0);\n addReflection();\n dDiffuseLight = mix(dDiffuseLight, dReflection.rgb * dAlbedo, dTransmission);\n dReflection = tmpRefl;\n dReflDirW = tmpDir;\n}\n",refractionDynamicPS:"\nuniform float material_refractionIndex;\nuniform float material_invAttenuationDistance;\nuniform vec3 material_attenuation;\n\nvec3 refract2(vec3 viewVec, vec3 Normal, float IOR) {\n float vn = dot(viewVec, Normal);\n float k = 1.0 - IOR * IOR * (1.0 - vn * vn);\n vec3 refrVec = IOR * viewVec - (IOR * vn + sqrt(k)) * Normal;\n return refrVec;\n}\n\nvoid addRefraction() {\n\n // Extract scale from the model transform\n vec3 modelScale;\n modelScale.x = length(vec3(matrix_model[0].xyz));\n modelScale.y = length(vec3(matrix_model[1].xyz));\n modelScale.z = length(vec3(matrix_model[2].xyz));\n\n // Calculate the refraction vector, scaled by the thickness and scale of the object\n vec3 refractionVector = normalize(refract(-dViewDirW, dNormalW, material_refractionIndex)) * dThickness * modelScale;\n\n // The refraction point is the entry point + vector to exit point\n vec4 pointOfRefraction = vec4(vPositionW + refractionVector, 1.0);\n\n // Project to texture space so we can sample it\n vec4 projectionPoint = matrix_viewProjection * pointOfRefraction;\n vec2 uv = projectionPoint.xy / projectionPoint.ww;\n uv += vec2(1.0);\n uv *= vec2(0.5);\n\n #ifdef GL2\n // Use IOR and roughness to select mip\n float iorToRoughness = (1.0 - dGlossiness) * clamp((1.0 / material_refractionIndex) * 2.0 - 2.0, 0.0, 1.0);\n float refractionLod = log2(uScreenSize.x) * iorToRoughness;\n vec3 refraction = texture2DLodEXT(uSceneColorMap, uv, refractionLod).rgb;\n #else\n vec3 refraction = texture2D(uSceneColorMap, uv).rgb;\n #endif\n\n // Transmittance is our final refraction color\n vec3 transmittance;\n if (material_invAttenuationDistance != 0.0)\n {\n vec3 attenuation = -log(material_attenuation) * material_invAttenuationDistance;\n transmittance = exp(-attenuation * length(refractionVector));\n }\n else\n {\n transmittance = refraction;\n }\n\n // Apply fresnel effect on refraction\n vec3 fresnel = vec3(1.0) - getFresnel(dot(dViewDirW, dNormalW), dSpecularity);\n dDiffuseLight = mix(dDiffuseLight, refraction * transmittance * fresnel, dTransmission);\n}\n",reprojectPS:'\n// This shader requires the following #DEFINEs:\n//\n// PROCESS_FUNC - must be one of reproject, prefilter\n// DECODE_FUNC - must be one of decodeRGBM, decodeRGBE, decodeGamma or decodeLinear\n// ENCODE_FUNC - must be one of encodeRGBM, encodeRGBE, encideGamma or encodeLinear\n// SOURCE_FUNC - must be one of sampleCubemap, sampleEquirect, sampleOctahedral\n// TARGET_FUNC - must be one of getDirectionCubemap, getDirectionEquirect, getDirectionOctahedral\n//\n// When filtering:\n// NUM_SAMPLES - number of samples\n// NUM_SAMPLES_SQRT - sqrt of number of samples\n//\n// SUPPORTS_TEXLOD - whether supports texlod is supported\n\nvarying vec2 vUv0;\n\n// source\nuniform sampler2D sourceTex;\nuniform samplerCube sourceCube;\n\n// samples\nuniform sampler2D samplesTex;\nuniform vec2 samplesTexInverseSize;\n\n// params:\n// x - target cubemap face 0..6\n// y - specular power (when prefiltering)\n// z - source cubemap seam scale (0 to disable)\n// w - target cubemap size for seam calc (0 to disable)\nuniform vec4 params;\n\n// params2:\n// x - target image total pixels\n// y - source cubemap size\nuniform vec2 params2;\n\nfloat targetFace() { return params.x; }\nfloat specularPower() { return params.y; }\nfloat sourceCubeSeamScale() { return params.z; }\nfloat targetCubeSeamScale() { return params.w; }\n\nfloat targetTotalPixels() { return params2.x; }\nfloat sourceTotalPixels() { return params2.y; }\n\nfloat PI = 3.141592653589793;\n\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n\n\nvec3 decodeLinear(vec4 raw) {\n return raw.rgb;\n}\n\nfloat decodeGamma(float raw) {\n return pow(raw, 2.2);\n}\n\nvec3 decodeGamma(vec3 raw) {\n return pow(raw, vec3(2.2));\n}\n\nvec3 decodeGamma(vec4 raw) {\n return pow(raw.xyz, vec3(2.2));\n}\n\nvec3 decodeRGBM(vec4 raw) {\n vec3 color = (8.0 * raw.a) * raw.rgb;\n return color * color;\n}\n\nvec3 decodeRGBP(vec4 raw) {\n vec3 color = raw.rgb * (-raw.a * 7.0 + 8.0);\n return color * color;\n}\n\nvec3 decodeRGBE(vec4 raw) {\n if (raw.a == 0.0) {\n return vec3(0.0, 0.0, 0.0);\n } else {\n return raw.xyz * pow(2.0, raw.w * 255.0 - 128.0);\n }\n}\n\nvec4 passThrough(vec4 raw) {\n return raw;\n}\n\n\nvec4 encodeLinear(vec3 source) {\n return vec4(source, 1.0);\n}\n\nvec4 encodeGamma(vec3 source) {\n return vec4(pow(source + 0.0000001, vec3(1.0 / 2.2)), 1.0);\n}\n\nvec4 encodeRGBM(vec3 source) { // modified RGBM\n vec4 result;\n result.rgb = pow(source.rgb, vec3(0.5));\n result.rgb *= 1.0 / 8.0;\n\n result.a = saturate( max( max( result.r, result.g ), max( result.b, 1.0 / 255.0 ) ) );\n result.a = ceil(result.a * 255.0) / 255.0;\n\n result.rgb /= result.a;\n return result;\n}\n\nvec4 encodeRGBP(vec3 source) {\n // convert incoming linear to gamma(ish)\n vec3 gamma = pow(source, vec3(0.5));\n\n // calculate the maximum component clamped to 1..8\n float maxVal = min(8.0, max(1.0, max(gamma.x, max(gamma.y, gamma.z))));\n\n // calculate storage factor\n float v = 1.0 - ((maxVal - 1.0) / 7.0);\n\n // round the value for storage in 8bit channel\n v = ceil(v * 255.0) / 255.0;\n\n return vec4(gamma / (-v * 7.0 + 8.0), v); \n}\n\nvec4 encodeRGBE(vec3 source) {\n float maxVal = max(source.x, max(source.y, source.z));\n if (maxVal < 1e-32) {\n return vec4(0, 0, 0, 0);\n } else {\n float e = ceil(log2(maxVal));\n return vec4(source / pow(2.0, e), (e + 128.0) / 255.0);\n }\n}\n\n\n//-- supported projections\n\nvec3 modifySeams(vec3 dir, float scale) {\n vec3 adir = abs(dir);\n float M = max(max(adir.x, adir.y), adir.z);\n return dir / M * vec3(\n adir.x == M ? 1.0 : scale,\n adir.y == M ? 1.0 : scale,\n adir.z == M ? 1.0 : scale\n );\n}\n\nvec2 toSpherical(vec3 dir) {\n return vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y));\n}\n\nvec3 fromSpherical(vec2 uv) {\n return vec3(cos(uv.y) * sin(uv.x),\n sin(uv.y),\n cos(uv.y) * cos(uv.x));\n}\n\nvec3 getDirectionEquirect() {\n return fromSpherical((vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0) * vec2(PI, PI * 0.5));\n}\n\nvec4 sampleEquirect(vec2 sph) {\n vec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;\n return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n}\n\nvec4 sampleEquirect(vec3 dir) {\n return sampleEquirect(toSpherical(dir));\n}\n\nvec4 sampleCubemap(vec3 dir) {\n return textureCube(sourceCube, modifySeams(dir, 1.0 - sourceCubeSeamScale()));\n}\n\nvec4 sampleCubemap(vec2 sph) {\n return sampleCubemap(fromSpherical(sph));\n}\n\nvec4 sampleEquirect(vec2 sph, float mipLevel) {\n vec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;\n#ifdef SUPPORTS_TEXLOD\n return texture2DLodEXT(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);\n#else\n return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n#endif\n}\n\nvec4 sampleEquirect(vec3 dir, float mipLevel) {\n return sampleEquirect(toSpherical(dir), mipLevel);\n}\n\nvec4 sampleCubemap(vec3 dir, float mipLevel) {\n#ifdef SUPPORTS_TEXLOD\n return textureCubeLodEXT(sourceCube, modifySeams(dir, 1.0 - exp2(mipLevel) * sourceCubeSeamScale()), mipLevel);\n#else\n return textureCube(sourceCube, modifySeams(dir, 1.0 - exp2(mipLevel) * sourceCubeSeamScale()));\n#endif\n}\n\nvec4 sampleCubemap(vec2 sph, float mipLevel) {\n return sampleCubemap(fromSpherical(sph), mipLevel);\n}\n\n// octahedral code, based on http://jcgt.org/published/0003/02/01\n// "Survey of Efficient Representations for Independent Unit Vectors" by Cigolle, Donow, Evangelakos, Mara, McGuire, Meyer\n\nfloat signNotZero(float k){\n return(k >= 0.0) ? 1.0 : -1.0;\n}\n\nvec2 signNotZero(vec2 v) {\n return vec2(signNotZero(v.x), signNotZero(v.y));\n}\n\n// Returns a unit vector. Argument o is an octahedral vector packed via octEncode, on the [-1, +1] square\nvec3 octDecode(vec2 o) {\n vec3 v = vec3(o.x, 1.0 - abs(o.x) - abs(o.y), o.y);\n if (v.y < 0.0) {\n v.xz = (1.0 - abs(v.zx)) * signNotZero(v.xz);\n }\n return normalize(v);\n}\n\nvec3 getDirectionOctahedral() {\n return octDecode(vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0);\n}\n\n// Assumes that v is a unit vector. The result is an octahedral vector on the [-1, +1] square\nvec2 octEncode(in vec3 v) {\n float l1norm = abs(v.x) + abs(v.y) + abs(v.z);\n vec2 result = v.xz * (1.0 / l1norm);\n if (v.y < 0.0) {\n result = (1.0 - abs(result.yx)) * signNotZero(result.xy);\n }\n return result;\n}\n\nvec4 sampleOctahedral(vec3 dir) {\n vec2 uv = octEncode(dir) * 0.5 + 0.5;\n return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n}\n\nvec4 sampleOctahedral(vec2 sph) {\n return sampleOctahedral(fromSpherical(sph));\n}\n\nvec4 sampleOctahedral(vec3 dir, float mipLevel) {\n vec2 uv = octEncode(dir) * 0.5 + 0.5;\n#ifdef SUPPORTS_TEXLOD\n return texture2DLodEXT(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);\n#else\n return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n#endif\n}\n\nvec4 sampleOctahedral(vec2 sph, float mipLevel) {\n return sampleOctahedral(fromSpherical(sph), mipLevel);\n}\n\n/////////////////////////////////////////////////////////////////////\n\nvec3 getDirectionCubemap() {\n vec2 st = vUv0 * 2.0 - 1.0;\n float face = targetFace();\n\n vec3 vec;\n if (face == 0.0) {\n vec = vec3(1, -st.y, -st.x);\n } else if (face == 1.0) {\n vec = vec3(-1, -st.y, st.x);\n } else if (face == 2.0) {\n vec = vec3(st.x, 1, st.y);\n } else if (face == 3.0) {\n vec = vec3(st.x, -1, -st.y);\n } else if (face == 4.0) {\n vec = vec3(st.x, -st.y, 1);\n } else {\n vec = vec3(-st.x, -st.y, -1);\n }\n\n return normalize(modifySeams(vec, 1.0 / (1.0 - targetCubeSeamScale())));\n}\n\nmat3 matrixFromVector(vec3 n) { // frisvad\n float a = 1.0 / (1.0 + n.z);\n float b = -n.x * n.y * a;\n vec3 b1 = vec3(1.0 - n.x * n.x * a, b, -n.x);\n vec3 b2 = vec3(b, 1.0 - n.y * n.y * a, -n.y);\n return mat3(b1, b2, n);\n}\n\nmat3 matrixFromVectorSlow(vec3 n) {\n vec3 up = (1.0 - abs(n.y) <= 0.0000001) ? vec3(0.0, 0.0, n.y > 0.0 ? 1.0 : -1.0) : vec3(0.0, 1.0, 0.0);\n vec3 x = normalize(cross(up, n));\n vec3 y = cross(n, x);\n return mat3(x, y, n);\n}\n\nvec4 reproject() {\n if (NUM_SAMPLES <= 1) {\n // single sample\n return ENCODE_FUNC(DECODE_FUNC(SOURCE_FUNC(TARGET_FUNC())));\n } else {\n // multi sample\n vec3 t = TARGET_FUNC();\n vec3 tu = dFdx(t);\n vec3 tv = dFdy(t);\n\n vec3 result = vec3(0.0);\n for (float u = 0.0; u < NUM_SAMPLES_SQRT; ++u) {\n for (float v = 0.0; v < NUM_SAMPLES_SQRT; ++v) {\n result += DECODE_FUNC(SOURCE_FUNC(normalize(t +\n tu * (u / NUM_SAMPLES_SQRT - 0.5) +\n tv * (v / NUM_SAMPLES_SQRT - 0.5))));\n }\n }\n return ENCODE_FUNC(result / (NUM_SAMPLES_SQRT * NUM_SAMPLES_SQRT));\n }\n}\n\nvec4 unpackFloat = vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0);\n\nvoid unpackSample(int i, out vec3 L, out float mipLevel) {\n float u = (float(i * 4) + 0.5) * samplesTexInverseSize.x;\n float v = (floor(u) + 0.5) * samplesTexInverseSize.y;\n\n vec4 raw;\n raw.x = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n raw.y = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n raw.z = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n raw.w = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat);\n\n L.xyz = raw.xyz * 2.0 - 1.0;\n mipLevel = raw.w * 8.0;\n}\n\n// convolve an environment given pre-generated samples\nvec4 prefilterSamples() {\n // construct vector space given target direction\n mat3 vecSpace = matrixFromVectorSlow(TARGET_FUNC());\n\n vec3 L;\n float mipLevel;\n\n vec3 result = vec3(0.0);\n float totalWeight = 0.0;\n for (int i = 0; i < NUM_SAMPLES; ++i) {\n unpackSample(i, L, mipLevel);\n result += DECODE_FUNC(SOURCE_FUNC(vecSpace * L, mipLevel)) * L.z;\n totalWeight += L.z;\n }\n\n return ENCODE_FUNC(result / totalWeight);\n}\n\n// unweighted version of prefilterSamples\nvec4 prefilterSamplesUnweighted() {\n // construct vector space given target direction\n mat3 vecSpace = matrixFromVectorSlow(TARGET_FUNC());\n\n vec3 L;\n float mipLevel;\n\n vec3 result = vec3(0.0);\n float totalWeight = 0.0;\n for (int i = 0; i < NUM_SAMPLES; ++i) {\n unpackSample(i, L, mipLevel);\n result += DECODE_FUNC(SOURCE_FUNC(vecSpace * L, mipLevel));\n }\n\n return ENCODE_FUNC(result / float(NUM_SAMPLES));\n}\n\nvoid main(void) {\n gl_FragColor = PROCESS_FUNC();\n}\n',screenDepthPS:"\nuniform highp sampler2D uSceneDepthMap;\n\n#ifndef SCREENSIZE\n#define SCREENSIZE\nuniform vec4 uScreenSize;\n#endif\n\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n\n\n\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params; // 1 / camera_far, camera_far, camera_near, is_ortho\n#endif\n\n#ifdef GL2\nfloat linearizeDepth(float z) {\n if (camera_params.w == 0.0)\n return (camera_params.z * camera_params.y) / (camera_params.y + z * (camera_params.z - camera_params.y));\n else\n return camera_params.z + z * (camera_params.y - camera_params.z);\n}\n#else\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n const vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n return dot(rgbaDepth, bitShift);\n}\n#endif\n#endif\n\n// Retrieves rendered linear camera depth by UV\nfloat getLinearScreenDepth(vec2 uv) {\n #ifdef GL2\n return linearizeDepth(texture2D(uSceneDepthMap, uv).r);\n #else\n return unpackFloat(texture2D(uSceneDepthMap, uv)) * camera_params.y;\n #endif\n}\n\n#ifndef VERTEXSHADER\n// Retrieves rendered linear camera depth under the current pixel\nfloat getLinearScreenDepth() {\n vec2 uv = gl_FragCoord.xy * uScreenSize.zw;\n return getLinearScreenDepth(uv);\n}\n#endif\n\n// Generates linear camera depth for the given world position\nfloat getLinearDepth(vec3 pos) {\n return -(matrix_view * vec4(pos, 1.0)).z;\n}\n",shadowCascadesPS:"\nconst float maxCascades = 4.0;\n\n// shadow matrix for selected cascade\nmat4 cascadeShadowMat;\n\n// function which selects a shadow projection matrix based on cascade distances \nvoid getShadowCascadeMatrix(mat4 shadowMatrixPalette[4], float shadowCascadeDistances[4], float shadowCascadeCount) {\n\n // depth in 0 .. far plane range\n float depth = 1.0 / gl_FragCoord.w;\n\n // find cascade index based on the depth (loop as there is no per component vec compare operator in webgl)\n float cascadeIndex = 0.0;\n for (float i = 0.0; i < maxCascades; i++) {\n if (depth < shadowCascadeDistances[int(i)]) {\n cascadeIndex = i;\n break;\n }\n }\n\n // limit to actual number of used cascades\n cascadeIndex = min(cascadeIndex, shadowCascadeCount - 1.0);\n\n // pick shadow matrix\n #ifdef GL2\n cascadeShadowMat = shadowMatrixPalette[int(cascadeIndex)];\n #else\n // webgl 1 does not allow non-cost index array lookup\n if (cascadeIndex == 0.0) {\n cascadeShadowMat = shadowMatrixPalette[0];\n }\n else if (cascadeIndex == 1.0) {\n cascadeShadowMat = shadowMatrixPalette[1];\n }\n else if (cascadeIndex == 2.0) {\n cascadeShadowMat = shadowMatrixPalette[2];\n }\n else {\n cascadeShadowMat = shadowMatrixPalette[3];\n }\n #endif\n}\n\nvoid fadeShadow(float shadowCascadeDistances[4]) { \n\n // if the pixel is past the shadow distance, remove shadow\n // this enforces straight line instead of corner of shadow which moves when camera rotates \n float depth = 1.0 / gl_FragCoord.w;\n if (depth > shadowCascadeDistances[int(maxCascades - 1.0)]) {\n dShadowCoord.z = -9999999.0;\n }\n}\n",shadowCommonPS:"\nvoid normalOffsetPointShadow(vec4 shadowParams) {\n float distScale = length(dLightDirW);\n vec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0) * distScale; //0.02\n vec3 dir = wPos - dLightPosW;\n dLightDirW = dir;\n}\n",shadowCoordPS:"\nvoid _getShadowCoordOrtho(mat4 shadowMatrix, vec3 shadowParams, vec3 wPos) {\n dShadowCoord = (shadowMatrix * vec4(wPos, 1.0)).xyz;\n dShadowCoord.z = saturate(dShadowCoord.z) - 0.0001;\n\n #ifdef SHADOWBIAS\n dShadowCoord.z += getShadowBias(shadowParams.x, shadowParams.z);\n #endif\n}\n\nvoid _getShadowCoordPersp(mat4 shadowMatrix, vec4 shadowParams, vec3 wPos) {\n vec4 projPos = shadowMatrix * vec4(wPos, 1.0);\n projPos.xy /= projPos.w;\n dShadowCoord.xy = projPos.xy;\n dShadowCoord.z = length(dLightDirW) * shadowParams.w;\n\n #ifdef SHADOWBIAS\n dShadowCoord.z += getShadowBias(shadowParams.x, shadowParams.z);\n #endif\n}\n\nvoid getShadowCoordOrtho(mat4 shadowMatrix, vec3 shadowParams) {\n _getShadowCoordOrtho(shadowMatrix, shadowParams, vPositionW);\n}\n\nvoid getShadowCoordPersp(mat4 shadowMatrix, vec4 shadowParams) {\n _getShadowCoordPersp(shadowMatrix, shadowParams, vPositionW);\n}\n\nvoid getShadowCoordPerspNormalOffset(mat4 shadowMatrix, vec4 shadowParams) {\n float distScale = abs(dot(vPositionW - dLightPosW, dLightDirNormW)); // fov?\n vec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0) * distScale;\n\n _getShadowCoordPersp(shadowMatrix, shadowParams, wPos);\n}\n\nvoid getShadowCoordOrthoNormalOffset(mat4 shadowMatrix, vec3 shadowParams) {\n vec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0); //0.08\n\n _getShadowCoordOrtho(shadowMatrix, shadowParams, wPos);\n}\n",shadowCoordPerspZbufferPS:"\nvoid _getShadowCoordPerspZbuffer(mat4 shadowMatrix, vec4 shadowParams, vec3 wPos) {\n vec4 projPos = shadowMatrix * vec4(wPos, 1.0);\n projPos.xyz /= projPos.w;\n dShadowCoord = projPos.xyz;\n // depth bias is already applied on render\n}\n\nvoid getShadowCoordPerspZbufferNormalOffset(mat4 shadowMatrix, vec4 shadowParams) {\n vec3 wPos = vPositionW + dVertexNormalW * shadowParams.y;\n _getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, wPos);\n}\n\nvoid getShadowCoordPerspZbuffer(mat4 shadowMatrix, vec4 shadowParams) {\n _getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, vPositionW);\n}\n",shadowEVSMPS:"\nfloat VSM$(sampler2D tex, vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n vec3 moments = texture2D(tex, texCoords).xyz;\n return calculateEVSM(moments, Z, vsmBias, exponent);\n}\n\nfloat getShadowVSM$(sampler2D shadowMap, vec3 shadowParams, float exponent) {\n return VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, dShadowCoord.z, shadowParams.y, exponent);\n}\n\nfloat getShadowSpotVSM$(sampler2D shadowMap, vec4 shadowParams, float exponent) {\n return VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, length(dLightDirW) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);\n}\n",shadowEVSMnPS:"\nfloat VSM$(sampler2D tex, vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n float pixelSize = 1.0 / resolution;\n texCoords -= vec2(pixelSize);\n vec3 s00 = texture2D(tex, texCoords).xyz;\n vec3 s10 = texture2D(tex, texCoords + vec2(pixelSize, 0)).xyz;\n vec3 s01 = texture2D(tex, texCoords + vec2(0, pixelSize)).xyz;\n vec3 s11 = texture2D(tex, texCoords + vec2(pixelSize)).xyz;\n vec2 fr = fract(texCoords * resolution);\n vec3 h0 = mix(s00, s10, fr.x);\n vec3 h1 = mix(s01, s11, fr.x);\n vec3 moments = mix(h0, h1, fr.y);\n return calculateEVSM(moments, Z, vsmBias, exponent);\n}\n\nfloat getShadowVSM$(sampler2D shadowMap, vec3 shadowParams, float exponent) {\n return VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, dShadowCoord.z, shadowParams.y, exponent);\n}\n\nfloat getShadowSpotVSM$(sampler2D shadowMap, vec4 shadowParams, float exponent) {\n return VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, length(dLightDirW) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);\n}\n",shadowStandardPS:"\nvec3 lessThan2(vec3 a, vec3 b) {\n return clamp((b - a)*1000.0, 0.0, 1.0); // softer version\n}\n\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n const vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n return dot(rgbaDepth, bitShift);\n}\n#endif\n\n// ----- Direct/Spot Sampling -----\n\n#ifdef GL2\nfloat _getShadowPCF3x3(sampler2DShadow shadowMap, vec3 shadowParams) {\n float z = dShadowCoord.z;\n vec2 uv = dShadowCoord.xy * shadowParams.x; // 1 unit - 1 texel\n float shadowMapSizeInv = 1.0 / shadowParams.x;\n vec2 base_uv = floor(uv + 0.5);\n float s = (uv.x + 0.5 - base_uv.x);\n float t = (uv.y + 0.5 - base_uv.y);\n base_uv -= vec2(0.5);\n base_uv *= shadowMapSizeInv;\n\n float sum = 0.0;\n\n float uw0 = (3.0 - 2.0 * s);\n float uw1 = (1.0 + 2.0 * s);\n\n float u0 = (2.0 - s) / uw0 - 1.0;\n float u1 = s / uw1 + 1.0;\n\n float vw0 = (3.0 - 2.0 * t);\n float vw1 = (1.0 + 2.0 * t);\n\n float v0 = (2.0 - t) / vw0 - 1.0;\n float v1 = t / vw1 + 1.0;\n\n u0 = u0 * shadowMapSizeInv + base_uv.x;\n v0 = v0 * shadowMapSizeInv + base_uv.y;\n\n u1 = u1 * shadowMapSizeInv + base_uv.x;\n v1 = v1 * shadowMapSizeInv + base_uv.y;\n\n sum += uw0 * vw0 * texture(shadowMap, vec3(u0, v0, z));\n sum += uw1 * vw0 * texture(shadowMap, vec3(u1, v0, z));\n sum += uw0 * vw1 * texture(shadowMap, vec3(u0, v1, z));\n sum += uw1 * vw1 * texture(shadowMap, vec3(u1, v1, z));\n\n sum *= 1.0f / 16.0;\n return sum;\n}\n\nfloat getShadowPCF3x3(sampler2DShadow shadowMap, vec3 shadowParams) {\n return _getShadowPCF3x3(shadowMap, shadowParams);\n}\n\nfloat getShadowSpotPCF3x3(sampler2DShadow shadowMap, vec4 shadowParams) {\n return _getShadowPCF3x3(shadowMap, shadowParams.xyz);\n}\n#else\nfloat _xgetShadowPCF3x3(mat3 depthKernel, sampler2D shadowMap, vec3 shadowParams) {\n mat3 shadowKernel;\n vec3 shadowCoord = dShadowCoord;\n vec3 shadowZ = vec3(shadowCoord.z);\n shadowKernel[0] = vec3(greaterThan(depthKernel[0], shadowZ));\n shadowKernel[1] = vec3(greaterThan(depthKernel[1], shadowZ));\n shadowKernel[2] = vec3(greaterThan(depthKernel[2], shadowZ));\n\n vec2 fractionalCoord = fract( shadowCoord.xy * shadowParams.x );\n\n shadowKernel[0] = mix(shadowKernel[0], shadowKernel[1], fractionalCoord.x);\n shadowKernel[1] = mix(shadowKernel[1], shadowKernel[2], fractionalCoord.x);\n\n vec4 shadowValues;\n shadowValues.x = mix(shadowKernel[0][0], shadowKernel[0][1], fractionalCoord.y);\n shadowValues.y = mix(shadowKernel[0][1], shadowKernel[0][2], fractionalCoord.y);\n shadowValues.z = mix(shadowKernel[1][0], shadowKernel[1][1], fractionalCoord.y);\n shadowValues.w = mix(shadowKernel[1][1], shadowKernel[1][2], fractionalCoord.y);\n\n return dot( shadowValues, vec4( 1.0 ) ) * 0.25;\n}\n\nfloat _getShadowPCF3x3(sampler2D shadowMap, vec3 shadowParams) {\n vec3 shadowCoord = dShadowCoord;\n\n float xoffset = 1.0 / shadowParams.x; // 1/shadow map width\n float dx0 = -xoffset;\n float dx1 = xoffset;\n\n mat3 depthKernel;\n depthKernel[0][0] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx0, dx0)));\n depthKernel[0][1] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx0, 0.0)));\n depthKernel[0][2] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx0, dx1)));\n depthKernel[1][0] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(0.0, dx0)));\n depthKernel[1][1] = unpackFloat(texture2D(shadowMap, shadowCoord.xy));\n depthKernel[1][2] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(0.0, dx1)));\n depthKernel[2][0] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx1, dx0)));\n depthKernel[2][1] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx1, 0.0)));\n depthKernel[2][2] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx1, dx1)));\n\n return _xgetShadowPCF3x3(depthKernel, shadowMap, shadowParams);\n}\n\nfloat getShadowPCF3x3(sampler2D shadowMap, vec3 shadowParams) {\n return _getShadowPCF3x3(shadowMap, shadowParams);\n}\n\nfloat getShadowSpotPCF3x3(sampler2D shadowMap, vec4 shadowParams) {\n return _getShadowPCF3x3(shadowMap, shadowParams.xyz);\n}\n#endif\n\n\n// ----- Omni Sampling -----\n\nfloat _getShadowPoint(samplerCube shadowMap, vec4 shadowParams, vec3 dir) {\n\n vec3 tc = normalize(dir);\n vec3 tcAbs = abs(tc);\n\n vec4 dirX = vec4(1,0,0, tc.x);\n vec4 dirY = vec4(0,1,0, tc.y);\n float majorAxisLength = tc.z;\n if ((tcAbs.x > tcAbs.y) && (tcAbs.x > tcAbs.z)) {\n dirX = vec4(0,0,1, tc.z);\n dirY = vec4(0,1,0, tc.y);\n majorAxisLength = tc.x;\n } else if ((tcAbs.y > tcAbs.x) && (tcAbs.y > tcAbs.z)) {\n dirX = vec4(1,0,0, tc.x);\n dirY = vec4(0,0,1, tc.z);\n majorAxisLength = tc.y;\n }\n\n float shadowParamsInFaceSpace = ((1.0/shadowParams.x) * 2.0) * abs(majorAxisLength);\n\n vec3 xoffset = (dirX.xyz * shadowParamsInFaceSpace);\n vec3 yoffset = (dirY.xyz * shadowParamsInFaceSpace);\n vec3 dx0 = -xoffset;\n vec3 dy0 = -yoffset;\n vec3 dx1 = xoffset;\n vec3 dy1 = yoffset;\n\n mat3 shadowKernel;\n mat3 depthKernel;\n\n depthKernel[0][0] = unpackFloat(textureCube(shadowMap, tc + dx0 + dy0));\n depthKernel[0][1] = unpackFloat(textureCube(shadowMap, tc + dx0));\n depthKernel[0][2] = unpackFloat(textureCube(shadowMap, tc + dx0 + dy1));\n depthKernel[1][0] = unpackFloat(textureCube(shadowMap, tc + dy0));\n depthKernel[1][1] = unpackFloat(textureCube(shadowMap, tc));\n depthKernel[1][2] = unpackFloat(textureCube(shadowMap, tc + dy1));\n depthKernel[2][0] = unpackFloat(textureCube(shadowMap, tc + dx1 + dy0));\n depthKernel[2][1] = unpackFloat(textureCube(shadowMap, tc + dx1));\n depthKernel[2][2] = unpackFloat(textureCube(shadowMap, tc + dx1 + dy1));\n\n vec3 shadowZ = vec3(length(dir) * shadowParams.w + shadowParams.z);\n\n shadowKernel[0] = vec3(lessThan2(depthKernel[0], shadowZ));\n shadowKernel[1] = vec3(lessThan2(depthKernel[1], shadowZ));\n shadowKernel[2] = vec3(lessThan2(depthKernel[2], shadowZ));\n\n vec2 uv = (vec2(dirX.w, dirY.w) / abs(majorAxisLength)) * 0.5;\n\n vec2 fractionalCoord = fract( uv * shadowParams.x );\n\n shadowKernel[0] = mix(shadowKernel[0], shadowKernel[1], fractionalCoord.x);\n shadowKernel[1] = mix(shadowKernel[1], shadowKernel[2], fractionalCoord.x);\n\n vec4 shadowValues;\n shadowValues.x = mix(shadowKernel[0][0], shadowKernel[0][1], fractionalCoord.y);\n shadowValues.y = mix(shadowKernel[0][1], shadowKernel[0][2], fractionalCoord.y);\n shadowValues.z = mix(shadowKernel[1][0], shadowKernel[1][1], fractionalCoord.y);\n shadowValues.w = mix(shadowKernel[1][1], shadowKernel[1][2], fractionalCoord.y);\n\n return 1.0 - dot( shadowValues, vec4( 1.0 ) ) * 0.25;\n}\n\nfloat getShadowPointPCF3x3(samplerCube shadowMap, vec4 shadowParams) {\n return _getShadowPoint(shadowMap, shadowParams, dLightDirW);\n}\n",shadowStandardGL2PS:"\nfloat _getShadowPCF5x5(sampler2DShadow shadowMap, vec3 shadowParams) {\n // http://the-witness.net/news/2013/09/shadow-mapping-summary-part-1/\n\n float z = dShadowCoord.z;\n vec2 uv = dShadowCoord.xy * shadowParams.x; // 1 unit - 1 texel\n float shadowMapSizeInv = 1.0 / shadowParams.x;\n vec2 base_uv = floor(uv + 0.5);\n float s = (uv.x + 0.5 - base_uv.x);\n float t = (uv.y + 0.5 - base_uv.y);\n base_uv -= vec2(0.5);\n base_uv *= shadowMapSizeInv;\n\n\n float uw0 = (4.0 - 3.0 * s);\n float uw1 = 7.0;\n float uw2 = (1.0 + 3.0 * s);\n\n float u0 = (3.0 - 2.0 * s) / uw0 - 2.0;\n float u1 = (3.0 + s) / uw1;\n float u2 = s / uw2 + 2.0;\n\n float vw0 = (4.0 - 3.0 * t);\n float vw1 = 7.0;\n float vw2 = (1.0 + 3.0 * t);\n\n float v0 = (3.0 - 2.0 * t) / vw0 - 2.0;\n float v1 = (3.0 + t) / vw1;\n float v2 = t / vw2 + 2.0;\n\n float sum = 0.0;\n\n u0 = u0 * shadowMapSizeInv + base_uv.x;\n v0 = v0 * shadowMapSizeInv + base_uv.y;\n\n u1 = u1 * shadowMapSizeInv + base_uv.x;\n v1 = v1 * shadowMapSizeInv + base_uv.y;\n\n u2 = u2 * shadowMapSizeInv + base_uv.x;\n v2 = v2 * shadowMapSizeInv + base_uv.y;\n\n sum += uw0 * vw0 * texture(shadowMap, vec3(u0, v0, z));\n sum += uw1 * vw0 * texture(shadowMap, vec3(u1, v0, z));\n sum += uw2 * vw0 * texture(shadowMap, vec3(u2, v0, z));\n\n sum += uw0 * vw1 * texture(shadowMap, vec3(u0, v1, z));\n sum += uw1 * vw1 * texture(shadowMap, vec3(u1, v1, z));\n sum += uw2 * vw1 * texture(shadowMap, vec3(u2, v1, z));\n\n sum += uw0 * vw2 * texture(shadowMap, vec3(u0, v2, z));\n sum += uw1 * vw2 * texture(shadowMap, vec3(u1, v2, z));\n sum += uw2 * vw2 * texture(shadowMap, vec3(u2, v2, z));\n\n sum *= 1.0f / 144.0;\n\n sum = gammaCorrectInput(sum); // gives softer gradient\n sum = saturate(sum);\n\n return sum;\n}\n\nfloat getShadowPCF5x5(sampler2DShadow shadowMap, vec3 shadowParams) {\n return _getShadowPCF5x5(shadowMap, shadowParams);\n}\n\nfloat getShadowSpotPCF5x5(sampler2DShadow shadowMap, vec4 shadowParams) {\n return _getShadowPCF5x5(shadowMap, shadowParams.xyz);\n}\n",shadowVSM8PS:"\nfloat calculateVSM8(vec3 moments, float Z, float vsmBias) {\n float VSMBias = vsmBias;//0.01 * 0.25;\n float depthScale = VSMBias * Z;\n float minVariance1 = depthScale * depthScale;\n return chebyshevUpperBound(moments.xy, Z, minVariance1, 0.1);\n}\n\nfloat decodeFloatRG(vec2 rg) {\n return rg.y*(1.0/255.0) + rg.x;\n}\n\nfloat VSM8(sampler2D tex, vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n vec4 c = texture2D(tex, texCoords);\n vec3 moments = vec3(decodeFloatRG(c.xy), decodeFloatRG(c.zw), 0.0);\n return calculateVSM8(moments, Z, vsmBias);\n}\n\nfloat getShadowVSM8(sampler2D shadowMap, vec3 shadowParams, float exponent) {\n return VSM8(shadowMap, dShadowCoord.xy, shadowParams.x, dShadowCoord.z, shadowParams.y, 0.0);\n}\n\nfloat getShadowSpotVSM8(sampler2D shadowMap, vec4 shadowParams, float exponent) {\n return VSM8(shadowMap, dShadowCoord.xy, shadowParams.x, length(dLightDirW) * shadowParams.w + shadowParams.z, shadowParams.y, 0.0);\n}\n",shadowVSM_commonPS:"\nfloat linstep(float a, float b, float v) {\n return saturate((v - a) / (b - a));\n}\n\nfloat reduceLightBleeding(float pMax, float amount) {\n // Remove the [0, amount] tail and linearly rescale (amount, 1].\n return linstep(amount, 1.0, pMax);\n}\n\nfloat chebyshevUpperBound(vec2 moments, float mean, float minVariance, float lightBleedingReduction) {\n // Compute variance\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, minVariance);\n\n // Compute probabilistic upper bound\n float d = mean - moments.x;\n float pMax = variance / (variance + (d * d));\n\n pMax = reduceLightBleeding(pMax, lightBleedingReduction);\n\n // One-tailed Chebyshev\n return (mean <= moments.x ? 1.0 : pMax);\n}\n\nfloat calculateEVSM(vec3 moments, float Z, float vsmBias, float exponent) {\n Z = 2.0 * Z - 1.0;\n float warpedDepth = exp(exponent * Z);\n\n moments.xy += vec2(warpedDepth, warpedDepth*warpedDepth) * (1.0 - moments.z);\n\n float VSMBias = vsmBias;//0.01 * 0.25;\n float depthScale = VSMBias * exponent * warpedDepth;\n float minVariance1 = depthScale * depthScale;\n return chebyshevUpperBound(moments.xy, warpedDepth, minVariance1, 0.1);\n}\n",skinBatchConstVS:"\nattribute float vertex_boneIndices;\n\nuniform vec4 matrix_pose[BONE_LIMIT * 3];\n\nmat4 getBoneMatrix(const in float i) {\n // read 4x3 matrix\n vec4 v1 = matrix_pose[int(3.0 * i)];\n vec4 v2 = matrix_pose[int(3.0 * i + 1.0)];\n vec4 v3 = matrix_pose[int(3.0 * i + 2.0)];\n\n // transpose to 4x4 matrix\n return mat4(\n v1.x, v2.x, v3.x, 0,\n v1.y, v2.y, v3.y, 0,\n v1.z, v2.z, v3.z, 0,\n v1.w, v2.w, v3.w, 1\n );\n}\n",skinBatchTexVS:"\nattribute float vertex_boneIndices;\n\nuniform highp sampler2D texture_poseMap;\nuniform vec4 texture_poseMapSize;\n\nmat4 getBoneMatrix(const in float i) {\n float j = i * 3.0;\n float dx = texture_poseMapSize.z;\n float dy = texture_poseMapSize.w;\n\n float y = floor(j * dx);\n float x = j - (y * texture_poseMapSize.x);\n y = dy * (y + 0.5);\n\n // read elements of 4x3 matrix\n vec4 v1 = texture2D(texture_poseMap, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(texture_poseMap, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(texture_poseMap, vec2(dx * (x + 2.5), y));\n\n // transpose to 4x4 matrix\n return mat4(\n v1.x, v2.x, v3.x, 0,\n v1.y, v2.y, v3.y, 0,\n v1.z, v2.z, v3.z, 0,\n v1.w, v2.w, v3.w, 1\n );\n}\n",skinConstVS:"\nattribute vec4 vertex_boneWeights;\nattribute vec4 vertex_boneIndices;\n\nuniform vec4 matrix_pose[BONE_LIMIT * 3];\n\nvoid getBoneMatrix(const in float i, out vec4 v1, out vec4 v2, out vec4 v3) {\n // read 4x3 matrix\n v1 = matrix_pose[int(3.0 * i)];\n v2 = matrix_pose[int(3.0 * i + 1.0)];\n v3 = matrix_pose[int(3.0 * i + 2.0)];\n}\n\nmat4 getSkinMatrix(const in vec4 indices, const in vec4 weights) {\n // get 4 bone matrices\n vec4 a1, a2, a3;\n getBoneMatrix(indices.x, a1, a2, a3);\n\n vec4 b1, b2, b3;\n getBoneMatrix(indices.y, b1, b2, b3);\n\n vec4 c1, c2, c3;\n getBoneMatrix(indices.z, c1, c2, c3);\n\n vec4 d1, d2, d3;\n getBoneMatrix(indices.w, d1, d2, d3);\n\n // multiply them by weights and add up to get final 4x3 matrix\n vec4 v1 = a1 * weights.x + b1 * weights.y + c1 * weights.z + d1 * weights.w;\n vec4 v2 = a2 * weights.x + b2 * weights.y + c2 * weights.z + d2 * weights.w;\n vec4 v3 = a3 * weights.x + b3 * weights.y + c3 * weights.z + d3 * weights.w;\n\n // add up weights\n float one = dot(weights, vec4(1.0));\n\n // transpose to 4x4 matrix\n return mat4(\n v1.x, v2.x, v3.x, 0,\n v1.y, v2.y, v3.y, 0,\n v1.z, v2.z, v3.z, 0,\n v1.w, v2.w, v3.w, one\n );\n}\n",skinTexVS:"\nattribute vec4 vertex_boneWeights;\nattribute vec4 vertex_boneIndices;\n\nuniform highp sampler2D texture_poseMap;\nuniform vec4 texture_poseMapSize;\n\nvoid getBoneMatrix(const in float i, out vec4 v1, out vec4 v2, out vec4 v3) {\n float j = i * 3.0;\n float dx = texture_poseMapSize.z;\n float dy = texture_poseMapSize.w;\n \n float y = floor(j * dx);\n float x = j - (y * texture_poseMapSize.x);\n y = dy * (y + 0.5);\n\n // read elements of 4x3 matrix\n v1 = texture2D(texture_poseMap, vec2(dx * (x + 0.5), y));\n v2 = texture2D(texture_poseMap, vec2(dx * (x + 1.5), y));\n v3 = texture2D(texture_poseMap, vec2(dx * (x + 2.5), y));\n}\n\nmat4 getSkinMatrix(const in vec4 indices, const in vec4 weights) {\n // get 4 bone matrices\n vec4 a1, a2, a3;\n getBoneMatrix(indices.x, a1, a2, a3);\n\n vec4 b1, b2, b3;\n getBoneMatrix(indices.y, b1, b2, b3);\n\n vec4 c1, c2, c3;\n getBoneMatrix(indices.z, c1, c2, c3);\n\n vec4 d1, d2, d3;\n getBoneMatrix(indices.w, d1, d2, d3);\n\n // multiply them by weights and add up to get final 4x3 matrix\n vec4 v1 = a1 * weights.x + b1 * weights.y + c1 * weights.z + d1 * weights.w;\n vec4 v2 = a2 * weights.x + b2 * weights.y + c2 * weights.z + d2 * weights.w;\n vec4 v3 = a3 * weights.x + b3 * weights.y + c3 * weights.z + d3 * weights.w;\n\n // add up weights\n float one = dot(weights, vec4(1.0));\n\n // transpose to 4x4 matrix\n return mat4(\n v1.x, v2.x, v3.x, 0,\n v1.y, v2.y, v3.y, 0,\n v1.z, v2.z, v3.z, 0,\n v1.w, v2.w, v3.w, one\n );\n}\n",skyboxEnvPS:"\nvarying vec3 vViewDir;\n\nuniform sampler2D texture_envAtlas;\nuniform float mipLevel;\n\nvoid main(void) {\n vec3 dir = vViewDir * vec3(-1.0, 1.0, 1.0);\n vec2 uv = toSphericalUv(normalize(dir));\n\n vec3 linear = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, mipLevel)));\n\n gl_FragColor = vec4(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0);\n}\n",skyboxHDRPS:"\nvarying vec3 vViewDir;\n\nuniform samplerCube texture_cubeMap;\n\nvoid main(void) {\n vec3 dir=vViewDir;\n dir.x *= -1.0;\n\n vec3 linear = $DECODE(textureCube(texture_cubeMap, fixSeamsStatic(dir, $FIXCONST)));\n\n gl_FragColor = vec4(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0);\n}\n",skyboxVS:"\nattribute vec3 aPosition;\n\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n\nuniform mat4 matrix_projectionSkybox;\nuniform mat3 cubeMapRotationMatrix;\n\nvarying vec3 vViewDir;\n\nvoid main(void) {\n mat4 view = matrix_view;\n view[3][0] = view[3][1] = view[3][2] = 0.0;\n gl_Position = matrix_projectionSkybox * view * vec4(aPosition, 1.0);\n\n // Force skybox to far Z, regardless of the clip planes on the camera\n // Subtract a tiny fudge factor to ensure floating point errors don't\n // still push pixels beyond far Z. See:\n // http://www.opengl.org/discussion_boards/showthread.php/171867-skybox-problem\n\n gl_Position.z = gl_Position.w - 0.00001;\n vViewDir = aPosition * cubeMapRotationMatrix;\n}\n",specularPS:"\n\n#ifdef MAPCOLOR\nuniform vec3 material_specular;\n#endif\n\nvoid getSpecularity() {\n vec3 specularColor = vec3(1,1,1);\n\n #ifdef MAPCOLOR\n specularColor *= material_specular;\n #endif\n\n #ifdef MAPTEXTURE\n specularColor *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n #endif\n\n #ifdef MAPVERTEX\n specularColor *= saturate(vVertexColor.$VC);\n #endif\n\n dSpecularity = specularColor;\n}\n",sphericalPS:"\n// equirectangular helper functions\nconst float PI = 3.141592653589793;\n\nvec2 toSpherical(vec3 dir) {\n return vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y));\n}\n\nvec2 toSphericalUv(vec3 dir) {\n vec2 uv = toSpherical(dir) / vec2(PI * 2.0, PI) + 0.5;\n return vec2(uv.x, 1.0 - uv.y);\n}\n",specularityFactorPS:"\n\n#ifdef MAPFLOAT\nuniform float material_specularityFactor;\n#endif\n\nvoid getSpecularityFactor() {\n float specularityFactor = 1.0;\n\n #ifdef MAPFLOAT\n specularityFactor *= material_specularityFactor;\n #endif\n\n #ifdef MAPTEXTURE\n specularityFactor *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n specularityFactor *= saturate(vVertexColor.$VC);\n #endif\n\n dSpecularityFactor = specularityFactor;\n}\n",spotPS:"\nfloat getSpotEffect(vec3 lightSpotDirW, float lightInnerConeAngle, float lightOuterConeAngle) {\n float cosAngle = dot(dLightDirNormW, lightSpotDirW);\n return smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle);\n}\n",startPS:"\nvoid main(void) {\n dReflection = vec4(0);\n\n #ifdef LIT_CLEARCOAT\n ccSpecularLight = vec3(0);\n ccReflection = vec3(0);\n #endif\n",startVS:"\nvoid main(void) {\n gl_Position = getPosition();\n",startNineSlicedPS:"\n nineSlicedUv = vUv0;\n nineSlicedUv.y = 1.0 - nineSlicedUv.y;\n\n",startNineSlicedTiledPS:"\n vec2 tileMask = step(vMask, vec2(0.99999));\n vec2 tileSize = 0.5 * (innerOffset.xy + innerOffset.zw);\n vec2 tileScale = vec2(1.0) / (vec2(1.0) - tileSize);\n vec2 clampedUv = mix(innerOffset.xy * 0.5, vec2(1.0) - innerOffset.zw * 0.5, fract((vTiledUv - tileSize) * tileScale));\n clampedUv = clampedUv * atlasRect.zw + atlasRect.xy;\n nineSlicedUv = vUv0 * tileMask + clampedUv * (vec2(1.0) - tileMask);\n nineSlicedUv.y = 1.0 - nineSlicedUv.y;\n \n",storeEVSMPS:"\nfloat exponent = VSM_EXPONENT;\n\ndepth = 2.0 * depth - 1.0;\ndepth = exp(exponent * depth);\ngl_FragColor = vec4(depth, depth*depth, 1.0, 1.0);\n",tangentBinormalVS:"\nvec3 getTangent() {\n return normalize(dNormalMatrix * vertex_tangent.xyz);\n}\n\nvec3 getBinormal() {\n return cross(vNormalW, vTangentW) * vertex_tangent.w;\n}\n\nvec3 getObjectSpaceUp() {\n return normalize(dNormalMatrix * vec3(0, 1, 0));\n}\n",TBNPS:"\nvoid getTBN() {\n dTBN = mat3(normalize(dTangentW), normalize(dBinormalW), normalize(dVertexNormalW));\n}\n",TBNderivativePS:"\nuniform float tbnBasis;\n\n// http://www.thetenthplanet.de/archives/1180\nvoid getTBN() {\n vec2 uv = $UV;\n\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx( vPositionW );\n vec3 dp2 = dFdy( vPositionW );\n vec2 duv1 = dFdx( uv );\n vec2 duv2 = dFdy( uv );\n\n // solve the linear system\n vec3 dp2perp = cross( dp2, dVertexNormalW );\n vec3 dp1perp = cross( dVertexNormalW, dp1 );\n vec3 T = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 B = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame\n float denom = max( dot(T,T), dot(B,B) );\n float invmax = (denom == 0.0) ? 0.0 : tbnBasis / sqrt( denom );\n dTBN = mat3(T * invmax, -B * invmax, dVertexNormalW );\n}\n",TBNfastPS:"\nvoid getTBN() {\n dTBN = mat3(dTangentW, dBinormalW, dVertexNormalW);\n}\n",TBNObjectSpacePS:"\nvoid getTBN() {\n\n vec3 B = cross(dVertexNormalW, vObjectSpaceUpW);\n vec3 T = cross(dVertexNormalW, B);\n\n if (dot(B,B)==0.0) // deal with case when vObjectSpaceUpW dVertexNormalW are parallel\n {\n float major=max(max(dVertexNormalW.x, dVertexNormalW.y),dVertexNormalW.z);\n\n if (dVertexNormalW.x==major)\n {\n B=cross(dVertexNormalW, vec3(0,1,0));\n T=cross(dVertexNormalW, B);\n }\n else if (dVertexNormalW.y==major)\n {\n B=cross(dVertexNormalW, vec3(0,0,1));\n T=cross(dVertexNormalW, B);\n }\n else if (dVertexNormalW.z==major)\n {\n B=cross(dVertexNormalW, vec3(1,0,0));\n T=cross(dVertexNormalW, B);\n }\n }\n\n dTBN = mat3(normalize(T), normalize(B), normalize(dVertexNormalW));\n}\n",textureSamplePS:"\nvec4 texture2DSRGB(sampler2D tex, vec2 uv) {\n return gammaCorrectInput(texture2D(tex, uv));\n}\n\nvec4 texture2DSRGB(sampler2D tex, vec2 uv, float bias) {\n return gammaCorrectInput(texture2D(tex, uv, bias));\n}\n\nvec3 texture2DRGBM(sampler2D tex, vec2 uv) {\n return decodeRGBM(texture2D(tex, uv));\n}\n\nvec3 texture2DRGBM(sampler2D tex, vec2 uv, float bias) {\n return decodeRGBM(texture2D(tex, uv, bias));\n}\n\nvec3 texture2DRGBE(sampler2D tex, vec2 uv) {\n return decodeRGBM(texture2D(tex, uv));\n}\n\nvec3 texture2DRGBE(sampler2D tex, vec2 uv, float bias) {\n return decodeRGBM(texture2D(tex, uv, bias));\n}\n",thicknessPS:"\n#ifdef MAPFLOAT\nuniform float material_thickness;\n#endif\n\nvoid getThickness() {\n dThickness = 1.0;\n\n #ifdef MAPFLOAT\n dThickness *= material_thickness;\n #endif\n\n #ifdef MAPTEXTURE\n dThickness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n dThickness *= saturate(vVertexColor.$VC);\n #endif\n}\n",tonemappingAcesPS:"\nuniform float exposure;\n\nvec3 toneMap(vec3 color) {\n float tA = 2.51;\n float tB = 0.03;\n float tC = 2.43;\n float tD = 0.59;\n float tE = 0.14;\n vec3 x = color * exposure;\n return (x*(tA*x+tB))/(x*(tC*x+tD)+tE);\n}\n",tonemappingAces2PS:"\nuniform float exposure;\n\n// ACES approximation by Stephen Hill\n\n// sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT\nconst mat3 ACESInputMat = mat3(\n 0.59719, 0.35458, 0.04823,\n 0.07600, 0.90834, 0.01566,\n 0.02840, 0.13383, 0.83777\n);\n\n// ODT_SAT => XYZ => D60_2_D65 => sRGB\nconst mat3 ACESOutputMat = mat3(\n 1.60475, -0.53108, -0.07367,\n -0.10208, 1.10813, -0.00605,\n -0.00327, -0.07276, 1.07602\n);\n\nvec3 RRTAndODTFit(vec3 v) {\n vec3 a = v * (v + 0.0245786) - 0.000090537;\n vec3 b = v * (0.983729 * v + 0.4329510) + 0.238081;\n return a / b;\n}\n\nvec3 toneMap(vec3 color) {\n color *= exposure;\n color = color * ACESInputMat;\n\n // Apply RRT and ODT\n color = RRTAndODTFit(color);\n color = color * ACESOutputMat;\n\n // Clamp to [0, 1]\n color = clamp(color, 0.0, 1.0);\n\n return color;\n}\n",tonemappingFilmicPS:"\nconst float A = 0.15;\nconst float B = 0.50;\nconst float C = 0.10;\nconst float D = 0.20;\nconst float E = 0.02;\nconst float F = 0.30;\nconst float W = 11.2;\n\nuniform float exposure;\n\nvec3 uncharted2Tonemap(vec3 x) {\n return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\n}\n\nvec3 toneMap(vec3 color) {\n color = uncharted2Tonemap(color * exposure);\n vec3 whiteScale = 1.0 / uncharted2Tonemap(vec3(W,W,W));\n color = color * whiteScale;\n\n return color;\n}\n",tonemappingHejlPS:"\nuniform float exposure;\n\nvec3 toneMap(vec3 color) {\n color *= exposure;\n const float A = 0.22, B = 0.3, C = .1, D = 0.2, E = .01, F = 0.3;\n const float Scl = 1.25;\n\n vec3 h = max( vec3(0.0), color - vec3(0.004) );\n return (h*((Scl*A)*h+Scl*vec3(C*B,C*B,C*B))+Scl*vec3(D*E,D*E,D*E)) / (h*(A*h+vec3(B,B,B))+vec3(D*F,D*F,D*F)) - Scl*vec3(E/F,E/F,E/F);\n}\n",tonemappingLinearPS:"\nuniform float exposure;\n\nvec3 toneMap(vec3 color) {\n return color * exposure;\n}\n",tonemappingNonePS:"\nvec3 toneMap(vec3 color) {\n return color;\n}\n",transformVS:"\n#ifdef PIXELSNAP\nuniform vec4 uScreenSize;\n#endif\n\n#ifdef SCREENSPACE\nuniform float projectionFlipY;\n#endif\n\n#ifdef MORPHING\nuniform vec4 morph_weights_a;\nuniform vec4 morph_weights_b;\n#endif\n\n#ifdef MORPHING_TEXTURE_BASED\nuniform vec4 morph_tex_params;\n\nvec2 getTextureMorphCoords() {\n float vertexId = morph_vertex_id;\n vec2 textureSize = morph_tex_params.xy;\n vec2 invTextureSize = morph_tex_params.zw;\n\n // turn vertexId into int grid coordinates\n float morphGridV = floor(vertexId * invTextureSize.x);\n float morphGridU = vertexId - (morphGridV * textureSize.x);\n\n // convert grid coordinates to uv coordinates with half pixel offset\n return (vec2(morphGridU, morphGridV) * invTextureSize) + (0.5 * invTextureSize);\n}\n#endif\n\n#ifdef MORPHING_TEXTURE_BASED_POSITION\nuniform highp sampler2D morphPositionTex;\n#endif\n\nmat4 getModelMatrix() {\n #ifdef DYNAMICBATCH\n return getBoneMatrix(vertex_boneIndices);\n #elif defined(SKIN)\n return matrix_model * getSkinMatrix(vertex_boneIndices, vertex_boneWeights);\n #elif defined(INSTANCING)\n return mat4(instance_line1, instance_line2, instance_line3, instance_line4);\n #else\n return matrix_model;\n #endif\n}\n\nvec4 getPosition() {\n dModelMatrix = getModelMatrix();\n vec3 localPos = vertex_position;\n\n #ifdef NINESLICED\n // outer and inner vertices are at the same position, scale both\n localPos.xz *= outerScale;\n\n // offset inner vertices inside\n // (original vertices must be in [-1;1] range)\n vec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0));\n vec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0));\n localPos.xz += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;\n\n vTiledUv = (localPos.xz - outerScale + innerOffset.xy) * -0.5 + 1.0; // uv = local pos - inner corner\n\n localPos.xz *= -0.5; // move from -1;1 to -0.5;0.5\n localPos = localPos.xzy;\n #endif\n\n #ifdef MORPHING\n #ifdef MORPHING_POS03\n localPos.xyz += morph_weights_a[0] * morph_pos0;\n localPos.xyz += morph_weights_a[1] * morph_pos1;\n localPos.xyz += morph_weights_a[2] * morph_pos2;\n localPos.xyz += morph_weights_a[3] * morph_pos3;\n #endif // MORPHING_POS03\n #ifdef MORPHING_POS47\n localPos.xyz += morph_weights_b[0] * morph_pos4;\n localPos.xyz += morph_weights_b[1] * morph_pos5;\n localPos.xyz += morph_weights_b[2] * morph_pos6;\n localPos.xyz += morph_weights_b[3] * morph_pos7;\n #endif // MORPHING_POS47\n #endif // MORPHING\n\n #ifdef MORPHING_TEXTURE_BASED_POSITION\n // apply morph offset from texture\n vec2 morphUV = getTextureMorphCoords();\n vec3 morphPos = texture2D(morphPositionTex, morphUV).xyz;\n localPos += morphPos;\n #endif\n\n vec4 posW = dModelMatrix * vec4(localPos, 1.0);\n #ifdef SCREENSPACE\n posW.zw = vec2(0.0, 1.0);\n #endif\n dPositionW = posW.xyz;\n\n vec4 screenPos;\n #ifdef UV1LAYOUT\n screenPos = vec4(vertex_texCoord1.xy * 2.0 - 1.0, 0.5, 1);\n #else\n #ifdef SCREENSPACE\n screenPos = posW;\n screenPos.y *= projectionFlipY;\n #else\n screenPos = matrix_viewProjection * posW;\n #endif\n\n #ifdef PIXELSNAP\n // snap vertex to a pixel boundary\n screenPos.xy = (screenPos.xy * 0.5) + 0.5;\n screenPos.xy *= uScreenSize.xy;\n screenPos.xy = floor(screenPos.xy);\n screenPos.xy *= uScreenSize.zw;\n screenPos.xy = (screenPos.xy * 2.0) - 1.0;\n #endif\n #endif\n\n return screenPos;\n}\n\nvec3 getWorldPosition() {\n return dPositionW;\n}\n",transformDeclVS:"\nattribute vec3 vertex_position;\n\nuniform mat4 matrix_model;\nuniform mat4 matrix_viewProjection;\n\nvec3 dPositionW;\nmat4 dModelMatrix;\n",transmissionPS:"\n\n#ifdef MAPFLOAT\nuniform float material_refraction;\n#endif\n\nvoid getRefraction() {\n float refraction = 1.0;\n\n #ifdef MAPFLOAT\n refraction = material_refraction;\n #endif\n\n #ifdef MAPTEXTURE\n refraction *= gammaCorrectInput(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n #endif\n\n #ifdef MAPVERTEX\n refraction *= saturate(vVertexColor.$VC);\n #endif\n\n dTransmission = refraction;\n}\n",uv0VS:"\n#ifdef NINESLICED\nvec2 getUv0() {\n vec2 uv = vertex_position.xz;\n\n // offset inner vertices inside\n // (original vertices must be in [-1;1] range)\n vec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0));\n vec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0));\n uv += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;\n\n uv = uv * -0.5 + 0.5;\n uv = uv * atlasRect.zw + atlasRect.xy;\n\n vMask = vertex_texCoord0.xy;\n\n return uv;\n}\n#else\nvec2 getUv0() {\n return vertex_texCoord0;\n}\n#endif\n",uv1VS:"\nvec2 getUv1() {\n return vertex_texCoord1;\n}\n",viewDirPS:"\nvoid getViewDir() {\n dViewDirW = normalize(view_position - vPositionW);\n}\n",viewNormalVS:"\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n\nvec3 getViewNormal() {\n return mat3(matrix_view) * vNormalW;\n}\n",webgpuPS:"\n\nlayout(location = 0) out highp vec4 pc_fragColor;\n#define gl_FragColor pc_fragColor\n\n#define texture2D(res, uv) texture(sampler2D(res, res ## _sampler), uv)\n#define texture2DBias(res, uv, bias) texture(sampler2D(res, res ## _sampler), uv, bias)\n#define texture2DLodEXT(res, uv, lod) textureLod(sampler2D(res, res ## _sampler), uv, lod)\n\n// TODO: implement other texture sampling macros\n// #define textureCube texture\n// #define texture2DProj textureProj\n// #define texture2DProjLodEXT textureProjLod\n// #define textureCubeLodEXT textureLod\n// #define texture2DGradEXT textureGrad\n// #define texture2DProjGradEXT textureProjGrad\n// #define textureCubeGradEXT textureGrad\n#define GL2\n#define SUPPORTS_TEXLOD\n",webgpuVS:"\n#define texture2D(res, uv) texture(sampler2D(res, res ## _sampler), uv)\n\n#define GL2\n#define VERTEXSHADER\n"},Hi=function(){function e(){}return e.getType=function(e){switch(e){case 0:case 1:return Ye;case 2:return Ke;case 3:return Ze;default:return e>=4&&e<22?$e:Ye}},e.isForward=function(e){return this.getType(e)===Ye},e.isShadow=function(e){return this.getType(e)===$e},e.toLightType=function(e){var t=e-4;return Math.floor(t/6)},e.toShadowType=function(e){var t=e-4;return t-6*Math.floor(t/6)},e.getShadow=function(e,t){return 4+(t+6*e)},e.getPassShaderDefine=function(t){return 3===t?"#define PICK_PASS\n":2===t?"#define DEPTH_PASS\n":e.isShadow(t)?"#define SHADOW_PASS\n":""},e}();function Xi(e,t){return t||(t=Wi),1===e||2===e?t.gamma2_2PS?t.gamma2_2PS:Wi.gamma2_2PS:3===e?"#define HDR\n"+(t.gamma2_2PS?t.gamma2_2PS:Wi.gamma2_2PS):t.gamma1_0PS?t.gamma1_0PS:Wi.gamma1_0PS}function qi(e,t){return t||(t=Wi),1===e?t.tonemappingFilmicPS?t.tonemappingFilmicPS:Wi.tonemappingFilmicPS:0===e?t.tonemappingLinearPS?t.tonemappingLinearPS:Wi.tonemappingLinearPS:2===e?t.tonemappingHejlPS?t.tonemappingHejlPS:Wi.tonemappingHejlPS:3===e?t.tonemappingAcesPS?t.tonemappingAcesPS:Wi.tonemappingAcesPS:4===e?t.tonemappingAces2PS?t.tonemappingAces2PS:Wi.tonemappingAces2PS:t.tonemapingNonePS?t.tonemapingNonePS:Wi.tonemappingNonePS}function ji(e,t){return t||(t=Wi),"linear"===e?t.fogLinearPS?t.fogLinearPS:Wi.fogLinearPS:"exp"===e?t.fogExpPS?t.fogExpPS:Wi.fogExpPS:"exp2"===e?t.fogExp2PS?t.fogExp2PS:Wi.fogExp2PS:t.fogNonePS?t.fogNonePS:Wi.fogNonePS}function Yi(e,t){return t||(t=Wi),e.supportsBoneTextures?t.skinTexVS:"#define BONE_LIMIT "+e.getBoneLimit()+"\n"+t.skinConstVS}function Ki(e,t,i){var n="";if(e.deviceType===li){t&&"highp"!==t&&"mediump"!==t&&"lowp"!==t&&(t=null),t&&("highp"===t&&"highp"!==e.maxPrecision&&(t="mediump"),"mediump"===t&&"lowp"===e.maxPrecision&&(t="lowp"));var s=t||e.precision;n="precision "+s+" float;\n",i&&e.webgl2&&(n+="precision "+s+" sampler2DShadow;\n")}return n}function Zi(e){return e.deviceType===ci?"#version 450\n":e.webgl2?"#version 300 es\n":""}function $i(e){return"#define SHADER_NAME "+e+"\n"}function Qi(e,t,i,n){var s=Zi(e);return e.deviceType===ci?s+=Wi.webgpuVS:(n&&(s+=n+"\n"),e.webgl2&&(s+=Wi.gles3VS)),s+=$i(t),s+=Hi.getPassShaderDefine(i)}function Ji(e,t,i,n,s){var r=Zi(e);return e.deviceType===ci?r+=Wi.webgpuPS:(n&&(r+=n+"\n"),e.webgl2?r+=Wi.gles3PS:(e.extStandardDerivatives&&(r+="#extension GL_OES_standard_derivatives : enable\n"),e.extTextureLod&&(r+="#extension GL_EXT_shader_texture_lod : enable\n",r+="#define SUPPORTS_TEXLOD\n"),r+=Wi.gles2PS)),r+=Ki(e,s,!0),r+=$i(t),r+=Hi.getPassShaderDefine(i)}function en(){return"void main(void) {gl_FragColor = vec4(0.0);}"}function tn(){return"void main(void)\n{\n"}function nn(){return"}\n"}var sn={vertex_position:vt,vertex_normal:yt,vertex_tangent:xt,vertex_texCoord0:At,vertex_texCoord1:Mt,vertex_texCoord2:Ct,vertex_texCoord3:Et,vertex_texCoord4:Pt,vertex_texCoord5:Rt,vertex_texCoord6:It,vertex_texCoord7:Lt,vertex_color:wt,vertex_boneIndices:St,vertex_boneWeights:bt};function rn(e){for(var t={},i=0,n=e.indexOf("attribute");n>=0&&!(n>0&&"/"===e[n-1]);){var s=e.indexOf(";",n),r=e.lastIndexOf(" ",s),a=e.substring(r+1,s),o=sn[a];void 0!==o?t[a]=o:(t[a]="ATTR"+i,i++),n=e.indexOf("attribute",n+1)}return t}function an(e,t,i,n){void 0===n&&(n=!1);var s=Wi[t],r=Ki(e)+"\n"+Wi[i],a=rn(s);return e.deviceType===ci?(s=Zi(e)+Wi.webgpuVS+s,r=Zi(e)+Wi.webgpuPS+r):e.webgl2&&(s=Zi(e)+Wi.gles3VS+s,r=Zi(e)+Wi.gles3PS+r),new zi(e,{attributes:a,vshader:s,fshader:r,useTransformFeedback:n,name:t+"_"+i})}function on(e,t,i,n,s,r){void 0===s&&(s=!1),void 0===r&&(r="");var a=e.programLib._cache,o=a[n];if(void 0!==o)return o;i=Ki(e)+"\n"+(i||"void main(void) {gl_FragColor = vec4(0.0);}");var h=rn(t);return e.deviceType===ci?(t=Zi(e)+Wi.webgpuVS+t,i=Zi(e)+Wi.webgpuPS+i):e.webgl2&&(t=Zi(e)+Wi.gles3VS+t,i=Zi(e)+Wi.gles3PS+i),a[n]=new zi(e,{name:n,attributes:h,vshader:t,fshader:r+i,useTransformFeedback:s}),a[n]}Wi.collectAttribs=rn,Wi.createShader=an,Wi.createShaderFromCode=on;var hn=function(){function e(){this.globalId=0,this.revision=0}var t=e.prototype;return t.equals=function(e){return this.globalId===e.globalId&&this.revision===e.revision},t.copy=function(e){this.globalId=e.globalId,this.revision=e.revision},t.reset=function(){this.globalId=0,this.revision=0},e}(),ln=0,cn=function(){function e(){ln++,this.version=new hn,this.version.globalId=ln}return e.prototype.increment=function(){this.version.revision++},e}(),un=function(){function e(e){this.name=e,this.value=null,this.versionObject=new cn}var t=e.prototype;return t.toJSON=function(e){},t.setValue=function(e){this.value=e,this.versionObject.increment()},t.getValue=function(){return this.value},e}(),dn=function(){function e(e){this.name=e,this.variables=new Map}var t=e.prototype;return t.resolve=function(e){return this.variables.has(e)||this.variables.set(e,new un(e)),this.variables.get(e)},t.removeValue=function(e){for(var t in this.variables){var i=this.variables[t];i.value===e&&(i.value=null)}},e}(),fn={linear:"decodeLinear",srgb:"decodeGamma",rgbm:"decodeRGBM",rgbe:"decodeRGBE",rgbp:"decodeRGBP"},pn={linear:"encodeLinear",srgb:"encodeGamma",rgbm:"encodeRGBM",rgbe:"encodeRGBE",rgbp:"encodeRGBP"},mn=function(){function e(){}return e.decodeFunc=function(e){return fn[e]||"decodeGamma"},e.encodeFunc=function(e){return pn[e]||"encodeGamma"},e}(),_n=1/255,gn=new Float32Array(1),vn=new Int32Array(gn.buffer),yn=function(){function e(){}return e.float2Half=function(e){gn[0]=e;var t=vn[0],i=t>>16&32768,n=t>>12&2047,s=t>>23&255;return s<103?i:s>142?(i|=31744,i|=(255===s?0:1)&&8388607&t):s<113?i|=((n|=2048)>>114-s)+(n>>113-s&1):(i|=s-112<<10|n>>1,i+=1&n)},e.float2Bytes=function(e,t,i,n){var s=255*e%1;if(t[i+0]=Math.round(255*(e%1-_n*s)),n>1){var r=65025*e%1;if(t[i+1]=Math.round(255*(s-_n*r)),n>2){var a=16581375*e%1;t[i+2]=Math.round(255*(r-_n*a)),n>3&&(t[i+3]=Math.round(255*a))}}},e.float2BytesRange=function(t,i,n,s,r,a){t=de.clamp((t-s)/(r-s),0,1),e.float2Bytes(t,i,n,a)},e.float2MantissaExponent=function(t,i,n,s){var r=Math.floor(Math.log2(Math.abs(t)))+1;t/=Math.pow(2,r),e.float2BytesRange(t,i,n,-1,1,s-1),i[n+s-1]=Math.round(r+127)},e}(),xn=null,bn=null,Sn=0,wn=function(){function e(e,t){this.id=Sn++,this.device=e,this.name=null,this._width=4,this._height=4,this._depth=1,this._format=7,this.type=Zt,this.projection=si,this._cubemap=!1,this._volume=!1,this.fixCubemapSeams=!1,this._flipY=!1,this._premultiplyAlpha=!1,this._isRenderTarget=!1,this._mipmaps=!0,this._minFilter=5,this._magFilter=1,this._anisotropy=1,this._addressU=0,this._addressV=0,this._addressW=0,this._compareOnRead=!1,this._compareFunc=1,void 0!==t&&(void 0!==t.name&&(this.name=t.name),this._width=void 0!==t.width?t.width:this._width,this._height=void 0!==t.height?t.height:this._height,this._format=void 0!==t.format?t.format:this._format,t.hasOwnProperty("type")?this.type=t.type:t.hasOwnProperty("rgbm")?this.type=t.rgbm?$t:Zt:t.hasOwnProperty("swizzleGGGR")&&(this.type=t.swizzleGGGR?ei:Zt),void 0!==t.mipmaps?this._mipmaps=t.mipmaps:this._mipmaps=void 0!==t.autoMipmap?t.autoMipmap:this._mipmaps,this._levels=t.levels,this._cubemap=void 0!==t.cubemap?t.cubemap:this._cubemap,this.fixCubemapSeams=void 0!==t.fixCubemapSeams?t.fixCubemapSeams:this.fixCubemapSeams,this._cubemap?this.projection=ri:t.projection&&t.projection!==ri&&(this.projection=t.projection),this._minFilter=void 0!==t.minFilter?t.minFilter:this._minFilter,this._magFilter=void 0!==t.magFilter?t.magFilter:this._magFilter,this._anisotropy=void 0!==t.anisotropy?t.anisotropy:this._anisotropy,this._addressU=void 0!==t.addressU?t.addressU:this._addressU,this._addressV=void 0!==t.addressV?t.addressV:this._addressV,this._compareOnRead=void 0!==t.compareOnRead?t.compareOnRead:this._compareOnRead,this._compareFunc=void 0!==t._compareFunc?t._compareFunc:this._compareFunc,this._flipY=void 0!==t.flipY?t.flipY:this._flipY,this._premultiplyAlpha=void 0!==t.premultiplyAlpha?t.premultiplyAlpha:this._premultiplyAlpha,e.webgl2&&(this._depth=void 0!==t.depth?t.depth:this._depth,this._volume=void 0!==t.volume?t.volume:this._volume,this._addressW=void 0!==t.addressW?t.addressW:this._addressW)),this._compressed=8===this._format||9===this._format||this._format===ht||this._format>=mt,this._invalid=!1,this._lockedLevel=-1,this._levels||(this._levels=this._cubemap?[[null,null,null,null,null,null]]:[null]),this.dirtyAll(),this._gpuSize=0,this.impl=e.createTextureImpl(this),e.textures.push(this)}var t=e.prototype;return t.destroy=function(){if(this.device){var e=this.device,t=e.textures.indexOf(this);-1!==t&&e.textures.splice(t,1),e.scope.removeValue(this),this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this._gpuSize),this._levels=null,this.device=null}},t.loseContext=function(){this.impl.loseContext(),this.dirtyAll()},t.adjustVramSizeTracking=function(e,t){e.tex+=t},e.calcGpuSize=function(e,t,i,n,s,r){xn||((xn=[])[0]=1,xn[1]=1,xn[2]=2,xn[3]=2,xn[4]=2,xn[5]=2,xn[6]=4,xn[7]=4,xn[11]=8,xn[12]=8,xn[13]=16,xn[14]=16,xn[15]=4,xn[16]=4,xn[17]=4,xn[18]=4,xn[19]=4,xn[20]=4),bn||((bn=[])[21]=8,bn[22]=8,bn[24]=8,bn[25]=8,bn[26]=8,bn[27]=8,bn[8]=8,bn[29]=8,bn[23]=16,bn[9]=16,bn[10]=16,bn[28]=16,bn[30]=16);for(var a=xn.hasOwnProperty(n)?xn[n]:0,o=bn.hasOwnProperty(n)?bn[n]:0,h=0;;){if(a>0)h+=e*t*i*a;else{var l=Math.floor((e+3)/4),c=Math.floor((t+3)/4),u=Math.floor((i+3)/4);n!==_t&&n!==gt||(l=Math.max(Math.floor(l/2),1)),h+=l*c*u*o}if(!s||1===e&&1===t&&1===i)break;e=Math.max(Math.floor(e/2),1),t=Math.max(Math.floor(t/2),1),i=Math.max(Math.floor(i/2),1)}return h*(r?6:1)},t.dirtyAll=function(){this._levelsUpdated=this._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0],this._needsUpload=!0,this._needsMipmapsUpload=this._mipmaps,this._mipmapsUploaded=!1,this._parameterFlags=255},t.lock=function(e){if(void 0===e&&(e={}),void 0===e.level&&(e.level=0),void 0===e.face&&(e.face=0),void 0===e.mode&&(e.mode=2),this._lockedLevel=e.level,null===this._levels[e.level])switch(this._format){case 0:case 1:this._levels[e.level]=new Uint8Array(this._width*this._height*this._depth);break;case 2:this._levels[e.level]=new Uint8Array(this._width*this._height*this._depth*2);break;case 3:case 4:case 5:this._levels[e.level]=new Uint16Array(this._width*this._height*this._depth);break;case 6:this._levels[e.level]=new Uint8Array(this._width*this._height*this._depth*3);break;case 7:this._levels[e.level]=new Uint8Array(this._width*this._height*this._depth*4);break;case 8:this._levels[e.level]=new Uint8Array(Math.floor((this._width+3)/4)*Math.floor((this._height+3)/4)*8*this._depth);break;case 9:case ht:this._levels[e.level]=new Uint8Array(Math.floor((this._width+3)/4)*Math.floor((this._height+3)/4)*16*this._depth);break;case lt:this._levels[e.level]=new Uint16Array(this._width*this._height*this._depth*3);break;case ut:this._levels[e.level]=new Float32Array(this._width*this._height*this._depth*3);break;case ct:this._levels[e.level]=new Uint16Array(this._width*this._height*this._depth*4);break;case dt:this._levels[e.level]=new Float32Array(this._width*this._height*this._depth*4)}return this._levels[e.level]},t.setSource=function(e,t){void 0===t&&(t=0);var i,n,s=!1;if(this._cubemap){if(e[0]){i=e[0].width||0,n=e[0].height||0;for(var r=0;r<6;r++){var a=e[r];if(!a||a.width!==i||a.height!==n||!this.device._isBrowserInterface(a)){s=!0;break}}}else s=!0;if(!s)for(var o=0;o<6;o++)this._levels[t][o]!==e[o]&&(this._levelsUpdated[t][o]=!0)}else this.device._isBrowserInterface(e)||(s=!0),s||(e!==this._levels[t]&&(this._levelsUpdated[t]=!0),i=e.width,n=e.height);if(s)if(this._width=4,this._height=4,this._cubemap)for(var h=0;h<6;h++)this._levels[t][h]=null,this._levelsUpdated[t][h]=!0;else this._levels[t]=null,this._levelsUpdated[t]=!0;else 0===t&&(this._width=i,this._height=n),this._levels[t]=e;this._invalid===s&&s||(this._invalid=s,this.upload())},t.getSource=function(e){return void 0===e&&(e=0),this._levels[e]},t.unlock=function(){this._lockedLevel,this.upload(),this._lockedLevel=-1},t.upload=function(){this._needsUpload=!0,this._needsMipmapsUpload=this._mipmaps},t.getDds=function(){for(var e=128,t=0;this._levels[t];){if(this.cubemap)for(var i=0;i<6;i++){if(!this._levels[t][i])return;var n=this._levels[t][i].length;if(!n)return;e+=n}else{var s=this._levels[t].length;if(!s)return;e+=s}e+=this._levels[t].length,t++}var r=new ArrayBuffer(e),a=new Uint32Array(r,0,32),o=528391;this._levels.length>1&&(o|=131072);var h=4096;this._levels.length>1&&(h|=4194304),(this._levels.length>1||this.cubemap)&&(h|=8);var l=this.cubemap?65024:0;a[0]=542327876,a[1]=124,a[2]=o,a[3]=this.height,a[4]=this.width,a[5]=this.width*this.height*4,a[6]=0,a[7]=this._levels.length;for(var c=0;c<11;c++)a[8+c]=0;a[19]=32,a[20]=65,a[21]=0,a[22]=32,a[23]=16711680,a[24]=65280,a[25]=255,a[26]=4278190080,a[27]=h,a[28]=l,a[29]=0,a[30]=0,a[31]=0;var u=128;if(this.cubemap)for(var d=0;d<6;d++)for(var f=0;f<this._levels.length;f++){for(var p=this._levels[f][d],m=new Uint8Array(r,u,p.length),_=0;_<p.length;_++)m[_]=p[_];u+=p.length}else for(var g=0;g<this._levels.length;g++){for(var v=this._levels[g],y=new Uint8Array(r,u,v.length),x=0;x<v.length;x++)y[x]=v[x];u+=v.length}return r},$(e,[{key:"minFilter",get:function(){return this._minFilter},set:function(e){this._minFilter!==e&&(this._minFilter=e,this._parameterFlags|=1)}},{key:"magFilter",get:function(){return this._magFilter},set:function(e){this._magFilter!==e&&(this._magFilter=e,this._parameterFlags|=2)}},{key:"addressU",get:function(){return this._addressU},set:function(e){this._addressU!==e&&(this._addressU=e,this._parameterFlags|=4)}},{key:"addressV",get:function(){return this._addressV},set:function(e){this._addressV!==e&&(this._addressV=e,this._parameterFlags|=8)}},{key:"addressW",get:function(){return this._addressW},set:function(e){this.device.webgl2&&this._volume&&e!==this._addressW&&(this._addressW=e,this._parameterFlags|=16)}},{key:"compareOnRead",get:function(){return this._compareOnRead},set:function(e){this._compareOnRead!==e&&(this._compareOnRead=e,this._parameterFlags|=32)}},{key:"compareFunc",get:function(){return this._compareFunc},set:function(e){this._compareFunc!==e&&(this._compareFunc=e,this._parameterFlags|=64)}},{key:"anisotropy",get:function(){return this._anisotropy},set:function(e){this._anisotropy!==e&&(this._anisotropy=e,this._parameterFlags|=128)}},{key:"autoMipmap",get:function(){return this._mipmaps},set:function(e){this._mipmaps=e}},{key:"mipmaps",get:function(){return this._mipmaps},set:function(e){this._mipmaps!==e&&(this._mipmaps=e,e&&(this._needsMipmapsUpload=!0))}},{key:"width",get:function(){return this._width}},{key:"height",get:function(){return this._height}},{key:"depth",get:function(){return this._depth}},{key:"format",get:function(){return this._format}},{key:"cubemap",get:function(){return this._cubemap}},{key:"gpuSize",get:function(){var t=this.pot&&this._mipmaps&&!(this._compressed&&1===this._levels.length);return e.calcGpuSize(this._width,this._height,this._depth,this._format,t,this._cubemap)}},{key:"volume",get:function(){return this._volume}},{key:"flipY",get:function(){return this._flipY},set:function(e){this._flipY!==e&&(this._flipY=e,this._needsUpload=!0)}},{key:"premultiplyAlpha",get:function(){return this._premultiplyAlpha},set:function(e){this._premultiplyAlpha!==e&&(this._premultiplyAlpha=e,this._needsUpload=!0)}},{key:"pot",get:function(){return de.powerOfTwo(this._width)&&de.powerOfTwo(this._height)}},{key:"encoding",get:function(){switch(this.type){case $t:return"rgbm";case Qt:return"rgbe";case Jt:return"rgbp";default:return this.format===lt||this.format===ut||this.format===ct||this.format===dt?"linear":"srgb"}}}]),e}(),Tn=new ye,An=new ye,Mn=new ye,Cn=new Ee,En=function(){function e(){this._aspectRatio=16/9,this._aspectRatioMode=0,this._calculateProjection=null,this._calculateTransform=null,this._clearColor=new me(.75,.75,.75,1),this._clearColorBuffer=!0,this._clearDepth=1,this._clearDepthBuffer=!0,this._clearStencil=0,this._clearStencilBuffer=!0,this._cullingMask=4294967295,this._cullFaces=!0,this._farClip=1e3,this._flipFaces=!1,this._fov=45,this._frustumCulling=!0,this._horizontalFov=!1,this._layers=[0,1,2,4,3],this._layersSet=new Set(this._layers),this._nearClip=.1,this._node=null,this._orthoHeight=10,this._projection=0,this._rect=new Se(0,0,1,1),this._renderTarget=null,this._scissorRect=new Se(0,0,1,1),this._scissorRectClear=!1,this._aperture=16,this._shutter=.001,this._sensitivity=1e3,this._projMat=new Ee,this._projMatDirty=!0,this._projMatSkybox=new Ee,this._viewMat=new Ee,this._viewMatDirty=!0,this._viewProjMat=new Ee,this._viewProjMatDirty=!0,this.frustum=new Je}var t=e.prototype;return t.clone=function(){return(new e).copy(this)},t.copy=function(e){return this.aspectRatio=e.aspectRatio,this.aspectRatioMode=e.aspectRatioMode,this.calculateProjection=e.calculateProjection,this.calculateTransform=e.calculateTransform,this.clearColor=e.clearColor,this.clearColorBuffer=e.clearColorBuffer,this.clearDepth=e.clearDepth,this.clearDepthBuffer=e.clearDepthBuffer,this.clearStencil=e.clearStencil,this.clearStencilBuffer=e.clearStencilBuffer,this.cullFaces=e.cullFaces,this.cullingMask=e.cullingMask,this.farClip=e.farClip,this.flipFaces=e.flipFaces,this.fov=e.fov,this.frustumCulling=e.frustumCulling,this.horizontalFov=e.horizontalFov,this.layers=e.layers,this.nearClip=e.nearClip,this.orthoHeight=e.orthoHeight,this.projection=e.projection,this.rect=e.rect,this.renderTarget=e.renderTarget,this.scissorRect=e.scissorRect,this.aperture=e.aperture,this.shutter=e.shutter,this.sensitivity=e.sensitivity,this},t._updateViewProjMat=function(){(this._projMatDirty||this._viewMatDirty||this._viewProjMatDirty)&&(this._viewProjMat.mul2(this.projectionMatrix,this.viewMatrix),this._viewProjMatDirty=!1)},t.worldToScreen=function(e,t,i,n){void 0===n&&(n=new ye),this._updateViewProjMat(),this._viewProjMat.transformPoint(e,n);var s=this._viewProjMat.data,r=e.x*s[3]+e.y*s[7]+e.z*s[11]+1*s[15];return n.x=.5*(n.x/r+1)*t,n.y=.5*(1-n.y/r)*i,n},t.screenToWorld=function(e,t,i,n,s,r){void 0===r&&(r=new ye);var a=this._farClip-this._nearClip;if(Tn.set(e/n,(s-t)/s,i/a),Tn.mulScalar(2),Tn.sub(ye.ONE),0===this._projection){Ee._getPerspectiveHalfSize(An,this._fov,this._aspectRatio,this._nearClip,this._horizontalFov),An.x*=Tn.x,An.y*=Tn.y;var o=this._node.getWorldTransform();An.z=-this._nearClip,o.transformPoint(An,Mn);var h=this._node.getPosition();r.sub2(Mn,h),r.normalize(),r.mulScalar(i),r.add(h)}else this._updateViewProjMat(),Cn.copy(this._viewProjMat).invert(),Cn.transformPoint(Tn,r);return r},t._evaluateProjectionMatrix=function(){if(this._projMatDirty){if(0===this._projection)this._projMat.setPerspective(this._fov,this._aspectRatio,this._nearClip,this._farClip,this._horizontalFov),this._projMatSkybox.copy(this._projMat);else{var e=this._orthoHeight,t=e*this._aspectRatio;this._projMat.setOrtho(-t,t,-e,e,this._nearClip,this._farClip),this._projMatSkybox.setPerspective(this._fov,this._aspectRatio,this._nearClip,this._farClip)}this._projMatDirty=!1}},t.getProjectionMatrixSkybox=function(){return this._evaluateProjectionMatrix(),this._projMatSkybox},t.getExposure=function(){var e=Math.log2(this._aperture*this._aperture/this._shutter*100/this._sensitivity);return 1/(1.2*Math.pow(2,e))},t.getScreenSize=function(e){if(0===this._projection){var t=this._node.getPosition().distance(e.center);if(t<e.radius)return 1;var i=Math.asin(e.radius/t),n=Math.tan(i),s=Math.tan(this._fov/2*de.DEG_TO_RAD);return Math.min(n/s,1)}return de.clamp(e.radius/this._orthoHeight,0,1)},$(e,[{key:"fullSizeClearRect",get:function(){var e=this._scissorRectClear?this.scissorRect:this._rect;return 0===e.x&&0===e.y&&1===e.z&&1===e.w}},{key:"aspectRatio",get:function(){return this._aspectRatio},set:function(e){this._aspectRatio!==e&&(this._aspectRatio=e,this._projMatDirty=!0)}},{key:"aspectRatioMode",get:function(){return this._aspectRatioMode},set:function(e){this._aspectRatioMode!==e&&(this._aspectRatioMode=e,this._projMatDirty=!0)}},{key:"calculateProjection",get:function(){return this._calculateProjection},set:function(e){this._calculateProjection=e,this._projMatDirty=!0}},{key:"calculateTransform",get:function(){return this._calculateTransform},set:function(e){this._calculateTransform=e}},{key:"clearColor",get:function(){return this._clearColor},set:function(e){this._clearColor.copy(e)}},{key:"clearColorBuffer",get:function(){return this._clearColorBuffer},set:function(e){this._clearColorBuffer=e}},{key:"clearDepth",get:function(){return this._clearDepth},set:function(e){this._clearDepth=e}},{key:"clearDepthBuffer",get:function(){return this._clearDepthBuffer},set:function(e){this._clearDepthBuffer=e}},{key:"clearStencil",get:function(){return this._clearStencil},set:function(e){this._clearStencil=e}},{key:"clearStencilBuffer",get:function(){return this._clearStencilBuffer},set:function(e){this._clearStencilBuffer=e}},{key:"cullingMask",get:function(){return this._cullingMask},set:function(e){this._cullingMask=e}},{key:"cullFaces",get:function(){return this._cullFaces},set:function(e){this._cullFaces=e}},{key:"farClip",get:function(){return this._farClip},set:function(e){this._farClip!==e&&(this._farClip=e,this._projMatDirty=!0)}},{key:"flipFaces",get:function(){return this._flipFaces},set:function(e){this._flipFaces=e}},{key:"fov",get:function(){return this._fov},set:function(e){this._fov!==e&&(this._fov=e,this._projMatDirty=!0)}},{key:"frustumCulling",get:function(){return this._frustumCulling},set:function(e){this._frustumCulling=e}},{key:"horizontalFov",get:function(){return this._horizontalFov},set:function(e){this._horizontalFov!==e&&(this._horizontalFov=e,this._projMatDirty=!0)}},{key:"layers",get:function(){return this._layers},set:function(e){this._layers=e.slice(0),this._layersSet=new Set(this._layers)}},{key:"layersSet",get:function(){return this._layersSet}},{key:"nearClip",get:function(){return this._nearClip},set:function(e){this._nearClip!==e&&(this._nearClip=e,this._projMatDirty=!0)}},{key:"node",get:function(){return this._node},set:function(e){this._node=e}},{key:"orthoHeight",get:function(){return this._orthoHeight},set:function(e){this._orthoHeight!==e&&(this._orthoHeight=e,this._projMatDirty=!0)}},{key:"projection",get:function(){return this._projection},set:function(e){this._projection!==e&&(this._projection=e,this._projMatDirty=!0)}},{key:"projectionMatrix",get:function(){return this._evaluateProjectionMatrix(),this._projMat}},{key:"rect",get:function(){return this._rect},set:function(e){this._rect.copy(e)}},{key:"renderTarget",get:function(){return this._renderTarget},set:function(e){this._renderTarget=e}},{key:"scissorRect",get:function(){return this._scissorRect},set:function(e){this._scissorRect.copy(e)}},{key:"viewMatrix",get:function(){if(this._viewMatDirty){var e=this._node.getWorldTransform();this._viewMat.copy(e).invert(),this._viewMatDirty=!1}return this._viewMat}},{key:"aperture",get:function(){return this._aperture},set:function(e){this._aperture=e}},{key:"sensitivity",get:function(){return this._sensitivity},set:function(e){this._sensitivity=e}},{key:"shutter",get:function(){return this._shutter},set:function(e){this._shutter=e}}]),e}(),Pn=new Ee,Rn=new ye,In=new Pe,Ln=new Pe,Dn=new ye,kn=new ye,On=new Ee,Fn=new Pe,Bn=new ye,Nn=new Ee,Un=new Pe,zn=new Pe,Vn=new Ee,Gn=new ye,Wn=new ye,Hn=function(e){function t(t){var i;return void 0===t&&(t="Untitled"),(i=e.call(this)||this).name=t,i.tags=new ae(te(i)),i._labels={},i.localPosition=new ye,i.localRotation=new Pe,i.localScale=new ye(1,1,1),i.localEulerAngles=new ye,i.position=new ye,i.rotation=new Pe,i.eulerAngles=new ye,i._scale=null,i.localTransform=new Ee,i._dirtyLocal=!1,i._aabbVer=0,i._frozen=!1,i.worldTransform=new Ee,i._dirtyWorld=!1,i._normalMatrix=new xe,i._dirtyNormal=!0,i._right=null,i._up=null,i._forward=null,i._parent=null,i._children=[],i._graphDepth=0,i._enabled=!0,i._enabledInHierarchy=!1,i.scaleCompensation=!1,i}J(t,e);var i=t.prototype;return i._notifyHierarchyStateChanged=function(e,t){e._onHierarchyStateChanged(t);for(var i=e._children,n=0,s=i.length;n<s;n++)i[n]._enabled&&this._notifyHierarchyStateChanged(i[n],t)},i._onHierarchyStateChanged=function(e){this._enabledInHierarchy=e,e&&!this._frozen&&this._unfreezeParentToRoot()},i._cloneInternal=function(e){e.name=this.name;var t=this.tags._list;e.tags.clear();for(var i=0;i<t.length;i++)e.tags.add(t[i]);e._labels=Object.assign({},this._labels),e.localPosition.copy(this.localPosition),e.localRotation.copy(this.localRotation),e.localScale.copy(this.localScale),e.localEulerAngles.copy(this.localEulerAngles),e.position.copy(this.position),e.rotation.copy(this.rotation),e.eulerAngles.copy(this.eulerAngles),e.localTransform.copy(this.localTransform),e._dirtyLocal=this._dirtyLocal,e.worldTransform.copy(this.worldTransform),e._dirtyWorld=this._dirtyWorld,e._dirtyNormal=this._dirtyNormal,e._aabbVer=this._aabbVer+1,e._enabled=this._enabled,e.scaleCompensation=this.scaleCompensation,e._enabledInHierarchy=!1},i.clone=function(){var e=new this.constructor;return this._cloneInternal(e),e},i.copy=function(e){return e._cloneInternal(this),this},i.find=function(e,t){var i=[],n=this._children.length;if(e instanceof Function){var s=e;s(this)&&i.push(this);for(var r=0;r<n;r++){var a=this._children[r].find(s);a.length&&(i=i.concat(a))}}else{this[e]&&(this[e]instanceof Function?this[e]():this[e])===t&&i.push(this);for(var o=0;o<n;++o){var h=this._children[o].find(e,t);h.length&&(i=i.concat(h))}}return i},i.findOne=function(e,t){var i=this._children.length,n=null;if(e instanceof Function){var s=e;if(n=s(this))return this;for(var r=0;r<i;r++)if(n=this._children[r].findOne(s))return n}else{if(this[e]&&(this[e]instanceof Function?this[e]():this[e])===t)return this;for(var a=0;a<i;a++)if(null!==(n=this._children[a].findOne(e,t)))return n}return null},i.findByTag=function(){var e=arguments,t=[],i=function i(n,s){var r;s&&(r=n.tags).has.apply(r,e)&&t.push(n);for(var a=0;a<n._children.length;a++)i(n._children[a],!0)};return i(this,!1),t},i.findByName=function(e){if(this.name===e)return this;for(var t=0;t<this._children.length;t++){var i=this._children[t].findByName(e);if(null!==i)return i}return null},i.findByPath=function(e){for(var t=Array.isArray(e)?e:e.split("/"),i=this,n=function(e,n){if(i=i.children.find((function(i){return i.name===t[e]})),!i)return{v:null}},s=0,r=t.length;s<r;++s){var a=n(s);if("object"==typeof a)return a.v}return i},i.forEach=function(e,t){e.call(t,this);for(var i=this._children,n=0;n<i.length;n++)i[n].forEach(e,t)},i.isDescendantOf=function(e){for(var t=this._parent;t;){if(t===e)return!0;t=t._parent}return!1},i.isAncestorOf=function(e){return e.isDescendantOf(this)},i.getEulerAngles=function(){return this.getWorldTransform().getEulerAngles(this.eulerAngles),this.eulerAngles},i.getLocalEulerAngles=function(){return this.localRotation.getEulerAngles(this.localEulerAngles),this.localEulerAngles},i.getLocalPosition=function(){return this.localPosition},i.getLocalRotation=function(){return this.localRotation},i.getLocalScale=function(){return this.localScale},i.getLocalTransform=function(){return this._dirtyLocal&&(this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale),this._dirtyLocal=!1),this.localTransform},i.getPosition=function(){return this.getWorldTransform().getTranslation(this.position),this.position},i.getRotation=function(){return this.rotation.setFromMat4(this.getWorldTransform()),this.rotation},i.getScale=function(){return this._scale||(this._scale=new ye),this.getWorldTransform().getScale(this._scale)},i.getWorldTransform=function(){return this._dirtyLocal||this._dirtyWorld?(this._parent&&this._parent.getWorldTransform(),this._sync(),this.worldTransform):this.worldTransform},i.reparent=function(e,t){var i=this._parent;i&&i.removeChild(this),e&&(t>=0?e.insertChild(this,t):e.addChild(this))},i.setLocalEulerAngles=function(e,t,i){this.localRotation.setFromEulerAngles(e,t,i),this._dirtyLocal||this._dirtifyLocal()},i.setLocalPosition=function(e,t,i){e instanceof ye?this.localPosition.copy(e):this.localPosition.set(e,t,i),this._dirtyLocal||this._dirtifyLocal()},i.setLocalRotation=function(e,t,i,n){e instanceof Pe?this.localRotation.copy(e):this.localRotation.set(e,t,i,n),this._dirtyLocal||this._dirtifyLocal()},i.setLocalScale=function(e,t,i){e instanceof ye?this.localScale.copy(e):this.localScale.set(e,t,i),this._dirtyLocal||this._dirtifyLocal()},i._dirtifyLocal=function(){this._dirtyLocal||(this._dirtyLocal=!0,this._dirtyWorld||this._dirtifyWorld())},i._unfreezeParentToRoot=function(){for(var e=this._parent;e;)e._frozen=!1,e=e._parent},i._dirtifyWorld=function(){this._dirtyWorld||this._unfreezeParentToRoot(),this._dirtifyWorldInternal()},i._dirtifyWorldInternal=function(){if(!this._dirtyWorld){this._frozen=!1,this._dirtyWorld=!0;for(var e=0;e<this._children.length;e++)this._children[e]._dirtyWorld||this._children[e]._dirtifyWorldInternal()}this._dirtyNormal=!0,this._aabbVer++},i.setPosition=function(e,t,i){e instanceof ye?Bn.copy(e):Bn.set(e,t,i),null===this._parent?this.localPosition.copy(Bn):(Nn.copy(this._parent.getWorldTransform()).invert(),Nn.transformPoint(Bn,this.localPosition)),this._dirtyLocal||this._dirtifyLocal()},i.setRotation=function(e,t,i,n){if(e instanceof Pe?Un.copy(e):Un.set(e,t,i,n),null===this._parent)this.localRotation.copy(Un);else{var s=this._parent.getRotation();zn.copy(s).invert(),this.localRotation.copy(zn).mul(Un)}this._dirtyLocal||this._dirtifyLocal()},i.setEulerAngles=function(e,t,i){if(this.localRotation.setFromEulerAngles(e,t,i),null!==this._parent){var n=this._parent.getRotation();zn.copy(n).invert(),this.localRotation.mul2(zn,this.localRotation)}this._dirtyLocal||this._dirtifyLocal()},i.addChild=function(e){this._prepareInsertChild(e),this._children.push(e),this._onInsertChild(e)},i.addChildAndSaveTransform=function(e){var t=e.getPosition(),i=e.getRotation();this._prepareInsertChild(e),e.setPosition(On.copy(this.worldTransform).invert().transformPoint(t)),e.setRotation(Fn.copy(this.getRotation()).invert().mul(i)),this._children.push(e),this._onInsertChild(e)},i.insertChild=function(e,t){this._prepareInsertChild(e),this._children.splice(t,0,e),this._onInsertChild(e)},i._prepareInsertChild=function(e){e._parent&&e._parent.removeChild(e)},i._fireOnHierarchy=function(e,t,i){this.fire(e,i);for(var n=0;n<this._children.length;n++)this._children[n]._fireOnHierarchy(t,t,i)},i._onInsertChild=function(e){e._parent=this;var t=e._enabled&&this.enabled;e._enabledInHierarchy!==t&&(e._enabledInHierarchy=t,e._notifyHierarchyStateChanged(e,t)),e._updateGraphDepth(),e._dirtifyWorld(),this._frozen&&e._unfreezeParentToRoot(),e._fireOnHierarchy("insert","inserthierarchy",this),this.fire&&this.fire("childinsert",e)},i._updateGraphDepth=function(){this._graphDepth=this._parent?this._parent._graphDepth+1:0;for(var e=0,t=this._children.length;e<t;e++)this._children[e]._updateGraphDepth()},i.removeChild=function(e){var t=this._children.indexOf(e);-1!==t&&(this._children.splice(t,1),e._parent=null,e._fireOnHierarchy("remove","removehierarchy",this),this.fire("childremove",e))},i._sync=function(){if(this._dirtyLocal&&(this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale),this._dirtyLocal=!1),this._dirtyWorld){if(null===this._parent)this.worldTransform.copy(this.localTransform);else if(this.scaleCompensation){var e,t=this._parent,i=this.localScale,n=t;if(n){for(;n&&n.scaleCompensation;)n=n._parent;n&&(n=n._parent)&&(e=n.worldTransform.getScale(),Dn.mul2(e,this.localScale),i=Dn)}Ln.setFromMat4(t.worldTransform),In.mul2(Ln,this.localRotation);var s=t.worldTransform;t.scaleCompensation&&(kn.mul2(e,t.getLocalScale()),Pn.setTRS(t.worldTransform.getTranslation(Rn),Ln,kn),s=Pn),s.transformPoint(this.localPosition,Rn),this.worldTransform.setTRS(Rn,In,i)}else this.worldTransform.mulAffine2(this._parent.worldTransform,this.localTransform);this._dirtyWorld=!1}},i.syncHierarchy=function(){if(this._enabled&&!this._frozen){this._frozen=!0,(this._dirtyLocal||this._dirtyWorld)&&this._sync();for(var e=this._children,t=0,i=e.length;t<i;t++)e[t].syncHierarchy()}},i.lookAt=function(e,t,i,n,s,r){if(void 0===n&&(n=0),void 0===s&&(s=1),void 0===r&&(r=0),e instanceof ye)Gn.copy(e),t instanceof ye?Wn.copy(t):Wn.copy(ye.UP);else{if(void 0===i)return;Gn.set(e,t,i),Wn.set(n,s,r)}Vn.setLookAt(this.getPosition(),Gn,Wn),Un.setFromMat4(Vn),this.setRotation(Un)},i.translate=function(e,t,i){e instanceof ye?Bn.copy(e):Bn.set(e,t,i),Bn.add(this.getPosition()),this.setPosition(Bn)},i.translateLocal=function(e,t,i){e instanceof ye?Bn.copy(e):Bn.set(e,t,i),this.localRotation.transformVector(Bn,Bn),this.localPosition.add(Bn),this._dirtyLocal||this._dirtifyLocal()},i.rotate=function(e,t,i){if(Un.setFromEulerAngles(e,t,i),null===this._parent)this.localRotation.mul2(Un,this.localRotation);else{var n=this.getRotation(),s=this._parent.getRotation();zn.copy(s).invert(),Un.mul2(zn,Un),this.localRotation.mul2(Un,n)}this._dirtyLocal||this._dirtifyLocal()},i.rotateLocal=function(e,t,i){Un.setFromEulerAngles(e,t,i),this.localRotation.mul(Un),this._dirtyLocal||this._dirtifyLocal()},$(t,[{key:"right",get:function(){return this._right||(this._right=new ye),this.getWorldTransform().getX(this._right).normalize()}},{key:"up",get:function(){return this._up||(this._up=new ye),this.getWorldTransform().getY(this._up).normalize()}},{key:"forward",get:function(){return this._forward||(this._forward=new ye),this.getWorldTransform().getZ(this._forward).normalize().mulScalar(-1)}},{key:"normalMatrix",get:function(){var e=this._normalMatrix;return this._dirtyNormal&&(this.getWorldTransform().invertTo3x3(e),e.transpose(),this._dirtyNormal=!1),e}},{key:"enabled",get:function(){return this._enabled&&this._enabledInHierarchy},set:function(e){var t;this._enabled!==e&&(this._enabled=e,(e&&null!=(t=this._parent)&&t.enabled||!e)&&this._notifyHierarchyStateChanged(this,e))}},{key:"parent",get:function(){return this._parent}},{key:"path",get:function(){var e=this._parent;if(!e)return"";for(var t=this.name;e&&e._parent;)t=e.name+"/"+t,e=e._parent;return t}},{key:"root",get:function(){for(var e=this;e._parent;)e=e._parent;return e}},{key:"children",get:function(){return this._children}},{key:"graphDepth",get:function(){return this._graphDepth}}]),t}(m),Xn=new Ee,qn=new Ee,jn=new Ee,Yn=function(){function e(){}return e.create=function(t,i,n){var s=new En;switch(s.node=new Hn(t),s.aspectRatio=1,s.aspectRatioMode=1,s._scissorRectClear=!0,i){case 1:s.node.setRotation(e.pointLightRotations[n]),s.fov=90,s.projection=0;break;case 2:s.projection=0;break;case 0:s.projection=1}return s},e.evalSpotCookieMatrix=function(t){var i=e._spotCookieCamera;i||(i=e.create("SpotCookieCamera",2),e._spotCookieCamera=i),i.fov=2*t._outerConeAngle;var n=i._node;n.setPosition(t._node.getPosition()),n.setRotation(t._node.getRotation()),n.rotateLocal(-90,0,0),Xn.setTRS(n.getPosition(),n.getRotation(),ye.ONE).invert(),qn.mul2(i.projectionMatrix,Xn);var s=t.cookieMatrix,r=t.atlasViewport;return jn.setViewport(r.x,r.y,r.z,r.w),s.mul2(jn,qn),s},e}();Yn.pointLightRotations=[(new Pe).setFromEulerAngles(0,90,180),(new Pe).setFromEulerAngles(0,-90,180),(new Pe).setFromEulerAngles(90,0,0),(new Pe).setFromEulerAngles(-90,0,0),(new Pe).setFromEulerAngles(0,180,180),(new Pe).setFromEulerAngles(0,0,180)],Yn._spotCookieCamera=null;var Kn=new ye,Zn=new Float32Array(6),$n=new ye(-.5,0,0),Qn=new ye(0,0,.5),Jn={FLAGS:0,COLOR_A:1,COLOR_B:2,SPOT_ANGLES:3,SHADOW_BIAS:4,COOKIE_A:5,COOKIE_B:6,COUNT_ALWAYS:7,POSITION_X:7,POSITION_Y:8,POSITION_Z:9,RANGE:10,SPOT_DIRECTION_X:11,SPOT_DIRECTION_Y:12,SPOT_DIRECTION_Z:13,PROJ_MAT_00:14,ATLAS_VIEWPORT_A:14,PROJ_MAT_01:15,ATLAS_VIEWPORT_B:15,PROJ_MAT_02:16,PROJ_MAT_03:17,PROJ_MAT_10:18,PROJ_MAT_11:19,PROJ_MAT_12:20,PROJ_MAT_13:21,PROJ_MAT_20:22,PROJ_MAT_21:23,PROJ_MAT_22:24,PROJ_MAT_23:25,PROJ_MAT_30:26,PROJ_MAT_31:27,PROJ_MAT_32:28,PROJ_MAT_33:29,AREA_DATA_WIDTH_X:30,AREA_DATA_WIDTH_Y:31,AREA_DATA_WIDTH_Z:32,AREA_DATA_HEIGHT_X:33,AREA_DATA_HEIGHT_Y:34,AREA_DATA_HEIGHT_Z:35,COUNT:36},es={POSITION_RANGE:0,SPOT_DIRECTION:1,PROJ_MAT_0:2,ATLAS_VIEWPORT:2,PROJ_MAT_1:3,PROJ_MAT_2:4,PROJ_MAT_3:5,AREA_DATA_WIDTH:6,AREA_DATA_HEIGHT:7,COUNT:8},ts=function(){function e(t){this.device=t,this.cookiesEnabled=!1,this.shadowsEnabled=!1,this.areaLightsEnabled=!1,this.maxLights=255;var i=Jn.COUNT_ALWAYS,n=0;e.lightTextureFormat===e.FORMAT_FLOAT?n=es.COUNT:i=Jn.COUNT,this.lights8=new Uint8ClampedArray(4*i*this.maxLights),this.lightsTexture8=e.createTexture(this.device,i,this.maxLights,7,"LightsTexture8"),this._lightsTexture8Id=this.device.scope.resolve("lightsTexture8"),n?(this.lightsFloat=new Float32Array(4*n*this.maxLights),this.lightsTextureFloat=e.createTexture(this.device,n,this.maxLights,dt,"LightsTextureFloat"),this._lightsTextureFloatId=this.device.scope.resolve("lightsTextureFloat")):(this.lightsFloat=null,this.lightsTextureFloat=null,this._lightsTextureFloatId=void 0),this._lightsTextureInvSizeId=this.device.scope.resolve("lightsTextureInvSize"),this._lightsTextureInvSizeData=new Float32Array(4),this._lightsTextureInvSizeData[0]=n?1/this.lightsTextureFloat.width:0,this._lightsTextureInvSizeData[1]=n?1/this.lightsTextureFloat.height:0,this._lightsTextureInvSizeData[2]=1/this.lightsTexture8.width,this._lightsTextureInvSizeData[3]=1/this.lightsTexture8.height,this.invMaxColorValue=0,this.invMaxAttenuation=0,this.boundsMin=new ye,this.boundsDelta=new ye}e.initShaderDefines=function(){var t=e.lightTextureFormat===e.FORMAT_FLOAT?"FLOAT":"8BIT";e.shaderDefines="\n \n#define CLUSTER_TEXTURE_"+t+"\n "+e.buildShaderDefines(Jn,"CLUSTER_TEXTURE_8_")+"\n "+e.buildShaderDefines(es,"CLUSTER_TEXTURE_F_")+"\n "},e.buildShaderDefines=function(e,t){var i="";return Object.keys(e).forEach((function(n){i+="\n#define "+t+n+" "+e[n]+".5"})),i},e.init=function(t){e.lightTextureFormat=t.extTextureFloat&&t.maxTextures>8?e.FORMAT_FLOAT:e.FORMAT_8BIT,e.initShaderDefines()},e.createTexture=function(e,t,i,n,s){return new wn(e,{name:s,width:t,height:i,mipmaps:!1,format:n,addressU:1,addressV:1,type:Zt,magFilter:0,minFilter:0,anisotropy:1})};var t=e.prototype;return t.destroy=function(){this.lightsTexture8&&(this.lightsTexture8.destroy(),this.lightsTexture8=null),this.lightsTextureFloat&&(this.lightsTextureFloat.destroy(),this.lightsTextureFloat=null)},t.setCompressionRanges=function(e,t){this.invMaxColorValue=1/t,this.invMaxAttenuation=1/e},t.setBounds=function(e,t){this.boundsMin.copy(e),this.boundsDelta.copy(t)},t.uploadTextures=function(){this.lightsTextureFloat&&(this.lightsTextureFloat.lock().set(this.lightsFloat),this.lightsTextureFloat.unlock()),this.lightsTexture8.lock().set(this.lights8),this.lightsTexture8.unlock()},t.updateUniforms=function(){this._lightsTexture8Id.setValue(this.lightsTexture8),e.lightTextureFormat===e.FORMAT_FLOAT&&this._lightsTextureFloatId.setValue(this.lightsTextureFloat),this._lightsTextureInvSizeId.setValue(this._lightsTextureInvSizeData)},t.getSpotDirection=function(e,t){t._node.getWorldTransform().getY(e).mulScalar(-1),e.normalize()},t.getLightAreaSizes=function(e){var t=e._node.getWorldTransform();return t.transformVector($n,Kn),Zn[0]=Kn.x,Zn[1]=Kn.y,Zn[2]=Kn.z,t.transformVector(Qn,Kn),Zn[3]=Kn.x,Zn[4]=Kn.y,Zn[5]=Kn.z,Zn},t.addLightDataFlags=function(e,t,i,n,s,r){e[t+0]=n?255:0,e[t+1]=64*i._shape,e[t+2]=255*i._falloffMode,e[t+3]=s?255*r:0},t.addLightDataColor=function(e,t,i,n,s){var r=this.invMaxColorValue,a=n?i._linearFinalColor:i._finalColor;yn.float2Bytes(a[0]*r,e,t+0,2),yn.float2Bytes(a[1]*r,e,t+2,2),yn.float2Bytes(a[2]*r,e,t+4,2),e[t+6]=s?255:0;var o=!!(1&i.mask),h=!!(2&i.mask);e[t+7]=o&&h?127:h?255:0},t.addLightDataSpotAngles=function(e,t,i){yn.float2Bytes(.499999*i._innerConeAngleCos+.5,e,t+0,2),yn.float2Bytes(.499999*i._outerConeAngleCos+.5,e,t+2,2)},t.addLightDataShadowBias=function(e,t,i){var n=i.getRenderData(null,0),s=i._getUniformBiasValues(n);yn.float2BytesRange(s.bias,e,t,-1,20,2),yn.float2Bytes(s.normalBias,e,t+2,2)},t.addLightDataPositionRange=function(e,t,i,n){var s=Kn.sub2(n,this.boundsMin).div(this.boundsDelta);yn.float2Bytes(s.x,e,t+0,4),yn.float2Bytes(s.y,e,t+4,4),yn.float2Bytes(s.z,e,t+8,4),yn.float2Bytes(i.attenuationEnd*this.invMaxAttenuation,e,t+12,4)},t.addLightDataSpotDirection=function(e,t,i){this.getSpotDirection(Kn,i),yn.float2Bytes(.499999*Kn.x+.5,e,t+0,4),yn.float2Bytes(.499999*Kn.y+.5,e,t+4,4),yn.float2Bytes(.499999*Kn.z+.5,e,t+8,4)},t.addLightDataLightProjMatrix=function(e,t,i){for(var n=i.data,s=0;s<12;s++)yn.float2BytesRange(n[s],e,t+4*s,-2,2,4);for(var r=12;r<16;r++)yn.float2MantissaExponent(n[r],e,t+4*r,4)},t.addLightDataCookies=function(e,t,i){var n="rgb"===i._cookieChannel;if(e[t+0]=Math.floor(255*i.cookieIntensity),e[t+1]=n?255:0,!n){var s=i._cookieChannel;e[t+4]="rrr"===s?255:0,e[t+5]="ggg"===s?255:0,e[t+6]="bbb"===s?255:0,e[t+7]="aaa"===s?255:0}},t.addLightAtlasViewport=function(e,t,i){yn.float2Bytes(i.x,e,t+0,2),yn.float2Bytes(i.y,e,t+2,2),yn.float2Bytes(i.z/3,e,t+4,2)},t.addLightAreaSizes=function(e,t,i){for(var n=this.getLightAreaSizes(i),s=0;s<6;s++)yn.float2MantissaExponent(n[s],e,t+4*s,4)},t.addLightData=function(t,i,n){var s=2===t._type,r=t.atlasViewportAllocated,a=this.cookiesEnabled&&!!t._cookie&&r,o=this.areaLightsEnabled&&0!==t.shape,h=this.shadowsEnabled&&t.castShadows&&r,l=t._node.getPosition(),c=null,u=null;s?h?c=t.getRenderData(null,0).shadowMatrix:a&&(c=Yn.evalSpotCookieMatrix(t)):(h||a)&&(u=t.atlasViewport);var d=this.lights8,f=i*this.lightsTexture8.width*4;if(this.addLightDataFlags(d,f+4*Jn.FLAGS,t,s,h,t.shadowIntensity),this.addLightDataColor(d,f+4*Jn.COLOR_A,t,n,a),s&&this.addLightDataSpotAngles(d,f+4*Jn.SPOT_ANGLES,t),t.castShadows&&this.addLightDataShadowBias(d,f+4*Jn.SHADOW_BIAS,t),a&&this.addLightDataCookies(d,f+4*Jn.COOKIE_A,t),e.lightTextureFormat===e.FORMAT_FLOAT){var p=this.lightsFloat,m=i*this.lightsTextureFloat.width*4;if(p[m+4*es.POSITION_RANGE+0]=l.x,p[m+4*es.POSITION_RANGE+1]=l.y,p[m+4*es.POSITION_RANGE+2]=l.z,p[m+4*es.POSITION_RANGE+3]=t.attenuationEnd,s&&(this.getSpotDirection(Kn,t),p[m+4*es.SPOT_DIRECTION+0]=Kn.x,p[m+4*es.SPOT_DIRECTION+1]=Kn.y,p[m+4*es.SPOT_DIRECTION+2]=Kn.z),c)for(var _=c.data,g=0;g<16;g++)p[m+4*es.PROJ_MAT_0+g]=_[g];if(u&&(p[m+4*es.ATLAS_VIEWPORT+0]=u.x,p[m+4*es.ATLAS_VIEWPORT+1]=u.y,p[m+4*es.ATLAS_VIEWPORT+2]=u.z/3),o){var v=this.getLightAreaSizes(t);p[m+4*es.AREA_DATA_WIDTH+0]=v[0],p[m+4*es.AREA_DATA_WIDTH+1]=v[1],p[m+4*es.AREA_DATA_WIDTH+2]=v[2],p[m+4*es.AREA_DATA_HEIGHT+0]=v[3],p[m+4*es.AREA_DATA_HEIGHT+1]=v[4],p[m+4*es.AREA_DATA_HEIGHT+2]=v[5]}}else this.addLightDataPositionRange(d,f+4*Jn.POSITION_X,t,l),s&&this.addLightDataSpotDirection(d,f+4*Jn.SPOT_DIRECTION_X,t),c&&this.addLightDataLightProjMatrix(d,f+4*Jn.PROJ_MAT_00,c),u&&this.addLightAtlasViewport(d,f+4*Jn.ATLAS_VIEWPORT_A,u),o&&this.addLightAreaSizes(d,f+4*Jn.AREA_DATA_WIDTH_X,t)},e}();ts.FORMAT_FLOAT=0,ts.FORMAT_8BIT=1,ts.lightTextureFormat=ts.FORMAT_8BIT,ts.shaderDefines="";var is={vertex_normal:yt,vertex_tangent:xt,vertex_texCoord0:At,vertex_texCoord1:Mt,vertex_color:wt,vertex_boneWeights:bt,vertex_boneIndices:St},ns={vVertexColor:"vec4",vPositionW:"vec3",vNormalV:"vec3",vNormalW:"vec3",vTangentW:"vec3",vBinormalW:"vec3",vObjectSpaceUpW:"vec3",vUv0:"vec2",vUv1:"vec2"},ss=function(){function e(e,t){if(this.device=e,this.options=t,this.attributes={vertex_position:vt},t.chunks){this.chunks={};var i=t.chunks;for(var n in Wi)if(i.hasOwnProperty(n)){var s=i[n];for(var r in is)is.hasOwnProperty(r)&&s.indexOf(r)>=0&&(this.attributes[r]=is[r]);this.chunks[n]=s}else this.chunks[n]=Wi[n]}else this.chunks=Wi;this.lighting=t.lights.length>0||!!t.dirLightMap||!!t.clusteredLightingEnabled,this.reflections=!!t.reflectionSource,t.useSpecular||(t.specularMap=t.glossMap=null),this.shadowPass=Hi.isShadow(t.pass),this.needsNormal=this.lighting||this.reflections||t.useSpecular||t.ambientSH||t.heightMap||t.enableGGXSpecular||t.clusteredLightingEnabled&&!this.shadowPass||t.clearCoatNormalMap,this.needsSceneColor=t.useDynamicRefraction,this.needsScreenSize=t.useDynamicRefraction,this.needsTransforms=t.useDynamicRefraction,this.varyings="",this.vshader=null,this.frontendDecl=null,this.frontendCode=null,this.frontendFunc=null,this.lightingUv=null,this.defines=[],this.fshader=null}var t=e.prototype;return t._vsAddBaseCode=function(e,t,i){return e+=t.baseVS,1!==i.nineSlicedMode&&2!==i.nineSlicedMode||(e+=t.baseNineSlicedVS),e},t._vsAddTransformCode=function(e,t,i,n){return e+=this.chunks.transformVS},t._setMapTransform=function(e,t,i,n){var s=i+100*n;if(!e[3][s]){var r="texture_"+t+"MapTransform";e[0]+="uniform vec3 "+r+"0;\n",e[0]+="uniform vec3 "+r+"1;\n",e[1]+="varying vec2 vUV"+n+"_"+i+";\n",e[2]+=" vUV"+n+"_"+i+" = vec2(dot(vec3(uv"+n+", 1), "+r+"0), dot(vec3(uv"+n+", 1), "+r+"1));\n",e[3][s]=!0}return e},t._fsGetBaseCode=function(){var e=this.options,t=this.chunks,i=this.chunks.basePS;return 1===e.nineSlicedMode?i+=t.baseNineSlicedPS:2===e.nineSlicedMode&&(i+=t.baseNineSlicedTiledPS),i},t._fsGetStartCode=function(e,t,i,n){var s=i.startPS;return 1===n.nineSlicedMode?s+=i.startNineSlicedPS:2===n.nineSlicedMode&&(s+=i.startNineSlicedTiledPS),s},t._directionalShadowMapProjection=function(e,t,i,n,s){var r="";return e.numCascades>1&&(r+="getShadowCascadeMatrix(light"+n+"_shadowMatrixPalette, light"+n+"_shadowCascadeDistances, light"+n+"_shadowCascadeCount);\n",t="(cascadeShadowMat, "+i+");\n"),r+=s+t,r+="fadeShadow(light"+n+"_shadowCascadeDistances);\n"},t._nonPointShadowMapProjection=function(e,t,i,n,s){var r="("+i+", "+n+");\n";return!t._normalOffsetBias||t._isVsm?2===t._type?t._isPcf&&(e.webgl2||e.extStandardDerivatives)?" getShadowCoordPerspZbuffer"+r:" getShadowCoordPersp"+r:this._directionalShadowMapProjection(t,r,n,s,"getShadowCoordOrtho"):2===t._type?t._isPcf&&(e.webgl2||e.extStandardDerivatives)?" getShadowCoordPerspZbufferNormalOffset"+r:" getShadowCoordPerspNormalOffset"+r:this._directionalShadowMapProjection(t,r,n,s,"getShadowCoordOrthoNormalOffset")},t._getLightSourceShapeString=function(e){switch(e){case 1:return"Rect";case 2:return"Disk";case 3:return"Sphere";default:return""}},t.generateVertexShader=function(e,t,i){var n=this,s=this.device,r=this.options,a=this.chunks,o="",h="";o=this._vsAddBaseCode(o,a,r),h+=" vPositionW = getWorldPosition();\n",2===this.options.pass&&(o+="varying float vDepth;\n",o+="#ifndef VIEWMATRIX\n",o+="#define VIEWMATRIX\n",o+="uniform mat4 matrix_view;\n",o+="#endif\n",o+="#ifndef CAMERAPLANES\n",o+="#define CAMERAPLANES\n",o+="uniform vec4 camera_params;\n\n",o+="#endif\n",h+=" vDepth = -(matrix_view * vec4(vPositionW,1.0)).z * camera_params.x;\n"),this.options.useInstancing&&(this.attributes.instance_line1=qt,this.attributes.instance_line2=jt,this.attributes.instance_line3=Yt,this.attributes.instance_line4=Kt,o+=a.instancingVS),this.needsNormal&&(this.attributes.vertex_normal=yt,h+=" vNormalW = getNormal();\n","sphereMap"===r.reflectionSource&&s.fragmentUniformsCount<=16&&(o+=a.viewNormalVS,h+=" vNormalV = getViewNormal();\n"),r.hasTangents&&(r.heightMap||r.normalMap||r.enableGGXSpecular)?(this.attributes.vertex_tangent=xt,o+=a.tangentBinormalVS,h+=" vTangentW = getTangent();\n",h+=" vBinormalW = getBinormal();\n"):r.enableGGXSpecular&&(o+=a.tangentBinormalVS,h+=" vObjectSpaceUpW = getObjectSpaceUp();\n"));for(var l=0;l<2;l++)e[l]&&(this.attributes["vertex_texCoord"+l]="TEXCOORD"+l,o+=a["uv"+l+"VS"],h+=" vec2 uv"+l+" = getUv"+l+"();\n"),t[l]&&(h+=" vUv"+l+" = uv"+l+";\n");var c=[o,this.varyings,h,[]];i.forEach((function(e){n._setMapTransform(c,e.name,e.id,e.uv)})),o=c[0],this.varyings=c[1],h=c[2],r.vertexColors&&(this.attributes.vertex_color=wt,h+=" vVertexColor = vertex_color;\n"),r.msdf&&r.msdfTextAttribute&&(this.attributes.vertex_outlineParameters=Gt,this.attributes.vertex_shadowParameters=Wt,h+=" unpackMsdfParams();\n",o+=a.msdfVS),(r.useMorphPosition||r.useMorphNormal)&&(r.useMorphTextureBased?(o+="#define MORPHING_TEXTURE_BASED\n",r.useMorphPosition&&(o+="#define MORPHING_TEXTURE_BASED_POSITION\n"),r.useMorphNormal&&(o+="#define MORPHING_TEXTURE_BASED_NORMAL\n"),this.attributes.morph_vertex_id=Kt,o+="attribute float morph_vertex_id;\n"):(o+="#define MORPHING\n",r.useMorphPosition?(this.attributes.morph_pos0=Gt,this.attributes.morph_pos1=Wt,this.attributes.morph_pos2=Ht,this.attributes.morph_pos3=Xt,o+="#define MORPHING_POS03\n",o+="attribute vec3 morph_pos0;\n",o+="attribute vec3 morph_pos1;\n",o+="attribute vec3 morph_pos2;\n",o+="attribute vec3 morph_pos3;\n"):r.useMorphNormal&&(this.attributes.morph_nrm0=Gt,this.attributes.morph_nrm1=Wt,this.attributes.morph_nrm2=Ht,this.attributes.morph_nrm3=Xt,o+="#define MORPHING_NRM03\n",o+="attribute vec3 morph_nrm0;\n",o+="attribute vec3 morph_nrm1;\n",o+="attribute vec3 morph_nrm2;\n",o+="attribute vec3 morph_nrm3;\n"),r.useMorphNormal?(this.attributes.morph_nrm4=qt,this.attributes.morph_nrm5=jt,this.attributes.morph_nrm6=Yt,this.attributes.morph_nrm7=Kt,o+="#define MORPHING_NRM47\n",o+="attribute vec3 morph_nrm4;\n",o+="attribute vec3 morph_nrm5;\n",o+="attribute vec3 morph_nrm6;\n",o+="attribute vec3 morph_nrm7;\n"):(this.attributes.morph_pos4=qt,this.attributes.morph_pos5=jt,this.attributes.morph_pos6=Yt,this.attributes.morph_pos7=Kt,o+="#define MORPHING_POS47\n",o+="attribute vec3 morph_pos4;\n",o+="attribute vec3 morph_pos5;\n",o+="attribute vec3 morph_pos6;\n",o+="attribute vec3 morph_pos7;\n"))),r.skin?(this.attributes.vertex_boneWeights=bt,this.attributes.vertex_boneIndices=St,o+=Yi(s,a),o+="#define SKIN\n"):r.useInstancing&&(o+="#define INSTANCING\n"),r.screenSpace&&(o+="#define SCREENSPACE\n"),r.pixelSnap&&(o+="#define PIXELSNAP\n"),o=this._vsAddTransformCode(o,s,a,r),this.needsNormal&&(o+=a.normalVS),o+="\n",o+=a.startVS,o+=h,o+=a.endVS,o+="}",Object.keys(ns).forEach((function(e){o.indexOf(e)>=0&&(n.varyings+="varying "+ns[e]+" "+e+";\n")}));var u=Qi(s,"LitShader",this.options.pass,a.extensionVS);this.vshader=u+this.varyings+o},t._fsGetBeginCode=function(){for(var e=this.device,t=this.chunks,i=this.options.forceFragmentPrecision,n=Ji(e,"LitShader",this.options.pass,t.extensionPS,i),s=0;s<this.defines.length;s++)n+="#define "+this.defines[s]+"\n";return n},t._fsGetPickPassCode=function(){var e=this._fsGetBeginCode();return e+="uniform vec4 uColor;\n",e+=this.varyings,e+=this.frontendDecl,e+=this.frontendCode,e+="void main(void)\n{\n",e+=this.frontendFunc,e+=" gl_FragColor = uColor;\n",e+="}\n"},t._fsGetDepthPassCode=function(){var e=this.chunks,t=this._fsGetBeginCode();return t+="varying float vDepth;\n",t+=this.varyings,t+=e.packDepthPS,t+=this.frontendDecl,t+=this.frontendCode,t+="void main(void)\n{\n",t+=this.frontendFunc,t+=" gl_FragColor = packFloat(vDepth);\n",t+="}\n"},t._fsGetShadowPassCode=function(){var e=this.device,t=this.options,i=this.chunks,n=this.varyings,s=Hi.toLightType(t.pass),r=Hi.toShadowType(t.pass),a=this._fsGetBeginCode();return e.extStandardDerivatives&&!e.webgl2&&(a+="uniform vec2 polygonOffset;\n"),3===r?e.textureFloatHighPrecision?a+="#define VSM_EXPONENT 15.0\n\n":a+="#define VSM_EXPONENT 5.54\n\n":2===r&&(a+="#define VSM_EXPONENT 5.54\n\n"),0!==s&&(a+="uniform vec3 view_position;\n",a+="uniform float light_radius;\n"),a+=n,a+=this.frontendDecl,a+=this.frontendCode,0!==r||e.webgl2&&1!==s?1===r&&(a+="vec2 encodeFloatRG( float v ) {\n",a+=" vec2 enc = vec2(1.0, 255.0) * v;\n",a+=" enc = fract(enc);\n",a+=" enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n",a+=" return enc;\n",a+="}\n\n"):a+=i.packDepthPS,a+="void main(void)\n{\n",a+=this.frontendFunc,a+=1===s||(1===r||2===r||3===r)&&0!==s?" float depth = min(distance(view_position, vPositionW) / light_radius, 0.99999);\n":" float depth = gl_FragCoord.z;\n",!e.webgl2&&e.extStandardDerivatives&&(a+=" float minValue = 2.3374370500153186e-10; //(1.0 / 255.0) / (256.0 * 256.0 * 256.0);\n",a+=" depth += polygonOffset.x * max(abs(dFdx(depth)), abs(dFdy(depth))) + minValue * polygonOffset.y;\n"),0!==r||e.webgl2&&(1!==s||t.clusteredLightingEnabled)?0===r||4===r?(a+=" gl_FragColor = vec4(1.0);\n",t.clusteredLightingEnabled&&1===s&&e.webgl2&&(a+=" gl_FragDepth = depth;\n")):a+=1===r?" gl_FragColor = vec4(encodeFloatRG(depth), encodeFloatRG(depth*depth));\n":i.storeEVSMPS:a+=" gl_FragColor = packFloat(depth);\n",a+="}\n"},t._fsGetLitPassCode=function(){var e=this.device,t=this.options,i=this.chunks,n="";!1===t.opacityFadesSpecular&&(n+="uniform float material_alphaFade;\n"),t.useSpecular&&(this.defines.push("LIT_SPECULAR"),this.reflections&&this.defines.push("LIT_REFLECTIONS"),t.clearCoat&&this.defines.push("LIT_CLEARCOAT"),t.fresnelModel>0&&this.defines.push("LIT_SPECULAR_FRESNEL"),t.conserveEnergy&&this.defines.push("LIT_CONSERVE_ENERGY"),t.sheen&&this.defines.push("LIT_SHEEN"),t.iridescence&&this.defines.push("LIT_IRIDESCENCE"));var s=[],r=0,a=!1,o=!1,h=!1,l=t.lights.some((function(e){return e._shape&&0!==e._shape}));t.clusteredLightingEnabled&&t.clusteredLightingAreaLightsEnabled&&(l=!0);var c="highp";7===e.areaLightLutFormat&&(n+="#define AREA_R8_G8_B8_A8_LUTS\n",c="lowp"),(l||t.clusteredLightingEnabled)&&(n+="#define AREA_LIGHTS\n",n+="uniform "+c+" sampler2D areaLightsLutTex1;\n",n+="uniform "+c+" sampler2D areaLightsLutTex2;\n");for(var u=0;u<t.lights.length;u++){var d=t.lights[u],f=d._type;if(!t.clusteredLightingEnabled||0===f)n+="uniform vec3 light"+u+"_color;\n",0===f?n+="uniform vec3 light"+u+"_direction;\n":(n+="uniform vec3 light"+u+"_position;\n",n+="uniform float light"+u+"_radius;\n",2===f&&(n+="uniform vec3 light"+u+"_direction;\n",n+="uniform float light"+u+"_innerConeAngle;\n",n+="uniform float light"+u+"_outerConeAngle;\n")),0!==(l&&d._shape?d._shape:0)&&(0===f&&(n+="uniform vec3 light"+u+"_position;\n"),n+="uniform vec3 light"+u+"_halfWidth;\n",n+="uniform vec3 light"+u+"_halfHeight;\n"),d.castShadows&&!t.noShadow&&(n+="uniform mat4 light"+u+"_shadowMatrix;\n",n+="uniform float light"+u+"_shadowIntensity;\n",0===f&&(n+="uniform mat4 light"+u+"_shadowMatrixPalette[4];\n",n+="uniform float light"+u+"_shadowCascadeDistances[4];\n",n+="uniform float light"+u+"_shadowCascadeCount;\n"),0!==f?n+="uniform vec4 light"+u+"_shadowParams;\n":(a=!0,n+="uniform vec3 light"+u+"_shadowParams;\n"),1===f?n+="uniform samplerCube light"+u+"_shadowMap;\n":d._isPcf&&e.webgl2?n+="uniform sampler2DShadow light"+u+"_shadowMap;\n":n+="uniform sampler2D light"+u+"_shadowMap;\n",r++,s[d._shadowType]=!0,d._isVsm&&(o=!0),d._isPcf&&(e.webgl2||e.extStandardDerivatives)&&2===f&&(h=!0)),d._cookie&&(d._cookie._cubemap?1===f&&(n+="uniform samplerCube light"+u+"_cookie;\n",n+="uniform float light"+u+"_cookieIntensity;\n",d.castShadows&&!t.noShadow||(n+="uniform mat4 light"+u+"_shadowMatrix;\n")):2===f&&(n+="uniform sampler2D light"+u+"_cookie;\n",n+="uniform float light"+u+"_cookieIntensity;\n",d.castShadows&&!t.noShadow||(n+="uniform mat4 light"+u+"_shadowMatrix;\n"),d._cookieTransform&&(n+="uniform vec4 light"+u+"_cookieMatrix;\n",n+="uniform vec2 light"+u+"_cookieOffset;\n")))}n+="\n";var p=this.needsNormal&&(t.normalMap||t.clearCoatNormalMap||t.enableGGXSpecular&&!t.heightMap);p&&(t.hasTangents?n+=t.fastTbn?i.TBNfastPS:i.TBNPS:e.extStandardDerivatives&&(t.normalMap||t.clearCoatNormalMap)?n+=i.TBNderivativePS.replace(/\$UV/g,this.lightingUv):n+=i.TBNObjectSpacePS),n+=i.sphericalPS,n+=i.decodePS,n+=Xi(t.gamma,i),n+=qi(t.toneMap,i),n+=ji(t.fog,i),n+=this.frontendCode,t.useCubeMapRotation&&(n+="#define CUBEMAP_ROTATION\n"),this.needsNormal&&(n+=i.cubeMapRotatePS,n+=t.cubeMapProjection>0?i.cubeMapProjectBoxPS:i.cubeMapProjectNonePS,n+=t.skyboxIntensity?i.envMultiplyPS:i.envConstPS),(this.lighting&&t.useSpecular||this.reflections)&&(t.useMetalness&&(n+=i.metalnessModulatePS),2===t.fresnelModel&&(n+=i.fresnelSchlickPS),t.iridescence&&(n+=i.iridescenceDiffractionPS));var m=t.aoMap||t.aoVertexColor;if(m)switch(n+=i.aoDiffuseOccPS,t.occludeSpecular){case 1:n+=t.occludeSpecularFloat?i.aoSpecOccSimplePS:i.aoSpecOccConstSimplePS;break;case 2:n+=t.occludeSpecularFloat?i.aoSpecOccPS:i.aoSpecOccConstPS}if("envAtlasHQ"===t.reflectionSource)n+=t.fixSeams?i.fixCubemapSeamsStretchPS:i.fixCubemapSeamsNonePS,n+=i.envAtlasPS,n+=i.reflectionEnvHQPS.replace(/\$DECODE/g,mn.decodeFunc(t.reflectionEncoding));else if("envAtlas"===t.reflectionSource)n+=i.envAtlasPS,n+=i.reflectionEnvPS.replace(/\$DECODE/g,mn.decodeFunc(t.reflectionEncoding));else if("cubeMap"===t.reflectionSource)n+=t.fixSeams?i.fixCubemapSeamsStretchPS:i.fixCubemapSeamsNonePS,n+=i.reflectionCubePS.replace(/\$DECODE/g,mn.decodeFunc(t.reflectionEncoding));else if("sphereMap"===t.reflectionSource){n+=(e.fragmentUniformsCount>16?i.reflectionSpherePS:i.reflectionSphereLowPS).replace(/\$DECODE/g,mn.decodeFunc(t.reflectionEncoding))}this.reflections&&(t.clearCoat&&(n+=i.reflectionCCPS),t.sheen&&(n+=i.reflectionSheenPS)),t.refraction&&(t.useDynamicRefraction?n+=i.refractionDynamicPS:this.reflections&&(n+=i.refractionCubePS)),t.sheen&&(n+=i.lightSheenPS),t.clusteredLightingEnabled&&(n+=i.clusteredLightUtilsPS,t.clusteredLightingCookiesEnabled&&(n+=i.clusteredLightCookiesPS),t.clusteredLightingShadowsEnabled&&!t.noShadow&&(s[0]=!0,s[4]=!0),h=!0),(r>0||t.clusteredLightingEnabled)&&(a&&(n+=i.shadowCascadesPS),s[0]&&(n+=i.shadowStandardPS),s[4]&&e.webgl2&&(n+=i.shadowStandardGL2PS),o&&(n+=i.shadowVSM_commonPS,s[1]&&(n+=i.shadowVSM8PS),s[2]&&(n+=e.extTextureHalfFloatLinear?i.shadowEVSMPS.replace(/\$/g,"16"):i.shadowEVSMnPS.replace(/\$/g,"16")),s[3]&&(n+=e.extTextureFloatLinear?i.shadowEVSMPS.replace(/\$/g,"32"):i.shadowEVSMnPS.replace(/\$/g,"32"))),e.webgl2||e.extStandardDerivatives||(n+=i.biasConstPS),n+=i.shadowCoordPS+i.shadowCommonPS,h&&(n+=i.shadowCoordPerspZbufferPS)),t.enableGGXSpecular&&(n+="uniform float material_anisotropy;\n"),this.lighting&&(n+=i.lightDiffuseLambertPS,(l||t.clusteredLightingEnabled)&&(n+=i.ltc)),n+="\n";var _=!1;t.useSpecular&&(this.lighting&&(n+=0===t.shadingModel?i.lightSpecularPhongPS:t.enableGGXSpecular?i.lightSpecularAnisoGGXPS:i.lightSpecularBlinnPS),t.fresnelModel||this.reflections||t.diffuseMap||(n+=" uniform vec3 material_ambient;\n",n+="#define LIT_OLD_AMBIENT",_=!0)),n+=i.combinePS,(t.lightMap||t.lightVertexColor)&&(n+=t.useSpecular&&t.dirLightMap?i.lightmapDirAddPS:i.lightmapAddPS);var g=!t.lightMap&&!t.lightVertexColor||t.lightMapWithoutAmbient;g&&("ambientSH"===t.ambientSource?n+=i.ambientSHPS:"envAtlas"===t.ambientSource?("envAtlas"!==t.reflectionSource&&"envAtlasHQ"!==t.reflectionSource&&(n+=i.envAtlasPS),n+=i.ambientEnvPS.replace(/\$DECODE/g,mn.decodeFunc(t.ambientEncoding))):n+=i.ambientConstantPS),t.ambientTint&&!_&&(n+="uniform vec3 material_ambient;\n"),t.msdf&&(t.msdfTextAttribute||(n+="\n#define UNIFORM_TEXT_PARAMETERS"),n+=i.msdfPS),this.needsNormal&&(n+=i.viewDirPS,t.useSpecular&&(n+=t.enableGGXSpecular?i.reflDirAnisoPS:i.reflDirPS));var v,y=!1,x=!1,b=!1,S=!1,w=!1;if(t.clusteredLightingEnabled&&this.lighting&&(S=!0,y=!0,x=!0,w=!0,n+=i.floatUnpackingPS,t.lightMaskDynamic&&(n+="\n#define CLUSTER_MESH_DYNAMIC_LIGHTS"),t.clusteredLightingCookiesEnabled&&(n+="\n#define CLUSTER_COOKIES"),t.clusteredLightingShadowsEnabled&&!t.noShadow&&(n+="\n#define CLUSTER_SHADOWS",n+="\n#define CLUSTER_SHADOW_TYPE_"+Ve[t.clusteredLightingShadowType]),t.clusteredLightingAreaLightsEnabled&&(n+="\n#define CLUSTER_AREALIGHTS"),n+=ts.shaderDefines,t.clusteredLightingShadowsEnabled&&!t.noShadow&&(n+=i.clusteredLightShadowsPS),n+=i.clusteredLightPS),t.twoSidedLighting&&(n+="uniform float twoSidedLightingNegScaleFactor;\n"),n+=this._fsGetStartCode(n,e,i,t),this.needsNormal&&(t.twoSidedLighting?n+=" dVertexNormalW = normalize(gl_FrontFacing ? vNormalW * twoSidedLightingNegScaleFactor : -vNormalW * twoSidedLightingNegScaleFactor);\n":n+=" dVertexNormalW = normalize(vNormalW);\n",(t.heightMap||t.normalMap)&&t.hasTangents&&(t.twoSidedLighting?(n+=" dTangentW = gl_FrontFacing ? vTangentW * twoSidedLightingNegScaleFactor : -vTangentW * twoSidedLightingNegScaleFactor;\n",n+=" dBinormalW = gl_FrontFacing ? vBinormalW * twoSidedLightingNegScaleFactor : -vBinormalW * twoSidedLightingNegScaleFactor;\n"):(n+=" dTangentW = vTangentW;\n",n+=" dBinormalW = vBinormalW;\n")),n+=" getViewDir();\n",p&&(n+=" getTBN();\n")),n+=this.frontendFunc,this.needsNormal&&(t.useSpecular&&(n+=" getReflDir();\n"),t.clearCoat&&(n+=" ccReflDirW = normalize(-reflect(dViewDirW, ccNormalW));\n")),(this.lighting&&t.useSpecular||this.reflections)&&(t.useMetalness&&(n+=" getMetalnessModulate();\n"),t.iridescence&&(n+=" getIridescence(saturate(dot(dViewDirW, dNormalW)));\n")),g&&(n+=" addAmbient();\n",t.separateAmbient&&(n+="\n vec3 dAmbientLight = dDiffuseLight;\n dDiffuseLight = vec3(0);\n ")),t.ambientTint&&!_&&(n+=" dDiffuseLight *= material_ambient;\n"),m&&!t.occludeDirect&&(n+=" occludeDiffuse();\n"),(t.lightMap||t.lightVertexColor)&&(n+=" addLightMap();\n"),this.lighting||this.reflections){this.reflections&&(t.clearCoat&&(n+=" addReflectionCC();\n",t.fresnelModel>0?(n+=" ccFresnel = getFresnelCC(dot(dViewDirW, ccNormalW));\n",n+=" ccReflection.rgb *= ccFresnel;\n"):n+=" ccFresnel = 0.0;\n"),t.useSpecularityFactor&&(n+=" ccReflection.rgb *= dSpecularityFactor;\n"),t.sheen&&(n+=" addReflectionSheen();\n"),n+=" addReflection();\n",t.fresnelModel>0?n+=" dReflection.rgb *= getFresnel(dot(dViewDirW, dNormalW), dSpecularity);\n":n+=" dReflection.rgb *= dSpecularity;\n",t.useSpecularityFactor&&(n+=" dReflection.rgb *= dSpecularityFactor;\n")),l&&(n+=" dSpecularLight *= dSpecularity;\n",t.useSpecular&&(n+=" calcLTCLightValues();\n"));for(var T=0;T<t.lights.length;T++){var A=t.lights[T],M=A._type;if(!t.clusteredLightingEnabled||0===M){v=!1;var C=l&&A._shape?A.shape:0,E=l&&A._shape?this._getLightSourceShapeString(C):"";if(0!==C&&(n+=" calc"+E+"LightValues(light"+T+"_position, light"+T+"_halfWidth, light"+T+"_halfHeight);\n"),0===M?(n+=" dLightDirNormW = light"+T+"_direction;\n",n+=" dAtten = 1.0;\n"):(A._cookie&&(2!==M||A._cookie._cubemap?1===M&&A._cookie._cubemap&&(w=!0,v=!0):(w=!0,v=!0)),n+=" getLightDirPoint(light"+T+"_position);\n",y=!0,v&&(n+=2===M?" dAtten3 = getCookie2D"+(A._cookieFalloff?"":"Clip")+(A._cookieTransform?"Xform":"")+"(light"+T+"_cookie, light"+T+"_shadowMatrix, light"+T+"_cookieIntensity"+(A._cookieTransform?", light"+T+"_cookieMatrix, light"+T+"_cookieOffset":"")+")."+A._cookieChannel+";\n":" dAtten3 = getCookieCube(light"+T+"_cookie, light"+T+"_shadowMatrix, light"+T+"_cookieIntensity)."+A._cookieChannel+";\n"),0===C?0===A._falloffMode?(n+=" dAtten = getFalloffLinear(light"+T+"_radius);\n",x=!0):(n+=" dAtten = getFalloffInvSquared(light"+T+"_radius);\n",b=!0):(n+=" dAtten = getFalloffWindow(light"+T+"_radius);\n",b=!0),n+=" if (dAtten > 0.00001) {\n",2===M&&(v&&!A._cookieFalloff||(n+=" dAtten *= getSpotEffect(light"+T+"_direction, light"+T+"_innerConeAngle, light"+T+"_outerConeAngle);\n",S=!0))),n+=0!==C?0===M?" dAttenD = getLightDiffuse();\n":" dAttenD = get"+E+"LightDiffuse() * 16.0;\n":" dAtten *= getLightDiffuse();\n",A.castShadows&&!t.noShadow){var P=null,R=void 0;if(1===A._shadowType?(P="VSM8",R="0.0"):2===A._shadowType?(P="VSM16",R="5.54"):3===A._shadowType?(P="VSM32",R=e.textureFloatHighPrecision?"15.0":"5.54"):P=4===A._shadowType?"PCF5x5":"PCF3x3",null!==P)if(1===M){var I="(light"+T+"_shadowMap, light"+T+"_shadowParams);\n";A._normalOffsetBias&&(n+=" normalOffsetPointShadow(light"+T+"_shadowParams);\n"),n+=" float shadow"+T+" = getShadowPoint"+P+I,n+=" dAtten *= mix(1.0, shadow"+T+", light"+T+"_shadowIntensity);\n"}else{var L="light"+T+"_shadowMatrix",D="light"+T+"_shadowParams";n+=this._nonPointShadowMapProjection(e,t.lights[T],L,D,T),2===M&&(P="Spot"+P),n+=" float shadow"+T+" = getShadow"+P+"(light"+T+"_shadowMap, light"+T+"_shadowParams"+(A._isVsm?", "+R:"")+");\n",n+=" dAtten *= mix(1.0, shadow"+T+", light"+T+"_shadowIntensity);\n"}}if(0!==C?t.conserveEnergy&&t.useSpecular?n+=" dDiffuseLight += mix((dAttenD * dAtten) * light"+T+"_color"+(v?" * dAtten3":"")+", vec3(0), dLTCSpecFres);\n":n+=" dDiffuseLight += (dAttenD * dAtten) * light"+T+"_color"+(v?" * dAtten3":"")+";\n":l&&t.conserveEnergy&&t.useSpecular?n+=" dDiffuseLight += mix(dAtten * light"+T+"_color"+(v?" * dAtten3":"")+", vec3(0), dSpecularity);\n":n+=" dDiffuseLight += dAtten * light"+T+"_color"+(v?" * dAtten3":"")+";\n",t.useSpecular&&(n+=" dHalfDirW = normalize(-dLightDirNormW + dViewDirW);\n"),0!==C)t.clearCoat&&(n+=" ccSpecularLight += ccLTCSpecFres * get"+E+"LightSpecularCC() * dAtten * light"+T+"_color"+(v?" * dAtten3":"")+";\n"),t.useSpecular&&(n+=" dSpecularLight += dLTCSpecFres * get"+E+"LightSpecular() * dAtten * light"+T+"_color"+(v?" * dAtten3":"")+";\n");else{var k=!1;0===M&&t.fresnelModel>0&&(k=!0),t.clearCoat&&(n+=" ccSpecularLight += getLightSpecularCC(dHalfDirW) * dAtten * light"+T+"_color",n+=v?" * dAtten3":"",n+=k?" * getFresnelCC(dot(dViewDirW, dHalfDirW))":"",n+=";\n"),t.sheen&&(n+=" sSpecularLight += getLightSpecularSheen(dHalfDirW) * dAtten * light"+T+"_color",n+=v?" * dAtten3":"",n+=";\n"),t.useSpecular&&(n+=" dSpecularLight += getLightSpecular(dHalfDirW) * dAtten * light"+T+"_color",n+=v?" * dAtten3":"",n+=k?" * getFresnel(dot(dViewDirW, dHalfDirW), dSpecularity)":"",n+=";\n")}0!==M&&(n+=" }\n"),n+="\n"}}t.clusteredLightingEnabled&&this.lighting&&(x=!0,b=!0,y=!0,n+=" addClusteredLights();\n"),l&&(t.clearCoat&&(n+=" ccSpecularity = 1.0;\n"),t.useSpecular&&(n+=" dSpecularity = vec3(1);\n")),t.refraction&&(n+=" addRefraction();\n")}n+="\n",m&&(t.occludeDirect&&(n+=" occludeDiffuse();\n"),1!==t.occludeSpecular&&2!==t.occludeSpecular||(n+=" occludeSpecular();\n")),t.useSpecularityFactor&&(n+=" dSpecularLight *= dSpecularityFactor;\n"),!1===t.opacityFadesSpecular&&(2!==t.blendType&&4!==t.blendType||(n+="float specLum = dot((dSpecularLight + dReflection.rgb * dReflection.a), vec3( 0.2126, 0.7152, 0.0722 ));\n",n+="#ifdef LIT_CLEARCOAT\n specLum += dot(ccSpecularLight * ccSpecularity + ccReflection.rgb * ccSpecularity, vec3( 0.2126, 0.7152, 0.0722 ));\n#endif\n",n+="dAlpha = clamp(dAlpha + gammaCorrectInput(specLum), 0.0, 1.0);\n"),n+="dAlpha *= material_alphaFade;\n"),n+=i.endPS,2===t.blendType||6===t.blendType||t.alphaToCoverage?n+=i.outputAlphaPS:4===t.blendType?n+=i.outputAlphaPremulPS:n+=i.outputAlphaOpaquePS,t.msdf&&(n+=" gl_FragColor = applyMsdf(gl_FragColor);\n"),n+="\n",n+="}\n",y&&(n=i.lightDirPointPS+n),x&&(n=i.falloffLinearPS+n),b&&(n=i.falloffInvSquaredPS+n),S&&(n=i.spotPS+n),w&&!t.clusteredLightingEnabled&&(n=i.cookiePS+n);var O="";return n.includes("dReflection")&&(O+="vec4 dReflection;\n"),n.includes("dTBN")&&(O+="mat3 dTBN;\n"),n.includes("dVertexNormalW")&&(O+="vec3 dVertexNormalW;\n"),n.includes("dTangentW")&&(O+="vec3 dTangentW;\n"),n.includes("dBinormalW")&&(O+="vec3 dBinormalW;\n"),n.includes("dViewDirW")&&(O+="vec3 dViewDirW;\n"),n.includes("dReflDirW")&&(O+="vec3 dReflDirW;\n"),n.includes("dHalfDirW")&&(O+="vec3 dHalfDirW;\n"),n.includes("dDiffuseLight")&&(O+="vec3 dDiffuseLight;\n"),n.includes("dSpecularLight")&&(O+="vec3 dSpecularLight;\n"),n.includes("dLightDirNormW")&&(O+="vec3 dLightDirNormW;\n"),n.includes("dLightDirW")&&(O+="vec3 dLightDirW;\n"),n.includes("dLightPosW")&&(O+="vec3 dLightPosW;\n"),n.includes("dShadowCoord")&&(O+="vec3 dShadowCoord;\n"),n.includes("dAtten")&&(O+="float dAtten;\n"),n.includes("dAttenD")&&(O+="float dAttenD;\n"),n.includes("dAtten3")&&(O+="vec3 dAtten3;\n"),n.includes("dMsdf")&&(O+="vec4 dMsdf;\n"),n.includes("ccFresnel")&&(O+="float ccFresnel;\n"),n.includes("ccReflection")&&(O+="vec3 ccReflection;\n"),n.includes("ccReflDirW")&&(O+="vec3 ccReflDirW;\n"),n.includes("ccSpecularLight")&&(O+="vec3 ccSpecularLight;\n"),n.includes("ccSpecularityNoFres")&&(O+="float ccSpecularityNoFres;\n"),n.includes("sSpecularLight")&&(O+="vec3 sSpecularLight;\n"),n.includes("sReflection")&&(O+="vec3 sReflection;\n"),this._fsGetBeginCode()+this.varyings+this._fsGetBaseCode()+(t.detailModes?i.detailModesPS:"")+O+this.frontendDecl+n},t.generateFragmentShader=function(e,t,i,n){var s=this.options;this.frontendDecl=e,this.frontendCode=t,this.frontendFunc=i,this.lightingUv=n,3===s.pass?this.fshader=this._fsGetPickPassCode():2===s.pass?this.fshader=this._fsGetDepthPassCode():this.shadowPass?this.fshader=this._fsGetShadowPassCode():s.customFragmentShader?this.fshader=this._fsGetBeginCode()+s.customFragmentShader:this.fshader=this._fsGetLitPassCode()},t.getDefinition=function(){var e={attributes:this.attributes,vshader:this.vshader,fshader:this.fshader};return Hi.isForward(this.options.pass)&&(e.tag=1),e},e}(),rs=function(){function e(){this.code=""}var t=e.prototype;return t.append=function(){for(var e=this,t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];i.forEach((function(t){t.endsWith("\n")?e.code+=t:e.code+=t+"\n"}))},t.prepend=function(){for(var e=this,t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];i.forEach((function(t){t.endsWith("\n")?e.code=t+e.code:e.code=t+"\n"+e.code}))},e}(),as=[],os={optionsContext:{},optionsContextMin:{},generateKey:function(e){var t,i=function(e){var t=[];for(var i in e)e.hasOwnProperty(i)&&"chunks"!==i&&"lights"!==i&&t.push(i);return t.sort()};e===this.optionsContextMin?(this.propsMin||(this.propsMin=i(e)),t=this.propsMin):e===this.optionsContext?(this.props||(this.props=i(e)),t=this.props):t=i(e);for(var n="standard",s=0;s<t.length;s++)e[t[s]]&&(n+=t[s]+e[t[s]]);if(e.chunks){var r=[];for(var a in e.chunks)e.chunks.hasOwnProperty(a)&&r.push(a+e.chunks[a]);r.sort(),n+=r}if(e.lights)for(var o=e.clusteredLightingEnabled,h=0;h<e.lights.length;h++){var l=e.lights[h];o&&0!==l._type||(n+=l.key)}return wi(n)},_getUvSourceExpression:function(e,t,i){var n,s=i[e],r=i[t],a=Hi.isForward(i.pass);return a&&1===i.nineSlicedMode||a&&2===i.nineSlicedMode?n="nineSlicedUv":(n=0===s?"vUv"+r:"vUV"+r+"_"+s,i.heightMap&&"heightMapTransform"!==e&&(n+=" + dUvOffset")),n},_addMapDef:function(e,t){return t?"#define "+e+"\n":"#undef "+e+"\n"},_addMapDefs:function(e,t,i,n){return this._addMapDef("MAPFLOAT",e)+this._addMapDef("MAPCOLOR",t)+this._addMapDef("MAPVERTEX",i)+this._addMapDef("MAPTEXTURE",n)},_addMap:function(e,t,i,n,s,r){void 0===r&&(r=null);var a=e+"Map",o=a+"Uv",h=a+"Identifier",l=a+"Transform",c=a+"Channel",u=e+"VertexColorChannel",d=e+"VertexColor",f=e+"Mode",p=i[e+"Tint"],m=i[d],_=i[a],g=i[h],v=i[f],y=n[t];if(_){var x=this._getUvSourceExpression(l,o,i);if(y=y.replace(/\$UV/g,x).replace(/\$CH/g,i[c]),s&&-1!==y.search(/\$SAMPLER/g)){var b="texture_"+a,S=s[g];S?b=S:s[g]=b,y=y.replace(/\$SAMPLER/g,b)}if(r&&(y="aaa"===i[c]?y.replace(/\$DECODE/g,"passThrough"):y.replace(/\$DECODE/g,mn.decodeFunc(i.gamma||"srgb"!==r?r:"linear"))).indexOf("$texture2DSAMPLE")){y=y.replace(/\$texture2DSAMPLE/g,{linear:"texture2D",srgb:"texture2DSRGB",rgbm:"texture2DRGBM",rgbe:"texture2DRGBE"}[r]||"texture2D")}}m&&(y=y.replace(/\$VC/g,i[u])),v&&(y=y.replace(/\$DETAILMODE/g,v));var w=!!(1&p),T=!!(2&p);return(y=this._addMapDefs(w,T,m,_)+y).replace(/\$/g,"")},_correctChannel:function(e,t,i){if(i[e]>0){if(i[e]<t.length)return t.substring(0,i[e]);if(i[e]>t.length){for(var n=t,s=n.charAt(n.length-1),r=i[e]-n.length,a=0;a<r;a++)n+=s;return n}return t}},createShaderDefinition:function(e,t){var i=new ss(e,t),n=[],s=[],r=[],a={};for(var o in as){var h=o+"Map";if(t[o+"VertexColor"]){var l=o+"VertexColorChannel";t[l]=this._correctChannel(o,t[l],as)}if(t[h]){var c=h+"Channel",u=h+"Transform",d=h+"Uv";t[d]=Math.min(t[d],1),t[c]=this._correctChannel(o,t[c],as);var f=t[d];n[f]=!0,s[f]=s[f]||t[h]&&!t[u],t[u]&&r.push({name:o,id:t[u],uv:t[d]})}}t.forceUv1&&(n[1]=!0,s[1]=void 0===s[1]||s[1]),i.generateVertexShader(n,s,r),0===t.shadingModel?(t.fresnelModel=0,t.ambientSH=!1):t.fresnelModel=0===t.fresnelModel?2:t.fresnelModel;var p=new rs,m=new rs,_=new rs,g="";if(2===t.nineSlicedMode?p.append("const float textureBias = -1000.0;"):p.append("uniform float textureBias;"),Hi.isForward(t.pass)){if(t.heightMap&&(p.append("vec2 dUvOffset;"),m.append(this._addMap("height","parallaxPS",t,i.chunks,a)),_.append("getParallax();")),3!==t.blendType||t.alphaTest||t.alphaToCoverage?(p.append("float dAlpha;"),m.append(this._addMap("opacity","opacityPS",t,i.chunks,a)),_.append("getOpacity();"),t.alphaTest&&(m.append(i.chunks.alphaTestPS),_.append("alphaTest(dAlpha);"))):p.append("float dAlpha = 1.0;"),i.needsNormal){if((t.normalMap||t.clearCoatNormalMap)&&(m.append(t.packedNormal?i.chunks.normalXYPS:i.chunks.normalXYZPS),!t.hasTangents)){var v=t.normalMap?"normalMap":"clearCoatNormalMap";g=this._getUvSourceExpression(v+"Transform",v+"Uv",t)}p.append("vec3 dNormalW;"),m.append(this._addMap("normalDetail","normalDetailMapPS",t,i.chunks,a)),m.append(this._addMap("normal","normalMapPS",t,i.chunks,a)),_.append("getNormal();")}if(i.needsSceneColor&&p.append("uniform sampler2D uSceneColorMap;"),i.needsScreenSize&&p.append("uniform vec4 uScreenSize;"),i.needsTransforms&&(p.append("uniform mat4 matrix_viewProjection;"),p.append("uniform mat4 matrix_model;")),p.append("vec3 dAlbedo;"),t.diffuseDetail&&m.append(this._addMap("diffuseDetail","diffuseDetailMapPS",t,i.chunks,a,t.diffuseDetailEncoding)),m.append(this._addMap("diffuse","diffusePS",t,i.chunks,a,t.diffuseEncoding)),_.append("getAlbedo();"),t.refraction&&(p.append("float dTransmission;"),m.append(this._addMap("refraction","transmissionPS",t,i.chunks,a)),_.append("getRefraction();"),p.append("float dThickness;"),m.append(this._addMap("thickness","thicknessPS",t,i.chunks,a)),_.append("getThickness();")),t.iridescence&&(p.append("vec3 dIridescenceFresnel;"),p.append("float dIridescence;"),m.append(this._addMap("iridescence","iridescencePS",t,i.chunks,a)),_.append("getIridescence();"),p.append("float dIridescenceThickness;"),m.append(this._addMap("iridescenceThickness","iridescenceThicknessPS",t,i.chunks,a)),_.append("getIridescenceThickness();")),i.lighting&&t.useSpecular||i.reflections?(p.append("vec3 dSpecularity;"),p.append("float dGlossiness;"),t.sheen&&(p.append("vec3 sSpecularity;"),m.append(this._addMap("sheen","sheenPS",t,i.chunks,a,t.sheenEncoding)),_.append("getSheen();"),p.append("float sGlossiness;"),m.append(this._addMap("sheenGlossiness","sheenGlossPS",t,i.chunks,a)),_.append("getSheenGlossiness();")),t.useMetalness&&(p.append("float dMetalness;"),m.append(this._addMap("metalness","metalnessPS",t,i.chunks,a)),_.append("getMetalness();")),t.useSpecularityFactor&&(p.append("float dSpecularityFactor;"),m.append(this._addMap("specularityFactor","specularityFactorPS",t,i.chunks,a)),_.append("getSpecularityFactor();")),t.useSpecularColor?m.append(this._addMap("specular","specularPS",t,i.chunks,a,t.specularEncoding)):m.append("void getSpecularity() { dSpecularity = vec3(1); }"),m.append(this._addMap("gloss","glossPS",t,i.chunks,a)),_.append("getGlossiness();"),_.append("getSpecularity();")):(p.append("vec3 dSpecularity = vec3(0.0);"),p.append("float dGlossiness = 0.0;")),(t.aoMap||t.aoVertexColor)&&(p.append("float dAo;"),m.append(this._addMap("ao","aoPS",t,i.chunks,a)),_.append("getAO();")),p.append("vec3 dEmission;"),m.append(this._addMap("emissive","emissivePS",t,i.chunks,a,t.emissiveEncoding)),_.append("getEmission();"),t.clearCoat>0&&(p.append("float ccSpecularity;"),p.append("float ccGlossiness;"),p.append("vec3 ccNormalW;"),m.append(this._addMap("clearCoat","clearCoatPS",t,i.chunks,a)),m.append(this._addMap("clearCoatGloss","clearCoatGlossPS",t,i.chunks,a)),m.append(this._addMap("clearCoatNormal","clearCoatNormalPS",t,i.chunks,a)),_.append("getClearCoat();"),_.append("getClearCoatGlossiness();"),_.append("getClearCoatNormal();")),t.lightMap||t.lightVertexColor){var y=t.dirLightMap&&t.useSpecular,x=y?"lightmapDirPS":"lightmapSinglePS";p.append("vec3 dLightmap;"),y&&p.append("vec3 dLightmapDir;"),m.append(this._addMap("light",x,t,i.chunks,a,t.lightMapEncoding)),_.append("getLightMap();")}-1===m.code.indexOf("texture2DSRGB")&&-1===m.code.indexOf("texture2DRGBM")&&-1===m.code.indexOf("texture2DRGBE")||m.prepend(i.chunks.textureSamplePS)}else t.alphaTest&&(p.append("float dAlpha;"),m.append(this._addMap("opacity","opacityPS",t,i.chunks,a)),m.append(i.chunks.alphaTestPS),_.append("getOpacity();"),_.append("alphaTest(dAlpha);"));for(var b in a)p.append("uniform sampler2D "+a[b]+";");return _.code="\n"+_.code.split("\n").map((function(e){return" "+e})).join("\n")+"\n\n",i.generateFragmentShader(p.code,m.code,_.code,g),i.getDefinition()}},hs=2.399963229728653,ls=function(e,t,i){var n=t*hs,s=Math.sqrt(t)/Math.sqrt(i);e.x=s*Math.cos(n),e.y=s*Math.sin(n)},cs=function(e,t,i,n,s){void 0===n&&(n=0),void 0===s&&(s=1),n=1-2*n,s=1-2*s;var r=de.lerp(n,s,t/i),a=Math.sqrt(1-r*r),o=hs*t;e.x=Math.cos(o)*a,e.y=r,e.z=Math.sin(o)*a},us=function(e){var t=(e<<16|e>>>16)>>>0;return 2.3283064365386963e-10*(t=((16711935&(t=((252645135&(t=((858993459&(t=((1431655765&t)<<1|(2863311530&t)>>>1)>>>0))<<2|(3435973836&t)>>>2)>>>0))<<4|(4042322160&t)>>>4)>>>0))<<8|(4278255360&t)>>>8)>>>0)},ds=function(e){switch(e){case ri:return"Cubemap";case oi:return"Octahedral";default:return"Equirect"}},fs=function(e,t,i){if(e<=0)t[i+0]=0,t[i+1]=0,t[i+2]=0,t[i+3]=0;else if(e>=1)t[i+0]=255,t[i+1]=0,t[i+2]=0,t[i+3]=0;else{var n=1*e%1,s=255*e%1,r=65025*e%1,a=16581375*e%1;n-=s/255,s-=r/255,r-=a/255,t[i+0]=Math.min(255,Math.floor(256*n)),t[i+1]=Math.min(255,Math.floor(256*s)),t[i+2]=Math.min(255,Math.floor(256*r)),t[i+3]=Math.min(255,Math.floor(256*a))}},ps=function(e,t,i,n){var s=2*i*Math.PI,r=Math.pow(1-t,1/(n+1)),a=Math.sqrt(1-r*r);e.set(Math.cos(s)*a,Math.sin(s)*a,r).normalize()},ms=function(e,t,i){var n=2*i*Math.PI,s=Math.sqrt(1-t),r=Math.sqrt(t);e.set(Math.cos(n)*r,Math.sin(n)*r,s).normalize()},_s=function(e,t,i,n){var s=2*i*Math.PI,r=Math.sqrt((1-t)/(1+(n*n-1)*t)),a=Math.sqrt(1-r*r);e.set(Math.cos(s)*a,Math.sin(s)*a,r).normalize()},gs=function(e,t){var i=e*t,n=t/(1-e*e+i*i);return n*n*(1/Math.PI)},vs={16:{2:26,8:20,32:17,128:16,512:16},32:{2:53,8:40,32:34,128:32,512:32},128:{2:214,8:163,32:139,128:130,512:128},1024:{2:1722,8:1310,32:1114,128:1041,512:1025}},ys=function(e,t,i){for(var n=i/e,s=1-Math.log2(t)/11,r=s*s,a=new ye,o=new ye,h=new ye(0,0,1),l=[],c=function(e,t){var i=vs[e];return i&&i[t]||e}(e,t),u=0;u<c;++u){_s(a,u/c,us(u),r);var d=a.z;if(o.set(a.x,a.y,a.z).mulScalar(2*d).sub(h),o.z>0){var f=gs(Math.min(1,d),r)/4+.001,p=.5*Math.log2(n/f);l.push(o.x,o.y,o.z,p)}}for(;l.length<4*e;)l.push(0,0,0,0);return l},xs=function(e,t,i){var n=function(e){for(var t=e.length,i=Math.min(t,512),n=Math.ceil(t/i),s=new Uint8Array(i*n*4),r=0,a=0;a<t;++a)fs(.5*e[4*a+0]+.5,s,r+0),fs(.5*e[4*a+1]+.5,s,r+4),fs(.5*e[4*a+2]+.5,s,r+8),fs(e[4*a+3]/8,s,r+12),r+=16;return{width:i,height:n,data:s}}(i);return new wn(e,{name:t,width:n.width,height:n.height,mipmaps:!1,minFilter:0,magFilter:0,levels:[n.data]})},bs=function(){function e(e){void 0===e&&(e=!0),this.map=new Map,this.destroyContent=e}var t=e.prototype;return t.destroy=function(){this.destroyContent&&this.map.forEach((function(e,t){e.destroy()}))},t.get=function(e,t){if(!this.map.has(e)){var i=t();return this.map.set(e,i),i}return this.map.get(e)},e}(),Ss=new bs(!1),ws=new Ai,Ts=function(e,t,i){return ws.get(e,(function(){return new bs})).get(t,(function(){return xs(e,t,Ss.get(t,i))}))},As=function(e,t,i){return Ts(e,"lambert-samples-"+t+"-"+i,(function(){return function(e,t){for(var i=t/e,n=new ye,s=[],r=0;r<e;++r){ms(n,r/e,us(r));var a=n.z/Math.PI,o=.5*Math.log2(i/a);s.push(n.x,n.y,n.z,o)}return s}(t,i)}))},Ms=function(e,t,i){return Ts(e,"phong-samples-"+t+"-"+i,(function(){return function(e,t){for(var i=new ye,n=[],s=0;s<e;++s)ps(i,s/e,us(s),t),n.push(i.x,i.y,i.z,0);return n}(t,i)}))},Cs=function(e,t,i,n){return Ts(e,"ggx-samples-"+t+"-"+i+"-"+n,(function(){return ys(t,i,n)}))},Es="\nattribute vec2 vertex_position;\n\nuniform vec4 uvMod;\n\nvarying vec2 vUv0;\n\nvoid main(void) {\n gl_Position = vec4(vertex_position, 0.5, 1.0);\n vUv0 = (vertex_position.xy * 0.5 + 0.5) * uvMod.xy + uvMod.zw;\n}\n";function Ps(e,t,i){var n;void 0===i&&(i={}),e instanceof or&&(e=arguments[1],t=arguments[2],i={},void 0!==arguments[3]&&(i.specularPower=arguments[3]),void 0!==arguments[4]&&(i.numSamples=arguments[4]));var s={none:"reproject",lambert:"prefilterSamplesUnweighted",phong:"prefilterSamplesUnweighted",ggx:"prefilterSamples"},r=i.hasOwnProperty("specularPower")?i.specularPower:1,a=i.hasOwnProperty("face")?i.face:null,o=i.hasOwnProperty("distribution")?i.distribution:1===r?"none":"phong",h=s[o]||"reproject",l=mn.decodeFunc(e.encoding),c=mn.encodeFunc(t.encoding),u="sample"+ds(e.projection),d="getDirection"+ds(t.projection),f=i.hasOwnProperty("numSamples")?i.numSamples:1024,p=h+"_"+l+"_"+c+"_"+u+"_"+d+"_"+f,m=e.device,_=m.programLib._cache[p];if(!_){var g="#define PROCESS_FUNC "+h+"\n#define DECODE_FUNC "+l+"\n#define ENCODE_FUNC "+c+"\n#define SOURCE_FUNC "+u+"\n#define TARGET_FUNC "+d+"\n#define NUM_SAMPLES "+f+"\n#define NUM_SAMPLES_SQRT "+Math.round(Math.sqrt(f)).toFixed(1)+"\n"+(m.extTextureLod?"#define SUPPORTS_TEXLOD\n":""),v="";m.webgl2||(v="#extension GL_OES_standard_derivatives: enable\n",m.extTextureLod&&(v+="#extension GL_EXT_shader_texture_lod: enable\n\n")),_=on(m,Es,g+"\n"+Wi.reprojectPS,p,!1,v)}var y=m.scope.resolve(e.cubemap?"sourceCube":"sourceTex");y.setValue(e);var x=m.scope.resolve("params"),b=m.scope.resolve("params2"),S=m.scope.resolve("uvMod");if(null!=(n=i)&&n.seamPixels){var w=i.seamPixels,T=i.rect?i.rect.z:t.width,A=i.rect?i.rect.w:t.height,M=T-2*w,C=A-2*w;S.setValue([(M+2*w)/M,(C+2*w)/C,-w/M,-w/C])}else S.setValue([1,1,0,0]);var E=[0,r,e.fixCubemapSeams?1/e.width:0,t.fixCubemapSeams?1/t.width:0],P=[t.width*t.height*(t.cubemap?6:1),e.width*e.height*(e.cubemap?6:1)];if(h.startsWith("prefilterSamples")){var R=e.width*e.height*(e.cubemap?6:1),I="ggx"===o?Cs(m,f,r,R):"lambert"===o?As(m,f,R):Ms(m,f,r);m.scope.resolve("samplesTex").setValue(I),m.scope.resolve("samplesTexInverseSize").setValue([1/I.width,1/I.height])}for(var L=0;L<(t.cubemap?6:1);L++)if(null===a||L===a){var D,k=new cr({colorBuffer:t,face:L,depth:!1});E[0]=L,x.setValue(E),b.setValue(P),Ei(m,k,_,null==(D=i)?void 0:D.rect),k.destroy()}}var Rs=$t,Is=function(e,t){return void 0===t&&(t=0),1+Math.floor(Math.log2(Math.max(e,t)))},Ls=function(){function e(){}return e.generateSkyboxCubemap=function(e,t){var i=function(e,t,i,n){return new wn(e,{name:"lighting-"+t,cubemap:!0,width:t,height:t,format:i,type:7===i?Rs:Zt,addressU:1,addressV:1,fixCubemapSeams:!0,mipmaps:!!n})}(e.device,t||(e.cubemap?e.width:e.width/4),7,!1);return Ps(e,i,{numSamples:1024}),i},e.generateLightingSource=function(e,t){var i=e.device,n=function(e){return function(e){return e.extTextureHalfFloat&&e.textureHalfFloatRenderable}(e)?ct:function(e){return e.extTextureFloat&&e.textureFloatRenderable}(e)?dt:7}(i),s=(null==t?void 0:t.target)||new wn(i,{name:"lighting-source",cubemap:!0,width:(null==t?void 0:t.size)||128,height:(null==t?void 0:t.size)||128,format:n,type:7===n?Rs:Zt,addressU:1,addressV:1,fixCubemapSeams:!1,mipmaps:!0});return Ps(e,s,{numSamples:e.mipmaps?1:1024}),s},e.generateAtlas=function(e,t){for(var i=e.device,n=(null==t?void 0:t.target)||new wn(i,{name:"envAtlas",width:(null==t?void 0:t.size)||512,height:(null==t?void 0:t.size)||512,format:7,type:Rs,projection:ai,addressU:1,addressV:1,mipmaps:!1}),s=n.width/512,r=new Se(0,0,512*s,256*s),a=Is(256)-Is(4),o=0;o<a;++o)Ps(e,n,{numSamples:1,rect:r,seamPixels:s}),r.x+=r.w,r.y+=r.w,r.z=Math.max(1,Math.floor(.5*r.z)),r.w=Math.max(1,Math.floor(.5*r.w));r.set(0,256*s,256*s,128*s);for(var h=1;h<7;++h)Ps(e,n,{numSamples:(null==t?void 0:t.numReflectionSamples)||1024,distribution:(null==t?void 0:t.distribution)||"ggx",specularPower:Math.max(1,2048>>2*h),rect:r,seamPixels:s}),r.y+=r.w,r.z=Math.max(1,Math.floor(.5*r.z)),r.w=Math.max(1,Math.floor(.5*r.w));return r.set(128*s,384*s,64*s,32*s),Ps(e,n,{numSamples:(null==t?void 0:t.numAmbientSamples)||2048,distribution:"lambert",rect:r,seamPixels:s}),n},e.generatePrefilteredAtlas=function(e,t){for(var i=e[0].device,n=e[0].format,s=e[0].type,r=(null==t?void 0:t.target)||new wn(i,{name:"envPrefilteredAtlas",width:(null==t?void 0:t.size)||512,height:(null==t?void 0:t.size)||512,format:n,type:s,projection:ai,addressU:1,addressV:1,mipmaps:!1}),a=r.width/512,o=new Se(0,0,512*a,256*a),h=Is(512),l=0;l<h;++l)Ps(e[0],r,{numSamples:1,rect:o,seamPixels:a}),o.x+=o.w,o.y+=o.w,o.z=Math.max(1,Math.floor(.5*o.z)),o.w=Math.max(1,Math.floor(.5*o.w));o.set(0,256*a,256*a,128*a);for(var c=1;c<e.length;++c)Ps(e[c],r,{numSamples:1,rect:o,seamPixels:a}),o.y+=o.w,o.z=Math.max(1,Math.floor(.5*o.z)),o.w=Math.max(1,Math.floor(.5*o.w));return o.set(128*a,384*a,64*a,32*a),null!=t&&t.legacyAmbient?Ps(e[5],r,{numSamples:1,rect:o,seamPixels:a}):Ps(e[0],r,{numSamples:(null==t?void 0:t.numSamples)||2048,distribution:"lambert",rect:o,seamPixels:a}),r},e}(),Ds=new Ai;function ks(e){return Ds.get(e)}var Os=function(){function e(e,t){this.uniformFormats=[],this.bindGroupFormats=[],this.uniformFormats[0]=e,this.bindGroupFormats[0]=t}var t=e.prototype;return t.hasUniform=function(e){for(var t=0;t<this.uniformFormats.length;t++){if(this.uniformFormats[t].get(e))return!0}return!1},t.hasTexture=function(e){for(var t=0;t<this.bindGroupFormats.length;t++){if(this.bindGroupFormats[t].getTexture(e))return!0}return!1},e}(),Fs=0,Bs=function(){function e(){this._shader=null,this.meshInstances=[],this.name="Untitled",this.id=Fs++,this.variants={},this.parameters={},this.alphaTest=0,this.alphaToCoverage=!1,this.blend=!1,this.blendSrc=1,this.blendDst=0,this.blendEquation=0,this.separateAlphaBlend=!1,this.blendSrcAlpha=1,this.blendDstAlpha=0,this.blendAlphaEquation=0,this.cull=1,this.depthTest=!0,this.depthFunc=3,this.depthWrite=!0,this.stencilFront=null,this.stencilBack=null,this.depthBias=0,this.slopeDepthBias=0,this.redWrite=!0,this.greenWrite=!0,this.blueWrite=!0,this.alphaWrite=!0,this._shaderVersion=0,this._scene=null,this._dirtyBlend=!1,this.dirty=!0}var t=e.prototype;return t.copy=function(e){return this.name=e.name,this._shader=e._shader,this.alphaTest=e.alphaTest,this.alphaToCoverage=e.alphaToCoverage,this.blend=e.blend,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.separateAlphaBlend=e.separateAlphaBlend,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendAlphaEquation=e.blendAlphaEquation,this.cull=e.cull,this.depthTest=e.depthTest,this.depthFunc=e.depthFunc,this.depthWrite=e.depthWrite,this.depthBias=e.depthBias,this.slopeDepthBias=e.slopeDepthBias,e.stencilFront&&(this.stencilFront=e.stencilFront.clone()),e.stencilBack&&(e.stencilFront===e.stencilBack?this.stencilBack=this.stencilFront:this.stencilBack=e.stencilBack.clone()),this.redWrite=e.redWrite,this.greenWrite=e.greenWrite,this.blueWrite=e.blueWrite,this.alphaWrite=e.alphaWrite,this},t.clone=function(){var e=new this.constructor;return e.copy(this)},t._updateMeshInstanceKeys=function(){for(var e=this.meshInstances,t=0;t<e.length;t++)e[t].updateKey()},t.updateUniforms=function(e,t){},t.getShaderVariant=function(e,t,i,n,s,r,a,o){var h="shader-id-"+this._shader.id,l=this._shader.definition,c={generateKey:function(e){return h},createShaderDefinition:function(e,t){return l}},u="shader",d=e.getProgramLibrary();d.register(u,c);var f=new Os(a,o),p=d.getProgram(u,{},f);return d.unregister(u),p},t.update=function(){this.dirty=!0,this._shader&&(this._shader.failed=!1)},t.clearParameters=function(){this.parameters={}},t.getParameters=function(){return this.parameters},t.clearVariants=function(){this.variants={};for(var e=this.meshInstances,t=e.length,i=0;i<t;i++)e[i].clearShaders()},t.getParameter=function(e){return this.parameters[e]},t.setParameter=function(e,t){if(void 0===t&&"object"==typeof e){var i=e;if(i.length){for(var n=0;n<i.length;n++)this.setParameter(i[n]);return}e=i.name,t=i.value}var s=this.parameters[e];s?s.data=t:this.parameters[e]={scopeId:null,data:t}},t.deleteParameter=function(e){this.parameters[e]&&delete this.parameters[e]},t.setParameters=function(e,t){var i=this.parameters;for(var n in void 0===t&&(t=i),t){var s=i[n];s&&(s.scopeId||(s.scopeId=e.scope.resolve(n)),s.scopeId.setValue(s.data))}},t.destroy=function(){this.variants={},this._shader=null;for(var e=0;e<this.meshInstances.length;e++){var t=this.meshInstances[e];if(t.clearShaders(),t._material=null,t.mesh){var i=ks(t.mesh.device);this!==i&&(t.material=i)}}this.meshInstances.length=0},t.addMeshInstanceRef=function(e){this.meshInstances.push(e)},t.removeMeshInstanceRef=function(e){var t=this.meshInstances,i=t.indexOf(e);-1!==i&&t.splice(i,1)},$(e,[{key:"shader",get:function(){return this._shader},set:function(e){this._shader=e}},{key:"transparent",get:function(){return this.blend}},{key:"blendType",get:function(){return this.blend?6===this.blendSrc&&8===this.blendDst&&0===this.blendEquation?2:1===this.blendSrc&&1===this.blendDst&&0===this.blendEquation?1:6===this.blendSrc&&1===this.blendDst&&0===this.blendEquation?6:4===this.blendSrc&&2===this.blendDst&&0===this.blendEquation?7:5===this.blendSrc&&1===this.blendDst&&0===this.blendEquation?8:1===this.blendSrc&&1===this.blendDst&&3===this.blendEquation?9:1===this.blendSrc&&1===this.blendDst&&4===this.blendEquation?10:4===this.blendSrc&&0===this.blendDst&&0===this.blendEquation?5:1===this.blendSrc&&8===this.blendDst&&0===this.blendEquation?4:2:3},set:function(e){var t=!0;switch(e){case 3:t=!1,this.blendSrc=1,this.blendDst=0,this.blendEquation=0;break;case 2:this.blendSrc=6,this.blendDst=8,this.blendEquation=0;break;case 4:this.blendSrc=1,this.blendDst=8,this.blendEquation=0;break;case 1:this.blendSrc=1,this.blendDst=1,this.blendEquation=0;break;case 6:this.blendSrc=6,this.blendDst=1,this.blendEquation=0;break;case 7:this.blendSrc=4,this.blendDst=2,this.blendEquation=0;break;case 8:this.blendSrc=5,this.blendDst=1,this.blendEquation=0;break;case 5:this.blendSrc=4,this.blendDst=0,this.blendEquation=0;break;case 9:this.blendSrc=1,this.blendDst=1,this.blendEquation=3;break;case 10:this.blendSrc=1,this.blendDst=1,this.blendEquation=4}this.blend!==t&&(this.blend=t,this._scene?this._scene.layers._dirtyBlend=!0:this._dirtyBlend=!0),this._updateMeshInstanceKeys()}}]),e}(),Ns=function(e,t){if(e.length!==t.length)return!1;for(var i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0},Us=function(e){return 1!==e.r||1!==e.g||1!==e.b},zs=function(){function e(){this._mapXForms=null}var t=e.prototype;return t.updateMinRef=function(e,t,i,n,s,r,a){this._updateSharedOptions(e,t,i,n,r),this._updateMinOptions(e,i),this._updateUVOptions(e,i,n,!0)},t.updateRef=function(e,t,i,n,s,r,a){this._updateSharedOptions(e,t,i,n,r),this._updateEnvOptions(e,i,t),this._updateMaterialOptions(e,i),1===r&&(e.gamma&&(e.gamma=3),e.toneMap=0),e.hasTangents=n&&0!=(512&n),this._updateLightOptions(e,i,n,a,s),this._updateUVOptions(e,i,n,!1)},t._updateSharedOptions=function(e,t,i,n,s){e.pass=s,e.alphaTest=i.alphaTest>0,e.forceFragmentPrecision=i.forceFragmentPrecision||"",e.chunks=i.chunks||"",e.blendType=i.blendType,e.forceUv1=i.forceUv1,e.separateAmbient=!1,e.screenSpace=n&&0!=(n&We),e.skin=n&&0!=(2&n),e.useInstancing=n&&0!=(32&n),e.useMorphPosition=n&&0!=(n&He),e.useMorphNormal=n&&0!=(n&Xe),e.useMorphTextureBased=n&&0!=(n&qe),e.nineSlicedMode=i.nineSlicedMode||0,t.clusteredLightingEnabled&&i.useLighting?(e.clusteredLightingEnabled=!0,e.clusteredLightingCookiesEnabled=t.lighting.cookiesEnabled,e.clusteredLightingShadowsEnabled=t.lighting.shadowsEnabled,e.clusteredLightingShadowType=t.lighting.shadowType,e.clusteredLightingAreaLightsEnabled=t.lighting.areaLightsEnabled):(e.clusteredLightingEnabled=!1,e.clusteredLightingCookiesEnabled=!1,e.clusteredLightingShadowsEnabled=!1,e.clusteredLightingAreaLightsEnabled=!1)},t._updateUVOptions=function(e,t,i,n){var s=!1,r=!1,a=!1;i&&(s=0!=(4&i),r=0!=(8&i),a=0!=(16&i)),e.vertexColors=!1,this._mapXForms=[];var o={};for(var h in as)this._updateTexOptions(e,t,h,s,r,a,n,o);this._mapXForms=null},t._updateMinOptions=function(e,t){e.opacityTint=1!==t.opacity&&3!==t.blendType,e.lights=[]},t._updateMaterialOptions=function(e,t){var i,n,s,r,a,o=(t.diffuseTint||!t.diffuseMap&&!t.diffuseVertexColor)&&Us(t.diffuse),h=!!(t.useMetalness||t.specularMap||t.sphereMap||t.cubeMap||(a=t.specular,0!==a.r||0!==a.g||0!==a.b)||t.specularityFactor>0&&t.useMetalness||t.enableGGXSpecular||t.clearCoat>0),l=!t.useMetalness||t.useMetalnessSpecularColor,c=h&&(t.specularTint||!t.specularMap&&!t.specularVertexColor)&&Us(t.specular),u=h&&t.useMetalnessSpecularColor&&(t.specularityFactorTint||t.specularityFactor<1&&!t.specularityFactorMap),d=!t.emissiveMap||Us(t.emissive)&&t.emissiveTint,f=1!==t.emissiveIntensity,p=!!t.normalMap&&(t.normalMap.format===ht||t.normalMap.type===ei);e.opacityTint=1!==t.opacity&&3!==t.blendType?1:0,e.blendMapsWithColors=!0,e.ambientTint=t.ambientTint,e.diffuseTint=o?2:0,e.specularTint=c?2:0,e.specularityFactorTint=u?1:0,e.useSpecularityFactor=(u||!!t.specularityFactorMap)&&t.useMetalnessSpecularColor,e.useSpecularColor=l,e.metalnessTint=t.useMetalness&&t.metalness<1?1:0,e.glossTint=1,e.emissiveTint=(d?2:0)+(f?1:0),e.alphaToCoverage=t.alphaToCoverage,e.normalizeNormalMap=t.normalizeNormalMap,e.ambientSH=!!t.ambientSH,e.useSpecular=h,e.diffuseEncoding=null==(i=t.diffuseMap)?void 0:i.encoding,e.diffuseDetailEncoding=null==(n=t.diffuseDetailMap)?void 0:n.encoding,e.emissiveEncoding=null==(s=t.emissiveMap)?void 0:s.encoding,e.lightMapEncoding=null==(r=t.lightMap)?void 0:r.encoding,e.conserveEnergy=t.conserveEnergy,e.opacityFadesSpecular=t.opacityFadesSpecular,e.alphaFade=t.alphaFade,e.occludeSpecular=t.occludeSpecular,e.occludeSpecularFloat=1!==t.occludeSpecularIntensity,e.occludeDirect=t.occludeDirect,e.shadingModel=t.shadingModel,e.fresnelModel=t.fresnelModel,e.packedNormal=p,e.fastTbn=t.fastTbn,e.cubeMapProjection=t.cubeMapProjection,e.customFragmentShader=t.customFragmentShader,e.refraction=(t.refraction||!!t.refractionMap)&&(t.useDynamicRefraction||!!e.reflectionSource),e.useDynamicRefraction=t.useDynamicRefraction,e.refractionIndexTint=t.refractionIndex!==1/1.5?1:0,e.thicknessTint=t.useDynamicRefraction&&1!==t.thickness?1:0,e.useMetalness=t.useMetalness,e.specularEncoding=t.specularEncoding||"linear",e.sheenEncoding=t.sheenEncoding||"linear",e.enableGGXSpecular=t.enableGGXSpecular,e.msdf=!!t.msdfMap,e.msdfTextAttribute=!!t.msdfTextAttribute,e.twoSidedLighting=t.twoSidedLighting,e.pixelSnap=t.pixelSnap,e.aoMapUv=t.aoUvSet,e.diffuseDetail=!!t.diffuseMap,e.normalDetail=!!t.normalMap,e.diffuseDetailMode=t.diffuseDetailMode,e.detailModes=!!e.diffuseDetail,e.clearCoat=!!t.clearCoat,e.clearCoatTint=1!==t.clearCoat?1:0,e.clearCoatGlossiness=!!t.clearCoatGlossiness,e.clearCoatGlossTint=1!==t.clearCoatGlossiness?1:0,e.iridescence=t.useIridescence&&0!==t.iridescence,e.iridescenceTint=1!==t.iridescence?1:0,e.sheen=t.useSheen,e.sheenTint=t.useSheen&&Us(t.sheen)?2:0,e.sheenGlossinessTint=1},t._updateEnvOptions=function(e,t,i){e.fog=t.useFog?i.fog:"none",e.gamma=t.useGammaTonemap?i.gammaCorrection:0,e.toneMap=t.useGammaTonemap?i.toneMapping:-1,e.fixSeams=!!t.cubeMap&&t.cubeMap.fixCubemapSeams;var n=0===t.shadingModel,s=!1;if(t.envAtlas&&t.cubeMap&&!n?(e.reflectionSource="envAtlasHQ",e.reflectionEncoding=t.envAtlas.encoding):t.envAtlas&&!n?(e.reflectionSource="envAtlas",e.reflectionEncoding=t.envAtlas.encoding):t.cubeMap?(e.reflectionSource="cubeMap",e.reflectionEncoding=t.cubeMap.encoding):t.sphereMap?(e.reflectionSource="sphereMap",e.reflectionEncoding=t.sphereMap.encoding):t.useSkybox&&i.envAtlas&&i.skybox&&!n?(e.reflectionSource="envAtlasHQ",e.reflectionEncoding=i.envAtlas.encoding,s=!0):t.useSkybox&&i.envAtlas&&!n?(e.reflectionSource="envAtlas",e.reflectionEncoding=i.envAtlas.encoding,s=!0):t.useSkybox&&i.skybox?(e.reflectionSource="cubeMap",e.reflectionEncoding=i.skybox.encoding,s=!0):(e.reflectionSource=null,e.reflectionEncoding=null),t.ambientSH&&!n)e.ambientSource="ambientSH",e.ambientEncoding=null;else{var r=t.envAtlas||(t.useSkybox&&i.envAtlas?i.envAtlas:null);r&&!n?(e.ambientSource="envAtlas",e.ambientEncoding=r.encoding):(e.ambientSource="constant",e.ambientEncoding=null)}e.skyboxIntensity=s&&(1!==i.skyboxIntensity||i.physicalUnits),e.useCubeMapRotation=s&&i.skyboxRotation&&!i.skyboxRotation.equals(Pe.IDENTITY)},t._updateLightOptions=function(e,t,i,n,s){if(e.lightMap=!1,e.lightMapChannel="",e.lightMapUv=0,e.lightMapTransform=0,e.lightMapWithoutAmbient=!1,e.dirLightMap=!1,i&&(e.noShadow=0!=(1&i),0!=(64&i)&&(e.lightMapEncoding="rgbm",e.lightMap=!0,e.lightMapChannel="rgb",e.lightMapUv=1,e.lightMapTransform=0,e.lightMapWithoutAmbient=!t.lightMap,0!=(i&Ge)&&(e.dirLightMap=!0),0!=(i&je)&&(e.lightMapWithoutAmbient=!1))),t.useLighting){var r=[],a=i?i>>16:1;e.lightMaskDynamic=!!(1&a),n&&(this._collectLights(0,n[0],r,a),this._collectLights(1,n[1],r,a,s),this._collectLights(2,n[2],r,a,s)),e.lights=r}else e.lights=[];0===e.lights.length&&(e.noShadow=!0)},t._updateTexOptions=function(e,t,i,n,s,r,a,o){var h=i+"Map",l=i+"VertexColor",c=i+"VertexColorChannel",u=h+"Channel",d=h+"Transform",f=h+"Uv",p=h+"Identifier";"light"!==i&&(e[h]=!1,e[u]="",e[d]=0,e[f]=0,e[p]=void 0),e[l]=!1,e[c]="";var m="opacity"===i;if((!m||3!==t.blendType||0!==t.alphaTest||t.alphaToCoverage)&&(!a||m)&&("height"!==i&&t[l]&&r&&(e[l]=t[l],e[c]=t[c],e.vertexColors=!0),t[h])){var _=!0;if(0!==t[f]||n||(_=!1),1!==t[f]||s||(_=!1),_){var g=t[h].id,v=o[g];void 0===v&&(o[g]=i,v=i),e[h]=!!t[h],e[p]=v,e[d]=this._getMapTransformID(t.getUniform(d),t[f]),e[u]=t[u],e[f]=t[f]}}},t._collectLights=function(e,t,i,n,s){for(var r=0;r<t.length;r++){var a=t[r];if(a.enabled&&a.mask&n){if(0!==e&&a.isStatic)continue;i.push(a)}}if(s)for(var o=0;o<s.length;o++){var h=s[o];h._type===e&&i.push(h)}},t._getMapTransformID=function(e,t){if(!e)return 0;var i=this._mapXForms[t];i||(i=[],this._mapXForms[t]=i);for(var n=0;n<i.length;n++)if(Ns(i[n][0].value,e[0].value)&&Ns(i[n][1].value,e[1].value))return n+1;return i.push(e)},e}(),Vs={name:"string",chunks:"chunks",mappingFormat:"string",_engine:"boolean",ambient:"rgb",ambientTint:"boolean",aoVertexColor:"boolean",aoVertexColorChannel:"string",aoMap:"texture",aoMapChannel:"string",aoMapUv:"number",aoMapTiling:"vec2",aoMapOffset:"vec2",aoMapRotation:"number",diffuse:"rgb",diffuseTint:"boolean",diffuseVertexColor:"boolean",diffuseVertexColorChannel:"string",diffuseMap:"texture",diffuseMapChannel:"string",diffuseMapUv:"number",diffuseMapTiling:"vec2",diffuseMapOffset:"vec2",diffuseMapRotation:"number",diffuseDetailMap:"texture",diffuseDetailMapChannel:"string",diffuseDetailMapUv:"number",diffuseDetailMapTiling:"vec2",diffuseDetailMapOffset:"vec2",diffuseDetailMapRotation:"number",diffuseDetailMode:"string",specular:"rgb",specularTint:"boolean",specularVertexColor:"boolean",specularVertexColorChannel:"string",specularMap:"texture",specularMapChannel:"string",specularMapUv:"number",specularMapTiling:"vec2",specularMapOffset:"vec2",specularMapRotation:"number",occludeSpecular:"enum:occludeSpecular",specularityFactor:"number",specularityFactorTint:"boolean",specularityFactorVertexColor:"boolean",specularityFactorVertexColorChannel:"string",specularityFactorMap:"texture",specularityFactorMapChannel:"string",specularityFactorMapUv:"number",specularityFactorMapTiling:"vec2",specularityFactorMapOffset:"vec2",specularityFactorMapRotation:"number",useMetalness:"boolean",metalness:"number",enableGGXSpecular:"boolean",anisotropy:"number",metalnessTint:"boolean",metalnessVertexColor:"boolean",metalnessVertexColorChannel:"string",metalnessMap:"texture",metalnessMapChannel:"string",metalnessMapUv:"number",metalnessMapTiling:"vec2",metalnessMapOffset:"vec2",metalnessMapRotation:"number",useMetalnessSpecularColor:"boolean",conserveEnergy:"boolean",shininess:"number",glossVertexColor:"boolean",glossVertexColorChannel:"string",glossMap:"texture",glossMapChannel:"string",glossMapUv:"number",glossMapTiling:"vec2",glossMapOffset:"vec2",glossMapRotation:"number",clearCoat:"number",clearCoatVertexColor:"boolean",clearCoatVertexColorChannel:"string",clearCoatMap:"texture",clearCoatMapChannel:"string",clearCoatMapUv:"number",clearCoatMapTiling:"vec2",clearCoatMapOffset:"vec2",clearCoatMapRotation:"number",clearCoatGlossiness:"number",clearCoatGlossVertexColor:"boolean",clearCoatGlossVertexColorChannel:"string",clearCoatGlossMap:"texture",clearCoatGlossMapChannel:"string",clearCoatGlossMapUv:"number",clearCoatGlossMapTiling:"vec2",clearCoatGlossMapOffset:"vec2",clearCoatGlossMapRotation:"number",clearCoatBumpiness:"number",clearCoatNormalMap:"texture",clearCoatNormalMapUv:"number",clearCoatNormalMapTiling:"vec2",clearCoatNormalMapOffset:"vec2",clearCoatNormalMapRotation:"number",useSheen:"boolean",sheen:"rgb",sheenMap:"texture",sheenMapChannel:"string",sheenMapUv:"number",sheenMapTiling:"vec2",sheenMapOffset:"vec2",sheenMapMapRotation:"number",sheenTint:"boolean",sheenVertexColor:"boolean",sheenVertexColorChannel:"string",fresnelModel:"number",emissive:"rgb",emissiveTint:"boolean",emissiveVertexColor:"boolean",emissiveVertexColorChannel:"string",emissiveMap:"texture",emissiveMapChannel:"string",emissiveMapUv:"number",emissiveMapTiling:"vec2",emissiveMapOffset:"vec2",emissiveMapMapRotation:"number",emissiveIntensity:"number",normalMap:"texture",normalMapTiling:"vec2",normalMapOffset:"vec2",normalMapRotation:"number",normalMapUv:"number",bumpiness:"number",normalDetailMap:"texture",normalDetailMapTiling:"vec2",normalDetailMapOffset:"vec2",normalDetailMapRotation:"number",normalDetailMapUv:"number",normalDetailMapBumpiness:"number",heightMap:"texture",heightMapChannel:"string",heightMapUv:"number",heightMapTiling:"vec2",heightMapOffset:"vec2",heightMapRotation:"number",heightMapFactor:"number",alphaToCoverage:"boolean",alphaTest:"number",alphaFade:"number",opacity:"number",opacityVertexColor:"boolean",opacityVertexColorChannel:"string",opacityMap:"texture",opacityMapChannel:"string",opacityMapUv:"number",opacityMapTiling:"vec2",opacityMapOffset:"vec2",opacityMapRotation:"number",opacityFadesSpecular:"boolean",reflectivity:"number",refraction:"number",refractionIndex:"number",sphereMap:"texture",cubeMap:"cubemap",cubeMapProjection:"number",cubeMapProjectionBox:"boundingbox",lightVertexColor:"boolean",lightVertexColorChannel:"string",lightMap:"texture",lightMapChannel:"string",lightMapUv:"number",lightMapTiling:"vec2",lightMapOffset:"vec2",lightMapRotation:"number",depthTest:"boolean",depthFunc:"enum:depthFunc",depthWrite:"boolean",depthBias:"number",slopeDepthBias:"number",cull:"enum:cull",blendType:"enum:blendType",shadingModel:"enum:shadingModel",useFog:"boolean",useLighting:"boolean",useSkybox:"boolean",useGammaTonemap:"boolean",envAtlas:"texture"},Gs=[];for(var Ws in Vs){"texture"===Vs[Ws]&&Gs.push(Ws)}var Hs=[];for(var Xs in Vs){"cubemap"===Vs[Xs]&&Hs.push(Xs)}var qs={aoMapVertexColor:"boolean",diffuseMapTint:"boolean",diffuseMapVertexColor:"boolean",emissiveMapTint:"boolean",emissiveMapVertexColor:"boolean",glossMapVertexColor:"boolean",metalnessMapVertexColor:"boolean",opacityMapVertexColor:"boolean",specularAntialias:"boolean",specularMapTint:"boolean",specularMapVertexColor:"boolean"},js={},Ys={},Ks=new Set,Zs=function(e){function t(){var t;return(t=e.call(this)||this)._dirtyShader=!0,t._assetReferences={},t._activeParams=new Set,t._activeLightingParams=new Set,t.shaderOptBuilder=new zs,t.reset(),t}J(t,e);var i=t.prototype;return i.reset=function(){var e=this;Object.keys(js).forEach((function(t){e["_"+t]=js[t].value()})),this._chunks={},this._uniformCache={}},i.copy=function(t){var i=this;for(var n in e.prototype.copy.call(this,t),Object.keys(js).forEach((function(e){i[e]=t[e]})),t._chunks)t._chunks.hasOwnProperty(n)&&(this._chunks[n]=t._chunks[n]);return this},i._setParameter=function(e,t){Ks.add(e),this.setParameter(e,t)},i._setParameters=function(e){var t=this;e.forEach((function(e){t._setParameter(e.name,e.value)}))},i._processParameters=function(e){var t=this,i=this[e];i.forEach((function(e){Ks.has(e)||delete t.parameters[e]})),this[e]=Ks,(Ks=i).clear()},i._updateMap=function(e){var t=e+"Map",i=this[t];if(i){this._setParameter("texture_"+t,i);var n=t+"Transform",s=this.getUniform(n);s&&this._setParameters(s)}},i._allocUniform=function(e,t){var i=this._uniformCache[e];return i||(i=t(),this._uniformCache[e]=i),i},i.getUniform=function(e,t,i){return Ys[e](this,t,i)},i.updateUniforms=function(e,t){var i=this,n=function(n){return i.getUniform(n,e,t)};if(this._setParameter("material_ambient",n("ambient")),this.diffuseMap&&!this.diffuseTint||this._setParameter("material_diffuse",n("diffuse")),this.useMetalness)if((!this.metalnessMap||this.metalness<1)&&this._setParameter("material_metalness",this.metalness),this.specularMap&&!this.specularTint||this._setParameter("material_specular",n("specular")),this.specularityFactorMap&&!this.specularityFactorTint||this._setParameter("material_specularityFactor",this.specularityFactor),this.sheenMap&&!this.sheenTint||this._setParameter("material_sheen",n("sheen")),this.sheenGlossinessMap&&!this.sheenGlossinessTint||this._setParameter("material_sheenGlossiness",this.sheenGlossiness),this.refractionIndex>0){var s=1/this.refractionIndex,r=(s-1)/(s+1);this._setParameter("material_f0",r*r)}else this._setParameter("material_f0",1);else this.specularMap&&!this.specularTint||this._setParameter("material_specular",n("specular"));for(var a in this.enableGGXSpecular&&this._setParameter("material_anisotropy",this.anisotropy),this.clearCoat>0&&(this._setParameter("material_clearCoat",this.clearCoat),this._setParameter("material_clearCoatGlossiness",this.clearCoatGlossiness),this._setParameter("material_clearCoatBumpiness",this.clearCoatBumpiness)),this._setParameter("material_shininess",n("shininess")),this.emissiveMap&&!this.emissiveTint||this._setParameter("material_emissive",n("emissive")),1!==this.emissiveIntensity&&this._setParameter("material_emissiveIntensity",this.emissiveIntensity),this.refraction>0&&(this._setParameter("material_refraction",this.refraction),this._setParameter("material_refractionIndex",this.refractionIndex)),this.useDynamicRefraction&&(this._setParameter("material_thickness",this.thickness),this._setParameter("material_attenuation",n("attenuation")),this._setParameter("material_invAttenuationDistance",0===this.attenuationDistance?0:1/this.attenuationDistance)),this.useIridescence&&(this._setParameter("material_iridescence",this.iridescence),this._setParameter("material_iridescenceRefractionIndex",this.iridescenceRefractionIndex),this._setParameter("material_iridescenceThicknessMin",this.iridescenceThicknessMin),this._setParameter("material_iridescenceThicknessMax",this.iridescenceThicknessMax)),this._setParameter("material_opacity",this.opacity),!1===this.opacityFadesSpecular&&this._setParameter("material_alphaFade",this.alphaFade),this.occludeSpecular&&this._setParameter("material_occludeSpecularIntensity",this.occludeSpecularIntensity),1===this.cubeMapProjection&&this._setParameter(n("cubeMapProjectionBox")),as)this._updateMap(a);this.ambientSH&&this._setParameter("ambientSH[0]",this.ambientSH),this.normalMap&&this._setParameter("material_bumpiness",this.bumpiness),this.normalMap&&this.normalDetailMap&&this._setParameter("material_normalDetailMapBumpiness",this.normalDetailMapBumpiness),this.heightMap&&this._setParameter("material_heightMapFactor",n("heightMapFactor"));var o=0===this.shadingModel;this.envAtlas&&this.cubeMap&&!o?(this._setParameter("texture_envAtlas",this.envAtlas),this._setParameter("texture_cubeMap",this.cubeMap)):this.envAtlas&&!o?this._setParameter("texture_envAtlas",this.envAtlas):this.cubeMap?this._setParameter("texture_cubeMap",this.cubeMap):this.sphereMap&&this._setParameter("texture_sphereMap",this.sphereMap),this._setParameter("material_reflectivity",this.reflectivity),this._processParameters("_activeParams"),this._dirtyShader&&this.clearVariants()},i.updateEnvUniforms=function(e,t){var i=0===this.shadingModel;!(this.envAtlas&&!i||this.cubeMap||this.sphereMap)&&this.useSkybox&&(t.envAtlas&&t.skybox&&!i?(this._setParameter("texture_envAtlas",t.envAtlas),this._setParameter("texture_cubeMap",t.skybox)):t.envAtlas&&!i?this._setParameter("texture_envAtlas",t.envAtlas):t.skybox&&this._setParameter("texture_cubeMap",t.skybox),!t.skyboxRotation.equals(Pe.IDENTITY)&&t._skyboxRotationMat3&&this._setParameter("cubeMapRotationMatrix",t._skyboxRotationMat3.data)),this._processParameters("_activeLightingParams")},i.getShaderVariant=function(e,t,i,n,s,r,a,o){this.updateEnvUniforms(e,t);var h=2===s||3===s||Hi.isShadow(s),l=h?os.optionsContextMin:os.optionsContext;h?this.shaderOptBuilder.updateMinRef(l,t,this,i,n,s,r):this.shaderOptBuilder.updateRef(l,t,this,i,n,s,r),this.onUpdateShader&&(l=this.onUpdateShader(l));var c=new Os(a,o),u=e.getProgramLibrary();u.register("standard",os);var d=u.getProgram("standard",l,c);return this._dirtyShader=!1,d},i.destroy=function(){for(var t in this._assetReferences)this._assetReferences[t]._unbind();this._assetReferences=null,e.prototype.destroy.call(this)},$(t,[{key:"shader",get:function(){return null},set:function(e){}},{key:"chunks",get:function(){return this._dirtyShader=!0,this._chunks},set:function(e){this._dirtyShader=!0,this._chunks=e}}]),t}(Bs);Zs.TEXTURE_PARAMETERS=Gs,Zs.CUBEMAP_PARAMETERS=Hs;var $s=function(e,t){Ys[e]=t},Qs=function(e,t,i,n){Object.defineProperty(Zs.prototype,e,{get:n||function(){return this["_"+e]},set:i}),js[e]={value:t}},Js=function(e){return e.defaultValue&&e.defaultValue.clone?function(e){var t="_"+e.name,i=e.dirtyShaderFunc||function(){return!0};Qs(e.name,(function(){return e.defaultValue.clone()}),(function(e){var n=this[t];n.equals(e)||(this._dirtyShader=this._dirtyShader||i(n,e),this[t]=n.copy(e))}),e.getterFunc)}(e):function(e){var t="_"+e.name,i=e.dirtyShaderFunc||function(){return!0};Qs(e.name,(function(){return e.defaultValue}),(function(e){var n=this[t];n!==e&&(this._dirtyShader=this._dirtyShader||i(n,e),this[t]=e)}),e.getterFunc)}(e)};function er(e,t,i,n,s,r){as[e]=i,Js({name:e+"Map",defaultValue:null,dirtyShaderFunc:function(e,t){return!!e!=!!t||e&&(e.type!==t.type||e.fixCubemapSeams!==t.fixCubemapSeams||e.format!==t.format)}}),Js({name:e+"MapTiling",defaultValue:new be(1,1)}),Js({name:e+"MapOffset",defaultValue:new be(0,0)}),Js({name:e+"MapRotation",defaultValue:0}),Js({name:e+"MapUv",defaultValue:t}),i>0&&Js({name:e+"MapChannel",defaultValue:n||(i>1?"rgb":"g")}),s&&(Js({name:e+"VertexColor",defaultValue:!1}),i>0&&Js({name:e+"VertexColorChannel",defaultValue:n||(i>1?"rgb":"g")})),r&&Js({name:e+"Mode",defaultValue:"mul"});var a=e+"MapTiling",o=e+"MapOffset",h=e+"MapRotation",l=e+"MapTransform";$s(l,(function(e,t,i){var n=e[a],s=e[o],r=e[h];if(1===n.x&&1===n.y&&0===s.x&&0===s.y&&0===r)return null;var c=e._allocUniform(l,(function(){return[{name:"texture_"+l+"0",value:new Float32Array(3)},{name:"texture_"+l+"1",value:new Float32Array(3)}]})),u=Math.cos(r*de.DEG_TO_RAD),d=Math.sin(r*de.DEG_TO_RAD),f=c[0].value;f[0]=u*n.x,f[1]=-d*n.y,f[2]=s.x;var p=c[1].value;return p[0]=d*n.x,p[1]=u*n.y,p[2]=1-n.y-s.y,c}))}function tr(e,t){Js({name:e,defaultValue:t,getterFunc:function(){return this._dirtyShader=!0,this["_"+e]}}),$s(e,(function(t,i,n){var s=t._allocUniform(e,(function(){return new Float32Array(3)})),r=t[e];return t.useGammaTonemap&&n.gammaCorrection?(s[0]=Math.pow(r.r,2.2),s[1]=Math.pow(r.g,2.2),s[2]=Math.pow(r.b,2.2)):(s[0]=r.r,s[1]=r.g,s[2]=r.b),s}))}function ir(e,t,i){Js({name:e,defaultValue:t,dirtyShaderFunc:function(e,t){return(0===e||1===e)!=(0===t||1===t)}}),$s(e,i)}function nr(e,t){Js({name:e,defaultValue:null,dirtyShaderFunc:function(e,t){return!!e==!!t}}),$s(e,t)}function sr(e,t){Js({name:e,defaultValue:t})}!function(){tr("ambient",new me(.7,.7,.7)),tr("diffuse",new me(1,1,1)),tr("specular",new me(0,0,0)),tr("emissive",new me(0,0,0)),tr("sheen",new me(1,1,1)),tr("attenuation",new me(1,1,1)),ir("emissiveIntensity",1),ir("specularityFactor",1),ir("sheenGlossiness",0),ir("shininess",25,(function(e,t,i){return 0===e.shadingModel?Math.pow(2,.01*e.shininess*11):.01*e.shininess})),ir("heightMapFactor",1,(function(e,t,i){return.025*e.heightMapFactor})),ir("opacity",1),ir("alphaFade",1),ir("alphaTest",0),ir("bumpiness",1),ir("normalDetailMapBumpiness",1),ir("reflectivity",1),ir("occludeSpecularIntensity",1),ir("refraction",0),ir("refractionIndex",1/1.5),ir("thickness",0),ir("attenuationDistance",0),ir("metalness",1),ir("anisotropy",0),ir("clearCoat",0),ir("clearCoatGlossiness",1),ir("clearCoatBumpiness",1),ir("aoUvSet",0,null),ir("iridescence",0),ir("iridescenceRefractionIndex",1/1.5),ir("iridescenceThicknessMin",0),ir("iridescenceThicknessMax",0),nr("ambientSH"),nr("cubeMapProjectionBox",(function(e,t,i){var n=e._allocUniform("cubeMapProjectionBox",(function(){return[{name:"envBoxMin",value:new Float32Array(3)},{name:"envBoxMax",value:new Float32Array(3)}]})),s=e.cubeMapProjectionBox.getMin(),r=n[0].value;r[0]=s.x,r[1]=s.y,r[2]=s.z;var a=e.cubeMapProjectionBox.getMax(),o=n[1].value;return o[0]=a.x,o[1]=a.y,o[2]=a.z,n})),sr("ambientTint",!1),sr("diffuseTint",!1),sr("specularTint",!1),sr("specularityFactorTint",!1),sr("emissiveTint",!1),sr("fastTbn",!1),sr("useMetalness",!1),sr("useMetalnessSpecularColor",!1),sr("useSheen",!1),sr("enableGGXSpecular",!1),sr("occludeDirect",!1),sr("normalizeNormalMap",!0),sr("conserveEnergy",!0),sr("opacityFadesSpecular",!0),sr("occludeSpecular",1),sr("shadingModel",1),sr("fresnelModel",2),sr("useDynamicRefraction",!1),sr("cubeMapProjection",0),sr("customFragmentShader",null),sr("forceFragmentPrecision",null),sr("useFog",!0),sr("useLighting",!0),sr("useGammaTonemap",!0),sr("useSkybox",!0),sr("forceUv1",!1),sr("pixelSnap",!1),sr("twoSidedLighting",!1),sr("nineSlicedMode",void 0),sr("msdfTextAttribute",!1),sr("useIridescence",!1),er("diffuse",0,3,"",!0),er("specular",0,3,"",!0),er("emissive",0,3,"",!0),er("thickness",0,1,"",!0),er("specularityFactor",0,1,"",!0),er("normal",0,-1,"",!1),er("metalness",0,1,"",!0),er("gloss",0,1,"",!0),er("opacity",0,1,"a",!0),er("refraction",0,1,"",!0),er("height",0,1,"",!1),er("ao",0,1,"",!0),er("light",1,3,"",!0),er("msdf",0,3,"",!1),er("diffuseDetail",0,3,"",!1,!0),er("normalDetail",0,-1,"",!1),er("clearCoat",0,1,"",!0),er("clearCoatGloss",0,1,"",!0),er("clearCoatNormal",0,-1,"",!1),er("sheen",0,3,"",!0),er("sheenGloss",0,1,"",!0),er("iridescence",0,1,"",!0),er("iridescenceThickness",0,1,"",!0),nr("cubeMap"),nr("sphereMap"),nr("envAtlas");var e=[null,null,null,null,null,null];Qs("prefilteredCubemaps",(function(){return e.slice()}),(function(e){var t=this._prefilteredCubemaps;e=e||[];for(var i=!1,n=!0,s=0;s<6;++s){var r=e[s]||null;t[s]!==r&&(t[s]=r,i=!0),n=n&&!!t[s]}i&&(n?this.envAtlas=Ls.generatePrefilteredAtlas(t,{target:this.envAtlas}):this.envAtlas&&(this.envAtlas.destroy(),this.envAtlas=null),this._dirtyShader=!0)}),(function(){return this._prefilteredCubemaps}))}();var rr=function(){function e(e){this.processedCache=new Map,this._device=e,this._cache={},this._generators={},this._isClearingCache=!1,this._precached=!1,this._programsCollection=[],this._defaultStdMatOption={},this._defaultStdMatOptionMin={};var t=new Zs;t.shaderOptBuilder.updateRef(this._defaultStdMatOption,{},t,null,[],0,null),t.shaderOptBuilder.updateMinRef(this._defaultStdMatOptionMin,{},t,null,[],4,null)}var t=e.prototype;return t.register=function(e,t){this.isRegistered(e)||(this._generators[e]=t)},t.unregister=function(e){this.isRegistered(e)&&delete this._generators[e]},t.isRegistered=function(e){return void 0!==this._generators[e]},t.generateShader=function(e,t,i,n){var s=this._cache[i];if(!s){var r;n.lights&&(r=n.lights,n.lights=r.map((function(e){var t=e.clone?e.clone():e;return t.key=e.key,t}))),this.storeNewProgram(t,n),n.lights&&(n.lights=r),this._precached;var a=this._device,o=e.createShaderDefinition(a,n);o.name=t+"-pass:"+n.pass,s=this._cache[i]=new zi(a,o)}return s},t.getProgram=function(e,t,i){var n=this._generators[e];if(!n)return null;var s=n.generateKey(t),r=s+"#"+JSON.stringify(i),a=this.processedCache.get(r);if(!a){var o=this.generateShader(n,e,s,t).definition,h={attributes:o.attributes,vshader:o.vshader,fshader:o.fshader,processingOptions:i};a=new zi(this._device,h),this.processedCache.set(r,a)}return a},t.storeNewProgram=function(e,t){var i={};if("standard"===e){var n=this._getDefaultStdMatOptions(t.pass);for(var s in t)(t.hasOwnProperty(s)&&n[s]!==t[s]||"pass"===s)&&(i[s]=t[s])}else i=t;this._programsCollection.push(JSON.stringify({name:e,options:i}))},t.dumpPrograms=function(){var e="let device = pc.app ? pc.app.graphicsDevice : pc.Application.getApplication().graphicsDevice;\n";e+="let shaders = [",this._programsCollection[0]&&(e+="\n\t"+this._programsCollection[0]);for(var t=1;t<this._programsCollection.length;++t)e+=",\n\t"+this._programsCollection[t];e+="\n];\n",e+="device.programLib.precompile(shaders);\n",e+='if (pc.version != "1.57.1" || pc.revision != "256dd83c2")\n',e+='\tconsole.warn("precompile-shaders.js: engine version mismatch, rebuild shaders lib with current engine");';var i=document.createElement("a");i.setAttribute("href","data:text/plain;charset=utf-8,"+encodeURIComponent(e)),i.setAttribute("download","precompile-shaders.js"),i.style.display="none",document.body.appendChild(i),i.click(),document.body.removeChild(i)},t.clearCache=function(){var e=this._cache;for(var t in this._isClearingCache=!0,e)e.hasOwnProperty(t)&&e[t].destroy();this._cache={},this._isClearingCache=!1},t.removeFromCache=function(e){if(!this._isClearingCache){var t=this._cache;for(var i in t)if(t.hasOwnProperty(i)&&t[i]===e){delete t[i];break}}},t._getDefaultStdMatOptions=function(e){return 2===e||3===e||Hi.isShadow(e)?this._defaultStdMatOptionMin:this._defaultStdMatOption},t.precompile=function(e){if(e)for(var t=new Array(e.length),i=0;i<e.length;i++){if("standard"===e[i].name){var n=e[i].options,s=this._getDefaultStdMatOptions(n.pass);for(var r in s)s.hasOwnProperty(r)&&void 0===n[r]&&(n[r]=s[r])}t[i]=this.getProgram(e[i].name,e[i].options)}this._precached=!0},e}(),ar="resizecanvas",or=function(e){function t(t){var i;(i=e.call(this)||this).canvas=void 0,i.deviceType=void 0,i.scope=void 0,i.boneLimit=void 0,i.maxAnisotropy=void 0,i.maxCubeMapSize=void 0,i.maxTextureSize=void 0,i.maxVolumeSize=void 0,i.precision=void 0,i.renderTarget=null,i.insideRenderPass=!1,i.supportsInstancing=void 0,i.supportsUniformBuffers=!1,i.textureFloatRenderable=void 0,i.textureHalfFloatRenderable=void 0,i.canvas=t,i._width=0,i._height=0,i._maxPixelRatio=1,i.shaders=[],i.buffers=[],i.textures=[],i.targets=[],i._vram={tex:0,vb:0,ib:0,ub:0},i._shaderStats={vsCompiled:0,fsCompiled:0,linked:0,materialShaders:0,compileTime:0},i.initializeContextCaches(),i._drawCallsPerFrame=0,i._shaderSwitchesPerFrame=0,i._primsPerFrame=[];for(var n=0;n<=6;n++)i._primsPerFrame[n]=0;return i._renderTargetCreationTime=0,i.scope=new dn("Device"),i.textureBias=i.scope.resolve("textureBias"),i.textureBias.setValue(0),i.programLib=new rr(te(i)),i}J(t,e);var i=t.prototype;return i.destroy=function(){this.fire("destroy")},i.postDestroy=function(){this.scope=null,this.canvas=null},i.toJSON=function(e){},i.initializeContextCaches=function(){this.indexBuffer=null,this.vertexBuffers=[],this.shader=null,this.renderTarget=null},i.getProgramLibrary=function(){return this.programLib},i.setProgramLibrary=function(e){this.programLib=e},i.setRenderTarget=function(e){this.renderTarget=e},i.setIndexBuffer=function(e){this.indexBuffer=e},i.setVertexBuffer=function(e){e&&this.vertexBuffers.push(e)},i.getRenderTarget=function(){return this.renderTarget},i.initRenderTarget=function(e){e.initialized||(e.init(),this.targets.push(e))},i._isBrowserInterface=function(e){return"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap},i.resizeCanvas=function(e,t){this._width=e,this._height=t;var i=Math.min(this._maxPixelRatio,L.browser?window.devicePixelRatio:1);e=Math.floor(e*i),t=Math.floor(t*i),this.canvas.width===e&&this.canvas.height===t||(this.canvas.width=e,this.canvas.height=t,this.fire(ar,e,t))},i.setResolution=function(e,t){this._width=e,this._height=t,this.canvas.width=e,this.canvas.height=t,this.fire(ar,e,t)},i.updateClientRect=function(){this.clientRect=this.canvas.getBoundingClientRect()},i.getBoneLimit=function(){return this.boneLimit},i.setBoneLimit=function(e){this.boneLimit=e},$(t,[{key:"width",get:function(){return this.canvas.width}},{key:"height",get:function(){return this.canvas.height}},{key:"fullscreen",get:function(){return!1},set:function(e){}},{key:"maxPixelRatio",get:function(){return this._maxPixelRatio},set:function(e){this._maxPixelRatio=e,this.resizeCanvas(this._width,this._height)}}]),t}(m),hr={depth:!0,face:0},lr=0,cr=function(){function e(e){var t,i;this.id=lr++;var n=arguments[1],s=arguments[2];if(e instanceof or?(this._colorBuffer=n,e=s):this._colorBuffer=e.colorBuffer,this._colorBuffer&&(this._colorBuffer._isRenderTarget=!0),e=void 0!==e?e:hr,this._depthBuffer=e.depthBuffer,this._face=void 0!==e.face?e.face:0,this._depthBuffer){var r=this._depthBuffer._format;r===ft?(this._depth=!0,this._stencil=!1):r===pt?(this._depth=!0,this._stencil=!0):(this._depth=!1,this._stencil=!1)}else this._depth=void 0===e.depth||e.depth,this._stencil=void 0!==e.stencil&&e.stencil;var a,o,h=(null==(t=this._colorBuffer)?void 0:t.device)||(null==(i=this._depthBuffer)?void 0:i.device)||e.graphicsDevice;(this._device=h,this._samples=void 0!==e.samples?Math.min(e.samples,this._device.maxSamples):1,this.autoResolve=void 0===e.autoResolve||e.autoResolve,this.name=e.name,this.name)||(this.name=null==(a=this._colorBuffer)?void 0:a.name);this.name||(this.name=null==(o=this._depthBuffer)?void 0:o.name);this.name||(this.name="Untitled"),this.flipY=!!e.flipY,this.impl=h.createRenderTargetImpl(this)}var t=e.prototype;return t.destroy=function(){var e=this._device;if(e){var t=e.targets.indexOf(this);-1!==t&&e.targets.splice(t,1),e.renderTarget===this&&e.setRenderTarget(null),this.destroyFrameBuffers()}},t.destroyFrameBuffers=function(){var e=this._device;e&&this.impl.destroy(e)},t.destroyTextureBuffers=function(){this._depthBuffer&&(this._depthBuffer.destroy(),this._depthBuffer=null),this._colorBuffer&&(this._colorBuffer.destroy(),this._colorBuffer=null)},t.init=function(){this.impl.init(this._device,this)},t.loseContext=function(){this.impl.loseContext()},t.resolve=function(e,t){void 0===e&&(e=!0),void 0===t&&(t=!!this._depthBuffer),this._device&&this._samples>1&&this.impl.resolve(this._device,this,e,t)},t.copy=function(e,t,i){if(!this._device){if(!e._device)return!1;this._device=e._device}return this._device.copyRenderTarget(e,this,t,i)},$(e,[{key:"initialized",get:function(){return this.impl.initialized}},{key:"samples",get:function(){return this._samples}},{key:"depth",get:function(){return this._depth}},{key:"stencil",get:function(){return this._stencil}},{key:"colorBuffer",get:function(){return this._colorBuffer}},{key:"depthBuffer",get:function(){return this._depthBuffer}},{key:"face",get:function(){return this._face}},{key:"width",get:function(){var e,t;return(null==(e=this._colorBuffer)?void 0:e.width)||(null==(t=this._depthBuffer)?void 0:t.width)||this._device.width}},{key:"height",get:function(){var e,t;return(null==(e=this._colorBuffer)?void 0:e.height)||(null==(t=this._depthBuffer)?void 0:t.height)||this._device.height}}]),e}();function ur(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}function dr(e,t,i){var n=2*(e+.5)/i-1,s=2*(t+.5)/i-1,r=1/i,a=(n*=1-1/i)-r,o=(s*=1-1/i)-r,h=n+r,l=s+r,c=ur(a,o)-ur(a,l)-ur(h,o)+ur(h,l);return 0===e&&0===t||e===i-1&&0===t||0===e&&t===i-1||e===i-1&&t===i-1?c/=3:0!==e&&0!==t&&e!==i-1&&t!==i-1||(c*=.5),c}var fr={bakeDirLmEndPS:"\n vec4 dirLm = texture2D(texture_dirLightMap, vUv1);\n\n if (bakeDir > 0.5) {\n if (dAtten > 0.00001) {\n dirLm.xyz = dirLm.xyz * 2.0 - vec3(1.0);\n dAtten = saturate(dAtten);\n gl_FragColor.rgb = normalize(dLightDirNormW.xyz*dAtten + dirLm.xyz*dirLm.w) * 0.5 + vec3(0.5);\n gl_FragColor.a = dirLm.w + dAtten;\n gl_FragColor.a = max(gl_FragColor.a, 1.0 / 255.0);\n } else {\n gl_FragColor = dirLm;\n }\n } else {\n gl_FragColor.rgb = dirLm.xyz;\n gl_FragColor.a = max(dirLm.w, dAtten > 0.00001? (1.0/255.0) : 0.0);\n }\n",bakeLmEndPS:"\n gl_FragColor.rgb = dDiffuseLight;\n gl_FragColor.rgb = pow(gl_FragColor.rgb, vec3(0.5));\n gl_FragColor.rgb /= 8.0;\n gl_FragColor.a = clamp( max( max( gl_FragColor.r, gl_FragColor.g ), max( gl_FragColor.b, 1.0 / 255.0 ) ), 0.0,1.0 );\n gl_FragColor.a = ceil(gl_FragColor.a * 255.0) / 255.0;\n gl_FragColor.rgb /= gl_FragColor.a;\n",dilatePS:"\n#define SHADER_NAME Dilate\n\nvarying vec2 vUv0;\n\nuniform sampler2D source;\nuniform vec2 pixelOffset;\n\nvoid main(void) {\n vec4 c = texture2D(source, vUv0);\n c = c.a>0.0? c : texture2D(source, vUv0 - pixelOffset);\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(0, -pixelOffset.y));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(pixelOffset.x, -pixelOffset.y));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(-pixelOffset.x, 0));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(pixelOffset.x, 0));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(-pixelOffset.x, pixelOffset.y));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(0, pixelOffset.y));\n c = c.a>0.0? c : texture2D(source, vUv0 + pixelOffset);\n gl_FragColor = c;\n}\n",bilateralDeNoisePS:"\n// bilateral filter, based on https://www.shadertoy.com/view/4dfGDH# and\n// http://people.csail.mit.edu/sparis/bf_course/course_notes.pdf\n\n// A bilateral filter is a non-linear, edge-preserving, and noise-reducing smoothing filter for images.\n// It replaces the intensity of each pixel with a weighted average of intensity values from nearby pixels.\n// This weight can be based on a Gaussian distribution. Crucially, the weights depend not only on\n// Euclidean distance of pixels, but also on the radiometric differences (e.g., range differences, such\n// as color intensity, depth distance, etc.). This preserves sharp edges.\n\n#define SHADER_NAME BilateralDeNoise\n\nfloat normpdf3(in vec3 v, in float sigma) {\n return 0.39894 * exp(-0.5 * dot(v, v) / (sigma * sigma)) / sigma;\n}\n\nvec3 decodeRGBM(vec4 rgbm) {\n vec3 color = (8.0 * rgbm.a) * rgbm.rgb;\n return color * color;\n}\n\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n\nvec4 encodeRGBM(vec3 color) { // modified RGBM\n vec4 encoded;\n encoded.rgb = pow(color.rgb, vec3(0.5));\n encoded.rgb *= 1.0 / 8.0;\n\n encoded.a = saturate( max( max( encoded.r, encoded.g ), max( encoded.b, 1.0 / 255.0 ) ) );\n encoded.a = ceil(encoded.a * 255.0) / 255.0;\n\n encoded.rgb /= encoded.a;\n return encoded;\n}\n\n// filter size\n#define MSIZE 15\n\nvarying vec2 vUv0;\nuniform sampler2D source;\nuniform vec2 pixelOffset;\nuniform vec2 sigmas;\nuniform float bZnorm;\nuniform float kernel[MSIZE];\n\nvoid main(void) {\n \n vec4 pixelRgbm = texture2D(source, vUv0);\n\n // lightmap specific optimization - skip pixels that were not baked\n // this also allows dilate filter that work on the output of this to work correctly, as it depends on .a being zero\n // to dilate, which the following blur filter would otherwise modify\n if (pixelRgbm.a <= 0.0) {\n gl_FragColor = pixelRgbm;\n return ;\n }\n\n // range sigma - controls blurriness based on a pixel distance\n float sigma = sigmas.x;\n\n // domain sigma - controls blurriness based on a pixel similarity (to preserve edges)\n float bSigma = sigmas.y;\n\n vec3 pixelHdr = decodeRGBM(pixelRgbm);\n vec3 accumulatedHdr = vec3(0.0);\n float accumulatedFactor = 0.0;\n\n // read out the texels\n const int kSize = (MSIZE-1)/2;\n for (int i = -kSize; i <= kSize; ++i) {\n for (int j = -kSize; j <= kSize; ++j) {\n \n // sample the pixel with offset\n vec2 coord = vUv0 + vec2(float(i), float(j)) * pixelOffset;\n vec4 rgbm = texture2D(source, coord);\n\n // lightmap - only use baked pixels\n if (rgbm.a > 0.0) {\n vec3 hdr = decodeRGBM(rgbm);\n\n // bilateral factors\n float factor = kernel[kSize + j] * kernel[kSize + i];\n factor *= normpdf3(hdr - pixelHdr, bSigma) * bZnorm;\n\n // accumulate\n accumulatedHdr += factor * hdr;\n accumulatedFactor += factor;\n }\n }\n }\n\n gl_FragColor = encodeRGBM(accumulatedHdr / accumulatedFactor);\n}\n"},pr=0,mr=function(){function e(e,t,i,n,s){void 0===n&&(n=0),this.device=e,this.format=t,this.numIndices=i,this.usage=n,this.id=pr++,this.impl=e.createIndexBufferImpl(this);var r=gi[t];this.bytesPerIndex=r,this.numBytes=this.numIndices*r,s?this.setData(s):this.storage=new ArrayBuffer(this.numBytes),this.adjustVramSizeTracking(e._vram,this.numBytes),this.device.buffers.push(this)}var t=e.prototype;return t.destroy=function(){var e=this.device,t=e.buffers.indexOf(this);-1!==t&&e.buffers.splice(t,1),this.device.indexBuffer===this&&(this.device.indexBuffer=null),this.impl.initialized&&(this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this.storage.byteLength))},t.adjustVramSizeTracking=function(e,t){e.ib+=t},t.loseContext=function(){this.impl.loseContext()},t.getFormat=function(){return this.format},t.getNumIndices=function(){return this.numIndices},t.lock=function(){return this.storage},t.unlock=function(){this.impl.unlock(this)},t.setData=function(e){return e.byteLength===this.numBytes&&(this.storage=e,this.unlock(),!0)},t._lockTypedArray=function(){var e=this.lock();return 2===this.format?new Uint32Array(e):1===this.format?new Uint16Array(e):new Uint8Array(e)},t.writeData=function(e,t){var i=this._lockTypedArray();if(e.length>t)if(ArrayBuffer.isView(e))e=e.subarray(0,t),i.set(e);else for(var n=0;n<t;n++)i[n]=e[n];else i.set(e);this.unlock()},t.readData=function(e){var t=this._lockTypedArray(),i=this.numIndices;if(ArrayBuffer.isView(e))e.set(t);else{e.length=0;for(var n=0;n<i;n++)e[n]=t[n]}return i},e}();function _r(e){this.array[this.index]=e}function gr(e,t){this.array[this.index]=e,this.array[this.index+1]=t}function vr(e,t,i){this.array[this.index]=e,this.array[this.index+1]=t,this.array[this.index+2]=i}function yr(e,t,i,n){this.array[this.index]=e,this.array[this.index+1]=t,this.array[this.index+2]=i,this.array[this.index+3]=n}function xr(e,t,i){this.array[e]=t[i]}function br(e,t,i){this.array[e]=t[i],this.array[e+1]=t[i+1]}function Sr(e,t,i){this.array[e]=t[i],this.array[e+1]=t[i+1],this.array[e+2]=t[i+2]}function wr(e,t,i){this.array[e]=t[i],this.array[e+1]=t[i+1],this.array[e+2]=t[i+2],this.array[e+3]=t[i+3]}function Tr(e,t,i){t[i]=this.array[e]}function Ar(e,t,i){t[i]=this.array[e],t[i+1]=this.array[e+1]}function Mr(e,t,i){t[i]=this.array[e],t[i+1]=this.array[e+1],t[i+2]=this.array[e+2]}function Cr(e,t,i){t[i]=this.array[e],t[i+1]=this.array[e+1],t[i+2]=this.array[e+2],t[i+3]=this.array[e+3]}var Er=function(){function e(e,t,i){switch(this.index=0,this.numComponents=t.numComponents,i.interleaved?this.array=new fi[t.dataType](e,t.offset):this.array=new fi[t.dataType](e,t.offset,i.vertexCount*t.numComponents),this.stride=t.stride/this.array.constructor.BYTES_PER_ELEMENT,t.numComponents){case 1:this.set=_r,this.getToArray=Tr,this.setFromArray=xr;break;case 2:this.set=gr,this.getToArray=Ar,this.setFromArray=br;break;case 3:this.set=vr,this.getToArray=Mr,this.setFromArray=Sr;break;case 4:this.set=yr,this.getToArray=Cr,this.setFromArray=wr}}var t=e.prototype;return t.get=function(e){return this.array[this.index+e]},t.set=function(e,t,i,n){},t.getToArray=function(e,t,i){},t.setFromArray=function(e,t,i){},e}(),Pr=function(){function e(e){this.vertexBuffer=e,this.vertexFormatSize=e.getFormat().size,this.buffer=this.vertexBuffer.lock(),this.accessors=[],this.element={};for(var t=this.vertexBuffer.getFormat(),i=0;i<t.elements.length;i++){var n=t.elements[i];this.accessors[i]=new Er(this.buffer,n,t),this.element[n.name]=this.accessors[i]}}var t=e.prototype;return t.next=function(e){void 0===e&&(e=1);for(var t=0,i=this.accessors,n=this.accessors.length;t<n;){var s=i[t++];s.index+=e*s.stride}},t.end=function(){this.vertexBuffer.unlock()},t.writeData=function(e,t,i){var n=this.element[e];if(n){i>this.vertexBuffer.numVertices&&(i=this.vertexBuffer.numVertices);var s=n.numComponents;if(this.vertexBuffer.getFormat().interleaved)for(var r=0,a=0;a<i;a++)n.setFromArray(r,t,a*s),r+=n.stride;else if(t.length>i*s){var o=i*s;if(ArrayBuffer.isView(t))t=t.subarray(0,o),n.array.set(t);else for(var h=0;h<o;h++)n.array[h]=t[h]}else n.array.set(t)}},t.readData=function(e,t){var i=this.element[e],n=0;if(i){var s;n=this.vertexBuffer.numVertices;var r=i.numComponents;if(this.vertexBuffer.getFormat().interleaved){Array.isArray(t)&&(t.length=0),i.index=0;var a=0;for(s=0;s<n;s++)i.getToArray(a,t,s*r),a+=i.stride}else if(ArrayBuffer.isView(t))t.set(i.array);else{t.length=0;var o=n*r;for(s=0;s<o;s++)t[s]=i.array[s]}}return n},e}(),Rr={type:5,base:0,count:4,indexed:!1},Ir=function(){function e(e){this.device=e,this.shader=null,this.vertexBuffer=Lr(e),this.needsDepthBuffer=!1,this.depthMap=null}return e.prototype.render=function(e,t,i){},e}();function Lr(e){var t=new Ti(e,[{semantic:vt,components:2,type:6}]),i=new Si(e,t,4),n=new Pr(i);return n.element.POSITION.set(-1,-1),n.next(),n.element.POSITION.set(1,-1),n.next(),n.element.POSITION.set(-1,1),n.next(),n.element.POSITION.set(1,1),n.end(),i}function Dr(e,t,i,n,s){var r=e.getRenderTarget();e.setRenderTarget(t),e.updateBegin();var a=t?t.width:e.width,o=t?t.height:e.height,h=0,l=0;s&&(h=s.x*a,l=s.y*o,a*=s.z,o*=s.w);var c=e.vx,u=e.vy,d=e.vw,f=e.vh;e.setViewport(h,l,a,o);var p=e.sx,m=e.sy,_=e.sw,g=e.sh;e.setScissor(h,l,a,o);var v=e.getBlending(),y=e.getDepthTest(),x=e.getDepthWrite(),b=e.getCullMode(),S=e.writeRed,w=e.writeGreen,T=e.writeBlue,A=e.writeAlpha;e.setBlending(!1),e.setDepthTest(!1),e.setDepthWrite(!1),e.setCullMode(0),e.setColorWrite(!0,!0,!0,!0),e.setVertexBuffer(i,0),e.setShader(n),e.draw(Rr),e.setBlending(v),e.setDepthTest(y),e.setDepthWrite(x),e.setCullMode(b),e.setColorWrite(S,w,T,A),e.updateEnd(),e.setRenderTarget(r),e.updateBegin(),e.setViewport(c,u,d,f),e.setScissor(p,m,_,g)}var kr=function(){function e(e,t){void 0===t&&(t=3),this.device=e.device;var i=this.device.gl;this._inputBuffer=e,3===t&&e.usage!==t&&(i.bindBuffer(i.ARRAY_BUFFER,e.impl.bufferId),i.bufferData(i.ARRAY_BUFFER,e.storage,i.DYNAMIC_COPY)),this._outputBuffer=new Si(e.device,e.format,e.numVertices,t,e.storage)}e.createShader=function(e,t,i){return on(e,t,null,i,!0)};var t=e.prototype;return t.destroy=function(){this._outputBuffer.destroy()},t.process=function(e,t){void 0===t&&(t=!0);var i=this.device,n=i.getRenderTarget();if(i.setRenderTarget(null),i.updateBegin(),i.setVertexBuffer(this._inputBuffer,0),i.setRaster(!1),i.setTransformFeedbackBuffer(this._outputBuffer),i.setShader(e),i.draw({type:0,base:0,count:this._inputBuffer.numVertices,indexed:!1}),i.setTransformFeedbackBuffer(null),i.setRaster(!0),i.updateEnd(),i.setRenderTarget(n),t){var s=this._inputBuffer.impl.bufferId;this._inputBuffer.impl.bufferId=this._outputBuffer.impl.bufferId,this._outputBuffer.impl.bufferId=s,s=this._inputBuffer.impl.vao,this._inputBuffer.impl.vao=this._outputBuffer.impl.vao,this._outputBuffer.impl.vao=s}},$(e,[{key:"inputBuffer",get:function(){return this._inputBuffer}},{key:"outputBuffer",get:function(){return this._outputBuffer}}]),e}(),Or=function(){function e(){this.bufferId=null}var t=e.prototype;return t.destroy=function(e){this.bufferId&&(e.gl.deleteBuffer(this.bufferId),this.bufferId=null)},t.loseContext=function(){this.bufferId=null},t.unlock=function(e,t,i,n){var s,r=e.gl;switch(this.bufferId||(this.bufferId=r.createBuffer()),t){case 0:s=r.STATIC_DRAW;break;case 1:s=r.DYNAMIC_DRAW;break;case 2:s=r.STREAM_DRAW;break;case 3:s=e.webgl2?r.DYNAMIC_COPY:r.STATIC_DRAW}r.bindBuffer(i,this.bufferId),r.bufferData(i,n,s)},$(e,[{key:"initialized",get:function(){return!!this.bufferId}}]),e}(),Fr=function(e){function t(){for(var t,i=arguments.length,n=new Array(i),s=0;s<i;s++)n[s]=arguments[s];return(t=e.call.apply(e,[this].concat(n))||this).vao=null,t}J(t,e);var i=t.prototype;return i.destroy=function(t){e.prototype.destroy.call(this,t),t.boundVao=null,t.gl.bindVertexArray(null)},i.loseContext=function(){e.prototype.loseContext.call(this),this.vao=null},i.unlock=function(t){var i=t.device;e.prototype.unlock.call(this,i,t.usage,i.gl.ARRAY_BUFFER,t.storage)},t}(Or),Br=function(e){function t(t){var i;i=e.call(this)||this;var n=t.device.gl,s=t.format;return 0===s?i.glFormat=n.UNSIGNED_BYTE:1===s?i.glFormat=n.UNSIGNED_SHORT:2===s&&(i.glFormat=n.UNSIGNED_INT),i}return J(t,e),t.prototype.unlock=function(t){var i=t.device;e.prototype.unlock.call(this,i,t.usage,i.gl.ELEMENT_ARRAY_BUFFER,t.storage)},t}(Or),Nr=function(e,t,i,n){if(this.locationId=n,this.scopeId=e.scope.resolve(t),this.version=new hn,"[0]"===t.substring(t.length-3))switch(i){case 2:i=17;break;case 3:i=21;break;case 4:i=22;break;case 5:i=23}this.dataType=i,this.value=[null,null,null,null],this.array=[]},Ur=["gl_VertexID","gl_InstanceID","gl_DrawID","gl_BaseVertex","gl_BaseInstance"],zr=function(){function e(e){this.init(),this.compileAndLink(e.device,e),e.device.shaders.push(e)}var t=e.prototype;return t.destroy=function(e){var t=e.device,i=t.shaders.indexOf(e);-1!==i&&t.shaders.splice(i,1),this.glProgram&&(t.gl.deleteProgram(this.glProgram),this.glProgram=null,t.removeShaderFromCache(e))},t.init=function(){this.uniforms=[],this.samplers=[],this.attributes=[],this.glProgram=null,this.glVertexShader=null,this.glFragmentShader=null},t.loseContext=function(){this.init()},t.restoreContext=function(e,t){this.compileAndLink(e,t)},t.compileAndLink=function(e,t){var i=t.definition,n=this._compileShaderSource(e,i.vshader,!0),s=this._compileShaderSource(e,i.fshader,!1),r=e.gl,a=r.createProgram();r.attachShader(a,n),r.attachShader(a,s);var o=i.attributes;if(e.webgl2&&i.useTransformFeedback){var h=[];for(var l in o)o.hasOwnProperty(l)&&h.push("out_"+l);r.transformFeedbackVaryings(a,h,r.INTERLEAVED_ATTRIBS)}for(var c in o)if(o.hasOwnProperty(c)){var u=o[c],d=vi[u];r.bindAttribLocation(a,d,c)}r.linkProgram(a),this.glVertexShader=n,this.glFragmentShader=s,this.glProgram=a},t._compileShaderSource=function(e,t,i){var n=e.gl,s=i?e.vertexShaderCache:e.fragmentShaderCache,r=s[t];return r||(r=n.createShader(i?n.VERTEX_SHADER:n.FRAGMENT_SHADER),n.shaderSource(r,t),n.compileShader(r),s[t]=r),r},t.postLink=function(e,t){var i=e.gl,n=this.glProgram,s=t.definition;if(!this._isCompiled(e,t,this.glVertexShader,s.vshader,"vertex"))return!1;if(!this._isCompiled(e,t,this.glFragmentShader,s.fshader,"fragment"))return!1;if(!i.getProgramParameter(n,i.LINK_STATUS)){var r="Failed to link shader program. Error: "+i.getProgramInfoLog(n);return console.error(r),!1}for(var a=0,o=i.getProgramParameter(n,i.ACTIVE_ATTRIBUTES);a<o;){var h=i.getActiveAttrib(n,a++),l=i.getAttribLocation(n,h.name);if(-1===Ur.indexOf(h.name)){void 0===s.attributes[h.name]&&console.error('Vertex shader attribute "'+h.name+'" is not mapped to a semantic in shader definition.');var c=new Nr(e,s.attributes[h.name],e.pcUniformType[h.type],l);this.attributes.push(c)}}a=0;for(var u=i.getProgramParameter(n,i.ACTIVE_UNIFORMS);a<u;){var d=i.getActiveUniform(n,a++),f=i.getUniformLocation(n,d.name),p=new Nr(e,d.name,e.pcUniformType[d.type],f);d.type===i.SAMPLER_2D||d.type===i.SAMPLER_CUBE||e.webgl2&&(d.type===i.SAMPLER_2D_SHADOW||d.type===i.SAMPLER_CUBE_SHADOW||d.type===i.SAMPLER_3D)?this.samplers.push(p):this.uniforms.push(p)}return t.ready=!0,!0},t._isCompiled=function(e,t,i,n,s){var r=e.gl;if(!r.getShaderParameter(i,r.COMPILE_STATUS)){var a=r.getShaderInfoLog(i),o=this._processError(n,a),h=o[0];o[1];var l="Failed to compile "+s+" shader:\n\n"+a+"\n"+h;return console.error(l),!1}return!0},t._processError=function(e,t){var i={},n="";if(e){var s=e.split("\n"),r=0,a=s.length;if(t&&t.startsWith("ERROR:")){var o=t.match(/^ERROR:\s([0-9]+):([0-9]+):\s*(.+)/);o&&(i.message=o[3],i.line=parseInt(o[2],10),r=Math.max(0,i.line-6),a=Math.min(s.length,i.line+5))}for(var h=r;h<a;h++)n+=h+1+":\t"+s[h]+"\n";i.source=e}return[n,i]},e}();function Vr(e,t){var i=e.width,n=e.height;if(i>t||n>t){var s=t/Math.max(i,n),r=Math.floor(i*s),a=Math.floor(n*s),o=document.createElement("canvas");return o.width=r,o.height=a,o.getContext("2d").drawImage(e,0,0,i,n,0,0,r,a),o}return e}var Gr=function(){function e(){this._glTexture=null,this._glTarget=void 0,this._glFormat=void 0,this._glInternalFormat=void 0,this._glPixelType=void 0}var t=e.prototype;return t.destroy=function(e){if(this._glTexture){for(var t=0;t<e.textureUnits.length;t++)for(var i=e.textureUnits[t],n=0;n<i.length;n++)i[n]===this._glTexture&&(i[n]=null);e.gl.deleteTexture(this._glTexture),this._glTexture=null}},t.loseContext=function(){this._glTexture=null},t.initialize=function(e,t){var i=e.gl;switch(this._glTexture=i.createTexture(),this._glTarget=t._cubemap?i.TEXTURE_CUBE_MAP:t._volume?i.TEXTURE_3D:i.TEXTURE_2D,t._format){case 0:this._glFormat=i.ALPHA,this._glInternalFormat=i.ALPHA,this._glPixelType=i.UNSIGNED_BYTE;break;case 1:this._glFormat=i.LUMINANCE,this._glInternalFormat=i.LUMINANCE,this._glPixelType=i.UNSIGNED_BYTE;break;case 2:this._glFormat=i.LUMINANCE_ALPHA,this._glInternalFormat=i.LUMINANCE_ALPHA,this._glPixelType=i.UNSIGNED_BYTE;break;case 3:this._glFormat=i.RGB,this._glInternalFormat=i.RGB,this._glPixelType=i.UNSIGNED_SHORT_5_6_5;break;case 4:this._glFormat=i.RGBA,this._glInternalFormat=i.RGBA,this._glPixelType=i.UNSIGNED_SHORT_5_5_5_1;break;case 5:this._glFormat=i.RGBA,this._glInternalFormat=i.RGBA,this._glPixelType=i.UNSIGNED_SHORT_4_4_4_4;break;case 6:this._glFormat=i.RGB,this._glInternalFormat=e.webgl2?i.RGB8:i.RGB,this._glPixelType=i.UNSIGNED_BYTE;break;case 7:this._glFormat=i.RGBA,this._glInternalFormat=e.webgl2?i.RGBA8:i.RGBA,this._glPixelType=i.UNSIGNED_BYTE;break;case 8:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;break;case 9:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;break;case ht:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;break;case mt:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTextureETC1.COMPRESSED_RGB_ETC1_WEBGL;break;case _t:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTexturePVRTC.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;break;case gt:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTexturePVRTC.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;break;case 26:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTexturePVRTC.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;break;case 27:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTexturePVRTC.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;break;case 22:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTextureETC.COMPRESSED_RGB8_ETC2;break;case 23:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTextureETC.COMPRESSED_RGBA8_ETC2_EAC;break;case 28:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTextureASTC.COMPRESSED_RGBA_ASTC_4x4_KHR;break;case 29:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTextureATC.COMPRESSED_RGB_ATC_WEBGL;break;case 30:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTextureATC.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL;break;case lt:this._glFormat=i.RGB,e.webgl2?(this._glInternalFormat=i.RGB16F,this._glPixelType=i.HALF_FLOAT):(this._glInternalFormat=i.RGB,this._glPixelType=e.extTextureHalfFloat.HALF_FLOAT_OES);break;case ct:this._glFormat=i.RGBA,e.webgl2?(this._glInternalFormat=i.RGBA16F,this._glPixelType=i.HALF_FLOAT):(this._glInternalFormat=i.RGBA,this._glPixelType=e.extTextureHalfFloat.HALF_FLOAT_OES);break;case ut:this._glFormat=i.RGB,e.webgl2?this._glInternalFormat=i.RGB32F:this._glInternalFormat=i.RGB,this._glPixelType=i.FLOAT;break;case dt:this._glFormat=i.RGBA,e.webgl2?this._glInternalFormat=i.RGBA32F:this._glInternalFormat=i.RGBA,this._glPixelType=i.FLOAT;break;case 15:this._glFormat=i.RED,this._glInternalFormat=i.R32F,this._glPixelType=i.FLOAT;break;case ft:e.webgl2?(this._glFormat=i.DEPTH_COMPONENT,this._glInternalFormat=i.DEPTH_COMPONENT32F,this._glPixelType=i.FLOAT):(this._glFormat=i.DEPTH_COMPONENT,this._glInternalFormat=i.DEPTH_COMPONENT,this._glPixelType=i.UNSIGNED_SHORT);break;case pt:this._glFormat=i.DEPTH_STENCIL,e.webgl2?(this._glInternalFormat=i.DEPTH24_STENCIL8,this._glPixelType=i.UNSIGNED_INT_24_8):(this._glInternalFormat=i.DEPTH_STENCIL,this._glPixelType=e.extDepthTexture.UNSIGNED_INT_24_8_WEBGL);break;case 18:this._glFormat=i.RGB,this._glInternalFormat=i.R11F_G11F_B10F,this._glPixelType=i.UNSIGNED_INT_10F_11F_11F_REV;break;case 19:this._glFormat=i.RGB,this._glInternalFormat=i.SRGB8,this._glPixelType=i.UNSIGNED_BYTE;break;case 20:this._glFormat=i.RGBA,this._glInternalFormat=i.SRGB8_ALPHA8,this._glPixelType=i.UNSIGNED_BYTE}},t.upload=function(e,t){var i=e.gl;if(t._needsUpload||!(t._needsMipmapsUpload&&t._mipmapsUploaded||!t.pot)){for(var n,s,r=0,a=Math.log2(Math.max(t._width,t._height))+1;t._levels[r]||0===r;)if(t._needsUpload||0!==r){if(r&&(!t._needsMipmapsUpload||!t._mipmaps))break;if(n=t._levels[r],1===r&&!t._compressed&&t._levels.length<a&&(i.generateMipmap(this._glTarget),t._mipmapsUploaded=!0),t._cubemap){var o=void 0;if(e._isBrowserInterface(n[0])){for(o=0;o<6;o++)if(t._levelsUpdated[0][o]){var h=n[o];h instanceof HTMLImageElement&&(h.width>e.maxCubeMapSize||h.height>e.maxCubeMapSize)&&(h=Vr(h,e.maxCubeMapSize),0===r&&(t._width=h.width,t._height=h.height)),e.setUnpackFlipY(!1),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+o,r,this._glInternalFormat,this._glFormat,this._glPixelType,h)}}else for(s=1/Math.pow(2,r),o=0;o<6;o++)if(t._levelsUpdated[0][o]){var l=n[o];t._compressed?i.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+o,r,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),0,l):(e.setUnpackFlipY(!1),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+o,r,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),0,this._glFormat,this._glPixelType,l))}}else t._volume?(s=1/Math.pow(2,r),t._compressed?i.compressedTexImage3D(i.TEXTURE_3D,r,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),Math.max(t._depth*s,1),0,n):(e.setUnpackFlipY(!1),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),i.texImage3D(i.TEXTURE_3D,r,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),Math.max(t._depth*s,1),0,this._glFormat,this._glPixelType,n))):(e._isBrowserInterface(n)?(n instanceof HTMLImageElement&&(n.width>e.maxTextureSize||n.height>e.maxTextureSize)&&(n=Vr(n,e.maxTextureSize),0===r&&(t._width=n.width,t._height=n.height)),e.setUnpackFlipY(t._flipY),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),i.texImage2D(i.TEXTURE_2D,r,this._glInternalFormat,this._glFormat,this._glPixelType,n)):(s=1/Math.pow(2,r),t._compressed?i.compressedTexImage2D(i.TEXTURE_2D,r,this._glInternalFormat,Math.max(Math.floor(t._width*s),1),Math.max(Math.floor(t._height*s),1),0,n):(e.setUnpackFlipY(!1),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),i.texImage2D(i.TEXTURE_2D,r,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),0,this._glFormat,this._glPixelType,n))),t._mipmapsUploaded=0!==r);r++}else r++;if(t._needsUpload)if(t._cubemap)for(var c=0;c<6;c++)t._levelsUpdated[0][c]=!1;else t._levelsUpdated[0]=!1;!t._compressed&&t._mipmaps&&t._needsMipmapsUpload&&(t.pot||e.webgl2)&&1===t._levels.length&&(i.generateMipmap(this._glTarget),t._mipmapsUploaded=!0),t._gpuSize&&t.adjustVramSizeTracking(e._vram,-t._gpuSize),t._gpuSize=t.gpuSize,t.adjustVramSizeTracking(e._vram,t._gpuSize)}},e}(),Wr=function(){function e(){this._glFrameBuffer=null,this._glDepthBuffer=null,this._glResolveFrameBuffer=null,this._glMsaaColorBuffer=null,this._glMsaaDepthBuffer=null}var t=e.prototype;return t.destroy=function(e){var t=e.gl;this._glFrameBuffer&&(t.deleteFramebuffer(this._glFrameBuffer),this._glFrameBuffer=null),this._glDepthBuffer&&(t.deleteRenderbuffer(this._glDepthBuffer),this._glDepthBuffer=null),this._glResolveFrameBuffer&&(t.deleteFramebuffer(this._glResolveFrameBuffer),this._glResolveFrameBuffer=null),this._glMsaaColorBuffer&&(t.deleteRenderbuffer(this._glMsaaColorBuffer),this._glMsaaColorBuffer=null),this._glMsaaDepthBuffer&&(t.deleteRenderbuffer(this._glMsaaDepthBuffer),this._glMsaaDepthBuffer=null)},t.init=function(e,t){var i=e.gl;this._glFrameBuffer=i.createFramebuffer(),e.setFramebuffer(this._glFrameBuffer);var n=t._colorBuffer;n&&(n.impl._glTexture||(n._width=Math.min(n.width,e.maxRenderBufferSize),n._height=Math.min(n.height,e.maxRenderBufferSize),e.setTexture(n,0)),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,n._cubemap?i.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:i.TEXTURE_2D,n.impl._glTexture,0));var s=t._depthBuffer;if(s)s.impl._glTexture||(s._width=Math.min(s.width,e.maxRenderBufferSize),s._height=Math.min(s.height,e.maxRenderBufferSize),e.setTexture(s,0)),t._stencil?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,s._cubemap?i.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:i.TEXTURE_2D,t._depthBuffer.impl._glTexture,0):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,s._cubemap?i.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:i.TEXTURE_2D,t._depthBuffer.impl._glTexture,0);else if(t._depth){if(!(t._samples>1&&e.webgl2)){if(this._glDepthBuffer||(this._glDepthBuffer=i.createRenderbuffer()),i.bindRenderbuffer(i.RENDERBUFFER,this._glDepthBuffer),t._stencil)i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,this._glDepthBuffer);else{var r=e.webgl2?i.DEPTH_COMPONENT32F:i.DEPTH_COMPONENT16;i.renderbufferStorage(i.RENDERBUFFER,r,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,this._glDepthBuffer)}i.bindRenderbuffer(i.RENDERBUFFER,null)}}e.webgl2&&t._samples>1&&(this._glResolveFrameBuffer=this._glFrameBuffer,this._glFrameBuffer=i.createFramebuffer(),e.setFramebuffer(this._glFrameBuffer),n&&(this._glMsaaColorBuffer||(this._glMsaaColorBuffer=i.createRenderbuffer()),i.bindRenderbuffer(i.RENDERBUFFER,this._glMsaaColorBuffer),i.renderbufferStorageMultisample(i.RENDERBUFFER,t._samples,n.impl._glInternalFormat,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,this._glMsaaColorBuffer)),t._depth&&(this._glMsaaDepthBuffer||(this._glMsaaDepthBuffer=i.createRenderbuffer()),i.bindRenderbuffer(i.RENDERBUFFER,this._glMsaaDepthBuffer),t._stencil?(i.renderbufferStorageMultisample(i.RENDERBUFFER,t._samples,i.DEPTH24_STENCIL8,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,this._glMsaaDepthBuffer)):(i.renderbufferStorageMultisample(i.RENDERBUFFER,t._samples,i.DEPTH_COMPONENT32F,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,this._glMsaaDepthBuffer))))},t._checkFbo=function(e){var t=e.gl;switch(t.checkFramebufferStatus(t.FRAMEBUFFER)){case t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:console.error("ERROR: FRAMEBUFFER_INCOMPLETE_ATTACHMENT");break;case t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:console.error("ERROR: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT");break;case t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:console.error("ERROR: FRAMEBUFFER_INCOMPLETE_DIMENSIONS");break;case t.FRAMEBUFFER_UNSUPPORTED:console.error("ERROR: FRAMEBUFFER_UNSUPPORTED");case t.FRAMEBUFFER_COMPLETE:}},t.loseContext=function(){this._glFrameBuffer=null,this._glDepthBuffer=null,this._glResolveFrameBuffer=null,this._glMsaaColorBuffer=null,this._glMsaaDepthBuffer=null},t.resolve=function(e,t,i,n){if(e.webgl2){var s=e.gl;s.bindFramebuffer(s.READ_FRAMEBUFFER,this._glFrameBuffer),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,this._glResolveFrameBuffer),s.blitFramebuffer(0,0,t.width,t.height,0,0,t.width,t.height,(i?s.COLOR_BUFFER_BIT:0)|(n?s.DEPTH_BUFFER_BIT:0),s.NEAREST),s.bindFramebuffer(s.FRAMEBUFFER,this._glFrameBuffer)}},$(e,[{key:"initialized",get:function(){return null!==this._glFrameBuffer}}]),e}(),Hr=[];function Xr(e,t){var i=!0,n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,2,2,0,e.RGBA,t,null);var s=e.createFramebuffer();return e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0),e.checkFramebufferStatus(e.FRAMEBUFFER)!==e.FRAMEBUFFER_COMPLETE&&(i=!1),e.bindTexture(e.TEXTURE_2D,null),e.deleteTexture(n),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteFramebuffer(s),i}var qr,jr=function(e){function t(t,i){var n;void 0===i&&(i={}),(n=e.call(this,t)||this).gl=void 0,n.webgl2=void 0,n.deviceType=li,n.defaultFramebuffer=null,n.defaultFramebufferAlpha=i.alpha,n.updateClientRect(),n.contextLost=!1,n._contextLostHandler=function(e){e.preventDefault(),n.contextLost=!0,n.loseContext(),n.fire("devicelost")},n._contextRestoredHandler=function(){n.restoreContext(),n.contextLost=!1,n.fire("devicerestored")},i.stencil=!0,i.powerPreference||(i.powerPreference="high-performance");var s="undefined"!=typeof navigator&&navigator.userAgent;n.forceDisableMultisampling=s&&s.includes("AppleWebKit")&&(s.includes("15.4")||s.includes("15_4")),n.forceDisableMultisampling&&(i.antialias=!1);for(var r=void 0===i.preferWebGl2||i.preferWebGl2?["webgl2","webgl","experimental-webgl"]:["webgl","experimental-webgl"],a=null,o=0;o<r.length;o++)if(a=t.getContext(r[o],i)){n.webgl2="webgl2"===r[o];break}if(!a)throw new Error("WebGL not supported");var l,c,u,d,f,p,m,_=L.browser&&!!window.chrome,g=L.browser&&-1!==navigator.appVersion.indexOf("Mac");n.gl=a,n._tempEnableSafariTextureUnitWorkaround=L.browser&&!!window.safari,n._tempMacChromeBlitFramebufferWorkaround=g&&_&&!i.alpha,n.webgl2||function(e){if(e.getSupportedExtensions){if(-1!=e.getSupportedExtensions().indexOf("OES_vertex_array_object"))return}else if(e.getExtension&&e.getExtension("OES_vertex_array_object"))return;if(e.getSupportedExtensions){var t=e.getSupportedExtensions;e.getSupportedExtensions=function(){var e=t.call(this)||[];return e.push("OES_vertex_array_object"),e}}var i=e.getExtension;e.getExtension=function(t){return"OES_vertex_array_object"==t?(e.__OESVertexArrayObject||(e.__OESVertexArrayObject=new h(e)),e.__OESVertexArrayObject):i?i.call(this,t):null}}(a),t.addEventListener("webglcontextlost",n._contextLostHandler,!1),t.addEventListener("webglcontextrestored",n._contextRestoredHandler,!1),n.initializeExtensions(),n.initializeCapabilities(),n.initializeRenderState(),n.initializeContextCaches(),n.supportsImageBitmap=null,"undefined"!=typeof ImageBitmap&&(l=te(n),c=new Uint8Array([137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,8,6,0,0,0,31,21,196,137,0,0,0,13,73,68,65,84,120,218,99,100,100,98,182,7,0,0,89,0,71,67,133,148,237,0,0,0,0,73,69,78,68,174,66,96,130]),createImageBitmap(new Blob([c],{type:"image/png"}),{premultiplyAlpha:"none"}).then((function(e){var t=new wn(l,{width:1,height:1,format:7,mipmaps:!1,levels:[e]}),i=new cr({colorBuffer:t,depth:!1});l.setFramebuffer(i.impl._glFrameBuffer),l.initRenderTarget(i);var n=new Uint8ClampedArray(4);return l.gl.readPixels(0,0,1,1,l.gl.RGBA,l.gl.UNSIGNED_BYTE,n),i.destroy(),t.destroy(),1===n[0]&&2===n[1]&&3===n[2]&&63===n[3]})).catch((function(e){return!1}))).then((function(e){n.supportsImageBitmap=e})),n.defaultClearOptions={color:[0,0,0,1],depth:1,stencil:0,flags:3},n.glAddress=[a.REPEAT,a.CLAMP_TO_EDGE,a.MIRRORED_REPEAT],n.glBlendEquation=[a.FUNC_ADD,a.FUNC_SUBTRACT,a.FUNC_REVERSE_SUBTRACT,n.webgl2?a.MIN:n.extBlendMinmax?n.extBlendMinmax.MIN_EXT:a.FUNC_ADD,n.webgl2?a.MAX:n.extBlendMinmax?n.extBlendMinmax.MAX_EXT:a.FUNC_ADD],n.glBlendFunction=[a.ZERO,a.ONE,a.SRC_COLOR,a.ONE_MINUS_SRC_COLOR,a.DST_COLOR,a.ONE_MINUS_DST_COLOR,a.SRC_ALPHA,a.SRC_ALPHA_SATURATE,a.ONE_MINUS_SRC_ALPHA,a.DST_ALPHA,a.ONE_MINUS_DST_ALPHA,a.CONSTANT_COLOR,a.ONE_MINUS_CONSTANT_COLOR,a.CONSTANT_ALPHA,a.ONE_MINUS_CONSTANT_ALPHA],n.glComparison=[a.NEVER,a.LESS,a.EQUAL,a.LEQUAL,a.GREATER,a.NOTEQUAL,a.GEQUAL,a.ALWAYS],n.glStencilOp=[a.KEEP,a.ZERO,a.REPLACE,a.INCR,a.INCR_WRAP,a.DECR,a.DECR_WRAP,a.INVERT],n.glClearFlag=[0,a.COLOR_BUFFER_BIT,a.DEPTH_BUFFER_BIT,a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT,a.STENCIL_BUFFER_BIT,a.STENCIL_BUFFER_BIT|a.COLOR_BUFFER_BIT,a.STENCIL_BUFFER_BIT|a.DEPTH_BUFFER_BIT,a.STENCIL_BUFFER_BIT|a.COLOR_BUFFER_BIT|a.DEPTH_BUFFER_BIT],n.glCull=[0,a.BACK,a.FRONT,a.FRONT_AND_BACK],n.glFilter=[a.NEAREST,a.LINEAR,a.NEAREST_MIPMAP_NEAREST,a.NEAREST_MIPMAP_LINEAR,a.LINEAR_MIPMAP_NEAREST,a.LINEAR_MIPMAP_LINEAR],n.glPrimitive=[a.POINTS,a.LINES,a.LINE_LOOP,a.LINE_STRIP,a.TRIANGLES,a.TRIANGLE_STRIP,a.TRIANGLE_FAN],n.glType=[a.BYTE,a.UNSIGNED_BYTE,a.SHORT,a.UNSIGNED_SHORT,a.INT,a.UNSIGNED_INT,a.FLOAT],n.pcUniformType={},n.pcUniformType[a.BOOL]=0,n.pcUniformType[a.INT]=1,n.pcUniformType[a.FLOAT]=2,n.pcUniformType[a.FLOAT_VEC2]=3,n.pcUniformType[a.FLOAT_VEC3]=4,n.pcUniformType[a.FLOAT_VEC4]=5,n.pcUniformType[a.INT_VEC2]=6,n.pcUniformType[a.INT_VEC3]=7,n.pcUniformType[a.INT_VEC4]=8,n.pcUniformType[a.BOOL_VEC2]=9,n.pcUniformType[a.BOOL_VEC3]=10,n.pcUniformType[a.BOOL_VEC4]=11,n.pcUniformType[a.FLOAT_MAT2]=12,n.pcUniformType[a.FLOAT_MAT3]=13,n.pcUniformType[a.FLOAT_MAT4]=14,n.pcUniformType[a.SAMPLER_2D]=15,n.pcUniformType[a.SAMPLER_CUBE]=16,n.webgl2&&(n.pcUniformType[a.SAMPLER_2D_SHADOW]=18,n.pcUniformType[a.SAMPLER_CUBE_SHADOW]=19,n.pcUniformType[a.SAMPLER_3D]=20),n.targetToSlot={},n.targetToSlot[a.TEXTURE_2D]=0,n.targetToSlot[a.TEXTURE_CUBE_MAP]=1,n.targetToSlot[a.TEXTURE_3D]=2,n.commitFunction=[],n.commitFunction[0]=function(e,t){e.value!==t&&(a.uniform1i(e.locationId,t),e.value=t)},n.commitFunction[1]=n.commitFunction[0],n.commitFunction[2]=function(e,t){e.value!==t&&(a.uniform1f(e.locationId,t),e.value=t)},n.commitFunction[3]=function(e,t){m=e.value,u=t[0],d=t[1],m[0]===u&&m[1]===d||(a.uniform2fv(e.locationId,t),m[0]=u,m[1]=d)},n.commitFunction[4]=function(e,t){m=e.value,u=t[0],d=t[1],f=t[2],m[0]===u&&m[1]===d&&m[2]===f||(a.uniform3fv(e.locationId,t),m[0]=u,m[1]=d,m[2]=f)},n.commitFunction[5]=function(e,t){m=e.value,u=t[0],d=t[1],f=t[2],p=t[3],m[0]===u&&m[1]===d&&m[2]===f&&m[3]===p||(a.uniform4fv(e.locationId,t),m[0]=u,m[1]=d,m[2]=f,m[3]=p)},n.commitFunction[6]=function(e,t){m=e.value,u=t[0],d=t[1],m[0]===u&&m[1]===d||(a.uniform2iv(e.locationId,t),m[0]=u,m[1]=d)},n.commitFunction[9]=n.commitFunction[6],n.commitFunction[7]=function(e,t){m=e.value,u=t[0],d=t[1],f=t[2],m[0]===u&&m[1]===d&&m[2]===f||(a.uniform3iv(e.locationId,t),m[0]=u,m[1]=d,m[2]=f)},n.commitFunction[10]=n.commitFunction[7],n.commitFunction[8]=function(e,t){m=e.value,u=t[0],d=t[1],f=t[2],p=t[3],m[0]===u&&m[1]===d&&m[2]===f&&m[3]===p||(a.uniform4iv(e.locationId,t),m[0]=u,m[1]=d,m[2]=f,m[3]=p)},n.commitFunction[11]=n.commitFunction[8],n.commitFunction[12]=function(e,t){a.uniformMatrix2fv(e.locationId,!1,t)},n.commitFunction[13]=function(e,t){a.uniformMatrix3fv(e.locationId,!1,t)},n.commitFunction[14]=function(e,t){a.uniformMatrix4fv(e.locationId,!1,t)},n.commitFunction[17]=function(e,t){a.uniform1fv(e.locationId,t)},n.commitFunction[21]=function(e,t){a.uniform2fv(e.locationId,t)},n.commitFunction[22]=function(e,t){a.uniform3fv(e.locationId,t)},n.commitFunction[23]=function(e,t){a.uniform4fv(e.locationId,t)},n.supportsBoneTextures=n.extTextureFloat&&n.maxVertexTextures>0;var v=n.vertexUniformsCount;return v-=16,v-=8,v-=1,v-=16,n.boneLimit=Math.floor(v/3),n.boneLimit=Math.min(n.boneLimit,128),"Mali-450 MP"===n.unmaskedRenderer&&(n.boneLimit=34),n.constantTexSource=n.scope.resolve("source"),n.extTextureFloat?n.webgl2?n.textureFloatRenderable=!!n.extColorBufferFloat:n.textureFloatRenderable=Xr(a,a.FLOAT):n.textureFloatRenderable=!1,n.extColorBufferHalfFloat?n.textureHalfFloatRenderable=!!n.extColorBufferHalfFloat:n.extTextureHalfFloat?n.webgl2?n.textureHalfFloatRenderable=!!n.extColorBufferFloat:n.textureHalfFloatRenderable=Xr(a,n.extTextureHalfFloat.HALF_FLOAT_OES):n.textureHalfFloatRenderable=!1,n.supportsMorphTargetTexturesCore="highp"===n.maxPrecision&&n.maxVertexTextures>=2,n._textureFloatHighPrecision=void 0,n._textureHalfFloatUpdatable=void 0,n.areaLightLutFormat=7,n.extTextureHalfFloat&&n.textureHalfFloatUpdatable&&n.extTextureHalfFloatLinear?n.areaLightLutFormat=ct:n.extTextureFloat&&n.extTextureFloatLinear&&(n.areaLightLutFormat=dt),n}J(t,e);var i=t.prototype;return i.destroy=function(){e.prototype.destroy.call(this);var t=this.gl;this.webgl2&&this.feedback&&t.deleteTransformFeedback(this.feedback),this.clearShaderCache(),this.clearVertexArrayObjectCache(),this.canvas.removeEventListener("webglcontextlost",this._contextLostHandler,!1),this.canvas.removeEventListener("webglcontextrestored",this._contextRestoredHandler,!1),this._contextLostHandler=null,this._contextRestoredHandler=null,this.gl=null,e.prototype.postDestroy.call(this)},i.createVertexBufferImpl=function(e,t){return new Fr},i.createIndexBufferImpl=function(e){return new Br(e)},i.createShaderImpl=function(e){return new zr(e)},i.createTextureImpl=function(e){return new Gr},i.createRenderTargetImpl=function(e){return new Wr},i.getPrecision=function(){var e=this.gl,t="highp";if(e.getShaderPrecisionFormat){var i=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT),n=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT),s=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT),r=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),a=i.precision>0&&s.precision>0,o=n.precision>0&&r.precision>0;a||(t=o?"mediump":"lowp")}return t},i.initializeExtensions=function(){var e=this.gl,t=e.getSupportedExtensions(),i=function(){for(var i=0;i<arguments.length;i++)if(-1!==t.indexOf(arguments[i]))return e.getExtension(arguments[i]);return null};if(this.webgl2)this.extBlendMinmax=!0,this.extDrawBuffers=!0,this.extInstancing=!0,this.extStandardDerivatives=!0,this.extTextureFloat=!0,this.extTextureHalfFloat=!0,this.extTextureLod=!0,this.extUintElement=!0,this.extVertexArrayObject=!0,this.extColorBufferFloat=i("EXT_color_buffer_float"),this.extDisjointTimerQuery=i("EXT_disjoint_timer_query_webgl2","EXT_disjoint_timer_query"),this.extDepthTexture=!0;else{if(this.extBlendMinmax=i("EXT_blend_minmax"),this.extDrawBuffers=i("EXT_draw_buffers"),this.extInstancing=i("ANGLE_instanced_arrays"),this.extInstancing){var n=this.extInstancing;e.drawArraysInstanced=n.drawArraysInstancedANGLE.bind(n),e.drawElementsInstanced=n.drawElementsInstancedANGLE.bind(n),e.vertexAttribDivisor=n.vertexAttribDivisorANGLE.bind(n)}if(this.extStandardDerivatives=i("OES_standard_derivatives"),this.extTextureFloat=i("OES_texture_float"),this.extTextureHalfFloat=i("OES_texture_half_float"),this.extTextureLod=i("EXT_shader_texture_lod"),this.extUintElement=i("OES_element_index_uint"),this.extVertexArrayObject=i("OES_vertex_array_object"),this.extVertexArrayObject){var s=this.extVertexArrayObject;e.createVertexArray=s.createVertexArrayOES.bind(s),e.deleteVertexArray=s.deleteVertexArrayOES.bind(s),e.isVertexArray=s.isVertexArrayOES.bind(s),e.bindVertexArray=s.bindVertexArrayOES.bind(s)}this.extColorBufferFloat=null,this.extDisjointTimerQuery=null,this.extDepthTexture=e.getExtension("WEBGL_depth_texture")}this.extDebugRendererInfo=i("WEBGL_debug_renderer_info"),this.extTextureFloatLinear=i("OES_texture_float_linear"),this.extTextureHalfFloatLinear=i("OES_texture_half_float_linear"),this.extFloatBlend=i("EXT_float_blend"),this.extTextureFilterAnisotropic=i("EXT_texture_filter_anisotropic","WEBKIT_EXT_texture_filter_anisotropic"),this.extCompressedTextureETC1=i("WEBGL_compressed_texture_etc1"),this.extCompressedTextureETC=i("WEBGL_compressed_texture_etc"),this.extCompressedTexturePVRTC=i("WEBGL_compressed_texture_pvrtc","WEBKIT_WEBGL_compressed_texture_pvrtc"),this.extCompressedTextureS3TC=i("WEBGL_compressed_texture_s3tc","WEBKIT_WEBGL_compressed_texture_s3tc"),this.extCompressedTextureATC=i("WEBGL_compressed_texture_atc"),this.extCompressedTextureASTC=i("WEBGL_compressed_texture_astc"),this.extParallelShaderCompile=i("KHR_parallel_shader_compile"),this.extColorBufferHalfFloat=i("EXT_color_buffer_half_float")},i.initializeCapabilities=function(){var e,t=this.gl,i="undefined"!=typeof navigator?navigator.userAgent:"";this.maxPrecision=this.precision=this.getPrecision();var n=t.getContextAttributes();this.supportsMsaa=n.antialias,this.supportsStencil=n.stencil,this.supportsInstancing=!!this.extInstancing,this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE),this.maxCubeMapSize=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),this.maxRenderBufferSize=t.getParameter(t.MAX_RENDERBUFFER_SIZE),this.maxTextures=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),this.maxCombinedTextures=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS),this.maxVertexTextures=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),this.vertexUniformsCount=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),this.fragmentUniformsCount=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),this.webgl2?(this.maxDrawBuffers=t.getParameter(t.MAX_DRAW_BUFFERS),this.maxColorAttachments=t.getParameter(t.MAX_COLOR_ATTACHMENTS),this.maxVolumeSize=t.getParameter(t.MAX_3D_TEXTURE_SIZE)):(e=this.extDrawBuffers,this.maxDrawBuffers=e?t.getParameter(e.MAX_DRAW_BUFFERS_EXT):1,this.maxColorAttachments=e?t.getParameter(e.MAX_COLOR_ATTACHMENTS_EXT):1,this.maxVolumeSize=1),e=this.extDebugRendererInfo,this.unmaskedRenderer=e?t.getParameter(e.UNMASKED_RENDERER_WEBGL):"",this.unmaskedVendor=e?t.getParameter(e.UNMASKED_VENDOR_WEBGL):"";this.supportsGpuParticles=!("ARM"===this.unmaskedVendor&&i.match(/SM-[a-zA-Z0-9]+/)),e=this.extTextureFilterAnisotropic,this.maxAnisotropy=e?t.getParameter(e.MAX_TEXTURE_MAX_ANISOTROPY_EXT):1,this.samples=t.getParameter(t.SAMPLES),this.maxSamples=this.webgl2&&!this.forceDisableMultisampling?t.getParameter(t.MAX_SAMPLES):1,this.supportsAreaLights=this.webgl2||!L.android,this.maxTextures<=8&&(this.supportsAreaLights=!1)},i.initializeRenderState=function(){var e=this.gl;this.blending=!1,e.disable(e.BLEND),this.blendSrc=1,this.blendDst=0,this.blendSrcAlpha=1,this.blendDstAlpha=0,this.separateAlphaBlend=!1,this.blendEquation=0,this.blendAlphaEquation=0,this.separateAlphaEquation=!1,e.blendFunc(e.ONE,e.ZERO),e.blendEquation(e.FUNC_ADD),this.blendColor=new me(0,0,0,0),e.blendColor(0,0,0,0),this.writeRed=!0,this.writeGreen=!0,this.writeBlue=!0,this.writeAlpha=!0,e.colorMask(!0,!0,!0,!0),this.cullMode=1,e.enable(e.CULL_FACE),e.cullFace(e.BACK),this.depthTest=!0,e.enable(e.DEPTH_TEST),this.depthFunc=3,e.depthFunc(e.LEQUAL),this.depthWrite=!0,e.depthMask(!0),this.stencil=!1,e.disable(e.STENCIL_TEST),this.stencilFuncFront=this.stencilFuncBack=7,this.stencilRefFront=this.stencilRefBack=0,this.stencilMaskFront=this.stencilMaskBack=255,e.stencilFunc(e.ALWAYS,0,255),this.stencilFailFront=this.stencilFailBack=0,this.stencilZfailFront=this.stencilZfailBack=0,this.stencilZpassFront=this.stencilZpassBack=0,this.stencilWriteMaskFront=255,this.stencilWriteMaskBack=255,e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.stencilMask(255),this.alphaToCoverage=!1,this.raster=!0,this.webgl2&&(e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.disable(e.RASTERIZER_DISCARD)),this.depthBiasEnabled=!1,e.disable(e.POLYGON_OFFSET_FILL),this.clearDepth=1,e.clearDepth(1),this.clearColor=new me(0,0,0,0),e.clearColor(0,0,0,0),this.clearStencil=0,e.clearStencil(0),this.vx=this.vy=this.vw=this.vh=0,this.sx=this.sy=this.sw=this.sh=0,this.webgl2?e.hint(e.FRAGMENT_SHADER_DERIVATIVE_HINT,e.NICEST):this.extStandardDerivatives&&e.hint(this.extStandardDerivatives.FRAGMENT_SHADER_DERIVATIVE_HINT_OES,e.NICEST),e.enable(e.SCISSOR_TEST),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.NONE),this.unpackFlipY=!1,e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),this.unpackPremultiplyAlpha=!1,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_ALIGNMENT,1)},i.initializeContextCaches=function(){e.prototype.initializeContextCaches.call(this),this.vertexShaderCache={},this.fragmentShaderCache={},this._vaoMap=new Map,this.boundVao=null,this.activeFramebuffer=null,this.feedback=null,this.transformFeedbackBuffer=null,this.textureUnit=0,this.textureUnits=[];for(var t=0;t<this.maxCombinedTextures;t++)this.textureUnits.push([null,null,null])},i.loseContext=function(){for(var e,t=ne(this.shaders);!(e=t()).done;){e.value.loseContext()}for(var i,n=ne(this.textures);!(i=n()).done;){i.value.loseContext()}for(var s,r=ne(this.buffers);!(s=r()).done;){s.value.loseContext()}for(var a,o=ne(this.targets);!(a=o()).done;){a.value.loseContext()}},i.restoreContext=function(){this.initializeExtensions(),this.initializeCapabilities(),this.initializeRenderState(),this.initializeContextCaches();for(var e,t=ne(this.shaders);!(e=t()).done;){e.value.restoreContext()}for(var i,n=ne(this.buffers);!(i=n()).done;){i.value.unlock()}},i.setViewport=function(e,t,i,n){this.vx===e&&this.vy===t&&this.vw===i&&this.vh===n||(this.gl.viewport(e,t,i,n),this.vx=e,this.vy=t,this.vw=i,this.vh=n)},i.setScissor=function(e,t,i,n){this.sx===e&&this.sy===t&&this.sw===i&&this.sh===n||(this.gl.scissor(e,t,i,n),this.sx=e,this.sy=t,this.sw=i,this.sh=n)},i.setFramebuffer=function(e){if(this.activeFramebuffer!==e){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,e),this.activeFramebuffer=e}},i.copyRenderTarget=function(e,t,i,n){var s=this.gl;if(!this.webgl2&&n)return!1;if(i)if(t){if(e){if(!e._colorBuffer||!t._colorBuffer)return!1;if(e._colorBuffer._format!==t._colorBuffer._format)return!1}}else if(!e._colorBuffer)return!1;if(n&&e&&!e._depth){if(!e._depthBuffer||!t._depthBuffer)return!1;if(e._depthBuffer._format!==t._depthBuffer._format)return!1}if(this.webgl2&&t){var r=this.renderTarget;this.renderTarget=t,this.updateBegin(),s.bindFramebuffer(s.READ_FRAMEBUFFER,e?e.impl._glFrameBuffer:null),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,t.impl._glFrameBuffer);var a=e?e.width:t.width,o=e?e.height:t.height;s.blitFramebuffer(0,0,a,o,0,0,a,o,(i?s.COLOR_BUFFER_BIT:0)|(n?s.DEPTH_BUFFER_BIT:0),s.NEAREST),this.renderTarget=r,s.bindFramebuffer(s.FRAMEBUFFER,r?r.impl._glFrameBuffer:null)}else{var h=this.getCopyShader();this.constantTexSource.setValue(e._colorBuffer),Ei(this,t,h)}return!0},i.getCopyShader=function(){if(!this._copyShader){var e=Wi.fullscreenQuadVS,t=Wi.outputTex2DPS;this._copyShader=on(this,e,t,"outputTex2D")}return this._copyShader},i.startPass=function(e){this.setRenderTarget(e.renderTarget),this.updateBegin();var t=e.colorOps,i=e.depthStencilOps;if(t.clear||i.clearDepth||i.clearStencil){var n=e.renderTarget,s=n?n.width:this.width,r=n?n.height:this.height;this.setViewport(0,0,s,r),this.setScissor(0,0,s,r);var a=0,o={};t.clear&&(a|=1,o.color=[t.clearValue.r,t.clearValue.g,t.clearValue.b,t.clearValue.a]),i.clearDepth&&(a|=2,o.depth=i.clearDepthValue),i.clearStencil&&(a|=4,o.stencil=i.clearStencilValue),o.flags=a,this.clear(o)}this.insideRenderPass=!0},i.endPass=function(e){this.unbindVertexArray();var t=this.renderTarget;if(t){if(this.webgl2){Hr.length=0;var i=this.gl;e.colorOps.store||e.colorOps.resolve||Hr.push(i.COLOR_ATTACHMENT0),e.depthStencilOps.storeDepth||Hr.push(i.DEPTH_ATTACHMENT),e.depthStencilOps.storeStencil||Hr.push(i.STENCIL_ATTACHMENT),Hr.length>0&&e.fullSizeClearRect&&i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,Hr)}if(e.colorOps.resolve&&this.webgl2&&e.samples>1&&t.autoResolve&&t.resolve(!0,!1),e.colorOps.mipmaps){var n=t._colorBuffer;n&&n.impl._glTexture&&n.mipmaps&&(n.pot||this.webgl2)&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(n),this.gl.generateMipmap(n.impl._glTarget))}}this.insideRenderPass=!1},i.updateBegin=function(){if(this.boundVao=null,this._tempEnableSafariTextureUnitWorkaround)for(var e=0;e<this.textureUnits.length;++e)for(var t=0;t<3;++t)this.textureUnits[e][t]=null;var i=this.renderTarget;i?i.impl.initialized?this.setFramebuffer(i.impl._glFrameBuffer):this.initRenderTarget(i):this.setFramebuffer(this.defaultFramebuffer)},i.updateEnd=function(){this.unbindVertexArray();var e=this.renderTarget;if(e){this.webgl2&&e._samples>1&&e.autoResolve&&e.resolve();var t=e._colorBuffer;t&&t.impl._glTexture&&t.mipmaps&&(t.pot||this.webgl2)&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(t),this.gl.generateMipmap(t.impl._glTarget))}},i.setUnpackFlipY=function(e){if(this.unpackFlipY!==e){this.unpackFlipY=e;var t=this.gl;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,e)}},i.setUnpackPremultiplyAlpha=function(e){if(this.unpackPremultiplyAlpha!==e){this.unpackPremultiplyAlpha=e;var t=this.gl;t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e)}},i.activeTexture=function(e){this.textureUnit!==e&&(this.gl.activeTexture(this.gl.TEXTURE0+e),this.textureUnit=e)},i.bindTexture=function(e){var t=e.impl,i=t._glTarget,n=t._glTexture,s=this.textureUnit,r=this.targetToSlot[i];this.textureUnits[s][r]!==n&&(this.gl.bindTexture(i,n),this.textureUnits[s][r]=n)},i.bindTextureOnUnit=function(e,t){var i=e.impl,n=i._glTarget,s=i._glTexture,r=this.targetToSlot[n];this.textureUnits[t][r]!==s&&(this.activeTexture(t),this.gl.bindTexture(n,s),this.textureUnits[t][r]=s)},i.setTextureParameters=function(e){var t=this.gl,i=e._parameterFlags,n=e.impl._glTarget;if(1&i){var s=e._minFilter;(!e.pot&&!this.webgl2||!e._mipmaps||e._compressed&&1===e._levels.length)&&(2===s||3===s?s=0:4!==s&&5!==s||(s=1)),t.texParameteri(n,t.TEXTURE_MIN_FILTER,this.glFilter[s])}if(2&i&&t.texParameteri(n,t.TEXTURE_MAG_FILTER,this.glFilter[e._magFilter]),4&i&&(this.webgl2?t.texParameteri(n,t.TEXTURE_WRAP_S,this.glAddress[e._addressU]):t.texParameteri(n,t.TEXTURE_WRAP_S,this.glAddress[e.pot?e._addressU:1])),8&i&&(this.webgl2?t.texParameteri(n,t.TEXTURE_WRAP_T,this.glAddress[e._addressV]):t.texParameteri(n,t.TEXTURE_WRAP_T,this.glAddress[e.pot?e._addressV:1])),16&i&&this.webgl2&&t.texParameteri(n,t.TEXTURE_WRAP_R,this.glAddress[e._addressW]),32&i&&this.webgl2&&t.texParameteri(n,t.TEXTURE_COMPARE_MODE,e._compareOnRead?t.COMPARE_REF_TO_TEXTURE:t.NONE),64&i&&this.webgl2&&t.texParameteri(n,t.TEXTURE_COMPARE_FUNC,this.glComparison[e._compareFunc]),128&i){var r=this.extTextureFilterAnisotropic;r&&t.texParameterf(n,r.TEXTURE_MAX_ANISOTROPY_EXT,Math.max(1,Math.min(Math.round(e._anisotropy),this.maxAnisotropy)))}},i.setTexture=function(e,t){e.impl._glTexture||e.impl.initialize(this,e),e._parameterFlags>0||e._needsUpload||e._needsMipmapsUpload?(this.activeTexture(t),this.bindTexture(e),e._parameterFlags&&(this.setTextureParameters(e),e._parameterFlags=0),(e._needsUpload||e._needsMipmapsUpload)&&(e.impl.upload(this,e),e._needsUpload=!1,e._needsMipmapsUpload=!1)):this.bindTextureOnUnit(e,t)},i.createVertexArray=function(e){var t,i,n=e.length>1;if(n){t="";for(var s=0;s<e.length;s++){var r=e[s];t+=r.id+r.format.renderingingHash}i=this._vaoMap.get(t)}if(!i){var a=this.gl;i=a.createVertexArray(),a.bindVertexArray(i),a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,null);for(var o=0;o<e.length;o++){var h=e[o];a.bindBuffer(a.ARRAY_BUFFER,h.impl.bufferId);for(var l=h.format.elements,c=0;c<l.length;c++){var u=l[c],d=vi[u.name];a.vertexAttribPointer(d,u.numComponents,this.glType[u.dataType],u.normalize,u.stride,u.offset),a.enableVertexAttribArray(d),h.instancing&&a.vertexAttribDivisor(d,1)}}a.bindVertexArray(null),a.bindBuffer(a.ARRAY_BUFFER,null),n&&this._vaoMap.set(t,i)}return i},i.unbindVertexArray=function(){this.boundVao&&(this.boundVao=null,this.gl.bindVertexArray(null))},i.setBuffers=function(){var e,t=this.gl;if(1===this.vertexBuffers.length){var i=this.vertexBuffers[0];i.impl.vao||(i.impl.vao=this.createVertexArray(this.vertexBuffers)),e=i.impl.vao}else e=this.createVertexArray(this.vertexBuffers);this.boundVao!==e&&(this.boundVao=e,t.bindVertexArray(e)),this.vertexBuffers.length=0;var n=this.indexBuffer?this.indexBuffer.impl.bufferId:null;t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n)},i.draw=function(e,t,i){var n,s,r,a,o,h,l,c,u=this.gl,d=this.shader;if(d){var f=d.impl.samplers,p=d.impl.uniforms;i||this.setBuffers();for(var m=0,_=0,g=f.length;_<g;_++)if(s=(n=f[_]).scopeId.value)if(s instanceof wn)r=s,this.setTexture(r,m),n.slot!==m&&(u.uniform1i(n.locationId,m),n.slot=m),m++;else{n.array.length=0,a=s.length;for(var v=0;v<a;v++)r=s[v],this.setTexture(r,m),n.array[v]=m,m++;u.uniform1iv(n.locationId,n.array)}for(var y=0,x=p.length;y<x;y++)h=(o=p[y]).scopeId,l=o.version,c=h.versionObject.version,l.globalId===c.globalId&&l.revision===c.revision||(l.globalId=c.globalId,l.revision=c.revision,null!==h.value&&this.commitFunction[o.dataType](o,h.value));this.webgl2&&this.transformFeedbackBuffer&&(u.bindBufferBase(u.TRANSFORM_FEEDBACK_BUFFER,0,this.transformFeedbackBuffer.impl.bufferId),u.beginTransformFeedback(u.POINTS));var b=this.glPrimitive[e.type],S=e.count;if(e.indexed){var w=this.indexBuffer,T=w.impl.glFormat,A=e.base*w.bytesPerIndex;t>0?u.drawElementsInstanced(b,S,T,A,t):u.drawElements(b,S,T,A)}else{var M=e.base;t>0?u.drawArraysInstanced(b,M,S,t):u.drawArrays(b,M,S)}this.webgl2&&this.transformFeedbackBuffer&&(u.endTransformFeedback(),u.bindBufferBase(u.TRANSFORM_FEEDBACK_BUFFER,0,null)),this._drawCallsPerFrame++}},i.clear=function(e){var t=this.defaultClearOptions,i=void 0===(e=e||t).flags?t.flags:e.flags;if(0!==i){var n=this.gl;if(1&i){var s=void 0===e.color?t.color:e.color;this.setClearColor(s[0],s[1],s[2],s[3]),this.setColorWrite(!0,!0,!0,!0)}if(2&i){var r=void 0===e.depth?t.depth:e.depth;this.setClearDepth(r),this.setDepthWrite(!0)}if(4&i){var a=void 0===e.stencil?t.stencil:e.stencil;this.setClearStencil(a)}n.clear(this.glClearFlag[i])}},i.readPixels=function(e,t,i,n,s){var r=this.gl;r.readPixels(e,t,i,n,r.RGBA,r.UNSIGNED_BYTE,s)},i.setClearDepth=function(e){e!==this.clearDepth&&(this.gl.clearDepth(e),this.clearDepth=e)},i.setClearColor=function(e,t,i,n){var s=this.clearColor;e===s.r&&t===s.g&&i===s.b&&n===s.a||(this.gl.clearColor(e,t,i,n),this.clearColor.set(e,t,i,n))},i.setClearStencil=function(e){e!==this.clearStencil&&(this.gl.clearStencil(e),this.clearStencil=e)},i.getDepthTest=function(){return this.depthTest},i.setDepthTest=function(e){if(this.depthTest!==e){var t=this.gl;e?t.enable(t.DEPTH_TEST):t.disable(t.DEPTH_TEST),this.depthTest=e}},i.setDepthFunc=function(e){this.depthFunc!==e&&(this.gl.depthFunc(this.glComparison[e]),this.depthFunc=e)},i.getDepthWrite=function(){return this.depthWrite},i.setDepthWrite=function(e){this.depthWrite!==e&&(this.gl.depthMask(e),this.depthWrite=e)},i.setColorWrite=function(e,t,i,n){this.writeRed===e&&this.writeGreen===t&&this.writeBlue===i&&this.writeAlpha===n||(this.gl.colorMask(e,t,i,n),this.writeRed=e,this.writeGreen=t,this.writeBlue=i,this.writeAlpha=n)},i.setAlphaToCoverage=function(e){this.webgl2&&this.alphaToCoverage!==e&&(this.alphaToCoverage=e,e?this.gl.enable(this.gl.SAMPLE_ALPHA_TO_COVERAGE):this.gl.disable(this.gl.SAMPLE_ALPHA_TO_COVERAGE))},i.setTransformFeedbackBuffer=function(e){if(this.transformFeedbackBuffer!==e&&(this.transformFeedbackBuffer=e,this.webgl2)){var t=this.gl;e?(this.feedback||(this.feedback=t.createTransformFeedback()),t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,this.feedback)):t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,null)}},i.setRaster=function(e){this.raster!==e&&(this.raster=e,this.webgl2&&(e?this.gl.disable(this.gl.RASTERIZER_DISCARD):this.gl.enable(this.gl.RASTERIZER_DISCARD)))},i.setDepthBias=function(e){this.depthBiasEnabled!==e&&(this.depthBiasEnabled=e,e?this.gl.enable(this.gl.POLYGON_OFFSET_FILL):this.gl.disable(this.gl.POLYGON_OFFSET_FILL))},i.setDepthBiasValues=function(e,t){this.gl.polygonOffset(t,e)},i.getBlending=function(){return this.blending},i.setBlending=function(e){if(this.blending!==e){var t=this.gl;e?t.enable(t.BLEND):t.disable(t.BLEND),this.blending=e}},i.setStencilTest=function(e){if(this.stencil!==e){var t=this.gl;e?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.stencil=e}},i.setStencilFunc=function(e,t,i){this.stencilFuncFront===e&&this.stencilRefFront===t&&this.stencilMaskFront===i&&this.stencilFuncBack===e&&this.stencilRefBack===t&&this.stencilMaskBack===i||(this.gl.stencilFunc(this.glComparison[e],t,i),this.stencilFuncFront=this.stencilFuncBack=e,this.stencilRefFront=this.stencilRefBack=t,this.stencilMaskFront=this.stencilMaskBack=i)},i.setStencilFuncFront=function(e,t,i){if(this.stencilFuncFront!==e||this.stencilRefFront!==t||this.stencilMaskFront!==i){var n=this.gl;n.stencilFuncSeparate(n.FRONT,this.glComparison[e],t,i),this.stencilFuncFront=e,this.stencilRefFront=t,this.stencilMaskFront=i}},i.setStencilFuncBack=function(e,t,i){if(this.stencilFuncBack!==e||this.stencilRefBack!==t||this.stencilMaskBack!==i){var n=this.gl;n.stencilFuncSeparate(n.BACK,this.glComparison[e],t,i),this.stencilFuncBack=e,this.stencilRefBack=t,this.stencilMaskBack=i}},i.setStencilOperation=function(e,t,i,n){this.stencilFailFront===e&&this.stencilZfailFront===t&&this.stencilZpassFront===i&&this.stencilFailBack===e&&this.stencilZfailBack===t&&this.stencilZpassBack===i||(this.gl.stencilOp(this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[i]),this.stencilFailFront=this.stencilFailBack=e,this.stencilZfailFront=this.stencilZfailBack=t,this.stencilZpassFront=this.stencilZpassBack=i),this.stencilWriteMaskFront===n&&this.stencilWriteMaskBack===n||(this.gl.stencilMask(n),this.stencilWriteMaskFront=n,this.stencilWriteMaskBack=n)},i.setStencilOperationFront=function(e,t,i,n){this.stencilFailFront===e&&this.stencilZfailFront===t&&this.stencilZpassFront===i||(this.gl.stencilOpSeparate(this.gl.FRONT,this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[i]),this.stencilFailFront=e,this.stencilZfailFront=t,this.stencilZpassFront=i),this.stencilWriteMaskFront!==n&&(this.gl.stencilMaskSeparate(this.gl.FRONT,n),this.stencilWriteMaskFront=n)},i.setStencilOperationBack=function(e,t,i,n){this.stencilFailBack===e&&this.stencilZfailBack===t&&this.stencilZpassBack===i||(this.gl.stencilOpSeparate(this.gl.BACK,this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[i]),this.stencilFailBack=e,this.stencilZfailBack=t,this.stencilZpassBack=i),this.stencilWriteMaskBack!==n&&(this.gl.stencilMaskSeparate(this.gl.BACK,n),this.stencilWriteMaskBack=n)},i.setBlendFunction=function(e,t){(this.blendSrc!==e||this.blendDst!==t||this.separateAlphaBlend)&&(this.gl.blendFunc(this.glBlendFunction[e],this.glBlendFunction[t]),this.blendSrc=e,this.blendDst=t,this.separateAlphaBlend=!1)},i.setBlendFunctionSeparate=function(e,t,i,n){this.blendSrc===e&&this.blendDst===t&&this.blendSrcAlpha===i&&this.blendDstAlpha===n&&this.separateAlphaBlend||(this.gl.blendFuncSeparate(this.glBlendFunction[e],this.glBlendFunction[t],this.glBlendFunction[i],this.glBlendFunction[n]),this.blendSrc=e,this.blendDst=t,this.blendSrcAlpha=i,this.blendDstAlpha=n,this.separateAlphaBlend=!0)},i.setBlendEquation=function(e){(this.blendEquation!==e||this.separateAlphaEquation)&&(this.gl.blendEquation(this.glBlendEquation[e]),this.blendEquation=e,this.separateAlphaEquation=!1)},i.setBlendEquationSeparate=function(e,t){this.blendEquation===e&&this.blendAlphaEquation===t&&this.separateAlphaEquation||(this.gl.blendEquationSeparate(this.glBlendEquation[e],this.glBlendEquation[t]),this.blendEquation=e,this.blendAlphaEquation=t,this.separateAlphaEquation=!0)},i.setBlendColor=function(e,t,i,n){var s=this.blendColor;e===s.r&&t===s.g&&i===s.b&&n===s.a||(this.gl.blendColor(e,t,i,n),s.set(e,t,i,n))},i.setCullMode=function(e){if(this.cullMode!==e){if(0===e)this.gl.disable(this.gl.CULL_FACE);else{0===this.cullMode&&this.gl.enable(this.gl.CULL_FACE);var t=this.glCull[e];this.cullFace!==t&&(this.gl.cullFace(t),this.cullFace=t)}this.cullMode=e}},i.getCullMode=function(){return this.cullMode},i.setShader=function(e){if(e!==this.shader){if(e.failed)return!1;if(!e.ready&&!e.impl.postLink(this,e))return e.failed=!0,!1;this.shader=e,this.gl.useProgram(e.impl.glProgram),this.attributesInvalidated=!0}return!0},i.getHdrFormat=function(){return this.textureHalfFloatRenderable?ct:this.textureFloatRenderable?dt:7},i.clearShaderCache=function(){var e=this.gl;for(var t in this.fragmentShaderCache)e.deleteShader(this.fragmentShaderCache[t]),delete this.fragmentShaderCache[t];for(var i in this.vertexShaderCache)e.deleteShader(this.vertexShaderCache[i]),delete this.vertexShaderCache[i];this.programLib.clearCache()},i.clearVertexArrayObjectCache=function(){var e=this.gl;this._vaoMap.forEach((function(t,i,n){e.deleteVertexArray(t)})),this._vaoMap.clear()},i.removeShaderFromCache=function(e){this.programLib.removeFromCache(e)},$(t,[{key:"width",get:function(){return this.gl.drawingBufferWidth||this.canvas.width}},{key:"height",get:function(){return this.gl.drawingBufferHeight||this.canvas.height}},{key:"fullscreen",get:function(){return!!document.fullscreenElement},set:function(e){e?this.gl.canvas.requestFullscreen():document.exitFullscreen()}},{key:"textureFloatHighPrecision",get:function(){return void 0===this._textureFloatHighPrecision&&(this._textureFloatHighPrecision=function(e){if(!e.textureFloatRenderable)return!1;var t=on(e,Wi.fullscreenQuadVS,Wi.precisionTestPS,"ptest1"),i=on(e,Wi.fullscreenQuadVS,Wi.precisionTest2PS,"ptest2"),n={format:dt,width:1,height:1,mipmaps:!1,minFilter:0,magFilter:0,name:"testFHP"},s=new wn(e,n),r=new cr({colorBuffer:s,depth:!1});Ei(e,r,t),n.format=7;var a=new wn(e,n),o=new cr({colorBuffer:a,depth:!1});e.constantTexSource.setValue(s),Ei(e,o,i);var h=e.activeFramebuffer;e.setFramebuffer(o.impl._glFrameBuffer);var l=new Uint8Array(4);e.readPixels(0,0,1,1,l),e.setFramebuffer(h);var c=l[0]/255/16777216+l[1]/255/65536+l[2]/255/256+l[3]/255;return s.destroy(),r.destroy(),a.destroy(),o.destroy(),0===c}(this)),this._textureFloatHighPrecision}},{key:"textureHalfFloatUpdatable",get:function(){return void 0===this._textureHalfFloatUpdatable&&(this.webgl2?this._textureHalfFloatUpdatable=!0:this._textureHalfFloatUpdatable=function(e,t){var i=!0,n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE);var s=new Uint16Array(16);return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,2,2,0,e.RGBA,t,s),e.getError()!==e.NO_ERROR&&(i=!1,console.log("Above error related to HALF_FLOAT_OES can be ignored, it was triggered by testing half float texture support")),e.bindTexture(e.TEXTURE_2D,null),e.deleteTexture(n),i}(this.gl,this.extTextureHalfFloat.HALF_FLOAT_OES)),this._textureHalfFloatUpdatable}}]),t}(or),Yr=function(){function e(){this._refCount=0}var t=e.prototype;return t.incRefCount=function(){this._refCount++},t.decRefCount=function(){this._refCount--},$(e,[{key:"refCount",get:function(){return this._refCount}}]),e}();function Kr(){return qr}function Zr(e){qr=e}var $r=0,Qr=function(){function e(){this.initDefaults()}var t=e.prototype;return t.initDefaults=function(){this.recreate=!1,this.verticesUsage=0,this.indicesUsage=0,this.maxVertices=0,this.maxIndices=0,this.vertexCount=0,this.indexCount=0,this.vertexStreamsUpdated=!1,this.indexStreamUpdated=!1,this.vertexStreamDictionary={},this.indices=null},t._changeVertexCount=function(e,t){this.vertexCount||(this.vertexCount=e)},e}();Qr.DEFAULT_COMPONENTS_POSITION=3,Qr.DEFAULT_COMPONENTS_NORMAL=3,Qr.DEFAULT_COMPONENTS_UV=2,Qr.DEFAULT_COMPONENTS_COLORS=4;var Jr=function(e,t,i,n){this.data=e,this.componentCount=t,this.dataType=i,this.dataTypeNormalize=n},ea=function(e){function t(t){var i;return(i=e.call(this)||this).id=$r++,i.device=t||Kr().graphicsDevice,i.vertexBuffer=null,i.indexBuffer=[null],i.primitive=[{type:0,base:0,count:0}],i.skin=null,i._morph=null,i._geometryData=null,i._aabb=new Oe,i.boneAabb=null,i}J(t,e);var i=t.prototype;return i.destroy=function(){var e=this.morph;e&&(this.morph=null,e.refCount<1&&e.destroy()),this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);for(var t=0;t<this.indexBuffer.length;t++)this._destroyIndexBuffer(t);this.indexBuffer.length=0,this._geometryData=null},i._destroyIndexBuffer=function(e){this.indexBuffer[e]&&(this.indexBuffer[e].destroy(),this.indexBuffer[e]=null)},i._initBoneAabbs=function(e){var t,i,n,s,r;this.boneAabb=[],this.boneUsed=[];for(var a,o,h,l=[],c=[],u=this.boneUsed,d=this.skin.boneNames.length,f=0;f<d;f++)l[f]=new ye(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),c[f]=new ye(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(var p=new Pr(this.vertexBuffer),m=p.element.POSITION,_=p.element.BLENDWEIGHT,g=p.element.BLENDINDICES,v=this.vertexBuffer.numVertices,y=0;y<v;y++){for(var x=0;x<4;x++){if(_.array[_.index+x]>0){var b=g.array[g.index+x];if(u[b]=!0,t=m.array[m.index],i=m.array[m.index+1],n=m.array[m.index+2],s=c[b],(r=l[b]).x>t&&(r.x=t),r.y>i&&(r.y=i),r.z>n&&(r.z=n),s.x<t&&(s.x=t),s.y<i&&(s.y=i),s.z<n&&(s.z=n),e){for(var S=a=t,w=o=i,T=h=n,A=0;A<e.length;A++){var M=e[A],C=M.deltaPositions[3*y],E=M.deltaPositions[3*y+1],P=M.deltaPositions[3*y+2];C<0?S+=C:a+=C,E<0?w+=E:o+=E,P<0?T+=P:h+=P}r.x>S&&(r.x=S),r.y>w&&(r.y=w),r.z>T&&(r.z=T),s.x<a&&(s.x=a),s.y<o&&(s.y=o),s.z<h&&(s.z=h)}}}p.next()}var R=this.vertexBuffer.getFormat().elements.find((function(e){return e.name===vt}));if(R&&R.normalize)for(var I=function(){switch(R.dataType){case 0:return function(e){return Math.max(e/127,-1)};case 1:return function(e){return e/255};case 2:return function(e){return Math.max(e/32767,-1)};case 3:return function(e){return e/65535};default:return function(e){return e}}}(),L=0;L<d;L++)if(u[L]){var D=l[L],k=c[L];D.set(I(D.x),I(D.y),I(D.z)),k.set(I(k.x),I(k.y),I(k.z))}for(var O=0;O<d;O++){var F=new Oe;F.setMinMax(l[O],c[O]),this.boneAabb.push(F)}},i._initGeometryData=function(){this._geometryData||(this._geometryData=new Qr,this.vertexBuffer&&(this._geometryData.vertexCount=this.vertexBuffer.numVertices,this._geometryData.maxVertices=this.vertexBuffer.numVertices),this.indexBuffer.length>0&&this.indexBuffer[0]&&(this._geometryData.indexCount=this.indexBuffer[0].numIndices,this._geometryData.maxIndices=this.indexBuffer[0].numIndices))},i.clear=function(e,t,i,n){void 0===i&&(i=0),void 0===n&&(n=0),this._initGeometryData(),this._geometryData.initDefaults(),this._geometryData.recreate=!0,this._geometryData.maxVertices=i,this._geometryData.maxIndices=n,this._geometryData.verticesUsage=e?0:1,this._geometryData.indicesUsage=t?0:1},i.setVertexStream=function(e,t,i,n,s,r){void 0===s&&(s=6),void 0===r&&(r=!1),this._initGeometryData();var a=n||t.length/i;this._geometryData._changeVertexCount(a,e),this._geometryData.vertexStreamsUpdated=!0,this._geometryData.vertexStreamDictionary[e]=new Jr(t,i,s,r)},i.getVertexStream=function(e,t){var i=0,n=!1;if(this._geometryData){var s=this._geometryData.vertexStreamDictionary[e];s&&(n=!0,i=this._geometryData.vertexCount,ArrayBuffer.isView(t)?t.set(s.data):(t.length=0,t.push(s.data)))}n||this.vertexBuffer&&(i=new Pr(this.vertexBuffer).readData(e,t));return i},i.setPositions=function(e,t,i){void 0===t&&(t=Qr.DEFAULT_COMPONENTS_POSITION),this.setVertexStream(vt,e,t,i,6,!1)},i.setNormals=function(e,t,i){void 0===t&&(t=Qr.DEFAULT_COMPONENTS_NORMAL),this.setVertexStream(yt,e,t,i,6,!1)},i.setUvs=function(e,t,i,n){void 0===i&&(i=Qr.DEFAULT_COMPONENTS_UV),this.setVertexStream(Tt+e,t,i,n,6,!1)},i.setColors=function(e,t,i){void 0===t&&(t=Qr.DEFAULT_COMPONENTS_COLORS),this.setVertexStream(wt,e,t,i,6,!1)},i.setColors32=function(e,t){this.setVertexStream(wt,e,Qr.DEFAULT_COMPONENTS_COLORS,t,1,!0)},i.setIndices=function(e,t){this._initGeometryData(),this._geometryData.indexStreamUpdated=!0,this._geometryData.indices=e,this._geometryData.indexCount=t||e.length},i.getPositions=function(e){return this.getVertexStream(vt,e)},i.getNormals=function(e){return this.getVertexStream(yt,e)},i.getUvs=function(e,t){return this.getVertexStream(Tt+e,t)},i.getColors=function(e){return this.getVertexStream(wt,e)},i.getIndices=function(e){var t=0;if(this._geometryData&&this._geometryData.indices){var i=this._geometryData.indices;t=this._geometryData.indexCount,ArrayBuffer.isView(e)?e.set(i):(e.length=0,e.push(i))}else{if(this.indexBuffer.length>0&&this.indexBuffer[0])t=this.indexBuffer[0].readData(e)}return t},i.update=function(e,t){if(void 0===e&&(e=4),void 0===t&&(t=!0),this._geometryData){if(t){var i=this._geometryData.vertexStreamDictionary.POSITION;i&&3===i.componentCount&&this._aabb.compute(i.data,this._geometryData.vertexCount)}var n=this._geometryData.recreate;this._geometryData.vertexCount>this._geometryData.maxVertices&&(n=!0,this._geometryData.maxVertices=this._geometryData.vertexCount),n&&this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);var s=this._geometryData.recreate;this._geometryData.indexCount>this._geometryData.maxIndices&&(s=!0,this._geometryData.maxIndices=this._geometryData.indexCount),s&&this.indexBuffer.length>0&&this.indexBuffer[0]&&(this.indexBuffer[0].destroy(),this.indexBuffer[0]=null),this._geometryData.vertexStreamsUpdated&&this._updateVertexBuffer(),this._geometryData.indexStreamUpdated&&this._updateIndexBuffer(),this.primitive[0].type=e,this.indexBuffer.length>0&&this.indexBuffer[0]?this._geometryData.indexStreamUpdated&&(this.primitive[0].count=this._geometryData.indexCount,this.primitive[0].indexed=!0):this._geometryData.vertexStreamsUpdated&&(this.primitive[0].count=this._geometryData.vertexCount,this.primitive[0].indexed=!1),this._geometryData.vertexCount=0,this._geometryData.indexCount=0,this._geometryData.vertexStreamsUpdated=!1,this._geometryData.indexStreamUpdated=!1,this._geometryData.recreate=!1,this.updateRenderStates()}},i._buildVertexFormat=function(e){var t=[];for(var i in this._geometryData.vertexStreamDictionary){var n=this._geometryData.vertexStreamDictionary[i];t.push({semantic:i,components:n.componentCount,type:n.dataType,normalize:n.dataTypeNormalize})}return new Ti(this.device,t,e)},i._updateVertexBuffer=function(){if(!this.vertexBuffer){var e=this._geometryData.maxVertices,t=this._buildVertexFormat(e);this.vertexBuffer=new Si(this.device,t,e,this._geometryData.verticesUsage)}var i=new Pr(this.vertexBuffer),n=this._geometryData.vertexCount;for(var s in this._geometryData.vertexStreamDictionary){var r=this._geometryData.vertexStreamDictionary[s];i.writeData(s,r.data,n),delete this._geometryData.vertexStreamDictionary[s]}i.end()},i._updateIndexBuffer=function(){if(this.indexBuffer.length<=0||!this.indexBuffer[0]){var e=this._geometryData.maxVertices>65535?2:1;this.indexBuffer[0]=new mr(this.device,e,this._geometryData.maxIndices,this._geometryData.indicesUsage)}var t=this._geometryData.indices;t&&(this.indexBuffer[0].writeData(t,this._geometryData.indexCount),this._geometryData.indices=null)},i.prepareRenderState=function(e){1===e?this.generateWireframe():2===e&&(this.primitive[2]={type:0,base:0,count:this.vertexBuffer?this.vertexBuffer.numVertices:0,indexed:!1})},i.updateRenderStates=function(){this.primitive[2]&&this.prepareRenderState(2),this.primitive[1]&&this.prepareRenderState(1)},i.generateWireframe=function(){this._destroyIndexBuffer(1);var e,t=[];if(this.indexBuffer.length>0&&this.indexBuffer[0]){for(var i=[[0,1],[1,2],[2,0]],n=this.primitive[0].base,s=this.primitive[0].count,r=this.indexBuffer[0],a=new _i[r.format](r.storage),o={},h=n;h<n+s;h+=3)for(var l=0;l<3;l++){var c=a[h+i[l][0]],u=a[h+i[l][1]],d=c>u?u<<16|c:c<<16|u;void 0===o[d]&&(o[d]=0,t.push(c,u))}e=r.format}else{for(var f=0;f<this.vertexBuffer.numVertices;f+=3)t.push(f,f+1,f+1,f+2,f+2,f);e=t.length>65535?2:1}var p=new mr(this.vertexBuffer.device,e,t.length);new _i[p.format](p.storage).set(t),p.unlock(),this.primitive[1]={type:1,base:0,count:t.length,indexed:!0},this.indexBuffer[1]=p},$(t,[{key:"morph",get:function(){return this._morph},set:function(e){e!==this._morph&&(this._morph&&this._morph.decRefCount(),this._morph=e,e&&e.incRefCount())}},{key:"aabb",get:function(){return this._aabb},set:function(e){this._aabb=e}}]),t}(Yr),ta=4/64,ia=.875,na=[];function sa(e,t){for(var i=t.length/3,n=e.length/3,s=new ye,r=new ye,a=new ye,o=new ye,h=new ye,l=new ye,c=[],u=0;u<e.length;u++)c[u]=0;for(var d=0;d<i;d++){var f=t[3*d],p=t[3*d+1],m=t[3*d+2];s.set(e[3*f],e[3*f+1],e[3*f+2]),r.set(e[3*p],e[3*p+1],e[3*p+2]),a.set(e[3*m],e[3*m+1],e[3*m+2]),o.sub2(r,s),h.sub2(a,s),l.cross(o,h).normalize(),c[3*f]+=l.x,c[3*f+1]+=l.y,c[3*f+2]+=l.z,c[3*p]+=l.x,c[3*p+1]+=l.y,c[3*p+2]+=l.z,c[3*m]+=l.x,c[3*m+1]+=l.y,c[3*m+2]+=l.z}for(var _=0;_<n;_++){var g=c[3*_],v=c[3*_+1],y=c[3*_+2],x=1/Math.sqrt(g*g+v*v+y*y);c[3*_]*=x,c[3*_+1]*=x,c[3*_+2]*=x}return c}function ra(e,t,i,n){for(var s=n.length/3,r=e.length/3,a=new ye,o=new ye,h=new ye,l=new be,c=new be,u=new be,d=new ye,f=new ye,p=new Float32Array(3*r),m=new Float32Array(3*r),_=[],g=0;g<s;g++){var v=n[3*g],y=n[3*g+1],x=n[3*g+2];a.set(e[3*v],e[3*v+1],e[3*v+2]),o.set(e[3*y],e[3*y+1],e[3*y+2]),h.set(e[3*x],e[3*x+1],e[3*x+2]),l.set(i[2*v],i[2*v+1]),c.set(i[2*y],i[2*y+1]),u.set(i[2*x],i[2*x+1]);var b=o.x-a.x,S=h.x-a.x,w=o.y-a.y,T=h.y-a.y,A=o.z-a.z,M=h.z-a.z,C=c.x-l.x,E=u.x-l.x,P=c.y-l.y,R=u.y-l.y,I=C*R-E*P;if(0===I)d.set(0,1,0),f.set(1,0,0);else{var L=1/I;d.set((R*b-P*S)*L,(R*w-P*T)*L,(R*A-P*M)*L),f.set((C*S-E*b)*L,(C*T-E*w)*L,(C*M-E*A)*L)}p[3*v+0]+=d.x,p[3*v+1]+=d.y,p[3*v+2]+=d.z,p[3*y+0]+=d.x,p[3*y+1]+=d.y,p[3*y+2]+=d.z,p[3*x+0]+=d.x,p[3*x+1]+=d.y,p[3*x+2]+=d.z,m[3*v+0]+=f.x,m[3*v+1]+=f.y,m[3*v+2]+=f.z,m[3*y+0]+=f.x,m[3*y+1]+=f.y,m[3*y+2]+=f.z,m[3*x+0]+=f.x,m[3*x+1]+=f.y,m[3*x+2]+=f.z}for(var D=new ye,k=new ye,O=new ye,F=new ye,B=0;B<r;B++){O.set(t[3*B],t[3*B+1],t[3*B+2]),D.set(p[3*B],p[3*B+1],p[3*B+2]),k.set(m[3*B],m[3*B+1],m[3*B+2]);var N=O.dot(D);F.copy(O).mulScalar(N),F.sub2(D,F).normalize(),_[4*B]=F.x,_[4*B+1]=F.y,_[4*B+2]=F.z,F.cross(O,D),_[4*B+3]=F.dot(k)<0?-1:1}return _}function aa(e,t,i){var n=new ea(e);return n.setPositions(t),i&&(i.normals&&n.setNormals(i.normals),i.tangents&&n.setVertexStream(xt,i.tangents,4),i.colors&&n.setColors32(i.colors),i.uvs&&n.setUvs(0,i.uvs),i.uvs1&&n.setUvs(1,i.uvs1),i.blendIndices&&n.setVertexStream(St,i.blendIndices,4,i.blendIndices.length/4,1),i.blendWeights&&n.setVertexStream(bt,i.blendWeights,4),i.indices&&n.setIndices(i.indices)),n.update(),n}function oa(e,t){for(var i=t&&void 0!==t.tubeRadius?t.tubeRadius:.2,n=t&&void 0!==t.ringRadius?t.ringRadius:.3,s=t&&void 0!==t.segments?t.segments:30,r=t&&void 0!==t.sides?t.sides:20,a=!(!t||void 0===t.calculateTangents)&&t.calculateTangents,o=[],h=[],l=[],c=[],u=0;u<=r;u++)for(var d=0;d<=s;d++){var f=Math.cos(2*Math.PI*d/s)*(n+i*Math.cos(2*Math.PI*u/r)),p=Math.sin(2*Math.PI*u/r)*i,m=Math.sin(2*Math.PI*d/s)*(n+i*Math.cos(2*Math.PI*u/r)),_=Math.cos(2*Math.PI*d/s)*Math.cos(2*Math.PI*u/r),g=Math.sin(2*Math.PI*u/r),v=Math.sin(2*Math.PI*d/s)*Math.cos(2*Math.PI*u/r),y=u/r,x=1-d/s;if(o.push(f,p,m),h.push(_,g,v),l.push(y,1-x),u<r&&d<s){var b=u*(s+1)+d,S=(u+1)*(s+1)+d,w=u*(s+1)+(d+1),T=(u+1)*(s+1)+(d+1);c.push(b,S,w),c.push(S,T,w)}}var A={normals:h,uvs:l,uvs1:l,indices:c};return a&&(A.tangents=ra(o,h,l,c)),aa(e,o,A)}function ha(e,t,i,n,s,r){var a,o=new ye,h=new ye,l=new ye,c=new ye,u=new ye,d=new ye,f=[],p=[],m=[],_=[],g=[];if(i>0)for(var v=0;v<=n;v++)for(var y=0;y<=s;y++){var x=y/s*2*Math.PI-Math.PI,b=Math.sin(x),S=Math.cos(x);u.set(b*e,-i/2,S*e),c.set(b*t,i/2,S*t),o.lerp(u,c,v/n),h.sub2(c,u).normalize(),d.set(S,0,-b),l.cross(d,h).normalize(),f.push(o.x,o.y,o.z),p.push(l.x,l.y,l.z);var w=y/s,T=v/n;m.push(w,1-T);var A=T;if(T=w,w=(w=A)*ia+ta,T=T*ia+ta,w/=3,_.push(w,1-T),v<n&&y<s){var M=v*(s+1)+y,C=v*(s+1)+(y+1),E=(v+1)*(s+1)+y,P=(v+1)*(s+1)+(y+1);g.push(M,C,E),g.push(C,P,E)}}if(r){for(var R=Math.floor(s/2),I=s,L=i/2,D=0;D<=R;D++)for(var k=D*Math.PI*.5/R,O=Math.sin(k),F=Math.cos(k),B=0;B<=I;B++){var N=2*B*Math.PI/I-Math.PI/2,U=Math.sin(N),z=Math.cos(N)*O,V=F,G=U*O,W=1-B/I,H=1-D/R;f.push(z*t,V*t+L,G*t),p.push(z,V,G),m.push(W,1-H),W=W*ia+ta,H=H*ia+ta,W/=3,H/=3,W+=1/3,_.push(W,1-H)}a=(n+1)*(s+1);for(var X=0;X<R;++X)for(var q=0;q<I;++q){var j=X*(I+1)+q,Y=j+I+1;g.push(a+j+1,a+Y,a+j),g.push(a+j+1,a+Y+1,a+Y)}for(var K=0;K<=R;K++)for(var Z=.5*Math.PI+K*Math.PI*.5/R,$=Math.sin(Z),Q=Math.cos(Z),J=0;J<=I;J++){var ee=2*J*Math.PI/I-Math.PI/2,te=Math.sin(ee),ie=Math.cos(ee)*$,ne=Q,se=te*$,re=1-J/I,ae=1-K/R;f.push(ie*t,ne*t-L,se*t),p.push(ie,ne,se),m.push(re,1-ae),re=re*ia+ta,ae=ae*ia+ta,re/=3,ae/=3,re+=2/3,_.push(re,1-ae)}a=(n+1)*(s+1)+(I+1)*(R+1);for(var oe=0;oe<R;++oe)for(var he=0;he<I;++he){var le=oe*(I+1)+he,ce=le+I+1;g.push(a+le+1,a+ce,a+le),g.push(a+le+1,a+ce+1,a+ce)}}else{if(a=(n+1)*(s+1),e>0)for(var ue=0;ue<s;ue++){var de=ue/s*2*Math.PI,fe=Math.sin(de),pe=-i/2,me=Math.cos(de),_e=1-(fe+1)/2,ge=(me+1)/2;f.push(fe*e,pe,me*e),p.push(0,-1,0),m.push(_e,1-ge),_e=_e*ia+ta,ge=ge*ia+ta,_e/=3,ge/=3,_e+=1/3,_.push(_e,1-ge),ue>1&&g.push(a,a+ue,a+ue-1)}if(a+=s,t>0)for(var ve=0;ve<s;ve++){var xe=ve/s*2*Math.PI,be=Math.sin(xe),Se=i/2,we=Math.cos(xe),Te=1-(be+1)/2,Ae=(we+1)/2;f.push(be*t,Se,we*t),p.push(0,1,0),m.push(Te,1-Ae),Te=Te*ia+ta,Ae=Ae*ia+ta,Te/=3,Ae/=3,Te+=2/3,_.push(Te,1-Ae),ve>1&&g.push(a,a+ve-1,a+ve)}}return{positions:f,normals:p,uvs:m,uvs1:_,indices:g}}function la(e,t){var i=t&&(t.radius||t.baseRadius);i=void 0!==i?i:.5;var n=t&&void 0!==t.height?t.height:1,s=t&&void 0!==t.heightSegments?t.heightSegments:5,r=t&&void 0!==t.capSegments?t.capSegments:20,a=!(!t||void 0===t.calculateTangents)&&t.calculateTangents,o=ha(i,i,n,s,r,!1);return a&&(o.tangents=ra(o.positions,o.normals,o.uvs,o.indices)),aa(e,o.positions,o)}function ca(e,t){var i=t&&void 0!==t.radius?t.radius:.3,n=t&&void 0!==t.height?t.height:1,s=t&&void 0!==t.heightSegments?t.heightSegments:1,r=t&&void 0!==t.sides?t.sides:20,a=!(!t||void 0===t.calculateTangents)&&t.calculateTangents,o=ha(i,i,n-2*i,s,r,!0);return a&&(o.tangents=ra(o.positions,o.normals,o.uvs,o.indices)),aa(e,o.positions,o)}function ua(e,t){var i=t&&void 0!==t.baseRadius?t.baseRadius:.5,n=t&&void 0!==t.peakRadius?t.peakRadius:0,s=t&&void 0!==t.height?t.height:1,r=t&&void 0!==t.heightSegments?t.heightSegments:5,a=t&&void 0!==t.capSegments?t.capSegments:18,o=!(!t||void 0===t.calculateTangents)&&t.calculateTangents,h=ha(i,n,s,r,a,!1);return o&&(h.tangents=ra(h.positions,h.normals,h.uvs,h.indices)),aa(e,h.positions,h)}function da(e,t){for(var i=t&&void 0!==t.radius?t.radius:.5,n=t&&void 0!==t.latitudeBands?t.latitudeBands:16,s=t&&void 0!==t.longitudeBands?t.longitudeBands:16,r=!(!t||void 0===t.calculateTangents)&&t.calculateTangents,a=[],o=[],h=[],l=[],c=0;c<=n;c++)for(var u=c*Math.PI/n,d=Math.sin(u),f=Math.cos(u),p=0;p<=s;p++){var m=2*p*Math.PI/s-Math.PI/2,_=Math.sin(m),g=Math.cos(m)*d,v=f,y=_*d,x=1-p/s,b=1-c/n;a.push(g*i,v*i,y*i),o.push(g,v,y),h.push(x,1-b)}for(var S=0;S<n;++S)for(var w=0;w<s;++w){var T=S*(s+1)+w,A=T+s+1;l.push(T+1,A,T),l.push(T+1,A+1,A)}var M={normals:o,uvs:h,uvs1:h,indices:l};return r&&(M.tangents=ra(a,o,h,l)),aa(e,a,M)}function fa(e,t){for(var i=t&&void 0!==t.halfExtents?t.halfExtents:new be(.5,.5),n=t&&void 0!==t.widthSegments?t.widthSegments:5,s=t&&void 0!==t.lengthSegments?t.lengthSegments:5,r=!(!t||void 0===t.calculateTangents)&&t.calculateTangents,a=[],o=[],h=[],l=[],c=0,u=0;u<=n;u++)for(var d=0;d<=s;d++){var f=-i.x+2*i.x*u/n,p=-(-i.y+2*i.y*d/s),m=u/n,_=d/s;a.push(f,0,p),o.push(0,1,0),h.push(m,1-_),u<n&&d<s&&(l.push(c+s+1,c+1,c),l.push(c+s+1,c+s+2,c+1)),c++}var g={normals:o,uvs:h,uvs1:h,indices:l};return r&&(g.tangents=ra(a,o,h,l)),aa(e,a,g)}function pa(e,t){var i=t&&void 0!==t.halfExtents?t.halfExtents:new ye(.5,.5,.5),n=t&&void 0!==t.widthSegments?t.widthSegments:1,s=t&&void 0!==t.lengthSegments?t.lengthSegments:1,r=t&&void 0!==t.heightSegments?t.heightSegments:1,a=!(!t||void 0===t.calculateTangents)&&t.calculateTangents,o=[new ye(-i.x,-i.y,i.z),new ye(i.x,-i.y,i.z),new ye(i.x,i.y,i.z),new ye(-i.x,i.y,i.z),new ye(i.x,-i.y,-i.z),new ye(-i.x,-i.y,-i.z),new ye(-i.x,i.y,-i.z),new ye(i.x,i.y,-i.z)],h=[[0,1,3],[4,5,7],[3,2,6],[1,0,4],[1,4,2],[5,0,6]],l=[[0,0,1],[0,0,-1],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0]],c=1,u=2,d=3,f=4,p=5,m=[],_=[],g=[],v=[],y=[],x=0,b=function(e,t,i){for(var n=new ye,s=new ye,r=new ye,a=new ye,c=0;c<=t;c++)for(var u=0;u<=i;u++){n.lerp(o[h[e][0]],o[h[e][1]],c/t),s.lerp(o[h[e][0]],o[h[e][2]],u/i),r.sub2(s,o[h[e][0]]),a.add2(n,r);var d=c/t,f=u/i;m.push(a.x,a.y,a.z),_.push(l[e][0],l[e][1],l[e][2]),g.push(d,1-f),d=d*ia+ta,f=f*ia+ta,d/=3,f/=3,d+=e%3/3,f+=Math.floor(e/3)/3,v.push(d,1-f),c<t&&u<i&&(y.push(x+i+1,x+1,x),y.push(x+i+1,x+i+2,x+1)),x++}};b(0,n,r),b(c,n,r),b(u,n,s),b(d,n,s),b(f,s,r),b(p,s,r);var S={normals:_,uvs:g,uvs1:v,indices:y};return a&&(S.tangents=ra(m,_,g,y)),aa(e,m,S)}function ma(e,t){for(var i=null,n=0;n<na.length;n++)na[n].type===t&&na[n].device===e&&(i=na[n].primData);if(!i){var s,r;switch(t){case"box":s=pa(e,{halfExtents:new ye(.5,.5,.5)}),r={x:2,y:2,z:2,uv:2/3};break;case"capsule":s=ca(e,{radius:.5,height:2}),r={x:2*Math.PI,y:Math.PI,z:2*Math.PI,uv:1/3+1/3/3*2};break;case"cone":s=ua(e,{baseRadius:.5,peakRadius:0,height:1}),r={x:2.54,y:2.54,z:2.54,uv:1/3+1/3/3};break;case"cylinder":s=la(e,{radius:.5,height:1}),r={x:Math.PI,y:1.58,z:Math.PI,uv:1/3+1/3/3*2};break;case"plane":s=fa(e,{halfExtents:new be(.5,.5),widthSegments:1,lengthSegments:1}),r={x:0,y:1,z:0,uv:1};break;case"sphere":s=da(e,{radius:.5}),r={x:Math.PI,y:Math.PI,z:Math.PI,uv:1};break;case"torus":s=oa(e,{tubeRadius:.2,ringRadius:.3}),r={x:.5*Math.PI*.5-.1*Math.PI*.1,y:.4,z:.4,uv:1};break;default:throw new Error("Invalid primitive type: "+t)}s.incRefCount(),i={mesh:s,area:r},na.push({type:t,device:e,primData:i})}return i}var _a={generateKey:function(e){var t="basic";return e.fog&&(t+="_fog"),e.alphaTest&&(t+="_atst"),e.vertexColors&&(t+="_vcol"),e.diffuseMap&&(t+="_diff"),e.skin&&(t+="_skin"),e.screenSpace&&(t+="_ss"),e.useInstancing&&(t+="_inst"),e.useMorphPosition&&(t+="_morphp"),e.useMorphNormal&&(t+="_morphn"),e.useMorphTextureBased&&(t+="_morpht"),t+="_"+e.pass},createShaderDefinition:function(e,t){var i={vertex_position:vt};t.skin&&(i.vertex_boneWeights=bt,i.vertex_boneIndices=St),t.vertexColors&&(i.vertex_color=wt),t.diffuseMap&&(i.vertex_texCoord0=At);var n=Qi(e,"BasicShader",t.pass);n+=Wi.transformDeclVS,t.skin?(n+=Yi(e),n+=Wi.transformSkinnedVS):n+=Wi.transformVS,t.vertexColors&&(n+="attribute vec4 vertex_color;\n",n+="varying vec4 vColor;\n"),t.diffuseMap&&(n+="attribute vec2 vertex_texCoord0;\n",n+="varying vec2 vUv0;\n"),2===t.pass&&(n+="varying float vDepth;\n",n+="#ifndef VIEWMATRIX\n",n+="#define VIEWMATRIX\n",n+="uniform mat4 matrix_view;\n",n+="#endif\n",n+="#ifndef CAMERAPLANES\n",n+="#define CAMERAPLANES\n",n+="uniform vec4 camera_params;\n\n",n+="#endif\n"),n+="void main(void)\n{\n",n+=" gl_Position = getPosition();\n",2===t.pass&&(n+=" vDepth = -(matrix_view * vec4(getWorldPosition(),1.0)).z * camera_params.x;\n"),t.vertexColors&&(n+=" vColor = vertex_color;\n"),t.diffuseMap&&(n+=" vUv0 = vertex_texCoord0;\n");var s=n+="}\n";return n=Ji(e,"BasicMaterial",t.pass),t.vertexColors?n+="varying vec4 vColor;\n":n+="uniform vec4 uColor;\n",t.diffuseMap&&(n+="varying vec2 vUv0;\n",n+="uniform sampler2D texture_diffuseMap;\n"),t.fog&&(n+=ji(t.fog)),t.alphaTest&&(n+=Wi.alphaTestPS),2===t.pass&&(n+="varying float vDepth;\n",n+=Wi.packDepthPS),n+="void main(void)\n{\n",t.vertexColors?n+=" gl_FragColor = vColor;\n":n+=" gl_FragColor = uColor;\n",t.diffuseMap&&(n+=" gl_FragColor *= texture2D(texture_diffuseMap, vUv0);\n"),t.alphaTest&&(n+=" alphaTest(gl_FragColor.a);\n"),3!==t.pass&&(2===t.pass?n+=" gl_FragColor = packFloat(vDepth);\n":t.fog&&(n+=" glFragColor.rgb = addFog(gl_FragColor.rgb);\n")),{attributes:i,vshader:s,fshader:n+="}\n"}}},ga=function(e){function t(){var t;return(t=e.call(this)||this).color=new me(1,1,1,1),t.colorUniform=new Float32Array(4),t.colorMap=null,t.vertexColors=!1,t}J(t,e);var i=t.prototype;return i.copy=function(t){return e.prototype.copy.call(this,t),this.color.copy(t.color),this.colorMap=t.colorMap,this.vertexColors=t.vertexColors,this},i.updateUniforms=function(e,t){this.clearParameters(),this.colorUniform[0]=this.color.r,this.colorUniform[1]=this.color.g,this.colorUniform[2]=this.color.b,this.colorUniform[3]=this.color.a,this.setParameter("uColor",this.colorUniform),this.colorMap&&this.setParameter("texture_diffuseMap",this.colorMap)},i.getShaderVariant=function(e,t,i,n,s,r,a,o){if(this.updateShader)return this.updateShader(e,t,i,n,s,r),this.shader;var h={skin:i&&0!=(2&i),screenSpace:i&&0!=(i&We),useInstancing:i&&0!=(32&i),useMorphPosition:i&&0!=(i&He),useMorphNormal:i&&0!=(i&Xe),useMorphTextureBased:i&&0!=(i&qe),alphaTest:this.alphaTest>0,vertexColors:this.vertexColors,diffuseMap:!!this.colorMap,pass:s},l=new Os(a,o),c=e.getProgramLibrary();return c.register("basic",_a),c.getProgram("basic",h,l)},t}(Bs),va=function(){function e(e,t,i){this.origMeshInstances=e,this._aabb=new Oe,this.meshInstance=null,this.dynamic=t,this.batchGroupId=i}var t=e.prototype;return t.destroy=function(e,t){this.meshInstance&&(this.removeFromLayers(e,t),this.meshInstance.destroy())},t.addToLayers=function(e,t){for(var i=0;i<t.length;i++){var n=e.layers.getLayerById(t[i]);n&&n.addMeshInstances([this.meshInstance])}},t.removeFromLayers=function(e,t){for(var i=0;i<t.length;i++){var n=e.layers.getLayerById(t[i]);n&&n.removeMeshInstances([this.meshInstance])}},t.updateBoundingBox=function(){this._aabb.copy(this.origMeshInstances[0].aabb);for(var e=1;e<this.origMeshInstances.length;e++)this._aabb.add(this.origMeshInstances[e].aabb);this.meshInstance.aabb=this._aabb,this.meshInstance._aabbVer=0},e}(),ya=function(e,t,i,n,s){void 0===s&&(s=[0]),this.dynamic=i,this.maxAabbSize=n,this.id=e,this.name=t,this.layers=s,this._ui=!1,this._sprite=!1,this._obj={model:[],element:[],sprite:[],render:[]}};ya.MODEL="model",ya.ELEMENT="element",ya.SPRITE="sprite",ya.RENDER="render";var xa=new Ee,ba=function(){function e(e){this.bones=void 0,this._dirty=!0,this._rootBone=null,this._skinUpdateIndex=-1,this._updateBeforeCull=!0,e&&this.initSkin(e)}var t=e.prototype;return t.init=function(e,t){if(e.supportsBoneTextures){var i=3*t,n=Math.ceil(Math.sqrt(i));n=de.roundUp(n,3);var s=Math.ceil(i/n);this.boneTexture=new wn(e,{width:n,height:s,format:dt,mipmaps:!1,minFilter:0,magFilter:0,name:"skin"}),this.matrixPalette=this.boneTexture.lock()}else this.matrixPalette=new Float32Array(12*t)},t.destroy=function(){this.boneTexture&&(this.boneTexture.destroy(),this.boneTexture=null)},t.resolve=function(e,t){this.rootBone=e;for(var i=this.skin,n=[],s=0;s<i.boneNames.length;s++){var r=i.boneNames[s],a=e.findByName(r);a||(a=t),n.push(a)}this.bones=n},t.initSkin=function(e){this.skin=e,this.bones=[];var t=e.inverseBindPose.length;this.init(e.device,t),this.matrices=[];for(var i=0;i<t;i++)this.matrices[i]=new Ee},t.uploadBones=function(e){e.supportsBoneTextures&&(this.boneTexture.lock(),this.boneTexture.unlock())},t._updateMatrices=function(e,t){if(this._skinUpdateIndex!==t){this._skinUpdateIndex=t,xa.copy(e.getWorldTransform()).invert();for(var i=this.bones.length-1;i>=0;i--)this.matrices[i].mulAffine2(xa,this.bones[i].getWorldTransform()),this.matrices[i].mulAffine2(this.matrices[i],this.skin.inverseBindPose[i])}},t.updateMatrices=function(e,t){this._updateBeforeCull&&this._updateMatrices(e,t)},t.updateMatrixPalette=function(e,t){this._updateMatrices(e,t);for(var i=this.matrixPalette,n=this.bones.length,s=0;s<n;s++){var r=this.matrices[s].data,a=12*s;i[a]=r[0],i[a+1]=r[4],i[a+2]=r[8],i[a+3]=r[12],i[a+4]=r[1],i[a+5]=r[5],i[a+6]=r[9],i[a+7]=r[13],i[a+8]=r[2],i[a+9]=r[6],i[a+10]=r[10],i[a+11]=r[14]}this.uploadBones(this.skin.device)},$(e,[{key:"rootBone",get:function(){return this._rootBone},set:function(e){this._rootBone=e}}]),e}(),Sa=function(e){function t(t,i,n){var s;s=e.call(this)||this;var r=i.length;return s.init(t,r),s.device=t,s.rootNode=n,s.bones=i,s}J(t,e);var i=t.prototype;return i.updateMatrices=function(e,t){},i.updateMatrixPalette=function(e,t){for(var i=this.matrixPalette,n=this.bones.length,s=0;s<n;s++){var r=this.bones[s].getWorldTransform().data,a=12*s;i[a]=r[0],i[a+1]=r[4],i[a+2]=r[8],i[a+3]=r[12],i[a+4]=r[1],i[a+5]=r[5],i[a+6]=r[9],i[a+7]=r[13],i[a+8]=r[2],i[a+9]=r[6],i[a+10]=r[10],i[a+11]=r[14]}this.uploadBones(this.device)},t}(ba),wa=function(){function e(e,t,i){this.device=e,this.format=t,this.dirty=!0,this.impl=e.createBindGroupImpl(this),this.textures=[],this.uniformBuffers=[],this.defaultUniformBuffer=i,i&&this.setUniformBuffer(ui,i)}var t=e.prototype;return t.destroy=function(){this.impl.destroy(),this.impl=null,this.format=null,this.defaultUniformBuffer=null},t.setUniformBuffer=function(e,t){var i=this.format.bufferFormatsMap.get(e);this.uniformBuffers[i]!==t&&(this.uniformBuffers[i]=t,this.dirty=!0)},t.setTexture=function(e,t){var i=this.format.textureFormatsMap.get(e);this.textures[i]!==t&&(this.textures[i]=t,this.dirty=!0)},t.update=function(){for(var e=this.format.textureFormats,t=0;t<e.length;t++){var i=e[t],n=i.scopeId.value;this.setTexture(i.name,n)}this.dirty&&(this.dirty=!1,this.impl.update(this))},e}(),Ta=[];Ta[2]=function(e,t,i){e.storageFloat32[i]=t},Ta[3]=function(e,t,i){var n=e.storageFloat32;n[i]=t[0],n[i+1]=t[1]},Ta[4]=function(e,t,i){var n=e.storageFloat32;n[i]=t[0],n[i+1]=t[1],n[i+2]=t[2]},Ta[5]=function(e,t,i){var n=e.storageFloat32;n[i]=t[0],n[i+1]=t[1],n[i+2]=t[2],n[i+3]=t[3]},Ta[1]=function(e,t,i){e.storageInt32[i]=t},Ta[6]=function(e,t,i){var n=e.storageInt32;n[i]=t[0],n[i+1]=t[1]},Ta[7]=function(e,t,i){var n=e.storageInt32;n[i]=t[0],n[i+1]=t[1],n[i+2]=t[2]},Ta[8]=function(e,t,i){var n=e.storageInt32;n[i]=t[0],n[i+1]=t[1],n[i+2]=t[2],n[i+3]=t[3]},Ta[12]=function(e,t,i){var n=e.storageFloat32;n[i]=t[0],n[i+1]=t[1],n[i+4]=t[2],n[i+5]=t[3],n[i+8]=t[4],n[i+9]=t[5]},Ta[13]=function(e,t,i){var n=e.storageFloat32;n[i]=t[0],n[i+1]=t[1],n[i+2]=t[2],n[i+4]=t[3],n[i+5]=t[4],n[i+6]=t[5],n[i+8]=t[6],n[i+9]=t[7],n[i+10]=t[8]};var Aa=function(){function e(e,t){this.device=e,this.format=t,this.impl=e.createUniformBufferImpl(this),this.storage=new ArrayBuffer(t.byteSize),this.storageFloat32=new Float32Array(this.storage),this.storageInt32=new Int32Array(this.storage),e._vram.ub+=this.format.byteSize}var t=e.prototype;return t.destroy=function(){var e=this.device;this.impl.destroy(e),e._vram.ub-=this.format.byteSize},t.loseContext=function(){this.impl.loseContext()},t.setUniform=function(e){var t=e.offset,i=e.scopeId.value;if(null!=i){var n=Ta[e.type];n?n(this,i,t):this.storageFloat32.set(i,t)}},t.set=function(e){var t=this.format.map.get(e);t&&this.setUniform(t)},t.update=function(){for(var e=this.format.uniforms,t=0;t<e.length;t++)this.setUniform(e[t]);this.impl.unlock(this)},e}(),Ma=function(){function e(){this.cache=new Map}var t=e.prototype;return t.destroy=function(){this.cache.forEach((function(e,t){t.destroy()})),this.cache.clear()},t.incRef=function(e){var t=(this.cache.get(e)||0)+1;this.cache.set(e,t)},t.decRef=function(e){if(e){var t=this.cache.get(e);t&&(0===--t?(this.cache.delete(e),e.destroy()):this.cache.set(e,t))}},e}(),Ca=function(){function e(){}return e.incRef=function(e){this.cache.incRef(e)},e.decRef=function(e){this.cache.decRef(e)},e.destroy=function(){this.cache.destroy()},e}();Ca.cache=new Ma;var Ea=new Oe,Pa=new Oe,Ra=new Ne,Ia=new Set,La=function(e){this.vertexBuffer=null,this.count=e},Da=function(){function e(e,t,i){this._key=[],this._key[0]=Oa(e,t,!0,0),this.command=i}return $(e,[{key:"key",get:function(){return this._key[0]},set:function(e){this._key[0]=e}}]),e}(),ka=function(){function e(e,t,i){if(void 0===i&&(i=null),this._material=void 0,this._shader=[],this._bindGroups=[],e instanceof Hn){var n=e;e=t,t=i,i=n}this._key=[0,0],this.isStatic=!1,this._staticLightList=null,this._staticSource=null,this.node=i,this._mesh=e,e.incRefCount(),this.material=t,this._shaderDefs=65536,this._shaderDefs|=e.vertexBuffer.format.hasUv0?4:0,this._shaderDefs|=e.vertexBuffer.format.hasUv1?8:0,this._shaderDefs|=e.vertexBuffer.format.hasColor?16:0,this._shaderDefs|=e.vertexBuffer.format.hasTangents?512:0,this._lightHash=0,this.visible=!0,this.layer=15,this._renderStyle=0,this.castShadow=!1,this._receiveShadow=!0,this._screenSpace=!1,this._noDepthDrawGl1=!1,this.cull=!0,this.pick=!0,this._updateAabb=!0,this._updateAabbFunc=null,this._calculateSortDistance=null,this.updateKey(),this._skinInstance=null,this._morphInstance=null,this.instancingData=null,this._customAabb=null,this.aabb=new Oe,this._aabbVer=-1,this.drawOrder=0,this.visibleThisFrame=!1,this.isVisibleFunc=null,this.parameters={},this.stencilFront=null,this.stencilBack=null,this.flipFaces=!1}var t=e.prototype;return t.clearShaders=function(){for(var e=this._shader,t=0;t<e.length;t++)e[t]=null;this.destroyBindGroups()},t.destroyBindGroups=function(){for(var e=this._bindGroups,t=0;t<e.length;t++){var i=e[t];if(i){var n=i.defaultUniformBuffer;n&&n.destroy(),i.destroy()}}e.length=0},t.getBindGroup=function(e,t){var i=this._bindGroups[t];if(!i){var n=this._shader[t],s=n.meshUniformBufferFormat,r=new Aa(e,s),a=n.meshBindGroupFormat;i=new wa(e,a,r),this._bindGroups[t]=i}return i},t.destroy=function(){var t,i,n=this.mesh;n&&(this.mesh=null,n.refCount<1&&n.destroy()),this.setRealtimeLightmap(e.lightmapParamNames[0],null),this.setRealtimeLightmap(e.lightmapParamNames[1],null),null==(t=this._skinInstance)||t.destroy(),this._skinInstance=null,null==(i=this.morphInstance)||i.destroy(),this.morphInstance=null,this.clearShaders(),this.material=null},e._prepareRenderStyleForArray=function(e,t){if(e){for(var i=0;i<e.length;i++){e[i]._renderStyle=t;var n=e[i].mesh;Ia.has(n)||(Ia.add(n),n.prepareRenderState(t))}Ia.clear()}},t._isVisible=function(e){return!!this.visible&&(this.isVisibleFunc?this.isVisibleFunc(e):(Ra.center=this.aabb.center,Ra.radius=this._aabb.halfExtents.length(),e.frustum.containsSphere(Ra)))},t.updateKey=function(){var e=this.material;this._key[0]=Oa(this.layer,e.alphaToCoverage||e.alphaTest?2:e.blendType,!1,e.id)},t.setInstancing=function(e){e?(this.instancingData=new La(e.numVertices),this.instancingData.vertexBuffer=e,e.instancing=!0,this.cull=!1):(this.instancingData=null,this.cull=!0)},t.updatePassShader=function(e,t,i,n,s,r){this._shader[t]=this.material.getShaderVariant(this.mesh.device,e,this._shaderDefs,i,t,n,s,r)},t.ensureMaterial=function(e){this.material||(this.material=ks(e))},t.clearParameters=function(){this.parameters={}},t.getParameters=function(){return this.parameters},t.getParameter=function(e){return this.parameters[e]},t.setParameter=function(e,t,i){if(void 0===i&&(i=-262141),void 0===t&&"object"==typeof e){var n=e;if(n.length){for(var s=0;s<n.length;s++)this.setParameter(n[s]);return}e=n.name,t=n.value}var r=this.parameters[e];r?(r.data=t,r.passFlags=i):this.parameters[e]={scopeId:null,data:t,passFlags:i}},t.setRealtimeLightmap=function(e,t){var i=this.getParameter(e);i!==t&&(i&&Ca.decRef(i.data),t?(Ca.incRef(t),this.setParameter(e,t)):this.deleteParameter(e))},t.deleteParameter=function(e){this.parameters[e]&&delete this.parameters[e]},t.setParameters=function(e,t){var i=this.parameters;for(var n in i){var s=i[n];s.passFlags&t&&(s.scopeId||(s.scopeId=e.scope.resolve(n)),s.scopeId.setValue(s.data))}},t.setLightmapped=function(t){t?this.mask=-6&(2|this.mask):(this.setRealtimeLightmap(e.lightmapParamNames[0],null),this.setRealtimeLightmap(e.lightmapParamNames[1],null),this._shaderDefs&=-8385,this.mask=-7&(1|this.mask))},t.setCustomAabb=function(e){e?this._customAabb?this._customAabb.copy(e):this._customAabb=e.clone():(this._customAabb=null,this._aabbVer=-1),this._setupSkinUpdate()},t._setupSkinUpdate=function(){this._skinInstance&&(this._skinInstance._updateBeforeCull=!this._customAabb)},$(e,[{key:"renderStyle",get:function(){return this._renderStyle},set:function(e){this._renderStyle=e,this.mesh.prepareRenderState(e)}},{key:"mesh",get:function(){return this._mesh},set:function(e){e!==this._mesh&&(this._mesh&&this._mesh.decRefCount(),this._mesh=e,e&&e.incRefCount())}},{key:"aabb",get:function(){if(!this._updateAabb)return this._aabb;if(this._updateAabbFunc)return this._updateAabbFunc(this._aabb);var e=this._customAabb,t=!!e;if(!e)if(e=Ea,this.skinInstance){if(!this.mesh.boneAabb){var i=this._morphInstance?this._morphInstance.morph._targets:null;this.mesh._initBoneAabbs(i)}for(var n=this.mesh.boneUsed,s=!0,r=0;r<this.mesh.boneAabb.length;r++)n[r]&&(Pa.setFromTransformedAabb(this.mesh.boneAabb[r],this.skinInstance.matrices[r]),s?(s=!1,e.center.copy(Pa.center),e.halfExtents.copy(Pa.halfExtents)):e.add(Pa));t=!0}else this.node._aabbVer!==this._aabbVer&&(this.mesh?(e.center.copy(this.mesh.aabb.center),e.halfExtents.copy(this.mesh.aabb.halfExtents)):(e.center.set(0,0,0),e.halfExtents.set(0,0,0)),this.mesh&&this.mesh.morph&&e._expand(this.mesh.morph.aabb.getMin(),this.mesh.morph.aabb.getMax()),t=!0,this._aabbVer=this.node._aabbVer);return t&&this._aabb.setFromTransformedAabb(e,this.node.getWorldTransform()),this._aabb},set:function(e){this._aabb=e}},{key:"material",get:function(){return this._material},set:function(e){this.clearShaders();var t=this._material;if(t&&t.removeMeshInstanceRef(this),this._material=e,e){e.addMeshInstanceRef(this),this.updateKey();var i=t&&t.transparent;if(e.transparent!==i){var n=this._material._scene||(null==t?void 0:t._scene);n?n.layers._dirtyBlend=!0:e._dirtyBlend=!0}}}},{key:"layer",get:function(){return this._layer},set:function(e){this._layer=e,this.updateKey()}},{key:"calculateSortDistance",get:function(){return this._calculateSortDistance},set:function(e){this._calculateSortDistance=e}},{key:"receiveShadow",get:function(){return this._receiveShadow},set:function(e){this._receiveShadow=e,this._shaderDefs=e?-2&this._shaderDefs:1|this._shaderDefs,this._shader[0]=null,this._shader[1]=null}},{key:"skinInstance",get:function(){return this._skinInstance},set:function(e){this._skinInstance=e;var t=this._shaderDefs;(t=e?2|t:-3&t)!==this._shaderDefs&&(this._shaderDefs=t,this.clearShaders()),this._setupSkinUpdate()}},{key:"morphInstance",get:function(){return this._morphInstance},set:function(e){var t;null==(t=this._morphInstance)||t.destroy(),this._morphInstance=e;var i=this._shaderDefs;i=e&&e.morph.useTextureMorph?i|qe:-4097&i,i=e&&e.morph.morphPositions?i|He:-1025&i,(i=e&&e.morph.morphNormals?i|Xe:-2049&i)!==this._shaderDefs&&(this._shaderDefs=i,this.clearShaders())}},{key:"screenSpace",get:function(){return this._screenSpace},set:function(e){this._screenSpace=e,this._shaderDefs=e?this._shaderDefs|We:-257&this._shaderDefs,this._shader[0]=null}},{key:"key",get:function(){return this._key[0]},set:function(e){this._key[0]=e}},{key:"mask",get:function(){return this._shaderDefs>>16},set:function(e){var t=65535&this._shaderDefs;this._shaderDefs=t|e<<16,this._shader[0]=null,this._shader[1]=null}},{key:"instancingCount",get:function(){return this.instancingData?this.instancingData.count:0},set:function(e){this.instancingData&&(this.instancingData.count=e)}}]),e}();function Oa(e,t,i,n){return(15&e)<<27|(3===t?1:0)<<26|(i?1:0)<<25|(33554431&n)<<0}function Fa(e,t){if(e&&!t)return!1;if(!e&&t)return!1;if((e=e.data)===(t=t.data))return!0;if(e instanceof Float32Array&&t instanceof Float32Array){if(e.length!==t.length)return!1;for(var i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}return!1}function Ba(e,t){for(var i in e)if(e.hasOwnProperty(i)&&!Fa(e[i],t[i]))return!1;for(var n in t)if(t.hasOwnProperty(n)&&!Fa(t[n],e[n]))return!1;return!0}function Na(e,t){for(var i=0;i<e.length;i++)if(t.indexOf(e[i])<0)return!1;for(var n=0;n<t.length;n++)if(e.indexOf(t[n])<0)return!1;return!0}ka.lightmapParamNames=["texture_lightMap","texture_dirLightMap"];var Ua=new xe,za=new ye,Va=new ye,Ga=new ye;function Wa(e){var t=e.node.worldTransform;return t.getX(za),t.getY(Va),t.getZ(Ga),za.cross(za,Va),za.dot(Ga)>=0?1:-1}var Ha=function(){function e(e,t,i){this.device=e,this.rootNode=t,this.scene=i,this._init=!1,this._batchGroups={},this._batchGroupCounter=0,this._batchList=[],this._dirtyGroups=[]}var t=e.prototype;return t.destroy=function(){this.device=null,this.rootNode=null,this.scene=null,this._batchGroups={},this._batchList=[],this._dirtyGroups=[]},t.addGroup=function(e,t,i,n,s){if(void 0===n&&(n=this._batchGroupCounter,this._batchGroupCounter++),!this._batchGroups[n]){var r=new ya(n,e,t,i,s);return this._batchGroups[n]=r,r}},t.removeGroup=function(e){if(this._batchGroups[e]){for(var t=[],i=0;i<this._batchList.length;i++)this._batchList[i].batchGroupId===e?this.destroyBatch(this._batchList[i]):t.push(this._batchList[i]);this._batchList=t,this._removeModelsFromBatchGroup(this.rootNode,e),delete this._batchGroups[e]}},t.markGroupDirty=function(e){this._dirtyGroups.indexOf(e)<0&&this._dirtyGroups.push(e)},t.getGroupByName=function(e){var t=this._batchGroups;for(var i in t)if(t.hasOwnProperty(i)&&t[i].name===e)return t[i];return null},t.getBatches=function(e){for(var t=[],i=this._batchList.length,n=0;n<i;n++){var s=this._batchList[n];s.batchGroupId===e&&t.push(s)}return t},t._removeModelsFromBatchGroup=function(e,t){if(e.enabled){e.model&&e.model.batchGroupId===t&&(e.model.batchGroupId=-1),e.render&&e.render.batchGroupId===t&&(e.render.batchGroupId=-1),e.element&&e.element.batchGroupId===t&&(e.element.batchGroupId=-1),e.sprite&&e.sprite.batchGroupId===t&&(e.sprite.batchGroupId=-1);for(var i=0;i<e._children.length;i++)this._removeModelsFromBatchGroup(e._children[i],t)}},t.insert=function(e,t,i){var n=this._batchGroups[t];n&&n._obj[e].indexOf(i)<0&&(n._obj[e].push(i),this.markGroupDirty(t))},t.remove=function(e,t,i){var n=this._batchGroups[t];if(n){var s=n._obj[e].indexOf(i);s>=0&&(n._obj[e].splice(s,1),this.markGroupDirty(t))}},t._extractRender=function(e,t,i,n){if(e.render){if(e.render.isStatic){for(var s=this.scene.drawCalls,r=e.render.meshInstances,a=0;a<s.length;a++)s[a]._staticSource&&(r.indexOf(s[a]._staticSource)<0||t.push(s[a]));for(var o=0;o<r.length;o++)s.indexOf(r[o])>=0&&t.push(r[o])}else t=n[e.render.batchGroupId]=t.concat(e.render.meshInstances);e.render.removeFromLayers()}return t},t._extractModel=function(e,t,i,n){if(e.model&&e.model.model){if(e.model.isStatic){for(var s=this.scene.drawCalls,r=e.model.meshInstances,a=0;a<s.length;a++)s[a]._staticSource&&(r.indexOf(s[a]._staticSource)<0||t.push(s[a]));for(var o=0;o<r.length;o++)s.indexOf(r[o])>=0&&t.push(r[o])}else t=n[e.model.batchGroupId]=t.concat(e.model.meshInstances);e.model.removeModelFromLayers()}return t},t._extractElement=function(e,t,i){if(e.element){var n=!1;e.element._text&&e.element._text._model.meshInstances.length>0?(t.push(e.element._text._model.meshInstances[0]),e.element.removeModelFromLayers(e.element._text._model),n=!0):e.element._image&&(t.push(e.element._image._renderable.meshInstance),e.element.removeModelFromLayers(e.element._image._renderable.model),e.element._image._renderable.unmaskMeshInstance&&(t.push(e.element._image._renderable.unmaskMeshInstance),e.element._image._renderable.unmaskMeshInstance.stencilFront&&e.element._image._renderable.unmaskMeshInstance.stencilBack||(e.element._dirtifyMask(),e.element._onPrerender())),n=!0),n&&(i._ui=!0)}},t._collectAndRemoveMeshInstances=function(e,t){for(var i=0;i<t.length;i++){var n=t[i],s=this._batchGroups[n];if(s){var r=e[n];r||(r=e[n]=[]);for(var a=0;a<s._obj.model.length;a++)r=this._extractModel(s._obj.model[a],r,s,e);for(var o=0;o<s._obj.render.length;o++)r=this._extractRender(s._obj.render[o],r,s,e);for(var h=0;h<s._obj.element.length;h++)this._extractElement(s._obj.element[h],r,s);for(var l=0;l<s._obj.sprite.length;l++){var c=s._obj.sprite[l];c.sprite&&c.sprite._meshInstance&&(s.dynamic||0===c.sprite.sprite._renderMode)&&(r.push(c.sprite._meshInstance),c.sprite.removeModelFromLayers(),s._sprite=!0,c.sprite._batchGroup=s)}}}},t.generate=function(e){var t={};e||(e=Object.keys(this._batchGroups));for(var i,n,s,r,a=[],o=0;o<this._batchList.length;o++)e.indexOf(this._batchList[o].batchGroupId)<0?a.push(this._batchList[o]):this.destroyBatch(this._batchList[o]);if(this._batchList=a,this._collectAndRemoveMeshInstances(t,e),e===this._dirtyGroups)this._dirtyGroups.length=0;else{for(var h=[],l=0;l<this._dirtyGroups.length;l++)e.indexOf(this._dirtyGroups[l])<0&&h.push(this._dirtyGroups[l]);this._dirtyGroups=h}for(var c in t)if(t.hasOwnProperty(c)&&(i=t[c],s=this._batchGroups[c])){n=this.prepare(i,s.dynamic,s.maxAabbSize,s._ui||s._sprite);for(var u=0;u<n.length;u++)(r=this.create(n[u],s.dynamic,parseInt(c,10)))&&r.addToLayers(this.scene,s.layers)}},t.prepare=function(e,t,i,n){if(void 0===i&&(i=Number.POSITIVE_INFINITY),0===e.length)return[];var s,r=.5*i,a=this.device.supportsBoneTextures?1024:this.device.boneLimit,o=this.device.extUintElement?4294967295:65535,h=new Oe,l=new Oe,c=null,u=[],d=0;n&&e.sort((function(e,t){return e.drawOrder-t.drawOrder}));for(var f,p=e,m=n?function(e){c?c.add(e.aabb):c=e.aabb.clone(),f.push(e)}:function(e){f.push(e)};p.length>0;){u[d]=[p[0]],f=[];var _=p[0].material,g=p[0].layer,v=p[0]._shaderDefs,y=p[0].parameters,x=p[0].stencilFront,b=p[0]._staticLightList,S=p[0].mesh.vertexBuffer.getNumVertices(),w=p[0].drawOrder;h.copy(p[0].aabb);var T=Wa(p[0]),A=p[0].mesh.vertexBuffer.format.batchingHash,M=p[0].mesh.primitive[0].indexed;c=null;for(var C=1;C<p.length;C++){var E=p[C];if(t&&u[d].length>=a){f=f.concat(p.slice(C));break}if(_!==E.material||g!==E.layer||A!==E.mesh.vertexBuffer.format.batchingHash||M!==E.mesh.primitive[0].indexed||v!==E._shaderDefs||S+E.mesh.vertexBuffer.getNumVertices()>o)m(E);else if(l.copy(h),l.add(E.aabb),l.halfExtents.x>r||l.halfExtents.y>r||l.halfExtents.z>r)m(E);else if(!x||(s=E.stencilFront)&&x.func===s.func&&x.zpass===s.zpass)if(T===Wa(E))if(Ba(y,E.parameters)){var P=E._staticLightList;if(b&&P){if(!Na(b,P)){m(E);continue}}else if(b||P){m(E);continue}n&&c&&c.intersects(E.aabb)&&E.drawOrder!==w?m(E):(h.add(E.aabb),S+=E.mesh.vertexBuffer.getNumVertices(),u[d].push(E))}else m(E);else m(E);else m(E)}d++,p=f}return u},t.collectBatchedMeshData=function(e,t){for(var i=null,n=0,s=0,r=null,a=0;a<e.length;a++)if(e[a].visible){var o=e[a].mesh;if(n+=o.vertexBuffer.numVertices,s+=o.primitive[0].indexed?o.primitive[0].count:6===o.primitive[0].type&&4===o.primitive[0].count?6:0,!i){r=e[a].material,i={};for(var h=o.vertexBuffer.format.elements,l=0;l<h.length;l++){i[h[l].name]={numComponents:h[l].numComponents,dataType:h[l].dataType,normalize:h[l].normalize,count:0}}t&&(i.BLENDINDICES={numComponents:1,dataType:6,normalize:!1,count:0})}}return{streams:i,batchNumVerts:n,batchNumIndices:s,material:r}},t.create=function(e,t,i){if(!this._init){var n="#define BONE_LIMIT "+this.device.getBoneLimit()+"\n";this.transformVS=n+"#define DYNAMICBATCH\n"+Wi.transformVS,this.skinTexVS=Wi.skinBatchTexVS,this.skinConstVS=Wi.skinBatchConstVS,this.vertexFormats={},this._init=!0}var s,r,a,o=null,h=null,l=this.collectBatchedMeshData(e,t);if(l.streams){var c,u,d,f=l.streams,p=l.material,m=l.batchNumVerts,_=l.batchNumIndices;h=new va(e,t,i),this._batchList.push(h);var g,v=0,y=0,x=new ye,b=new(m<=65535?Uint16Array:Uint32Array)(_);for(s in f)(o=f[s]).typeArrayType=fi[o.dataType],o.elementByteSize=pi[o.dataType],o.buffer=new o.typeArrayType(m*o.numComponents);for(var S=0;S<e.length;S++)if(e[S].visible){for(s in a=(r=e[S].mesh).vertexBuffer.numVertices,t||(g=e[S].node.getWorldTransform()),f)if(s!==St){var w=new(o=f[s]).typeArrayType(o.buffer.buffer,o.elementByteSize*o.count),T=r.getVertexStream(s,w)*o.numComponents;if(o.count+=T,!t&&o.numComponents>=3)if(s===vt)for(var A=0;A<T;A+=o.numComponents)x.set(w[A],w[A+1],w[A+2]),g.transformPoint(x,x),w[A]=x.x,w[A+1]=x.y,w[A+2]=x.z;else if(s===yt||s===xt){g.invertTo3x3(Ua),Ua.transpose();for(var M=0;M<T;M+=o.numComponents)x.set(w[M],w[M+1],w[M+2]),Ua.transformVector(x,x),w[M]=x.x,w[M+1]=x.y,w[M+2]=x.z}}if(t){o=f.BLENDINDICES;for(var C=0;C<a;C++)o.buffer[o.count++]=S}if(r.primitive[0].indexed){c=r.primitive[0].base,u=r.primitive[0].count;var E=r.indexBuffer[0].getFormat();d=new _i[E](r.indexBuffer[0].storage)}else{if(6!==r.primitive[0].type||4!==r.primitive[0].count){u=0;continue}c=0,u=6,d=[0,1,3,2,3,1]}for(var P=0;P<u;P++)b[P+y]=d[c+P]+v;y+=u,v+=a}for(s in r=new ea(this.device),f)o=f[s],r.setVertexStream(s,o.buffer,o.numComponents,void 0,o.dataType,o.normalize);b.length>0&&r.setIndices(b),r.update(4,!1),t&&((p=p.clone()).chunks.transformVS=this.transformVS,p.chunks.skinTexVS=this.skinTexVS,p.chunks.skinConstVS=this.skinConstVS,p.update());var R=new ka(r,p,this.rootNode);R.castShadow=h.origMeshInstances[0].castShadow,R.parameters=h.origMeshInstances[0].parameters,R.isStatic=h.origMeshInstances[0].isStatic,R.layer=h.origMeshInstances[0].layer,R._staticLightList=h.origMeshInstances[0]._staticLightList,R._shaderDefs=h.origMeshInstances[0]._shaderDefs,R.cull=h.origMeshInstances[0].cull;var I=this._batchGroups[i];if(I&&I._ui&&(R.cull=!1),t){for(var L=[],D=0;D<h.origMeshInstances.length;D++)L.push(h.origMeshInstances[D].node);R.skinInstance=new Sa(this.device,L,this.rootNode)}R._updateAabb=!1,R.drawOrder=h.origMeshInstances[0].drawOrder,R.stencilFront=h.origMeshInstances[0].stencilFront,R.stencilBack=h.origMeshInstances[0].stencilBack,R.flipFaces=Wa(h.origMeshInstances[0])<0,R.castShadow=h.origMeshInstances[0].castShadow,h.meshInstance=R,h.updateBoundingBox()}return h},t.updateAll=function(){this._dirtyGroups.length>0&&this.generate(this._dirtyGroups);for(var e=0;e<this._batchList.length;e++)this._batchList[e].dynamic&&this._batchList[e].updateBoundingBox()},t.clone=function(e,t){var i=new va(t,e.dynamic,e.batchGroupId);this._batchList.push(i);for(var n=[],s=0;s<t.length;s++)n.push(t[s].node);return i.meshInstance=new ka(e.meshInstance.mesh,e.meshInstance.material,e.meshInstance.node),i.meshInstance._updateAabb=!1,i.meshInstance.parameters=t[0].parameters,i.meshInstance.isStatic=t[0].isStatic,i.meshInstance.cull=t[0].cull,i.meshInstance.layer=t[0].layer,i.meshInstance._staticLightList=t[0]._staticLightList,e.dynamic&&(i.meshInstance.skinInstance=new Sa(this.device,n,this.rootNode)),i.meshInstance.castShadow=e.meshInstance.castShadow,i.meshInstance._shader=e.meshInstance._shader.slice(),i.meshInstance.castShadow=e.meshInstance.castShadow,i},t.destroyBatch=function(e){e.destroy(this.scene,this._batchGroups[e.batchGroupId].layers)},e}(),Xa=new ye,qa=new ye,ja=new ye,Ya=new Oe,Ka=1e-6,Za=function(){this.light=null,this.min=new ye,this.max=new ye},$a=function(){function e(e){this.device=e,this.name="Untitled",this.reportCount=0,this.boundsMin=new ye,this.boundsMax=new ye,this.boundsDelta=new ye,this._cells=new ye(1,1,1),this._cellsLimit=new ye,this.cells=this._cells,this._maxCellLightCount=0,this._pixelsPerCellCount=0,this.maxCellLightCount=4,this._maxAttenuation=0,this._maxColorValue=0,this._usedLights=[],this._usedLights.push(new Za),this.lightsBuffer=new ts(e),this.registerUniforms(e)}var t=e.prototype;return t.destroy=function(){this.lightsBuffer.destroy(),this.releaseClusterTexture()},t.releaseClusterTexture=function(){this.clusterTexture&&(this.clusterTexture.destroy(),this.clusterTexture=null)},t.registerUniforms=function(e){this._clusterWorldTextureId=e.scope.resolve("clusterWorldTexture"),this._clusterPixelsPerCellId=e.scope.resolve("clusterPixelsPerCell"),this._clusterTextureSizeId=e.scope.resolve("clusterTextureSize"),this._clusterTextureSizeData=new Float32Array(3),this._clusterBoundsMinId=e.scope.resolve("clusterBoundsMin"),this._clusterBoundsMinData=new Float32Array(3),this._clusterBoundsDeltaId=e.scope.resolve("clusterBoundsDelta"),this._clusterBoundsDeltaData=new Float32Array(3),this._clusterCellsCountByBoundsSizeId=e.scope.resolve("clusterCellsCountByBoundsSize"),this._clusterCellsCountByBoundsSizeData=new Float32Array(3),this._clusterCellsDotId=e.scope.resolve("clusterCellsDot"),this._clusterCellsDotData=new Float32Array(3),this._clusterCellsMaxId=e.scope.resolve("clusterCellsMax"),this._clusterCellsMaxData=new Float32Array(3),this._clusterCompressionLimit0Id=e.scope.resolve("clusterCompressionLimit0"),this._clusterCompressionLimit0Data=new Float32Array(2)},t.updateParams=function(e){e&&(this.cells=e.cells,this.maxCellLightCount=e.maxLightsPerCell,this.lightsBuffer.cookiesEnabled=e.cookiesEnabled,this.lightsBuffer.shadowsEnabled=e.shadowsEnabled,this.lightsBuffer.areaLightsEnabled=e.areaLightsEnabled)},t.updateCells=function(){if(this._cellsDirty){this._cellsDirty=!1;var e=this._cells.x,t=this._cells.y,i=this._cells.z,n=e*t*i,s=this._pixelsPerCellCount*n,r=Math.ceil(Math.sqrt(s));r=de.roundUp(r,this._pixelsPerCellCount);var a=Math.ceil(s/r);this._clusterCellsMaxData[0]=e,this._clusterCellsMaxData[1]=t,this._clusterCellsMaxData[2]=i,this._clusterCellsDotData[0]=this._pixelsPerCellCount,this._clusterCellsDotData[1]=e*i*this._pixelsPerCellCount,this._clusterCellsDotData[2]=e*this._pixelsPerCellCount,this.clusters=new Uint8ClampedArray(4*s),this.counts=new Int32Array(n),this._clusterTextureSizeData[0]=r,this._clusterTextureSizeData[1]=1/r,this._clusterTextureSizeData[2]=1/a,this.releaseClusterTexture(),this.clusterTexture=ts.createTexture(this.device,r,a,7,"ClusterTexture")}},t.uploadTextures=function(){this.clusterTexture.lock().set(this.clusters),this.clusterTexture.unlock(),this.lightsBuffer.uploadTextures()},t.updateUniforms=function(){this.lightsBuffer.updateUniforms(),this._clusterWorldTextureId.setValue(this.clusterTexture);var e=this.boundsDelta;this._clusterCellsCountByBoundsSizeData[0]=this._cells.x/e.x,this._clusterCellsCountByBoundsSizeData[1]=this._cells.y/e.y,this._clusterCellsCountByBoundsSizeData[2]=this._cells.z/e.z,this._clusterCellsCountByBoundsSizeId.setValue(this._clusterCellsCountByBoundsSizeData),this._clusterBoundsMinData[0]=this.boundsMin.x,this._clusterBoundsMinData[1]=this.boundsMin.y,this._clusterBoundsMinData[2]=this.boundsMin.z,this._clusterBoundsDeltaData[0]=e.x,this._clusterBoundsDeltaData[1]=e.y,this._clusterBoundsDeltaData[2]=e.z,this._clusterCompressionLimit0Data[0]=this._maxAttenuation,this._clusterCompressionLimit0Data[1]=this._maxColorValue,this._clusterPixelsPerCellId.setValue(this._pixelsPerCellCount),this._clusterTextureSizeId.setValue(this._clusterTextureSizeData),this._clusterBoundsMinId.setValue(this._clusterBoundsMinData),this._clusterBoundsDeltaId.setValue(this._clusterBoundsDeltaData),this._clusterCellsDotId.setValue(this._clusterCellsDotData),this._clusterCellsMaxId.setValue(this._clusterCellsMaxData),this._clusterCompressionLimit0Id.setValue(this._clusterCompressionLimit0Data)},t.evalLightCellMinMax=function(e,t,i){t.copy(e.min),t.sub(this.boundsMin),t.div(this.boundsDelta),t.mul2(t,this.cells),t.floor(),i.copy(e.max),i.sub(this.boundsMin),i.div(this.boundsDelta),i.mul2(i,this.cells),i.ceil(),t.max(ye.ZERO),i.min(this._cellsLimit)},t.collectLights=function(e){for(var t=this.lightsBuffer.maxLights,i=this._usedLights,n=1,s=0;s<e.length;s++){var r=e[s],a=!!(3&r.mask);if(r.enabled&&0!==r.type&&r.visibleThisFrame&&r.intensity>0&&a){if(!(n<t)){console.warn("Clustered lighting: more than "+(t-1)+" lights in the frame, ignoring some.");break}var o=void 0;n<i.length?o=i[n]:(o=new Za,i.push(o)),o.light=r,r.getBoundingBox(Ya),o.min.copy(Ya.getMin()),o.max.copy(Ya.getMax()),n++}}i.length=n},t.evaluateBounds=function(){var e=this._usedLights,t=this.boundsMin,i=this.boundsMax;if(e.length>1){t.copy(e[1].min),i.copy(e[1].max);for(var n=2;n<e.length;n++)t.min(e[n].min),i.max(e[n].max)}else t.set(0,0,0),i.set(1,1,1);this.boundsDelta.sub2(i,t),this.lightsBuffer.setBounds(t,this.boundsDelta)},t.evaluateCompressionLimits=function(e){for(var t=0,i=0,n=this._usedLights,s=1;s<n.length;s++){var r=n[s].light;t=Math.max(r.attenuationEnd,t);var a=e?r._linearFinalColor:r._finalColor;i=Math.max(a[0],i),i=Math.max(a[1],i),i=Math.max(a[2],i)}this._maxAttenuation=t+Ka,this._maxColorValue=i+Ka,this.lightsBuffer.setCompressionRanges(this._maxAttenuation,this._maxColorValue)},t.updateClusters=function(e){this.counts.fill(0),this.clusters.fill(0);for(var t=this._cells.x,i=this._cells.z,n=this.counts,s=this._maxCellLightCount,r=this.clusters,a=this._pixelsPerCellCount,o=this._usedLights,h=1;h<o.length;h++){var l=o[h],c=l.light;this.lightsBuffer.addLightData(c,h,e),this.evalLightCellMinMax(l,qa,ja);for(var u=qa.x,d=ja.x,f=qa.y,p=ja.y,m=qa.z,_=ja.z,g=u;g<=d;g++)for(var v=m;v<=_;v++)for(var y=f;y<=p;y++){var x=g+t*(v+y*i),b=n[x];b<s&&(r[a*x*4+b]=h,n[x]=b+1)}}},t.update=function(e,t,i){this.updateParams(i),this.updateCells(),this.collectLights(e),this.evaluateBounds(),this.evaluateCompressionLimits(t),this.updateClusters(t),this.uploadTextures()},t.activate=function(){this.updateUniforms()},$(e,[{key:"maxCellLightCount",get:function(){return this._maxCellLightCount},set:function(e){var t=de.roundUp(e,4);t!==this._maxCellLightCount&&(this._maxCellLightCount=t,this._pixelsPerCellCount=this._maxCellLightCount/4,this._cellsDirty=!0)}},{key:"cells",get:function(){return this._cells},set:function(e){Xa.copy(e).floor(),this._cells.equals(Xa)||(this._cells.copy(Xa),this._cellsLimit.copy(Xa).sub(ye.ONE),this._cellsDirty=!0)}}]),e}(),Qa=[];Qa[2]=1,Qa[3]=2,Qa[4]=3,Qa[5]=4,Qa[1]=1,Qa[6]=2,Qa[7]=3,Qa[8]=4,Qa[0]=1,Qa[9]=2,Qa[10]=3,Qa[11]=4,Qa[12]=8,Qa[13]=12,Qa[14]=16;var Ja=function(){function e(e,t,i){void 0===i&&(i=1),this.name=void 0,this.type=void 0,this.byteSize=void 0,this.offset=void 0,this.scopeId=void 0,this.count=void 0,this.name=e,this.type=t,this.count=i;var n=Qa[t];this.byteSize=i*n*4}return e.prototype.calculateOffset=function(e){var t=this.byteSize<=8?this.byteSize:16;e=de.roundUp(e,t),this.offset=e/4},e}(),eo=function(){function e(e,t){this.byteSize=0,this.map=new Map,this.scope=e.scope,this.uniforms=t;for(var i=0,n=0;n<t.length;n++){var s=t[n];s.calculateOffset(i),i=4*s.offset+s.byteSize,s.scopeId=this.scope.resolve(s.name),this.map.set(s.name,s)}this.byteSize=de.roundUp(i,16)}var t=e.prototype;return t.get=function(e){return this.map.get(e)},t.getShaderDeclaration=function(e,t){var i="layout(set = "+e+", binding = "+t+", std140) uniform ub_"+di[e]+" {\n";return this.uniforms.forEach((function(e){var t=hi[e.type];i+=" "+t+" "+e.name+";\n"})),i+"};\n"},e}(),to=function(e,t){this.name=e,this.visibility=t},io=function(e,t,i,n){void 0===i&&(i=ti),void 0===n&&(n=ii),this.scopeId=void 0,this.name=e,this.visibility=t,this.textureDimension=i,this.sampleType=n},no=function(){function e(e,t,i){var n=this;this.device=e,this.bufferFormats=t,this.bufferFormatsMap=new Map,t.forEach((function(e,t){return n.bufferFormatsMap.set(e.name,t)})),this.textureFormats=i;var s=e.scope;this.textureFormatsMap=new Map,i.forEach((function(e,t){n.textureFormatsMap.set(e.name,t),e.scopeId=s.resolve(e.name)})),this.impl=e.createBindGroupFormatImpl(this)}var t=e.prototype;return t.destroy=function(){this.impl.destroy()},t.getTexture=function(e){var t=this.textureFormatsMap.get(e);return void 0!==t?this.textureFormats[t]:null},t.getShaderDeclarationTextures=function(e){var t="",i=this.bufferFormats.length;return this.textureFormats.forEach((function(n){t+="layout(set = "+e+", binding = "+i+++") uniform texture2D "+n.name+";\nlayout(set = "+e+", binding = "+i+++") uniform sampler "+n.name+"_sampler;\n"})),t},t.loseContext=function(){},e}(),so=function(){this.clearValue=new me(0,0,0,1),this.clear=!1,this.store=!1,this.resolve=!0,this.mipmaps=!1},ro=function(){this.clearDepthValue=1,this.clearStencilValue=0,this.clearDepth=!1,this.clearStencil=!1,this.storeDepth=!1,this.storeStencil=!1},ao=function(){function e(e,t){this.name=void 0,this.renderTarget=void 0,this.samples=0,this.colorOps=void 0,this.depthStencilOps=void 0,this.requiresCubemaps=!0,this.fullSizeClearRect=!0,this.device=e,this.execute=t}var t=e.prototype;return t.init=function(e){var t,i;this.renderTarget=e||null,this.colorOps=new so,this.depthStencilOps=new ro,this.samples=Math.max(this.renderTarget?this.renderTarget.samples:this.device.samples,1),1===this.samples&&(this.colorOps.store=!0,this.colorOps.resolve=!1),null!=(t=this.renderTarget)&&null!=(i=t.colorBuffer)&&i.mipmaps&&(this.colorOps.mipmaps=!0)},t.setClearColor=function(e){this.colorOps.clearValue.copy(e),this.colorOps.clear=!0},t.setClearDepth=function(e){this.depthStencilOps.clearDepthValue=e,this.depthStencilOps.clearDepth=!0},t.setClearStencil=function(e){this.depthStencilOps.clearStencilValue=e,this.depthStencilOps.clearStencil=!0},t.render=function(){var e=this.device,t=void 0!==this.renderTarget;t&&e.startPass(this),this.execute(),t&&e.endPass(this)},e}(),oo=new Se,ho=function(){function e(e,t){this.device=e,this.lightTextureAtlas=t,this.blitShader2d=null,this.blitShaderCube=null,this.blitTextureId=null,this.invViewProjId=null}var t=e.prototype;return t.destroy=function(){},t.getShader=function(e,t){return this[e]||(this[e]=on(this.device,"\n attribute vec2 vertex_position;\n varying vec2 uv0;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.5, 1.0);\n uv0 = vertex_position.xy * 0.5 + 0.5;\n }",t,"cookie_renderer_"+e)),this.blitTextureId||(this.blitTextureId=this.device.scope.resolve("blitTexture")),this.invViewProjId||(this.invViewProjId=this.device.scope.resolve("invViewProj")),this[e]},e.createTexture=function(e,t){return new wn(e,{name:"CookieAtlas",width:t,height:t,format:7,cubemap:!1,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1})},t.initInvViewProjMatrices=function(){if(!e._invViewProjMatrices){e._invViewProjMatrices=[];for(var t=0;t<6;t++){var i=Yn.create(null,1,t),n=i.projectionMatrix,s=i.node.getLocalTransform().clone().invert();e._invViewProjMatrices[t]=(new Ee).mul2(n,s).invert()}}},t.render=function(t,i){if(t.enabled&&t.cookie&&t.visibleThisFrame){var n=t.numShadowFaces,s=n>1?this.shaderCube:this.shader2d,r=this.device;n>1&&this.initInvViewProjMatrices(),this.blitTextureId.setValue(t.cookie);for(var a=0;a<n;a++){if(oo.copy(t.atlasViewport),n>1){var o=oo.z/3,h=this.lightTextureAtlas.cubeSlotsOffsets[a];oo.x+=o*h.x,oo.y+=o*h.y,oo.z=o,oo.w=o,this.invViewProjId.setValue(e._invViewProjMatrices[a].data)}oo.mulScalar(i.colorBuffer.width),Ei(r,i,s,oo)}}},$(e,[{key:"shader2d",get:function(){return this.getShader("blitShader2d","\n varying vec2 uv0;\n uniform sampler2D blitTexture;\n void main(void) {\n gl_FragColor = texture2D(blitTexture, uv0);\n }")}},{key:"shaderCube",get:function(){return this.getShader("blitShaderCube","\n varying vec2 uv0;\n uniform samplerCube blitTexture;\n uniform mat4 invViewProj;\n void main(void) {\n vec4 projPos = vec4(uv0 * 2.0 - 1.0, 0.5, 1.0);\n vec4 worldPos = invViewProj * projPos;\n gl_FragColor = textureCube(blitTexture, worldPos.xyz);\n }")}}]),e}();ho._invViewProjMatrices=null;var lo=function(){function e(e,t){this.texture=e,this.cached=!1,this.renderTargets=t}return e.prototype.destroy=function(){this.texture&&(this.texture.destroy(),this.texture=null);for(var e=this.renderTargets,t=0;t<e.length;t++)e[t].destroy();this.renderTargets.length=0},e.getShadowFormat=function(e,t){return 3===t?dt:2===t?ct:4===t||0===t&&e.webgl2?ft:7},e.getShadowFiltering=function(e,t){return 0!==t||e.webgl2?3===t?e.extTextureFloatLinear?1:0:2===t?e.extTextureHalfFloatLinear?1:0:1:0},e.create=function(e,t){return 1===t._type?this.createCubemap(e,t._shadowResolution):this.create2dMap(e,t._shadowResolution,t._shadowType)},e.createAtlas=function(e,t,i){for(var n=this.create2dMap(e,t,i),s=n.renderTargets,r=s[0],a=0;a<5;a++)s.push(r);return n},e.create2dMap=function(t,i,n){var s=this.getShadowFormat(t,n),r=this.getShadowFiltering(t,n),a=new wn(t,{format:s,width:i,height:i,mipmaps:!1,minFilter:r,magFilter:r,addressU:1,addressV:1,name:"ShadowMap2D"}),o=null;return 4===n||0===n&&t.webgl2?(a.compareOnRead=!0,a.compareFunc=1,o=new cr({depthBuffer:a})):o=new cr({colorBuffer:a,depth:!0}),new e(a,[o])},e.createCubemap=function(t,i){for(var n=new wn(t,{format:7,width:i,height:i,cubemap:!0,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1,name:"ShadowMapCube"}),s=[],r=0;r<6;r++){var a=new cr({colorBuffer:n,face:r,depth:!0});s.push(a)}return new e(n,s)},e}(),co=[],uo=[],fo=new Se,po=new Se,mo=function(e){this.size=Math.floor(1024*e.w),this.used=!1,this.lightId=-1,this.rect=e},_o=function(){function e(e){this.device=e,this.version=1,this.shadowAtlasResolution=2048,this.shadowAtlas=null,this.shadowEdgePixels=3,this.cookieAtlasResolution=2048,this.cookieAtlas=null,this.cookieRenderTarget=null,this.slots=[],this.atlasSplit=[],this.cubeSlotsOffsets=[new be(0,0),new be(0,1),new be(1,0),new be(1,1),new be(2,0),new be(2,1)],this.scissorVec=new Se,this.allocateShadowAtlas(1),this.allocateCookieAtlas(1),this.allocateUniforms()}var t=e.prototype;return t.destroy=function(){this.destroyShadowAtlas(),this.destroyCookieAtlas()},t.destroyShadowAtlas=function(){this.shadowAtlas&&(this.shadowAtlas.destroy(),this.shadowAtlas=null)},t.destroyCookieAtlas=function(){this.cookieAtlas&&(this.cookieAtlas.destroy(),this.cookieAtlas=null),this.cookieRenderTarget&&(this.cookieRenderTarget.destroy(),this.cookieRenderTarget=null)},t.allocateShadowAtlas=function(e){if(!this.shadowAtlas||this.shadowAtlas.texture.width!==e){this.version++,this.destroyShadowAtlas(),this.shadowAtlas=lo.createAtlas(this.device,e,0),this.shadowAtlas.cached=!0;var t=4/this.shadowAtlasResolution;this.scissorVec.set(t,t,-2*t,-2*t)}},t.allocateCookieAtlas=function(e){this.cookieAtlas&&this.cookieAtlas.width===e||(this.version++,this.destroyCookieAtlas(),this.cookieAtlas=ho.createTexture(this.device,e),this.cookieRenderTarget=new cr({colorBuffer:this.cookieAtlas,depth:!1,flipY:!0}))},t.allocateUniforms=function(){this._shadowAtlasTextureId=this.device.scope.resolve("shadowAtlasTexture"),this._shadowAtlasParamsId=this.device.scope.resolve("shadowAtlasParams"),this._shadowAtlasParams=new Float32Array(2),this._cookieAtlasTextureId=this.device.scope.resolve("cookieAtlasTexture")},t.updateUniforms=function(){var e=this.shadowAtlas.renderTargets[0],t=this.device.webgl2?e.depthBuffer:e.colorBuffer;this._shadowAtlasTextureId.setValue(t),this._shadowAtlasParams[0]=this.shadowAtlasResolution,this._shadowAtlasParams[1]=this.shadowEdgePixels,this._shadowAtlasParamsId.setValue(this._shadowAtlasParams),this._cookieAtlasTextureId.setValue(this.cookieAtlas)},t.subdivide=function(e,t){var i=t.atlasSplit;if(!i){var n=Math.ceil(Math.sqrt(e));(i=uo)[0]=n,i.length=1}var s,r;if(s=i,r=this.atlasSplit,s.length!==r.length||!s.every((function(e,t){return e===r[t]}))){var a;this.version++,this.slots.length=0,this.atlasSplit.length=0,(a=this.atlasSplit).push.apply(a,i);var o=this.atlasSplit[0];if(o>1)for(var h=1/o,l=0;l<o;l++)for(var c=0;c<o;c++){var u=new Se(l*h,c*h,h,h),d=this.atlasSplit[1+l*o+c];if(d>1)for(var f=0;f<d;f++)for(var p=0;p<d;p++){var m=h/d,_=new Se(u.x+f*m,u.y+p*m,m,m);this.slots.push(new mo(_))}else this.slots.push(new mo(u))}else this.slots.push(new mo(new Se(0,0,1,1)));this.slots.sort((function(e,t){return t.size-e.size}))}},t.collectLights=function(e,t,i){var n=i.cookiesEnabled,s=i.shadowsEnabled,r=!1,a=!1,o=co;o.length=0;var h=function(e){for(var t=0;t<e.length;t++){var i=e[t];if(i.visibleThisFrame){var h=s&&i.castShadows,l=n&&!!i.cookie;r||(r=h),a||(a=l),(h||l)&&o.push(i)}}};return(n||s)&&(h(e),h(t)),o.sort((function(e,t){return t.maxScreenSize-e.maxScreenSize})),r&&this.allocateShadowAtlas(this.shadowAtlasResolution),a&&this.allocateCookieAtlas(this.cookieAtlasResolution),(r||a)&&this.subdivide(o.length,i),o},t.setupSlot=function(e,t){e.atlasViewport.copy(t);for(var i=e.numShadowFaces,n=0;n<i;n++)if(e.castShadows||e._cookie){if(fo.copy(t),po.copy(t),2===e._type&&fo.add(this.scissorVec),1===e._type){var s=fo.z/3,r=this.cubeSlotsOffsets[n];fo.x+=s*r.x,fo.y+=s*r.y,fo.z=s,fo.w=s,po.copy(fo)}if(e.castShadows){var a=e.getRenderData(null,n);a.shadowViewport.copy(fo),a.shadowScissor.copy(po)}}},t.assignSlot=function(e,t,i){e.atlasViewportAllocated=!0;var n=this.slots[t];n.lightId=e.id,n.used=!0,i&&(e.atlasSlotUpdated=!0,e.atlasVersion=this.version,e.atlasSlotIndex=t)},t.update=function(e,t,i){this.shadowAtlasResolution=i.shadowAtlasResolution,this.cookieAtlasResolution=i.cookieAtlasResolution;var n=this.collectLights(e,t,i);if(n.length>0){for(var s=this.slots,r=0;r<s.length;r++)s[r].used=!1;for(var a=Math.min(n.length,s.length),o=0;o<a;o++){var h=n[o];h.castShadows&&(h._shadowMap=this.shadowAtlas);var l=s[h.atlasSlotIndex];if(h.atlasVersion===this.version&&h.id===(null==l?void 0:l.lightId)){var c=s[h.atlasSlotIndex];c.size!==s[o].size||c.used||this.assignSlot(h,h.atlasSlotIndex,!1)}}for(var u=0,d=0;d<a;d++){for(;u<s.length&&s[u].used;)u++;var f=n[d];f.atlasViewportAllocated||this.assignSlot(f,u,!0);var p=s[f.atlasSlotIndex];this.setupSlot(f,p.rect)}}this.updateUniforms()},e}(),go=function(){function e(){this.shadowMapCache=new Map}var t=e.prototype;return t.destroy=function(){this.clear(),this.shadowMapCache=null},t.clear=function(){this.shadowMapCache.forEach((function(e){e.forEach((function(e){e.destroy()}))})),this.shadowMapCache.clear()},t.getKey=function(e){return(1===e._type)+"-"+e._shadowType+"-"+e._shadowResolution},t.get=function(e,t){var i=this.getKey(t),n=this.shadowMapCache.get(i);if(n&&n.length)return n.pop();var s=lo.create(e,t);return s.cached=!0,s},t.add=function(e,t){var i=this.getKey(e),n=this.shadowMapCache.get(i);n?n.push(t):this.shadowMapCache.set(i,[t])},e}(),vo=[new ye,new ye,new ye,new ye,new ye,new ye,new ye,new ye],yo={min:0,max:0};function xo(e,t,i){vo[0].x=vo[1].x=vo[2].x=vo[3].x=t.x,vo[1].y=vo[3].y=vo[7].y=vo[5].y=t.y,vo[2].z=vo[3].z=vo[6].z=vo[7].z=t.z,vo[4].x=vo[5].x=vo[6].x=vo[7].x=i.x,vo[0].y=vo[2].y=vo[4].y=vo[6].y=i.y,vo[0].z=vo[1].z=vo[4].z=vo[5].z=i.z;for(var n=9999999999,s=-9999999999,r=0;r<8;++r){e.transformPoint(vo[r],vo[r]);var a=vo[r].z;a<n&&(n=a),a>s&&(s=a)}return yo.min=n,yo.max=s,yo}function bo(e,t){return Math.exp(-e*e/(2*t*t))}var So=new Oe,wo=new Ee,To=new Ee,Ao=new Float32Array(2),Mo=new Se(1,1,0,0),Co={r:1,g:2,b:3,a:4},Eo=new ye,Po=new Ee;function Ro(e){var t=e.material,i=e.skinInstance?10:0,n=0;if(t.opacityMap){var s=t.opacityMapChannel;s&&(n=Co[s])}return i+n}var Io=function(){function e(e,t){this.device=e.device,this.forwardRenderer=e,this.lightTextureAtlas=t;var i=this.device.scope;this.polygonOffsetId=i.resolve("polygonOffset"),this.polygonOffset=new Float32Array(2),this.sourceId=i.resolve("source"),this.pixelOffsetId=i.resolve("pixelOffset"),this.weightId=i.resolve("weight[0]"),this.blurVsmShaderCode=[Wi.blurVSMPS,"#define GAUSS\n"+Wi.blurVSMPS];var n="#define PACKED\n";this.blurPackedVsmShaderCode=[n+this.blurVsmShaderCode[0],n+this.blurVsmShaderCode[1]],this.blurVsmShader=[{},{}],this.blurPackedVsmShader=[{},{}],this.blurVsmWeights={},this.shadowMapLightRadiusId=i.resolve("light_radius"),this.shadowMapCache=new go}var t=e.prototype;return t.destroy=function(){this.shadowMapCache.destroy(),this.shadowMapCache=null},e.createShadowCamera=function(e,t,i,n){var s=Yn.create("ShadowCamera",i,n);return s.clearColor=t>=1&&t<=3?new me(0,0,0,0):new me(1,1,1,1),s.clearDepthBuffer=!0,s.clearStencilBuffer=!1,s},e.setShadowCameraSettings=function(e,t,i,n,s){var r=4===i||0===i&&t.webgl2;1!==n||s||(r=!1),e.clearColorBuffer=!r},t.cullShadowCasters=function(e,t,i){for(var n=0,s=e.length,r=0;r<s;r++){var a=e[r];a.cull&&!a._isVisible(i)||(a.visibleThisFrame=!0,t[n]=a,n++)}t.length=n,t.sort(this.forwardRenderer.depthSortCompare)},t.cullLocal=function(e,t){var i=this.forwardRenderer.scene.clusteredLightingEnabled;e.visibleThisFrame=!0,i||e._shadowMap||(e._shadowMap=lo.create(this.device,e));for(var n=e._type,s=2===n?1:6,r=0;r<s;r++){var a=e.getRenderData(null,r),o=a.shadowCamera;o.nearClip=e.attenuationEnd/1e3,o.farClip=e.attenuationEnd;var h=o._node,l=e._node;if(h.setPosition(l.getPosition()),2===n)o.fov=2*e._outerConeAngle,h.setRotation(l.getRotation()),h.rotateLocal(-90,0,0);else if(1===n)if(i){var c=2/(this.lightTextureAtlas.shadowAtlasResolution*e.atlasViewport.z/3)*this.lightTextureAtlas.shadowEdgePixels;o.fov=Math.atan(1+c)*de.RAD_TO_DEG*2}else o.fov=90;this.forwardRenderer.updateCameraFrustum(o),this.cullShadowCasters(t,a.visibleCasters,o)}},t.generateSplitDistances=function(e,t,i){e._shadowCascadeDistances.fill(i);for(var n=1;n<e.numCascades;n++){var s=n/e.numCascades,r=t+(i-t)*s,a=t*Math.pow(i/t,s),o=de.lerp(r,a,e.cascadeDistribution);e._shadowCascadeDistances[n-1]=o}},t.cullDirectional=function(e,t,i){e.visibleThisFrame=!0,e._shadowMap||(e._shadowMap=lo.create(this.device,e));var n=i._nearClip;this.generateSplitDistances(e,n,e.shadowDistance);for(var s=0;s<e.numCascades;s++){var r=e.getRenderData(i,s),a=r.shadowCamera;a.renderTarget=e._shadowMap.renderTargets[0],r.shadowViewport.copy(e.cascades[s]),r.shadowScissor.copy(e.cascades[s]);var o=a._node,h=e._node;o.setPosition(h.getPosition()),o.setRotation(h.getRotation()),o.rotateLocal(-90,0,0);var l=0===s?n:e._shadowCascadeDistances[s-1],c=e._shadowCascadeDistances[s],u=Je.getPoints(i,l,c);Eo.set(0,0,0);for(var d=i.node.getWorldTransform(),f=0;f<8;f++)d.transformPoint(u[f],u[f]),Eo.add(u[f]);Eo.mulScalar(1/8);for(var p=0,m=0;m<8;m++){var _=u[m].sub(Eo).length();_>p&&(p=_)}var g=o.right,v=o.up,y=o.forward,x=.25*e._shadowResolution/p,b=Math.ceil(Eo.dot(v)*x)/x,S=Math.ceil(Eo.dot(g)*x)/x,w=v.mulScalar(b),T=g.mulScalar(S),A=Eo.dot(y),M=y.mulScalar(A);Eo.add2(w,T).add(M),o.setPosition(Eo),o.translateLocal(0,0,1e6),a.nearClip=0,a.farClip=2e6,a.orthoHeight=p,this.forwardRenderer.updateCameraFrustum(a),this.cullShadowCasters(t,r.visibleCasters,a);for(var C=!0,E=r.visibleCasters,P=0;P<E.length;P++){var R=E[P];C?(C=!1,So.copy(R.aabb)):So.add(R.aabb)}wo.copy(o.getWorldTransform()).invert();var I=xo(wo,So.getMin(),So.getMax());o.translateLocal(0,0,I.max+.1),a.farClip=I.max-I.min+.2}},t.setupRenderState=function(e,t){var i=this.forwardRenderer.scene.clusteredLightingEnabled;e.webgl2?1!==t._type||i?(e.setDepthBias(!0),e.setDepthBiasValues(-1e3*t.shadowBias,-1e3*t.shadowBias)):e.setDepthBias(!1):e.extStandardDerivatives&&(1===t._type?(this.polygonOffset[0]=0,this.polygonOffset[1]=0,this.polygonOffsetId.setValue(this.polygonOffset)):(this.polygonOffset[0]=-1e3*t.shadowBias,this.polygonOffset[1]=-1e3*t.shadowBias,this.polygonOffsetId.setValue(this.polygonOffset))),e.setBlending(!1),e.setDepthWrite(!0),e.setDepthTest(!0),e.setDepthFunc(3),(i?t._isPcf&&e.webgl2:t._isPcf&&e.webgl2&&1!==t._type)?e.setColorWrite(!1,!1,!1,!1):e.setColorWrite(!0,!0,!0,!0)},t.restoreRenderState=function(e){e.webgl2?e.setDepthBias(!1):e.extStandardDerivatives&&(this.polygonOffset[0]=0,this.polygonOffset[1]=0,this.polygonOffsetId.setValue(this.polygonOffset))},t.dispatchUniforms=function(e,t,i,n){var s=t._node;0!==e._type&&(this.forwardRenderer.dispatchViewPos(s.getPosition()),this.shadowMapLightRadiusId.setValue(e.attenuationEnd)),wo.setTRS(s.getPosition(),s.getRotation(),ye.ONE).invert(),To.mul2(t.projectionMatrix,wo);var r=i.shadowViewport;t.rect=r,t.scissorRect=i.shadowScissor,Po.setViewport(r.x,r.y,r.z,r.w),i.shadowMatrix.mul2(Po,To),0===e._type&&e._shadowMatrixPalette.set(i.shadowMatrix.data,16*n)},t.submitCasters=function(e,t){for(var i=this.device,n=this.forwardRenderer,s=n.scene,r=Hi.getShadow(t._type,t._shadowType),a=e.length,o=0;o<a;o++){var h=e[o],l=h.mesh;h.ensureMaterial(i);var c=h.material;n.setBaseConstants(i,c),n.setSkinning(i,h,c),c.dirty&&(c.updateUniforms(i,s),c.dirty=!1),c.chunks&&(n.setCullMode(!0,!1,h),c.setParameters(i),h.setParameters(i,16));var u=h._shader[r];u||(h.updatePassShader(s,r),u=h._shader[r],h._key[1]=Ro(h)),!u.failed&&i.setShader(u),n.setVertexBuffers(i,l),n.setMorphing(i,h.morphInstance);var d=h.renderStyle;i.setIndexBuffer(l.indexBuffer[d]),n.drawInstance(i,h,l,d),n._shadowDrawCalls++}},t.render=function(t,i){if(t.enabled&&t.castShadows&&0!==t.shadowUpdateMode&&t.visibleThisFrame){var n=this.device;1===t.shadowUpdateMode&&(t.shadowUpdateMode=0);var s=t._type,r=t._shadowType,a=t.numShadowFaces,o=this.forwardRenderer;o._shadowMapUpdates+=a;var h=o.scene.clusteredLightingEnabled;this.setupRenderState(n,t);for(var l=0;l<a;l++){var c=t.getRenderData(0===s?i:null,l),u=c.shadowCamera;e.setShadowCameraSettings(u,n,r,s,h);var d=0===s?0:l;u.renderTarget=t._shadowMap.renderTargets[d],this.dispatchUniforms(t,u,c,l),o.setCamera(u,u.renderTarget,!0),this.submitCasters(c.visibleCasters,t)}if(t._isVsm&&t._vsmBlurSize>1)this.forwardRenderer.scene.clusteredLightingEnabled&&0!==s||this.applyVsmBlur(t,i);this.restoreRenderState(n)}},t.getVsmBlurShader=function(e,t,i){var n=(e?this.blurPackedVsmShader:this.blurVsmShader)[t][i];if(!n){this.blurVsmWeights[i]=function(e){e>25&&(e=25);for(var t=(e-1)/6,i=.5*(e-1),n=new Array(e),s=0,r=0;r<e;++r)n[r]=bo(r-i,t),s+=n[r];for(var a=0;a<e;++a)n[a]/=s;return n}(i);var s=Wi.fullscreenQuadVS,r="#define SAMPLES "+i+"\n";r+=e?this.blurPackedVsmShaderCode[t]:this.blurVsmShaderCode[t];var a="blurVsm"+t+i+e;n=on(this.device,s,r,a),e?this.blurPackedVsmShader[t][i]=n:this.blurVsmShader[t][i]=n}return n},t.applyVsmBlur=function(e,t){var i=this.device,n=e.getRenderData(0===e._type?t:null,0).shadowCamera.renderTarget,s=this.shadowMapCache.get(i,e),r=s.renderTargets[0],a=1===e._shadowType,o=e.vsmBlurMode,h=e._vsmBlurSize,l=this.getVsmBlurShader(a,o,h);Mo.z=e._shadowResolution-2,Mo.w=Mo.z,this.sourceId.setValue(n.colorBuffer),Ao[0]=1/e._shadowResolution,Ao[1]=0,this.pixelOffsetId.setValue(Ao),1===o&&this.weightId.setValue(this.blurVsmWeights[h]),Ei(i,r,l,null,Mo),this.sourceId.setValue(r.colorBuffer),Ao[1]=Ao[0],Ao[0]=0,this.pixelOffsetId.setValue(Ao),Ei(i,n,l,null,Mo),this.shadowMapCache.add(e,s)},e}(),Lo=new Ne,Do=function(){function e(){}return e.lightCompare=function(e,t){return e.key-t.key},e.prepare=function(t,i,n,s){for(var r=n,a=r.length,o=[],h=new ye,l=new ye,c=new Oe,u=new Ee,d=[],f=[],p=[],m=[],_=0;_<a;_++){var g=r[_];if(g.isStatic){var v=g.aabb;m.length=0;for(var y=1;y<=2;y++)for(var x=0;x<s.length;x++){var b=s[x];if(b._type===y&&(b.enabled&&b.mask&g.mask&&b.isStatic)){if(f[x]||(f[x]=new Oe,b._node.getWorldTransform(),b.getBoundingSphere(Lo),f[x].center.copy(Lo.center),f[x].halfExtents.set(Lo.radius,Lo.radius,Lo.radius)),!f[x].intersects(v))continue;m.push(x)}}if(0===m.length){o.push(g);continue}for(var S=g.mesh,w=S.vertexBuffer,T=S.indexBuffer[g.renderStyle],A=2===T.bytesPerIndex?new Uint16Array(T.lock()):new Uint32Array(T.lock()),M=S.primitive[g.renderStyle].count/3,C=S.primitive[g.renderStyle].base,E=w.format.elements,P=w.format.size/4,R=new Float32Array(w.storage),I=void 0,L=0;L<E.length;L++)E[L].name===vt&&(I=E[L].offset/4);d.length=M;for(var D=0;D<M;D++)d[D]=0;var k=!1;p.length=6*M;for(var O=0;O<M;O++){for(var F=Number.MAX_VALUE,B=Number.MAX_VALUE,N=Number.MAX_VALUE,U=-Number.MAX_VALUE,z=-Number.MAX_VALUE,V=-Number.MAX_VALUE,G=0;G<3;G++){var W=A[3*O+G+C],H=R[W=W*P+I],X=R[W+1],q=R[W+2];H<F&&(F=H),X<B&&(B=X),q<N&&(N=q),H>U&&(U=H),X>z&&(z=X),q>V&&(V=q)}var j=6*O;p[j]=F,p[j+1]=B,p[j+2]=N,p[j+3]=U,p[j+4]=z,p[j+5]=V}for(var Y=0;Y<m.length;Y++){var K=m[Y];u.copy(g.node.worldTransform).invert(),c.setFromTransformedAabb(f[K],u);for(var Z=c.getMin(),$=c.getMax(),Q=1<<Y,J=0;J<M;J++){var ee=6*J;p[ee]<=$.x&&p[ee+3]>=Z.x&&p[ee+1]<=$.y&&p[ee+4]>=Z.y&&p[ee+2]<=$.z&&p[ee+5]>=Z.z&&(d[J]|=Q,k=!0)}}if(k){for(var te={},ie=0;ie<M;ie++){var ne=3*ie+C,se=d[ie];te[se]||(te[se]=[]);var re=te[se];re.push(A[ne]),re.push(A[ne+1]),re.push(A[ne+2])}for(var ae in te){var oe=te[ae],he=new mr(t,T.format,oe.length,T.usage);(2===he.bytesPerIndex?new Uint16Array(he.lock()):new Uint32Array(he.lock())).set(oe),he.unlock();for(var le=Number.MAX_VALUE,ce=Number.MAX_VALUE,ue=Number.MAX_VALUE,de=-Number.MAX_VALUE,fe=-Number.MAX_VALUE,pe=-Number.MAX_VALUE,me=0;me<oe.length;me++){var _e=oe[me],ge=R[_e*P+I],ve=R[_e*P+I+1],xe=R[_e*P+I+2];ge<le&&(le=ge),ve<ce&&(ce=ve),xe<ue&&(ue=xe),ge>de&&(de=ge),ve>fe&&(fe=ve),xe>pe&&(pe=xe)}h.set(le,ce,ue),l.set(de,fe,pe);var be=new Oe;be.setMinMax(h,l);var Se=new ea(t);Se.vertexBuffer=w,Se.indexBuffer[0]=he,Se.primitive[0].type=4,Se.primitive[0].base=0,Se.primitive[0].count=oe.length,Se.primitive[0].indexed=!0,Se.aabb=be;var we=new ka(Se,g.material,g.node);we.isStatic=g.isStatic,we.visible=g.visible,we.layer=g.layer,we.castShadow=g.castShadow,we._receiveShadow=g._receiveShadow,we.cull=g.cull,we.pick=g.pick,we.mask=g.mask,we.parameters=g.parameters,we._shaderDefs=g._shaderDefs,we._staticSource=g,g._staticLightList?we._staticLightList=g._staticLightList:we._staticLightList=[];for(var Te=0;Te<m.length;Te++){if(ae&1<<Te){var Ae=s[m[Te]];we._staticLightList.indexOf(Ae)<0&&we._staticLightList.push(Ae)}}we._staticLightList.sort(e.lightCompare),o.push(we)}}else o.push(g)}else o.push(g)}n.length=o.length;for(var Me=0;Me<o.length;Me++)n[Me]=o[Me]},e.revert=function(e){for(var t,i=e,n=i.length,s=[],r=0;r<n;r++){var a=i[r];a._staticSource?a._staticSource!==t&&(s.push(a._staticSource),t=a._staticSource):s.push(a)}e.length=s.length;for(var o=0;o<s.length;o++)e[o]=s[o]},e}();new ye(1,1,1),new ye(40,0,0);var ko,Oo,Fo,Bo,No,Uo,zo,Vo,Go,Wo,Ho=new Ee,Xo=new Ee,qo=new xe,jo=new Ee,Yo=(new Ee).setScale(1,-1,1),Ko=new Ee,Zo=new Ee,$o=new ye,Qo=new ye,Jo=new ye,eh=new me(254/255,254/255,254/255,254/255),th=new Ne,ih=[0,0,0,0],nh=0,sh={drawCalls:[],isNewMaterial:[],lightMaskChanged:[]},rh=new Set,ah=function(){function e(e){this.clustersDebugRendered=!1,this.device=e,this.scene=null,this._shadowDrawCalls=0,this._forwardDrawCalls=0,this._skinDrawCalls=0,this._numDrawCallsCulled=0,this._instancedDrawCalls=0,this._camerasRendered=0,this._materialSwitches=0,this._shadowMapUpdates=0,this._shadowMapTime=0,this._depthMapTime=0,this._forwardTime=0,this._cullTime=0,this._sortTime=0,this._skinTime=0,this._morphTime=0,this._layerCompositionUpdateTime=0,this._lightClustersTime=0,this._lightClusters=0;var t=this.device;this.library=t.getProgramLibrary(),this.lightTextureAtlas=new _o(t),this._shadowRenderer=new Io(this,this.lightTextureAtlas),this._cookieRenderer=new ho(t,this.lightTextureAtlas);var i=t.scope;this.projId=i.resolve("matrix_projection"),this.projSkyboxId=i.resolve("matrix_projectionSkybox"),this.viewId=i.resolve("matrix_view"),this.viewId3=i.resolve("matrix_view3"),this.viewInvId=i.resolve("matrix_viewInverse"),this.viewProjId=i.resolve("matrix_viewProjection"),this.flipYId=i.resolve("projectionFlipY"),this.viewPos=new Float32Array(3),this.viewPosId=i.resolve("view_position"),this.nearClipId=i.resolve("camera_near"),this.farClipId=i.resolve("camera_far"),this.cameraParamsId=i.resolve("camera_params"),this.tbnBasis=i.resolve("tbnBasis"),this.fogColorId=i.resolve("fog_color"),this.fogStartId=i.resolve("fog_start"),this.fogEndId=i.resolve("fog_end"),this.fogDensityId=i.resolve("fog_density"),this.modelMatrixId=i.resolve("matrix_model"),this.normalMatrixId=i.resolve("matrix_normal"),this.poseMatrixId=i.resolve("matrix_pose[0]"),this.boneTextureId=i.resolve("texture_poseMap"),this.boneTextureSizeId=i.resolve("texture_poseMapSize"),this.morphWeightsA=i.resolve("morph_weights_a"),this.morphWeightsB=i.resolve("morph_weights_b"),this.morphPositionTex=i.resolve("morphPositionTex"),this.morphNormalTex=i.resolve("morphNormalTex"),this.morphTexParams=i.resolve("morph_tex_params"),this.alphaTestId=i.resolve("alpha_ref"),this.opacityMapId=i.resolve("texture_opacityMap"),this.ambientId=i.resolve("light_globalAmbient"),this.exposureId=i.resolve("exposure"),this.skyboxIntensityId=i.resolve("skyboxIntensity"),this.lightColorId=[],this.lightDir=[],this.lightDirId=[],this.lightShadowMapId=[],this.lightShadowMatrixId=[],this.lightShadowParamsId=[],this.lightShadowIntensity=[],this.lightRadiusId=[],this.lightPos=[],this.lightPosId=[],this.lightWidth=[],this.lightWidthId=[],this.lightHeight=[],this.lightHeightId=[],this.lightInAngleId=[],this.lightOutAngleId=[],this.lightCookieId=[],this.lightCookieIntId=[],this.lightCookieMatrixId=[],this.lightCookieOffsetId=[],this.shadowMatrixPaletteId=[],this.shadowCascadeDistancesId=[],this.shadowCascadeCountId=[],this.screenSizeId=i.resolve("uScreenSize"),this._screenSize=new Float32Array(4),this.twoSidedLightingNegScaleFactorId=i.resolve("twoSidedLightingNegScaleFactor"),this.fogColor=new Float32Array(3),this.ambientColor=new Float32Array(3),this.cameraParams=new Float32Array(4),this.viewUniformFormat=null,this.viewBindGroupFormat=null}var t=e.prototype;return t.destroy=function(){this._shadowRenderer.destroy(),this._shadowRenderer=null,this._cookieRenderer.destroy(),this._cookieRenderer=null,this.lightTextureAtlas.destroy(),this.lightTextureAtlas=null},t.sortCompare=function(e,t){if(e.layer===t.layer){if(e.drawOrder&&t.drawOrder)return e.drawOrder-t.drawOrder;if(e.zdist&&t.zdist)return t.zdist-e.zdist;if(e.zdist2&&t.zdist2)return e.zdist2-t.zdist2}return t._key[0]-e._key[0]},t.sortCompareMesh=function(e,t){if(e.layer===t.layer){if(e.drawOrder&&t.drawOrder)return e.drawOrder-t.drawOrder;if(e.zdist&&t.zdist)return t.zdist-e.zdist}return No=e._key[0],Uo=t._key[0],No===Uo&&e.mesh&&t.mesh?t.mesh.id-e.mesh.id:Uo-No},t.depthSortCompare=function(e,t){return No=e._key[1],Uo=t._key[1],No===Uo&&e.mesh&&t.mesh?t.mesh.id-e.mesh.id:Uo-No},t.updateCameraFrustum=function(e){if(e.xr&&e.xr.views.length){var t=e.xr.views[0];return jo.mul2(t.projMat,t.viewOffMat),void e.frustum.setFromMat4(jo)}if(ko=e.projectionMatrix,e.calculateProjection&&e.calculateProjection(ko,0),e.calculateTransform)e.calculateTransform(Ho,0);else{var i=e._node.getPosition(),n=e._node.getRotation();Ho.setTRS(i,n,ye.ONE),this.viewInvId.setValue(Ho.data)}Xo.copy(Ho).invert(),jo.mul2(ko,Xo),e.frustum.setFromMat4(jo)},t.initViewBindGroupFormat=function(){this.device.supportsUniformBuffers&&!this.viewUniformFormat&&(this.viewUniformFormat=new eo(this.device,[new Ja("matrix_viewProjection",14)]),this.viewBindGroupFormat=new no(this.device,[new to(ui,3)],[new io("lightsTextureFloat",2,ti,ni)]))},t.setCameraUniforms=function(e,t,i){var n,s=1;if(e.xr&&e.xr.session){var r=e._node.parent;r&&(n=r.getWorldTransform());var a=e.xr.views;s=a.length;for(var o=0;o<s;o++){var h=a[o];r?(h.viewInvOffMat.mul2(n,h.viewInvMat),h.viewOffMat.copy(h.viewInvOffMat).invert()):(h.viewInvOffMat.copy(h.viewInvMat),h.viewOffMat.copy(h.viewMat)),h.viewMat3.setFromMat4(h.viewOffMat),h.projViewOffMat.mul2(h.projMat,h.viewOffMat),h.position[0]=h.viewInvOffMat.data[12],h.position[1]=h.viewInvOffMat.data[13],h.position[2]=h.viewInvOffMat.data[14],e.frustum.setFromMat4(h.projViewOffMat)}}else{if(ko=e.projectionMatrix,e.calculateProjection&&e.calculateProjection(ko,0),this.projId.setValue(ko.data),this.projSkyboxId.setValue(e.getProjectionMatrixSkybox().data),e.calculateTransform)e.calculateTransform(Ho,0);else{var l=e._node.getPosition(),c=e._node.getRotation();Ho.setTRS(l,c,ye.ONE)}this.viewInvId.setValue(Ho.data),Xo.copy(Ho).invert(),this.viewId.setValue(Xo.data),qo.setFromMat4(Xo),this.viewId3.setValue(qo.data),jo.mul2(ko,Xo),t&&t.flipY?(Ko.mul2(Yo,jo),Zo.mul2(Yo,e.getProjectionMatrixSkybox()),this.viewProjId.setValue(Ko.data),this.projSkyboxId.setValue(Zo.data)):(this.viewProjId.setValue(jo.data),this.projSkyboxId.setValue(e.getProjectionMatrixSkybox().data)),this.flipYId.setValue(null!=t&&t.flipY?-1:1),this.dispatchViewPos(e._node.getPosition()),e.frustum.setFromMat4(jo)}this.tbnBasis.setValue(t&&t.flipY?-1:1),this.nearClipId.setValue(e._nearClip),this.farClipId.setValue(e._farClip),this.scene.physicalUnits?this.exposureId.setValue(e.getExposure()):this.exposureId.setValue(this.scene.exposure);var u=e._nearClip,d=e._farClip;this.cameraParams[0]=1/d,this.cameraParams[1]=d,this.cameraParams[2]=u,this.cameraParams[3]=1===e.projection?1:0,this.cameraParamsId.setValue(this.cameraParams),this.device.supportsUniformBuffers&&this.setupViewUniformBuffers(i,s)},t.setCamera=function(e,t,i,n){void 0===n&&(n=null),this.setCameraUniforms(e,t,n),this.clearView(e,t,i,!1)},t.setupViewUniformBuffers=function(e,t){if(e){for(var i=this.device;e.viewBindGroups.length<t;){var n=new Aa(i,this.viewUniformFormat),s=new wa(i,this.viewBindGroupFormat,n);e.viewBindGroups.push(s)}var r=e.viewBindGroups[0];r.defaultUniformBuffer.update(),r.update(),i.setBindGroup(0,r)}},t.setupViewport=function(e,t){var i=this.device,n=t?t.width:i.width,s=t?t.height:i.height,r=e.rect,a=Math.floor(r.x*n),o=Math.floor(r.y*s),h=Math.floor(r.z*n),l=Math.floor(r.w*s);if(i.setViewport(a,o,h,l),e._scissorRectClear){var c=e.scissorRect;a=Math.floor(c.x*n),o=Math.floor(c.y*s),h=Math.floor(c.z*n),l=Math.floor(c.w*s)}i.setScissor(a,o,h,l)},t.clear=function(e,t){this.device.clear({color:[t._clearColor.r,t._clearColor.g,t._clearColor.b,t._clearColor.a],depth:t._clearDepth,stencil:t._clearStencil,flags:(e.clearColor?1:0)|(e.clearDepth?2:0)|(e.clearStencil?4:0)})},t.clearView=function(e,t,i,n){var s=this.device;if(s.setRenderTarget(t),s.updateBegin(),n&&(s.setColorWrite(!0,!0,!0,!0),s.setDepthWrite(!0)),this.setupViewport(e,t),i){var r=e._clearOptions;s.clear(r||{color:[e._clearColor.r,e._clearColor.g,e._clearColor.b,e._clearColor.a],depth:e._clearDepth,flags:(e._clearColorBuffer?1:0)|(e._clearDepthBuffer?2:0)|(e._clearStencilBuffer?4:0),stencil:e._clearStencil})}},t.dispatchGlobalLights=function(e){if(this.ambientColor[0]=e.ambientLight.r,this.ambientColor[1]=e.ambientLight.g,this.ambientColor[2]=e.ambientLight.b,e.gammaCorrection)for(var t=0;t<3;t++)this.ambientColor[t]=Math.pow(this.ambientColor[t],2.2);if(e.physicalUnits)for(var i=0;i<3;i++)this.ambientColor[i]*=e.ambientLuminance;this.ambientId.setValue(this.ambientColor),e.sky&&this.skyboxIntensityId.setValue(e.physicalUnits?e.skyboxLuminance:e.skyboxIntensity)},t._resolveLight=function(e,t){var i="light"+t;this.lightColorId[t]=e.resolve(i+"_color"),this.lightDir[t]=new Float32Array(3),this.lightDirId[t]=e.resolve(i+"_direction"),this.lightShadowMapId[t]=e.resolve(i+"_shadowMap"),this.lightShadowMatrixId[t]=e.resolve(i+"_shadowMatrix"),this.lightShadowParamsId[t]=e.resolve(i+"_shadowParams"),this.lightShadowIntensity[t]=e.resolve(i+"_shadowIntensity"),this.lightRadiusId[t]=e.resolve(i+"_radius"),this.lightPos[t]=new Float32Array(3),this.lightPosId[t]=e.resolve(i+"_position"),this.lightWidth[t]=new Float32Array(3),this.lightWidthId[t]=e.resolve(i+"_halfWidth"),this.lightHeight[t]=new Float32Array(3),this.lightHeightId[t]=e.resolve(i+"_halfHeight"),this.lightInAngleId[t]=e.resolve(i+"_innerConeAngle"),this.lightOutAngleId[t]=e.resolve(i+"_outerConeAngle"),this.lightCookieId[t]=e.resolve(i+"_cookie"),this.lightCookieIntId[t]=e.resolve(i+"_cookieIntensity"),this.lightCookieMatrixId[t]=e.resolve(i+"_cookieMatrix"),this.lightCookieOffsetId[t]=e.resolve(i+"_cookieOffset"),this.shadowMatrixPaletteId[t]=e.resolve(i+"_shadowMatrixPalette[0]"),this.shadowCascadeDistancesId[t]=e.resolve(i+"_shadowCascadeDistances[0]"),this.shadowCascadeCountId[t]=e.resolve(i+"_shadowCascadeCount")},t.setLTCDirectionalLight=function(e,t,i,n,s){this.lightPos[t][0]=n.x-i.x*s,this.lightPos[t][1]=n.y-i.y*s,this.lightPos[t][2]=n.z-i.z*s,this.lightPosId[t].setValue(this.lightPos[t]);var r=e.transformVector(new ye(-.5,0,0));this.lightWidth[t][0]=r.x*s,this.lightWidth[t][1]=r.y*s,this.lightWidth[t][2]=r.z*s,this.lightWidthId[t].setValue(this.lightWidth[t]);var a=e.transformVector(new ye(0,0,.5));this.lightHeight[t][0]=a.x*s,this.lightHeight[t][1]=a.y*s,this.lightHeight[t][2]=a.z*s,this.lightHeightId[t].setValue(this.lightHeight[t])},t.dispatchDirectLights=function(e,t,i,n){for(var s=0,r=this.device.scope,a=0;a<e.length;a++)if(e[a].mask&i){var o=e[a],h=o._node.getWorldTransform();if(this.lightColorId[s]||this._resolveLight(r,s),this.lightColorId[s].setValue(t.gammaCorrection?o._linearFinalColor:o._finalColor),h.getY(o._direction).mulScalar(-1),o._direction.normalize(),this.lightDir[s][0]=o._direction.x,this.lightDir[s][1]=o._direction.y,this.lightDir[s][2]=o._direction.z,this.lightDirId[s].setValue(this.lightDir[s]),0!==o.shape&&this.setLTCDirectionalLight(h,s,o._direction,n._node.getPosition(),n.farClip),o.castShadows){var l=o.getRenderData(n,0),c=o._getUniformBiasValues(l);this.lightShadowMapId[s].setValue(l.shadowBuffer),this.lightShadowMatrixId[s].setValue(l.shadowMatrix.data),this.shadowMatrixPaletteId[s].setValue(o._shadowMatrixPalette),this.shadowCascadeDistancesId[s].setValue(o._shadowCascadeDistances),this.shadowCascadeCountId[s].setValue(o.numCascades),this.lightShadowIntensity[s].setValue(o.shadowIntensity);var u=o._shadowRenderParams;u.length=3,u[0]=o._shadowResolution,u[1]=c.normalBias,u[2]=c.bias,this.lightShadowParamsId[s].setValue(u)}s++}return s},t.setLTCPositionalLight=function(e,t){var i=e.transformVector(new ye(-.5,0,0));this.lightWidth[t][0]=i.x,this.lightWidth[t][1]=i.y,this.lightWidth[t][2]=i.z,this.lightWidthId[t].setValue(this.lightWidth[t]);var n=e.transformVector(new ye(0,0,.5));this.lightHeight[t][0]=n.x,this.lightHeight[t][1]=n.y,this.lightHeight[t][2]=n.z,this.lightHeightId[t].setValue(this.lightHeight[t])},t.dispatchOmniLight=function(e,t,i,n){var s=i._node.getWorldTransform();if(this.lightColorId[n]||this._resolveLight(t,n),this.lightRadiusId[n].setValue(i.attenuationEnd),this.lightColorId[n].setValue(e.gammaCorrection?i._linearFinalColor:i._finalColor),s.getTranslation(i._position),this.lightPos[n][0]=i._position.x,this.lightPos[n][1]=i._position.y,this.lightPos[n][2]=i._position.z,this.lightPosId[n].setValue(this.lightPos[n]),0!==i.shape&&this.setLTCPositionalLight(s,n),i.castShadows){var r=i.getRenderData(null,0);this.lightShadowMapId[n].setValue(r.shadowBuffer);var a=i._getUniformBiasValues(r),o=i._shadowRenderParams;o.length=4,o[0]=i._shadowResolution,o[1]=a.normalBias,o[2]=a.bias,o[3]=1/i.attenuationEnd,this.lightShadowParamsId[n].setValue(o),this.lightShadowIntensity[n].setValue(i.shadowIntensity)}i._cookie&&(this.lightCookieId[n].setValue(i._cookie),this.lightShadowMatrixId[n].setValue(s.data),this.lightCookieIntId[n].setValue(i.cookieIntensity))},t.dispatchSpotLight=function(e,t,i,n){var s=i._node.getWorldTransform();if(this.lightColorId[n]||this._resolveLight(t,n),this.lightInAngleId[n].setValue(i._innerConeAngleCos),this.lightOutAngleId[n].setValue(i._outerConeAngleCos),this.lightRadiusId[n].setValue(i.attenuationEnd),this.lightColorId[n].setValue(e.gammaCorrection?i._linearFinalColor:i._finalColor),s.getTranslation(i._position),this.lightPos[n][0]=i._position.x,this.lightPos[n][1]=i._position.y,this.lightPos[n][2]=i._position.z,this.lightPosId[n].setValue(this.lightPos[n]),0!==i.shape&&this.setLTCPositionalLight(s,n),s.getY(i._direction).mulScalar(-1),i._direction.normalize(),this.lightDir[n][0]=i._direction.x,this.lightDir[n][1]=i._direction.y,this.lightDir[n][2]=i._direction.z,this.lightDirId[n].setValue(this.lightDir[n]),i.castShadows){var r=i.getRenderData(null,0);this.lightShadowMapId[n].setValue(r.shadowBuffer),this.lightShadowMatrixId[n].setValue(r.shadowMatrix.data);var a=i._getUniformBiasValues(r),o=i._shadowRenderParams;o.length=4,o[0]=i._shadowResolution,o[1]=a.normalBias,o[2]=a.bias,o[3]=1/i.attenuationEnd,this.lightShadowParamsId[n].setValue(o),this.lightShadowIntensity[n].setValue(i.shadowIntensity)}if(i._cookie){if(!i.castShadows){var h=Yn.evalSpotCookieMatrix(i);this.lightShadowMatrixId[n].setValue(h.data)}this.lightCookieId[n].setValue(i._cookie),this.lightCookieIntId[n].setValue(i.cookieIntensity),i._cookieTransform&&(i._cookieTransformUniform[0]=i._cookieTransform.x,i._cookieTransformUniform[1]=i._cookieTransform.y,i._cookieTransformUniform[2]=i._cookieTransform.z,i._cookieTransformUniform[3]=i._cookieTransform.w,this.lightCookieMatrixId[n].setValue(i._cookieTransformUniform),i._cookieOffsetUniform[0]=i._cookieOffset.x,i._cookieOffsetUniform[1]=i._cookieOffset.y,this.lightCookieOffsetId[n].setValue(i._cookieOffsetUniform))}},t.dispatchLocalLights=function(e,t,i,n,s){for(var r=n,a=this.device.scope,o=e[1],h=o.length,l=0;l<h;l++){var c=o[l];c.mask&i&&(c.isStatic||(this.dispatchOmniLight(t,a,c,r),r++))}var u=0;if(s)for(var d=s[u];d&&1===d._type;)this.dispatchOmniLight(t,a,d,r),r++,d=s[++u];for(var f=e[2],p=f.length,m=0;m<p;m++){var _=f[m];_.mask&i&&(_.isStatic||(this.dispatchSpotLight(t,a,_,r),r++))}if(s)for(var g=s[u];g&&2===g._type;)this.dispatchSpotLight(t,a,g,r),r++,g=s[++u]},t.cull=function(e,t,i){var n=0,s=t.length,r=e.cullingMask||4294967295;if(!e.frustumCulling){for(var a=0;a<s;a++){var o=t[a];(o.visible||o.command)&&(o.mask&&0==(o.mask&r)||(i[n]=o,n++,o.visibleThisFrame=!0))}return n}for(var h=0;h<s;h++){var l=t[h];if(l.command)i[n]=l,n++,l.visibleThisFrame=!0;else{if(!l.visible)continue;var c=!0;if(l.mask&&0==(l.mask&r))continue;l.cull&&(c=l._isVisible(e)),c&&(i[n]=l,n++,l.visibleThisFrame=!0)}}return n},t.cullLights=function(e,t){for(var i=this.scene.clusteredLightingEnabled,n=this.scene.physicalUnits,s=0;s<t.length;s++){var r=t[s];if(r.enabled)if(0!==r._type)if(r.getBoundingSphere(th),e.frustum.containsSphere(th)){r.visibleThisFrame=!0,r.usePhysicalUnits=n;var a=e.getScreenSize(th);r.maxScreenSize=Math.max(r.maxScreenSize,a)}else i||r.castShadows&&!r.shadowMap&&(r.visibleThisFrame=!0);else r.usePhysicalUnits=this.scene.physicalUnits}},t.updateCpuSkinMatrices=function(e){nh++;var t=e.length;if(0!==t)for(var i=0;i<t;i++){var n=e[i].skinInstance;n&&(n.updateMatrices(e[i].node,nh),n._dirty=!0)}},t.updateGpuSkinMatrices=function(e){for(var t=e.length,i=0;i<t;i++)if(e[i].visibleThisFrame){var n=e[i].skinInstance;n&&n._dirty&&(n.updateMatrixPalette(e[i].node,nh),n._dirty=!1)}},t.updateMorphing=function(e){for(var t=e.length,i=0;i<t;i++){var n=e[i].morphInstance;n&&n._dirty&&e[i].visibleThisFrame&&n.update()}},t.setBaseConstants=function(e,t){e.setCullMode(t.cull),t.opacityMap&&(this.opacityMapId.setValue(t.opacityMap),this.alphaTestId.setValue(t.alphaTest))},t.setSkinning=function(e,t,i){t.skinInstance&&(this._skinDrawCalls++,e.supportsBoneTextures?(Oo=t.skinInstance.boneTexture,this.boneTextureId.setValue(Oo),ih[0]=Oo.width,ih[1]=Oo.height,ih[2]=1/Oo.width,ih[3]=1/Oo.height,this.boneTextureSizeId.setValue(ih)):this.poseMatrixId.setValue(t.skinInstance.matrixPalette))},t.drawInstance=function(e,t,i,n,s){(Fo=t.instancingData)?Fo.count>0&&(this._instancedDrawCalls++,e.setVertexBuffer(Fo.vertexBuffer),e.draw(i.primitive[n],Fo.count)):(Bo=t.node.worldTransform,this.modelMatrixId.setValue(Bo.data),s&&this.normalMatrixId.setValue(t.node.normalMatrix.data),e.draw(i.primitive[n]))},t.drawInstance2=function(e,t,i,n){(Fo=t.instancingData)?Fo.count>0&&(this._instancedDrawCalls++,e.draw(i.primitive[n],Fo.count,!0)):e.draw(i.primitive[n],void 0,!0)},t.renderShadows=function(e,t){for(var i=this.scene.clusteredLightingEnabled,n=0;n<e.length;n++){var s=e[n];if(i&&0!==s._type){if(!s.atlasViewportAllocated)continue;s.atlasSlotUpdated&&0===s.shadowUpdateMode&&(s.shadowUpdateMode=1)}this._shadowRenderer.render(s,t)}},t.renderCookies=function(e){for(var t=this.lightTextureAtlas.cookieRenderTarget,i=0;i<e.length;i++){var n=e[i];n.atlasViewportAllocated&&(n.atlasSlotUpdated&&this._cookieRenderer.render(n,t))}},t.setCullMode=function(e,t,i){var n=i.material,s=0;if(e){var r=1;if(n.cull>0&&n.cull<3){i.flipFaces&&(r*=-1),t&&(r*=-1);var a=i.node.worldTransform;a.getX($o),a.getY(Qo),a.getZ(Jo),$o.cross($o,Qo),$o.dot(Jo)<0&&(r*=-1)}s=r<0?2===n.cull?1:2:n.cull}if(this.device.setCullMode(s),0===s&&0===n.cull){var o=i.node.worldTransform;o.getX($o),o.getY(Qo),o.getZ(Jo),$o.cross($o,Qo),$o.dot(Jo)<0?this.twoSidedLightingNegScaleFactorId.setValue(-1):this.twoSidedLightingNegScaleFactorId.setValue(1)}},t.setVertexBuffers=function(e,t){e.setVertexBuffer(t.vertexBuffer)},t.setMorphing=function(e,t){if(t)if(t.morph.useTextureMorph)e.setVertexBuffer(t.morph.vertexBufferIds),this.morphPositionTex.setValue(t.texturePositions),this.morphNormalTex.setValue(t.textureNormals),this.morphTexParams.setValue(t._textureParams);else{for(var i=0;i<t._activeVertexBuffers.length;i++){var n=t._activeVertexBuffers[i];if(n){var s=Dt+(i+8);n.format.elements[0].name=s,n.format.elements[0].scopeId=e.scope.resolve(s),n.format.update(),e.setVertexBuffer(n)}}this.morphWeightsA.setValue(t._shaderMorphWeightsA),this.morphWeightsB.setValue(t._shaderMorphWeightsB)}},t.dispatchViewPos=function(e){var t=this.viewPos;t[0]=e.x,t[1]=e.y,t[2]=e.z,this.viewPosId.setValue(t)},t.renderForwardPrepareMaterials=function(e,t,i,n,s,r,a){var o=function(e,t,i){sh.drawCalls.push(e),sh.isNewMaterial.push(t),sh.lightMaskChanged.push(i)};sh.drawCalls.length=0,sh.isNewMaterial.length=0,sh.lightMaskChanged.length=0;for(var h,l,c,u=this.device,d=this.scene,f=r?r._lightHash:0,p=null,m=0;m<i;m++){var _=t[m];if(!s||!_.mask||s&_.mask)if(_.command)o(_,!1,!1);else{_.ensureMaterial(u);var g=_.material,v=_._shaderDefs,y=_.mask;if(g&&g===p&&v!==h&&(p=null),(_.isStatic||l)&&(p=null),g!==p&&(this._materialSwitches++,g._scene=d,g.dirty&&(g.updateUniforms(u,d),g.dirty=!1),g._dirtyBlend&&(d.layers._dirtyBlend=!0),!_._shader[a]||_._shaderDefs!==v||_._lightHash!==f)){if(_.isStatic)_.updatePassShader(d,a,_._staticLightList,n,this.viewUniformFormat,this.viewBindGroupFormat);else{var x=a+"_"+v+"_"+f;_._shader[a]=g.variants[x],_._shader[a]||(_.updatePassShader(d,a,null,n,this.viewUniformFormat,this.viewBindGroupFormat),g.variants[x]=_._shader[a])}_._lightHash=f}o(_,g!==p,!p||y!==c),p=g,h=v,c=y,l=_.isStatic}}return sh},t.renderForwardInternal=function(e,t,i,n,s,r){for(var a=this.device,o=a.supportsUniformBuffers,h=this.scene,l=1<<n,c=t.drawCalls.length,u=0;u<c;u++){var d=t.drawCalls[u];if(d.command)d.command();else{var f=t.isNewMaterial[u],p=t.lightMaskChanged[u],m=d.material;d._shaderDefs;var _=d.mask;if(f){var g=d._shader[n];if(!g.failed&&a.setShader(g),m.setParameters(a),p){var v=this.dispatchDirectLights(i[0],h,_,e);this.dispatchLocalLights(i,h,_,v,d._staticLightList)}this.alphaTestId.setValue(m.alphaTest),a.setBlending(m.blend),m.blend&&(m.separateAlphaBlend?(a.setBlendFunctionSeparate(m.blendSrc,m.blendDst,m.blendSrcAlpha,m.blendDstAlpha),a.setBlendEquationSeparate(m.blendEquation,m.blendAlphaEquation)):(a.setBlendFunction(m.blendSrc,m.blendDst),a.setBlendEquation(m.blendEquation))),a.setColorWrite(m.redWrite,m.greenWrite,m.blueWrite,m.alphaWrite),a.setDepthWrite(m.depthWrite),m.depthWrite&&!m.depthTest?(a.setDepthFunc(7),a.setDepthTest(!0)):(a.setDepthFunc(m.depthFunc),a.setDepthTest(m.depthTest)),a.setAlphaToCoverage(m.alphaToCoverage),m.depthBias||m.slopeDepthBias?(a.setDepthBias(!0),a.setDepthBiasValues(m.depthBias,m.slopeDepthBias)):a.setDepthBias(!1)}this.setCullMode(e._cullFaces,r,d);var y=d.stencilFront||m.stencilFront,x=d.stencilBack||m.stencilBack;y||x?(a.setStencilTest(!0),y===x?(a.setStencilFunc(y.func,y.ref,y.readMask),a.setStencilOperation(y.fail,y.zfail,y.zpass,y.writeMask)):(y?(a.setStencilFuncFront(y.func,y.ref,y.readMask),a.setStencilOperationFront(y.fail,y.zfail,y.zpass,y.writeMask)):(a.setStencilFuncFront(7,0,255),a.setStencilOperationFront(0,0,0,255)),x?(a.setStencilFuncBack(x.func,x.ref,x.readMask),a.setStencilOperationBack(x.fail,x.zfail,x.zpass,x.writeMask)):(a.setStencilFuncBack(7,0,255),a.setStencilOperationBack(0,0,0,255)))):a.setStencilTest(!1);var b=d.mesh;if(d.setParameters(a,l),this.setVertexBuffers(a,b),this.setMorphing(a,d.morphInstance),this.setSkinning(a,d,m),o){this.modelMatrixId.setValue(d.node.worldTransform.data),this.normalMatrixId.setValue(d.node.normalMatrix.data);var S=d.getBindGroup(a,n);S.defaultUniformBuffer.update(),S.update(),a.setBindGroup(1,S)}var w=d.renderStyle;if(a.setIndexBuffer(b.indexBuffer[w]),s&&s(d,u),e.xr&&e.xr.session&&e.xr.views.length)for(var T=e.xr.views,A=0;A<T.length;A++){var M=T[A];a.setViewport(M.viewport.x,M.viewport.y,M.viewport.z,M.viewport.w),this.projId.setValue(M.projMat.data),this.projSkyboxId.setValue(M.projMat.data),this.viewId.setValue(M.viewOffMat.data),this.viewInvId.setValue(M.viewInvOffMat.data),this.viewId3.setValue(M.viewMat3.data),this.viewProjId.setValue(M.projViewOffMat.data),this.viewPosId.setValue(M.position),0===A?this.drawInstance(a,d,b,w,!0):this.drawInstance2(a,d,b,w),this._forwardDrawCalls++}else this.drawInstance(a,d,b,w,!0),this._forwardDrawCalls++;u<c-1&&!t.isNewMaterial[u+1]&&m.setParameters(a,d.parameters)}}},t.renderForward=function(e,t,i,n,s,r,a,o,h){var l=this.renderForwardPrepareMaterials(e,t,i,n,r,o,s);this.renderForwardInternal(e,l,n,s,a,h),sh.length=0},t.updateShaders=function(e,t){for(var i=e.length,n=0;n<i;n++){var s=e[n].material;if(s&&!rh.has(s)&&(rh.add(s),s.getShaderVariant!==Bs.prototype.getShaderVariant)){if(t&&(!s.useLighting||s.emitter&&!s.emitter.lighting))continue;s.clearVariants()}}rh.clear()},t.beginFrame=function(e,t){var i=e._meshInstances,n=this.scene;if(n.updateShaders||t){var s=!n.updateShaders&&t;this.updateShaders(i,s),n.updateShaders=!1,n._shaderVersion++}this.updateCpuSkinMatrices(i);for(var r=i.length,a=0;a<r;a++)i[a].visibleThisFrame=!1;for(var o=e._lights,h=o.length,l=0;l<h;l++)o[l].beginFrame()},t.updateLayerComposition=function(e,t){for(var i=e.layerList.length,n=0;n<i;n++)e.layerList[n]._postRenderCounter=0;for(var s=this.scene,r=s._shaderVersion,a=0;a<i;a++){var o=e.layerList[a];o._shaderVersion=r,o._preRenderCalledForCameras=0,o._postRenderCalledForCameras=0;var h=e.subLayerList[a];o._postRenderCounter|=h?2:1,o._postRenderCounterMax=o._postRenderCounter;for(var l=0;l<o.cameras.length;l++)o.instances.prepare(l);o._needsStaticPrepare&&o._staticLightHash&&!this.scene.clusteredLightingEnabled&&(o._staticPrepareDone&&(Do.revert(o.opaqueMeshInstances),Do.revert(o.transparentMeshInstances)),Do.prepare(this.device,s,o.opaqueMeshInstances,o._lights),Do.prepare(this.device,s,o.transparentMeshInstances,o._lights),e._dirty=!0,s.updateShaders=!0,o._needsStaticPrepare=!1,o._staticPrepareDone=!0)}return e._update(this.device,t)},t.gpuUpdate=function(e){this.updateGpuSkinMatrices(e),this.updateMorphing(e)},t.setSceneConstants=function(){var e=this.scene;if(this.dispatchGlobalLights(e),e.fog!==Ue){if(this.fogColor[0]=e.fogColor.r,this.fogColor[1]=e.fogColor.g,this.fogColor[2]=e.fogColor.b,e.gammaCorrection)for(var t=0;t<3;t++)this.fogColor[t]=Math.pow(this.fogColor[t],2.2);this.fogColorId.setValue(this.fogColor),e.fog===ze?(this.fogStartId.setValue(e.fogStart),this.fogEndId.setValue(e.fogEnd)):this.fogDensityId.setValue(e.fogDensity)}var i=this.device;this._screenSize[0]=i.width,this._screenSize[1]=i.height,this._screenSize[2]=1/i.width,this._screenSize[3]=1/i.height,this.screenSizeId.setValue(this._screenSize)},t.updateLightStats=function(e,t){},t.cullShadowmaps=function(e){for(var t=0;t<e._lights.length;t++){var i=e._lights[t];if(0!==i._type&&i.visibleThisFrame&&i.castShadows&&0!==i.shadowUpdateMode){var n=e._lightCompositionData[t].shadowCastersList;this._shadowRenderer.cullLocal(i,n)}}for(var s=e._renderActions,r=0;r<s.length;r++)for(var a=s[r],o=a.directionalLightsIndices.length,h=0;h<o;h++){var l=a.directionalLightsIndices[h],c=e._lights[l],u=e._lightCompositionData[l].shadowCastersList;this._shadowRenderer.cullDirectional(c,u,a.camera.camera)}},t.cullComposition=function(e){for(var t=e._renderActions,i=0;i<t.length;i++){var n=t[i],s=n.layerIndex,r=e.layerList[s];if(r.enabled&&e.subLayerEnabled[s]){var a=e.subLayerList[s],o=n.cameraIndex,h=r.cameras[o];if(h){h.frameUpdate(n.renderTarget),n.firstCameraUse&&(this.updateCameraFrustum(h.camera),this._camerasRendered++),this.cullLights(h.camera,r._lights);var l=r.instances,c=a?l.visibleTransparent[o]:l.visibleOpaque[o];if(!c.done){r.onPreCull&&r.onPreCull(o);var u=a?r.transparentMeshInstances:r.opaqueMeshInstances;c.length=this.cull(h.camera,u,c.list),c.done=!0,r.onPostCull&&r.onPostCull(o)}}}}this.cullShadowmaps(e)},t.updateLightTextureAtlas=function(e){this.lightTextureAtlas.update(e._splitLights[2],e._splitLights[1],this.scene.lighting)},t.updateClusters=function(e){for(var t=0;t<e._worldClusters.length;t++){e._worldClusters[t].update(e._lights,this.scene.gammaCorrection,this.scene.lighting)}},t.buildFrameGraph=function(e,t){var i=this;e.reset(),this.update(t);var n=this.scene.clusteredLightingEnabled;if(n){this.updateLightTextureAtlas(t);var s=new ao(this.device,(function(){i.scene.lighting.cookiesEnabled&&(i.renderCookies(t._splitLights[2]),i.renderCookies(t._splitLights[1]))}));s.requiresCubemaps=!1,e.addRenderPass(s)}var r=new ao(this.device,(function(){(!n||n&&i.scene.lighting.shadowsEnabled)&&(i.renderShadows(t._splitLights[2]),i.renderShadows(t._splitLights[1])),n&&i.updateClusters(t)}));r.requiresCubemaps=!1,e.addRenderPass(r);for(var a=0,o=!0,h=null,l=t._renderActions,c=function(n){var s=l[n],r=t.layerList[s.layerIndex],c=r.cameras[s.cameraIndex];if(!s.isLayerEnabled(t))return"continue";var u=1===r.id&&(c.renderSceneColorMap||c.renderSceneDepthMap);if(s.hasDirectionalShadowLights&&c){var d=new ao(i.device,(function(){i.renderPassDirectionalShadows(s,t)}));d.requiresCubemaps=!1,e.addRenderPass(d)}o&&(o=!1,a=n,h=s.renderTarget);for(var f=n+1;l[f]&&!l[f].isLayerEnabled(t);)f++;var p=l[f],m=!!p&&1===t.layerList[p.layerIndex].id&&(c.renderSceneColorMap||c.renderSceneDepthMap);if(!p||p.renderTarget!==h||p.hasDirectionalShadowLights||m||u){if(i.addMainRenderPass(e,t,h,a,n,u),s.triggerPostprocess&&null!=c&&c.onPostprocessing){var _=new ao(i.device,(function(){i.renderPassPostprocessing(s,t)}));_.requiresCubemaps=!1,e.addRenderPass(_)}o=!0}},u=a;u<l.length;u++)c(u)},t.addMainRenderPass=function(e,t,i,n,s,r){var a=this,o={start:n,end:s},h=new ao(this.device,(function(){a.renderPassRenderActions(t,o)})),l=t._renderActions[n],c=t.layerList[l.layerIndex].cameras[l.cameraIndex],u=r&&!this.device.webgl2&&c.renderSceneDepthMap;(!r||u)&&(h.init(i),h.fullSizeClearRect=c.camera.fullSizeClearRect,u?(h.setClearColor(eh),h.setClearDepth(1)):h.fullSizeClearRect&&(l.clearColor&&h.setClearColor(c.camera.clearColor),l.clearDepth&&h.setClearDepth(c.camera.clearDepth),l.clearStencil&&h.setClearStencil(c.camera.clearStencil))),e.addRenderPass(h)},t.update=function(e){var t=this.scene.clusteredLightingEnabled;this.clustersDebugRendered=!1,this.initViewBindGroupFormat(),this.scene._updateSky(this.device);var i=this.updateLayerComposition(e,t),n=0!=(2&i);this.updateLightStats(e,i),this.beginFrame(e,n),this.setSceneConstants(),this.cullComposition(e),this.gpuUpdate(e._meshInstances)},t.renderPassDirectionalShadows=function(e,t){var i=t.layerList[e.layerIndex].cameras[e.cameraIndex];this.renderShadows(e.directionalLights,i.camera)},t.renderPassPostprocessing=function(e,t){t.layerList[e.layerIndex].cameras[e.cameraIndex].onPostprocessing()},t.renderPassRenderActions=function(e,t){for(var i=e._renderActions,n=t.start;n<=t.end;n++)this.renderRenderAction(e,i[n],n===t.start)},t.renderRenderAction=function(e,t,i){var n=this.scene.clusteredLightingEnabled,s=this.device,r=t.layerIndex,a=e.layerList[r],o=e.subLayerList[r],h=t.cameraIndex,l=a.cameras[h];if(t.isLayerEnabled(e)){if(l&&t.firstCameraUse&&l.onPreRender&&l.onPreRender(),!o&&a.onPreRenderOpaque?a.onPreRenderOpaque(h):o&&a.onPreRenderTransparent&&a.onPreRenderTransparent(h),a._preRenderCalledForCameras&1<<h||(a.onPreRender&&a.onPreRender(h),a._preRenderCalledForCameras|=1<<h),l){var c;this.setupViewport(l.camera,t.renderTarget),i&&l.camera.fullSizeClearRect||this.clear(t,l.camera),a._sortVisible(o,l.camera.node,h);var u=a.instances,d=o?u.visibleTransparent[h]:u.visibleOpaque[h];this.scene.immediate.onPreRenderLayer(a,d,o),n&&t.lightClusters&&(t.lightClusters.activate(this.lightTextureAtlas),this.clustersDebugRendered||this.scene.lighting.debugLayer!==a.id||(this.clustersDebugRendered=!0)),this.scene._activeCamera=l.camera,this.setCameraUniforms(l.camera,t.renderTarget,t);var f=!!(l.camera._flipFaces^(null==t||null==(c=t.renderTarget)?void 0:c.flipY)),p=this._forwardDrawCalls;this.renderForward(l.camera,d.list,d.length,a._splitLights,a.shaderPass,a.cullingMask,a.onDrawCall,a,f),a._forwardDrawCalls+=this._forwardDrawCalls-p,s.setColorWrite(!0,!0,!0,!0),s.setStencilTest(!1),s.setAlphaToCoverage(!1),s.setDepthBias(!1),t.lastCameraUse&&l.onPostRender&&l.onPostRender()}!o&&a.onPostRenderOpaque?a.onPostRenderOpaque(h):o&&a.onPostRenderTransparent&&a.onPostRenderTransparent(h),!a.onPostRender||a._postRenderCalledForCameras&1<<h||(a._postRenderCounter&=~(o?2:1),0===a._postRenderCounter&&(a.onPostRender(h),a._postRenderCalledForCameras|=1<<h,a._postRenderCounter=a._postRenderCounterMax))}},e}();var oh=[null,function(e,t){return e.drawOrder-t.drawOrder},function(e,t){return zo=e._key[0],Vo=t._key[0],zo===Vo&&e.mesh&&t.mesh?t.mesh.id-e.mesh.id:Vo-zo},function(e,t){return t.zdist-e.zdist},function(e,t){return e.zdist-t.zdist}];function hh(e,t){return t.key-e.key}var lh,ch=0,uh=function(){this.list=[],this.length=0,this.done=!1},dh=function(){function e(){this.opaqueMeshInstances=[],this.transparentMeshInstances=[],this.shadowCasters=[],this.visibleOpaque=[],this.visibleTransparent=[]}var t=e.prototype;return t.prepare=function(e){this.visibleOpaque[e]||(this.visibleOpaque[e]=new uh),this.visibleTransparent[e]||(this.visibleTransparent[e]=new uh),this.visibleOpaque[e].done=!1,this.visibleTransparent[e].done=!1},t.delete=function(e){e<this.visibleOpaque.length&&this.visibleOpaque.splice(e,1),e<this.visibleTransparent.length&&this.visibleTransparent.splice(e,1)},e}(),fh=function(){function e(e){void 0===e&&(e={}),void 0!==e.id?(this.id=e.id,ch=Math.max(this.id+1,ch)):this.id=ch++,this.name=e.name,this._enabled=void 0===e.enabled||e.enabled,this._refCounter=this._enabled?1:0,this.opaqueSortMode=void 0===e.opaqueSortMode?2:e.opaqueSortMode,this.transparentSortMode=void 0===e.transparentSortMode?3:e.transparentSortMode,e.renderTarget&&(this.renderTarget=e.renderTarget),this.shaderPass=void 0===e.shaderPass?0:e.shaderPass,this.passThrough=void 0!==e.passThrough&&e.passThrough,this._clearColorBuffer=!!e.clearColorBuffer,this._clearDepthBuffer=!!e.clearDepthBuffer,this._clearStencilBuffer=!!e.clearStencilBuffer,this.onPreCull=e.onPreCull,this.onPreRender=e.onPreRender,this.onPreRenderOpaque=e.onPreRenderOpaque,this.onPreRenderTransparent=e.onPreRenderTransparent,this.onPostCull=e.onPostCull,this.onPostRender=e.onPostRender,this.onPostRenderOpaque=e.onPostRenderOpaque,this.onPostRenderTransparent=e.onPostRenderTransparent,this.onDrawCall=e.onDrawCall,this.onEnable=e.onEnable,this.onDisable=e.onDisable,this._enabled&&this.onEnable&&this.onEnable(),this.layerReference=e.layerReference,this.instances=e.layerReference?e.layerReference.instances:new dh,this.cullingMask=e.cullingMask?e.cullingMask:4294967295,this.opaqueMeshInstances=this.instances.opaqueMeshInstances,this.transparentMeshInstances=this.instances.transparentMeshInstances,this.shadowCasters=this.instances.shadowCasters,this.customSortCallback=null,this.customCalculateSortValues=null,this._lights=[],this._lightsSet=new Set,this._clusteredLightsSet=new Set,this._splitLights=[[],[],[]],this.cameras=[],this._dirty=!1,this._dirtyLights=!1,this._dirtyCameras=!1,this._lightHash=0,this._staticLightHash=0,this._needsStaticPrepare=!0,this._staticPrepareDone=!1,this._shaderVersion=-1,this._lightCube=null}var t=e.prototype;return t.incrementCounter=function(){0===this._refCounter&&(this._enabled=!0,this.onEnable&&this.onEnable()),this._refCounter++},t.decrementCounter=function(){if(1===this._refCounter)this._enabled=!1,this.onDisable&&this.onDisable();else if(0===this._refCounter)return;this._refCounter--},t.addMeshInstances=function(e,t){for(var i=this._shaderVersion,n=this.shadowCasters,s=0;s<e.length;s++){var r=e[s],a=r.material,o=3===a.blendType?this.opaqueMeshInstances:this.transparentMeshInstances;this.opaqueMeshInstances.indexOf(r)<0&&this.transparentMeshInstances.indexOf(r)<0&&o.push(r),!t&&r.castShadow&&n.indexOf(r)<0&&n.push(r),!this.passThrough&&i>=0&&a._shaderVersion!==i&&(a.getShaderVariant!==Bs.prototype.getShaderVariant&&a.clearVariants(),a._shaderVersion=i)}this.passThrough||(this._dirty=!0)},t.removeMeshInstanceFromArray=function(e,t){for(var i=-1,n=0,s=t.length,r=0;r<s;r++){var a=t[r];if(a===e){i=r,n=1;break}if(a._staticSource===e)i<0&&(i=r),n++;else if(i>=0)break}i>=0&&t.splice(i,n)},t.removeMeshInstances=function(e,t){for(var i=this.opaqueMeshInstances,n=this.transparentMeshInstances,s=this.shadowCasters,r=0;r<e.length;r++){var a=e[r];if(this.removeMeshInstanceFromArray(a,i),this.removeMeshInstanceFromArray(a,n),!t){var o=s.indexOf(a);o>=0&&s.splice(o,1)}}this._dirty=!0},t.clearMeshInstances=function(e){(0!==this.opaqueMeshInstances.length||0!==this.transparentMeshInstances.length||!e&&0!==this.shadowCasters.length)&&(this.opaqueMeshInstances.length=0,this.transparentMeshInstances.length=0,e||(this.shadowCasters.length=0),this.passThrough||(this._dirty=!0))},t.addLight=function(e){var t=e.light;this._lightsSet.has(t)||(this._lightsSet.add(t),0!==t.type&&this._clusteredLightsSet.add(t),this._lights.push(t),this._dirtyLights=!0,this._generateLightHash())},t.removeLight=function(e){var t=e.light;this._lightsSet.has(t)&&(this._lightsSet.delete(t),0!==t.type&&this._clusteredLightsSet.delete(t),this._lights.splice(this._lights.indexOf(t),1),this._dirtyLights=!0,this._generateLightHash())},t.clearLights=function(){this._lightsSet.clear(),this._clusteredLightsSet.clear(),this._lights.length=0,this._dirtyLights=!0},t.addShadowCasters=function(e){for(var t=this.shadowCasters,i=0;i<e.length;i++){var n=e[i];n.castShadow&&(t.indexOf(n)<0&&t.push(n))}this._dirtyLights=!0},t.removeShadowCasters=function(e){for(var t=this.shadowCasters,i=0;i<e.length;i++){var n=t.indexOf(e[i]);n>=0&&t.splice(n,1)}this._dirtyLights=!0},t._generateLightHash=function(){if(this._lights.length>0){this._lights.sort(hh);for(var e="",t="",i=0;i<this._lights.length;i++)this._lights[i].isStatic?t+=this._lights[i].key:e+=this._lights[i].key;0===e.length?this._lightHash=0:this._lightHash=wi(e),0===t.length?this._staticLightHash=0:this._staticLightHash=wi(t)}else this._lightHash=0,this._staticLightHash=0},t.addCamera=function(e){this.cameras.indexOf(e)>=0||(this.cameras.push(e),this._dirtyCameras=!0)},t.removeCamera=function(e){var t=this.cameras.indexOf(e);t>=0&&(this.cameras.splice(t,1),this._dirtyCameras=!0,this.instances.delete(t))},t.clearCameras=function(){this.cameras.length=0,this._dirtyCameras=!0},t._calculateSortDistances=function(e,t,i,n){for(var s=0;s<t;s++){var r=e[s];if(!r.command&&!(r.layer<=2))if(r.calculateSortDistance)r.zdist=r.calculateSortDistance(r,i,n);else{var a=r.aabb.center,o=a.x-i.x,h=a.y-i.y,l=a.z-i.z;r.zdist=o*n.x+h*n.y+l*n.z}}},t._sortVisible=function(e,t,i){var n=this.instances,s=e?this.transparentSortMode:this.opaqueSortMode;if(0!==s){var r=e?n.visibleTransparent[i]:n.visibleOpaque[i];5===s?(Go=t.getPosition(),Wo=t.forward,this.customCalculateSortValues&&this.customCalculateSortValues(r.list,r.length,Go,Wo),r.list.length!==r.length&&(r.list.length=r.length),this.customSortCallback&&r.list.sort(this.customSortCallback)):(3!==s&&4!==s||(Go=t.getPosition(),Wo=t.forward,this._calculateSortDistances(r.list,r.length,Go,Wo)),r.list.length!==r.length&&(r.list.length=r.length),r.list.sort(oh[s]))}},$(e,[{key:"hasClusteredLights",get:function(){return this._clusteredLightsSet.size>0}},{key:"renderTarget",get:function(){return this._renderTarget},set:function(e){this._renderTarget=e,this._dirtyCameras=!0}},{key:"enabled",get:function(){return this._enabled},set:function(e){e!==this._enabled&&(this._enabled=e,e?(this.incrementCounter(),this.onEnable&&this.onEnable()):(this.decrementCounter(),this.onDisable&&this.onDisable()))}},{key:"clearColorBuffer",get:function(){return this._clearColorBuffer},set:function(e){this._clearColorBuffer=e,this._dirtyCameras=!0}},{key:"clearDepthBuffer",get:function(){return this._clearDepthBuffer},set:function(e){this._clearDepthBuffer=e,this._dirtyCameras=!0}},{key:"clearStencilBuffer",get:function(){return this._clearStencilBuffer},set:function(e){this._clearStencilBuffer=e,this._dirtyCameras=!0}},{key:"clusteredLightsSet",get:function(){return this._clusteredLightsSet}}]),e}(),ph=function(e,t){if(e.size!==t.size)return!1;for(var i,n=ne(e);!(i=n()).done;){var s=i.value;if(!t.has(s))return!1}return!0},mh=function(e,t){return e.priority-t.priority},_h=function(e){return e.sort(mh)},gh=function(){function e(){this.layerIndex=0,this.cameraIndex=0,this.camera=null,this.renderTarget=null,this.lightClusters=null,this.clearColor=!1,this.clearDepth=!1,this.clearStencil=!1,this.triggerPostprocess=!1,this.firstCameraUse=!1,this.lastCameraUse=!1,this.directionalLightsSet=new Set,this.directionalLights=[],this.directionalLightsIndices=[],this.viewBindGroups=[]}var t=e.prototype;return t.destroy=function(){this.viewBindGroups.forEach((function(e){e.defaultUniformBuffer.destroy(),e.destroy()})),this.viewBindGroups.length=0},t.reset=function(){this.lightClusters=null,this.directionalLightsSet.clear(),this.directionalLights.length=0,this.directionalLightsIndices.length=0},t.isLayerEnabled=function(e){return e.layerList[this.layerIndex].enabled&&e.subLayerEnabled[this.layerIndex]},t.collectDirectionalLights=function(e,t,i){this.directionalLightsSet.clear(),this.directionalLights.length=0,this.directionalLightsIndices.length=0;for(var n=0;n<t.length;n++){var s=t[n];if(s.castShadows)for(var r=0;r<e.length;r++)if(e[r]._splitLights[0].indexOf(s)>=0&&!this.directionalLightsSet.has(s)){this.directionalLightsSet.add(s),this.directionalLights.push(s);var a=i.indexOf(s);this.directionalLightsIndices.push(a)}}},$(e,[{key:"hasDirectionalShadowLights",get:function(){return this.directionalLights.length>0}}]),e}(),vh=function(){function e(){this.shadowCastersSet=new Set,this.shadowCastersList=[]}var t=e.prototype;return t.clearShadowCasters=function(){this.shadowCastersSet.clear(),this.shadowCastersList.length=0},t.addShadowCasters=function(e){for(var t=0;t<e.length;t++){var i=e[t];this.shadowCastersSet.has(i)||(this.shadowCastersSet.add(i),this.shadowCastersList.push(i))}},e}(),yh=new Set,xh=[],bh=function(e){function t(t){var i;return void 0===t&&(t="Untitled"),(i=e.call(this)||this).name=t,i.layerList=[],i.subLayerList=[],i.subLayerEnabled=[],i._opaqueOrder={},i._transparentOrder={},i._dirty=!1,i._dirtyBlend=!1,i._dirtyLights=!1,i._dirtyCameras=!1,i._meshInstances=[],i._meshInstancesSet=new Set,i._lights=[],i._lightsMap=new Map,i._lightCompositionData=[],i._splitLights=[[],[],[]],i.cameras=[],i._renderActions=[],i._worldClusters=[],i._emptyWorldClusters=null,i}J(t,e);var i=t.prototype;return i.destroy=function(){this._emptyWorldClusters&&(this._emptyWorldClusters.destroy(),this._emptyWorldClusters=null),this._worldClusters.forEach((function(e){e.destroy()})),this._worldClusters=null,this._renderActions.forEach((function(e){return e.destroy()})),this._renderActions=null},i.getEmptyWorldClusters=function(e){return this._emptyWorldClusters||(this._emptyWorldClusters=new $a(e),this._emptyWorldClusters.name="ClusterEmpty",this._emptyWorldClusters.update([],!1,null)),this._emptyWorldClusters},i._splitLightsArray=function(e){var t=e._lights;e._splitLights[0].length=0,e._splitLights[1].length=0,e._splitLights[2].length=0;for(var i=0;i<t.length;i++){var n=t[i];n.enabled&&e._splitLights[n._type].push(n)}},i._update=function(e,t){void 0===t&&(t=!1);var i=this.layerList.length,n=0;if(!this._dirty||!this._dirtyLights||!this._dirtyCameras)for(var s=0;s<i;s++){var r=this.layerList[s];r._dirty&&(this._dirty=!0),r._dirtyLights&&(this._dirtyLights=!0),r._dirtyCameras&&(this._dirtyCameras=!0)}function a(e,t,i){for(var n=!1,s=i.length,r=0;r<s;r++){var a=i[r];if(!t.has(a)){t.add(a),e.push(a);var o=a.material;o&&o._dirtyBlend&&(n=!0,o._dirtyBlend=!1)}}return n}if(this._dirty){n|=1,this._meshInstances.length=0,this._meshInstancesSet.clear();for(var o=0;o<i;o++){var h=this.layerList[o];h.passThrough||(this._dirtyBlend=a(this._meshInstances,this._meshInstancesSet,h.opaqueMeshInstances)||this._dirtyBlend,this._dirtyBlend=a(this._meshInstances,this._meshInstancesSet,h.transparentMeshInstances)||this._dirtyBlend),h._dirty=!1}this._dirty=!1}function l(e,t,i){for(var n=0;n<t.length;){var s;(null==(s=t[n].material)?void 0:s.transparent)===i?(e.push(t[n]),t[n]=t[t.length-1],t.length--):n++}}if(this._dirtyBlend){n|=8;for(var c=0;c<i;c++){var u=this.layerList[c];u.passThrough||(l(u.opaqueMeshInstances,u.transparentMeshInstances,!1),l(u.transparentMeshInstances,u.opaqueMeshInstances,!0))}this._dirtyBlend=!1}if(this._dirtyLights&&(n|=2,this._dirtyLights=!1,this.updateLights()),n&&this.updateShadowCasters(),this._dirtyCameras||2&n){this._dirtyCameras=!1,n|=4,this.cameras.length=0;for(var d=0;d<i;d++){var f=this.layerList[d];f._dirtyCameras=!1;for(var p=0;p<f.cameras.length;p++){var m=f.cameras[p];this.cameras.indexOf(m)<0&&this.cameras.push(m)}}this.cameras.length>1&&_h(this.cameras);for(var _=[],g=0,v=0;v<this.cameras.length;v++){var y=this.cameras[v];_.length=0;for(var x=!0,b=g,S=null,w=!1,T=0;T<i;T++){var A=this.layerList[T];if(A&&A.cameras.length>0&&y.layers.indexOf(A.id)>=0){_.push(A),w||A.id!==y.disablePostEffectsLayer||(w=!0,S&&(S.triggerPostprocess=!0));var M=A.cameras.indexOf(y);M>=0&&(S=this.addRenderAction(this._renderActions,g,A,T,M,x,w),g++,x=!1)}}b<g&&(this._renderActions[b].collectDirectionalLights(_,this._splitLights[0],this._lights),S.lastCameraUse=!0),!w&&S&&(S.triggerPostprocess=!0),y.renderTarget&&y.postEffectsEnabled&&this.propagateRenderTarget(b-1,y)}for(var C=g;C<this._renderActions.length;C++)this._renderActions[C].destroy();this._renderActions.length=g}return 7&n&&t&&this.allocateLightClusters(e),2&n&&this._logRenderActions(),n},i.updateShadowCasters=function(){for(var e=this._lights.length,t=0;t<e;t++)this._lightCompositionData[t].clearShadowCasters();for(var i=this.layerList.length,n=0;n<i;n++){var s=this.layerList[n];if(!yh.has(s)){yh.add(s);for(var r=s._lights,a=0;a<r.length;a++)if(r[a].castShadows){var o=this._lightsMap.get(r[a]);this._lightCompositionData[o].addShadowCasters(s.shadowCasters)}}}yh.clear()},i.updateLights=function(){this._lights.length=0,this._lightsMap.clear();for(var e=this.layerList.length,t=0;t<e;t++){var i=this.layerList[t];if(!yh.has(i)){yh.add(i);for(var n=i._lights,s=0;s<n.length;s++){var r=n[s],a=this._lightsMap.get(r);if(void 0===a){a=this._lights.length,this._lightsMap.set(r,a),this._lights.push(r);var o=this._lightCompositionData[a];o||(o=new vh,this._lightCompositionData[a]=o)}}}this._splitLightsArray(i),i._dirtyLights=!1}yh.clear(),this._splitLightsArray(this);var h=this._lights.length;this._lightCompositionData.length=h},i.findCompatibleCluster=function(e,t,i){for(var n=0;n<t;n++){var s=this._renderActions[n],r=this.layerList[s.layerIndex];if(s.lightClusters!==i){if(e===r)return s.lightClusters;if(s.lightClusters&&ph(e._clusteredLightsSet,r._clusteredLightsSet))return s.lightClusters}}return null},i.allocateLightClusters=function(e){xh.push.apply(xh,this._worldClusters);var t=this.getEmptyWorldClusters(e);this._worldClusters.length=0;for(var i=this._renderActions.length,n=0;n<i;n++){var s=this._renderActions[n],r=this.layerList[s.layerIndex];if(r.hasClusteredLights)if((this.subLayerList[s.layerIndex]?r.transparentMeshInstances:r.opaqueMeshInstances).length){var a=this.findCompatibleCluster(r,n,t);a||(xh.length&&(a=xh.pop()),a||(a=new $a(e)),a.name="Cluster-"+this._worldClusters.length,this._worldClusters.push(a)),s.lightClusters=a}s.lightClusters||(s.lightClusters=t)}xh.forEach((function(e){e.destroy()})),xh.length=0},i.addRenderAction=function(e,t,i,n,s,r,a){var o=e[t];o||(o=e[t]=new gh);var h=i.renderTarget,l=i.cameras[s];l&&l.renderTarget&&1!==i.id&&(h=l.renderTarget);for(var c=!1,u=t-1;u>=0;u--)if(e[u].camera===l&&e[u].renderTarget===h){c=!0;break}var d=r||!c,f=!!d&&l.clearColorBuffer,p=!!d&&l.clearDepthBuffer,m=!!d&&l.clearStencilBuffer;return f||(f=i.clearColorBuffer),p||(p=i.clearDepthBuffer),m||(m=i.clearStencilBuffer),a&&l.postEffectsEnabled&&(h=null),o.reset(),o.triggerPostprocess=!1,o.layerIndex=n,o.cameraIndex=s,o.camera=l,o.renderTarget=h,o.clearColor=f,o.clearDepth=p,o.clearStencil=m,o.firstCameraUse=r,o.lastCameraUse=!1,o},i.propagateRenderTarget=function(e,t){for(var i=e;i>=0;i--){var n=this._renderActions[i],s=this.layerList[n.layerIndex];if(n.renderTarget&&1!==s.id)break;if(1!==s.id){var r=null==n?void 0:n.camera.camera;if(r&&(!t.camera.rect.equals(r.rect)||!t.camera.scissorRect.equals(r.scissorRect)))break;n.renderTarget=t.renderTarget}}},i._logRenderActions=function(){},i._isLayerAdded=function(e){return this.layerList.indexOf(e)>=0},i._isSublayerAdded=function(e,t){for(var i=0;i<this.layerList.length;i++)if(this.layerList[i]===e&&this.subLayerList[i]===t)return!0;return!1},i.push=function(e){this._isLayerAdded(e)||(this.layerList.push(e),this.layerList.push(e),this._opaqueOrder[e.id]=this.subLayerList.push(!1)-1,this._transparentOrder[e.id]=this.subLayerList.push(!0)-1,this.subLayerEnabled.push(!0),this.subLayerEnabled.push(!0),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("add",e))},i.insert=function(e,t){if(!this._isLayerAdded(e)){this.layerList.splice(t,0,e,e),this.subLayerList.splice(t,0,!1,!0);var i=this.layerList.length;this._updateOpaqueOrder(t,i-1),this._updateTransparentOrder(t,i-1),this.subLayerEnabled.splice(t,0,!0,!0),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("add",e)}},i.remove=function(e){var t=this.layerList.indexOf(e);for(delete this._opaqueOrder[t],delete this._transparentOrder[t];t>=0;)this.layerList.splice(t,1),this.subLayerList.splice(t,1),this.subLayerEnabled.splice(t,1),t=this.layerList.indexOf(e),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("remove",e);var i=this.layerList.length;this._updateOpaqueOrder(0,i-1),this._updateTransparentOrder(0,i-1)},i.pushOpaque=function(e){this._isSublayerAdded(e,!1)||(this.layerList.push(e),this._opaqueOrder[e.id]=this.subLayerList.push(!1)-1,this.subLayerEnabled.push(!0),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("add",e))},i.insertOpaque=function(e,t){if(!this._isSublayerAdded(e,!1)){this.layerList.splice(t,0,e),this.subLayerList.splice(t,0,!1);var i=this.subLayerList.length;this._updateOpaqueOrder(t,i-1),this.subLayerEnabled.splice(t,0,!0),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("add",e)}},i.removeOpaque=function(e){for(var t=0,i=this.layerList.length;t<i;t++)if(this.layerList[t]===e&&!this.subLayerList[t])return this.layerList.splice(t,1),this.subLayerList.splice(t,1),i--,this._updateOpaqueOrder(t,i-1),this.subLayerEnabled.splice(t,1),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,void(this.layerList.indexOf(e)<0&&this.fire("remove",e))},i.pushTransparent=function(e){this._isSublayerAdded(e,!0)||(this.layerList.push(e),this._transparentOrder[e.id]=this.subLayerList.push(!0)-1,this.subLayerEnabled.push(!0),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("add",e))},i.insertTransparent=function(e,t){if(!this._isSublayerAdded(e,!0)){this.layerList.splice(t,0,e),this.subLayerList.splice(t,0,!0);var i=this.subLayerList.length;this._updateTransparentOrder(t,i-1),this.subLayerEnabled.splice(t,0,!0),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("add",e)}},i.removeTransparent=function(e){for(var t=0,i=this.layerList.length;t<i;t++)if(this.layerList[t]===e&&this.subLayerList[t])return this.layerList.splice(t,1),this.subLayerList.splice(t,1),i--,this._updateTransparentOrder(t,i-1),this.subLayerEnabled.splice(t,1),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,void(this.layerList.indexOf(e)<0&&this.fire("remove",e))},i._getSublayerIndex=function(e,t){var i=this.layerList.indexOf(e);if(i<0)return-1;if(this.subLayerList[i]!==t){if((i=this.layerList.indexOf(e,i+1))<0)return-1;if(this.subLayerList[i]!==t)return-1}return i},i.getOpaqueIndex=function(e){return this._getSublayerIndex(e,!1)},i.getTransparentIndex=function(e){return this._getSublayerIndex(e,!0)},i.getLayerById=function(e){for(var t=0;t<this.layerList.length;t++)if(this.layerList[t].id===e)return this.layerList[t];return null},i.getLayerByName=function(e){for(var t=0;t<this.layerList.length;t++)if(this.layerList[t].name===e)return this.layerList[t];return null},i._updateOpaqueOrder=function(e,t){for(var i=e;i<=t;i++)!1===this.subLayerList[i]&&(this._opaqueOrder[this.layerList[i].id]=i)},i._updateTransparentOrder=function(e,t){for(var i=e;i<=t;i++)!0===this.subLayerList[i]&&(this._transparentOrder[this.layerList[i].id]=i)},i._sortLayersDescending=function(e,t,i){for(var n=-1,s=-1,r=0,a=e.length;r<a;r++){var o=e[r];i.hasOwnProperty(o)&&(n=Math.max(n,i[o]))}for(var h=0,l=t.length;h<l;h++){var c=t[h];i.hasOwnProperty(c)&&(s=Math.max(s,i[c]))}return-1===n&&-1!==s?1:-1===s&&-1!==n?-1:s-n},i.sortTransparentLayers=function(e,t){return this._sortLayersDescending(e,t,this._transparentOrder)},i.sortOpaqueLayers=function(e,t){return this._sortLayersDescending(e,t,this._opaqueOrder)},t}(m),Sh=new ye,wh=new ye,Th=new ye,Ah={bias:0,normalBias:0},Mh={r:0,g:1,b:2,a:3},Ch={directional:0,omni:1,point:1,spot:2},Eh=[[new Se(0,0,1,1)],[new Se(0,0,.5,.5),new Se(0,.5,.5,.5)],[new Se(0,0,.5,.5),new Se(0,.5,.5,.5),new Se(.5,0,.5,.5)],[new Se(0,0,.5,.5),new Se(0,.5,.5,.5),new Se(.5,0,.5,.5),new Se(.5,.5,.5,.5)]],Ph=0,Rh=function(){function e(e,t,i,n){this.light=n,this.camera=t,this.shadowCamera=Io.createShadowCamera(e,n._shadowType,n._type,i),this.shadowMatrix=new Ee,this.shadowViewport=new Se(0,0,1,1),this.shadowScissor=new Se(0,0,1,1),this.face=i,this.visibleCasters=[]}return $(e,[{key:"shadowBuffer",get:function(){var e=this.shadowCamera.renderTarget;if(e){var t=this.light;return 1===t._type?e.colorBuffer:t._isPcf&&t.device.webgl2?e.depthBuffer:e.colorBuffer}return null}}]),e}(),Ih=function(){function e(e){this.device=e,this.id=Ph++,this._type=0,this._color=new me(.8,.8,.8),this._intensity=1,this._luminance=0,this._castShadows=!1,this._enabled=!1,this.mask=1,this.isStatic=!1,this.key=0,this.bakeDir=!0,this.bakeNumSamples=1,this.bakeArea=0,this.attenuationStart=10,this.attenuationEnd=10,this._falloffMode=0,this._shadowType=0,this._vsmBlurSize=11,this.vsmBlurMode=1,this.vsmBias=.0025,this._cookie=null,this.cookieIntensity=1,this._cookieFalloff=!0,this._cookieChannel="rgb",this._cookieTransform=null,this._cookieTransformUniform=new Float32Array(4),this._cookieOffset=null,this._cookieOffsetUniform=new Float32Array(2),this._cookieTransformSet=!1,this._cookieOffsetSet=!1,this._innerConeAngle=40,this._outerConeAngle=45,this.cascades=null,this._shadowMatrixPalette=null,this._shadowCascadeDistances=null,this.numCascades=1,this.cascadeDistribution=.5,this._shape=0,this._finalColor=new Float32Array([.8,.8,.8]);var t=Math.pow(this._finalColor[0],2.2);this._linearFinalColor=new Float32Array([t,t,t]),this._position=new ye(0,0,0),this._direction=new ye(0,0,0),this._innerConeAngleCos=Math.cos(this._innerConeAngle*Math.PI/180),this._outerConeAngleCos=Math.cos(this._outerConeAngle*Math.PI/180),this._usePhysicalUnits=void 0,this._shadowMap=null,this._shadowRenderParams=[],this.shadowDistance=40,this._shadowResolution=1024,this.shadowBias=-5e-4,this.shadowIntensity=1,this._normalOffsetBias=0,this.shadowUpdateMode=2,this._isVsm=!1,this._isPcf=!0,this._cookieMatrix=null,this._atlasViewport=null,this.atlasViewportAllocated=!1,this.atlasVersion=0,this.atlasSlotIndex=0,this.atlasSlotUpdated=!1,this._scene=null,this._node=null,this._renderData=[],this.visibleThisFrame=!1,this.maxScreenSize=0}var t=e.prototype;return t.destroy=function(){this._destroyShadowMap(),this._renderData=null},t.beginFrame=function(){this.visibleThisFrame=0===this._type&&this._enabled,this.maxScreenSize=0,this.atlasViewportAllocated=!1,this.atlasSlotUpdated=!1},t._destroyShadowMap=function(){this._renderData&&(this._renderData.length=0),this._shadowMap&&(this._shadowMap.cached||this._shadowMap.destroy(),this._shadowMap=null),0===this.shadowUpdateMode&&(this.shadowUpdateMode=1)},t.getRenderData=function(e,t){for(var i=0;i<this._renderData.length;i++){var n=this._renderData[i];if(n.camera===e&&n.face===t)return n}var s=new Rh(this.device,e,t,this);return this._renderData.push(s),s},t.clone=function(){var t=new e(this.device);return t.type=this._type,t.setColor(this._color),t.intensity=this._intensity,t.luminance=this._luminance,t.castShadows=this.castShadows,t._enabled=this._enabled,t.attenuationStart=this.attenuationStart,t.attenuationEnd=this.attenuationEnd,t.falloffMode=this._falloffMode,t.shadowType=this._shadowType,t.vsmBlurSize=this._vsmBlurSize,t.vsmBlurMode=this.vsmBlurMode,t.vsmBias=this.vsmBias,t.shadowUpdateMode=this.shadowUpdateMode,t.mask=this.mask,t.innerConeAngle=this._innerConeAngle,t.outerConeAngle=this._outerConeAngle,t.numCascades=this.numCascades,t.cascadeDistribution=this.cascadeDistribution,t.shape=this._shape,t.shadowBias=this.shadowBias,t.normalOffsetBias=this._normalOffsetBias,t.shadowResolution=this._shadowResolution,t.shadowDistance=this.shadowDistance,t.shadowIntensity=this.shadowIntensity,t},e.getLightUnitConversion=function(e,t,i){switch(void 0===t&&(t=Math.PI/4),void 0===i&&(i=0),e){case 2:var n=Math.cos(t),s=Math.cos(i);return 2*Math.PI*(1-s+(s-n)/2);case 1:return 4*Math.PI;case 0:return 1}},t._getUniformBiasValues=function(e){var t=e.shadowCamera._farClip;switch(this._type){case 1:Ah.bias=this.shadowBias,Ah.normalBias=this._normalOffsetBias;break;case 2:this._isVsm?Ah.bias=-2e-4:(Ah.bias=20*this.shadowBias,!this.device.webgl2&&this.device.extStandardDerivatives&&(Ah.bias*=-100)),Ah.normalBias=this._isVsm?this.vsmBias/(this.attenuationEnd/7):this._normalOffsetBias;break;case 0:this._isVsm?Ah.bias=-2e-4:(Ah.bias=this.shadowBias/t*100,!this.device.webgl2&&this.device.extStandardDerivatives&&(Ah.bias*=-100)),Ah.normalBias=this._isVsm?this.vsmBias/(t/7):this._normalOffsetBias}return Ah},t.getColor=function(){return this._color},t.getBoundingSphere=function(e){if(2===this._type){var t=this.attenuationEnd,i=this._outerConeAngle,n=Math.cos(i*de.DEG_TO_RAD),s=this._node;Sh.copy(s.up),Sh.mulScalar(.5*-t*n),Sh.add(s.getPosition()),e.center=Sh,wh.copy(s.up),wh.mulScalar(-t),Th.copy(s.right),Th.mulScalar(Math.sin(i*de.DEG_TO_RAD)*t),wh.add(Th),e.radius=.5*wh.length()}else 1===this._type&&(e.center=this._node.getPosition(),e.radius=this.attenuationEnd)},t.getBoundingBox=function(e){if(2===this._type){var t=this.attenuationEnd,i=this._outerConeAngle,n=this._node,s=Math.abs(Math.sin(i*de.DEG_TO_RAD)*t);e.center.set(0,.5*-t,0),e.halfExtents.set(s,.5*t,s),e.setFromTransformedAabb(e,n.getWorldTransform(),!0)}else 1===this._type&&(e.center.copy(this._node.getPosition()),e.halfExtents.set(this.attenuationEnd,this.attenuationEnd,this.attenuationEnd))},t._updateFinalColor=function(){var t=this._color,i=t.r,n=t.g,s=t.b,r=this._intensity;this._usePhysicalUnits&&(r=this._luminance/e.getLightUnitConversion(this._type,this._outerConeAngle*de.DEG_TO_RAD,this._innerConeAngle*de.DEG_TO_RAD));var a=this._finalColor,o=this._linearFinalColor;a[0]=i*r,a[1]=n*r,a[2]=s*r,r>=1?(o[0]=Math.pow(i,2.2)*r,o[1]=Math.pow(n,2.2)*r,o[2]=Math.pow(s,2.2)*r):(o[0]=Math.pow(a[0],2.2),o[1]=Math.pow(a[1],2.2),o[2]=Math.pow(a[2],2.2))},t.setColor=function(){1===arguments.length?this._color.set(arguments[0].r,arguments[0].g,arguments[0].b):3===arguments.length&&this._color.set(arguments[0],arguments[1],arguments[2]),this._updateFinalColor()},t.updateShadow=function(){2!==this.shadowUpdateMode&&(this.shadowUpdateMode=1)},t.layersDirty=function(){var e;null!=(e=this._scene)&&e.layers&&(this._scene.layers._dirtyLights=!0)},t.updateKey=function(){var e=this._type<<29|(this._castShadows?1:0)<<28|this._shadowType<<25|this._falloffMode<<23|(0!==this._normalOffsetBias?1:0)<<22|(this._cookie?1:0)<<21|(this._cookieFalloff?1:0)<<20|Mh[this._cookieChannel.charAt(0)]<<18|(this._cookieTransform?1:0)<<12|this._shape<<10|this.numCascades-1<<8;3===this._cookieChannel.length&&(e|=Mh[this._cookieChannel.charAt(1)]<<16,e|=Mh[this._cookieChannel.charAt(2)]<<14),e!==this.key&&null!==this._scene&&this.layersDirty(),this.key=e},$(e,[{key:"numCascades",get:function(){return this.cascades.length},set:function(e){this.cascades&&this.numCascades===e||(this.cascades=Eh[e-1],this._shadowMatrixPalette=new Float32Array(64),this._shadowCascadeDistances=new Float32Array(4),this._destroyShadowMap(),this.updateKey())}},{key:"shadowMap",get:function(){return this._shadowMap},set:function(e){this._shadowMap!==e&&(this._destroyShadowMap(),this._shadowMap=e)}},{key:"numShadowFaces",get:function(){var e=this._type;return 0===e?this.numCascades:1===e?6:1}},{key:"type",get:function(){return this._type},set:function(e){if(this._type!==e){this._type=e,this._destroyShadowMap(),this.updateKey();var t=this._shadowType;this._shadowType=null,this.shadowType=t}}},{key:"shape",get:function(){return this._shape},set:function(e){if(this._shape!==e){this._shape=e,this._destroyShadowMap(),this.updateKey();var t=this._shadowType;this._shadowType=null,this.shadowType=t}}},{key:"usePhysicalUnits",get:function(){return this._usePhysicalUnits},set:function(e){this._usePhysicalUnits!==e&&(this._usePhysicalUnits=e,this._updateFinalColor())}},{key:"shadowType",get:function(){return this._shadowType},set:function(e){if(this._shadowType!==e){var t=this.device;1===this._type&&(e=0),4!==e||t.webgl2||(e=0),3!==e||t.textureFloatRenderable||(e=2),2!==e||t.textureHalfFloatRenderable||(e=1),this._isVsm=e>=1&&e<=3,this._isPcf=4===e||0===e,this._shadowType=e,this._destroyShadowMap(),this.updateKey()}}},{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled!==e&&(this._enabled=e,this.layersDirty())}},{key:"castShadows",get:function(){return this._castShadows&&4!==this.mask&&0!==this.mask},set:function(e){this._castShadows!==e&&(this._castShadows=e,this._destroyShadowMap(),this.layersDirty(),this.updateKey())}},{key:"shadowResolution",get:function(){return this._shadowResolution},set:function(e){this._shadowResolution!==e&&(e=1===this._type?Math.min(e,this.device.maxCubeMapSize):Math.min(e,this.device.maxTextureSize),this._shadowResolution=e,this._destroyShadowMap())}},{key:"vsmBlurSize",get:function(){return this._vsmBlurSize},set:function(e){this._vsmBlurSize!==e&&(e%2==0&&e++,this._vsmBlurSize=e)}},{key:"normalOffsetBias",get:function(){return this._normalOffsetBias},set:function(e){this._normalOffsetBias!==e&&((!this._normalOffsetBias&&e||this._normalOffsetBias&&!e)&&this.updateKey(),this._normalOffsetBias=e)}},{key:"falloffMode",get:function(){return this._falloffMode},set:function(e){this._falloffMode!==e&&(this._falloffMode=e,this.updateKey())}},{key:"innerConeAngle",get:function(){return this._innerConeAngle},set:function(e){this._innerConeAngle!==e&&(this._innerConeAngle=e,this._innerConeAngleCos=Math.cos(e*Math.PI/180),this._usePhysicalUnits&&this._updateFinalColor())}},{key:"outerConeAngle",get:function(){return this._outerConeAngle},set:function(e){this._outerConeAngle!==e&&(this._outerConeAngle=e,this._outerConeAngleCos=Math.cos(e*Math.PI/180),this._usePhysicalUnits&&this._updateFinalColor())}},{key:"intensity",get:function(){return this._intensity},set:function(e){this._intensity!==e&&(this._intensity=e,this._updateFinalColor())}},{key:"luminance",get:function(){return this._luminance},set:function(e){this._luminance!==e&&(this._luminance=e,this._updateFinalColor())}},{key:"cookieMatrix",get:function(){return this._cookieMatrix||(this._cookieMatrix=new Ee),this._cookieMatrix}},{key:"atlasViewport",get:function(){return this._atlasViewport||(this._atlasViewport=new Se(0,0,1,1)),this._atlasViewport}},{key:"cookie",get:function(){return this._cookie},set:function(e){this._cookie!==e&&(this._cookie=e,this.updateKey())}},{key:"cookieFalloff",get:function(){return this._cookieFalloff},set:function(e){this._cookieFalloff!==e&&(this._cookieFalloff=e,this.updateKey())}},{key:"cookieChannel",get:function(){return this._cookieChannel},set:function(e){if(this._cookieChannel!==e){if(e.length<3)for(var t=e.charAt(e.length-1),i=3-e.length,n=0;n<i;n++)e+=t;this._cookieChannel=e,this.updateKey()}}},{key:"cookieTransform",get:function(){return this._cookieTransform},set:function(e){this._cookieTransform!==e&&(this._cookieTransform=e,this._cookieTransformSet=!!e,e&&!this._cookieOffset&&(this.cookieOffset=new be,this._cookieOffsetSet=!1),this.updateKey())}},{key:"cookieOffset",get:function(){return this._cookieOffset},set:function(e){this._cookieOffset!==e&&(!(!this._cookieTransformSet&&!e)&&!e&&this._cookieOffset?this._cookieOffset.set(0,0):this._cookieOffset=e,this._cookieOffsetSet=!!e,e&&!this._cookieTransform&&(this.cookieTransform=new Se(1,1,0,0),this._cookieTransformSet=!1),this.updateKey())}}]),e}(),Lh=function(){function e(e,t,i){this._maxTextureSize=t,this._supportsAreaLights=e,this._dirtyLightsFnc=i,this._areaLightsEnabled=!1,this._cells=new ye(10,3,10),this._maxLightsPerCell=255,this._shadowsEnabled=!0,this._shadowType=0,this._shadowAtlasResolution=2048,this._cookiesEnabled=!1,this._cookieAtlasResolution=2048,this.atlasSplit=null,this.debugLayer=void 0}return e.prototype.applySettings=function(e){this.shadowsEnabled=e.lightingShadowsEnabled,this.cookiesEnabled=e.lightingCookiesEnabled,this.areaLightsEnabled=e.lightingAreaLightsEnabled,this.shadowAtlasResolution=e.lightingShadowAtlasResolution,this.cookieAtlasResolution=e.lightingCookieAtlasResolution,this.maxLightsPerCell=e.lightingMaxLightsPerCell,this.shadowType=e.lightingShadowType,this.cell=new ye(e.lightingCells)},$(e,[{key:"cells",get:function(){return this._cells},set:function(e){this._cells.copy(e)}},{key:"maxLightsPerCell",get:function(){return this._maxLightsPerCell},set:function(e){this._maxLightsPerCell=de.clamp(e,1,255)}},{key:"cookieAtlasResolution",get:function(){return this._cookieAtlasResolution},set:function(e){this._cookieAtlasResolution=de.clamp(e,32,this._maxTextureSize)}},{key:"shadowAtlasResolution",get:function(){return this._shadowAtlasResolution},set:function(e){this._shadowAtlasResolution=de.clamp(e,32,this._maxTextureSize)}},{key:"shadowType",get:function(){return this._shadowType},set:function(e){this._shadowType!==e&&(this._shadowType=e,this._dirtyLightsFnc())}},{key:"cookiesEnabled",get:function(){return this._cookiesEnabled},set:function(e){this._cookiesEnabled!==e&&(this._cookiesEnabled=e,this._dirtyLightsFnc())}},{key:"areaLightsEnabled",get:function(){return this._areaLightsEnabled},set:function(e){this._supportsAreaLights&&this._areaLightsEnabled!==e&&(this._areaLightsEnabled=e,this._dirtyLightsFnc())}},{key:"shadowsEnabled",get:function(){return this._shadowsEnabled},set:function(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this._dirtyLightsFnc())}}]),e}(),Dh=new Ne,kh=function(){function e(e,t){this.scene=e,this.light=t,this.store(),t.numCascades=1,0!==t.type&&(t._node.getWorldTransform(),t.getBoundingSphere(Dh),this.lightBounds=new Oe,this.lightBounds.center.copy(Dh.center),this.lightBounds.halfExtents.set(Dh.radius,Dh.radius,Dh.radius))}var t=e.prototype;return t.store=function(){this.mask=this.light.mask,this.shadowUpdateMode=this.light.shadowUpdateMode,this.enabled=this.light.enabled,this.intensity=this.light.intensity,this.rotation=this.light._node.getLocalRotation().clone(),this.numCascades=this.light.numCascades},t.restore=function(){var e=this.light;e.mask=this.mask,e.shadowUpdateMode=this.shadowUpdateMode,e.enabled=this.enabled,e.intensity=this.intensity,e._node.setLocalRotation(this.rotation),e.numCascades=this.numCascades},t.startBake=function(){this.light.enabled=!0,this.light._destroyShadowMap()},t.endBake=function(e){var t=this.light;t.enabled=!1,t.shadowMap&&(t.shadowMap.cached&&e.add(t,t.shadowMap),t.shadowMap=null)},e}(),Oh=new be,Fh=function(e){function t(){return e.apply(this,arguments)||this}return J(t,e),t.prototype.prepareVirtualLight=function(e,t){var i=this.light;if(i._node.setLocalRotation(this.rotation),e>0){var n=i.bakeArea;ls(Oh,e,t),Oh.mulScalar(.5*n),i._node.rotateLocal(Oh.x,0,Oh.y)}i._node.getWorldTransform();var s=this.scene.gammaCorrection?2.2:1,r=Math.pow(this.intensity,s);i.intensity=Math.pow(r/t,1/s)},$(t,[{key:"numVirtualLights",get:function(){return 0===this.light.type?this.light.bakeNumSamples:1}}]),t}(kh),Bh=function(){function e(){this.renderPasses=[],this.renderTargetMap=new Map}var t=e.prototype;return t.addRenderPass=function(e){this.renderPasses.push(e)},t.reset=function(){this.renderPasses.length=0},t.compile=function(){for(var e=this.renderTargetMap,t=this.renderPasses,i=0;i<t.length;i++){var n=t[i],s=n.renderTarget;if(void 0!==s){var r=e.get(s);r&&(n.colorOps.clear||(r.colorOps.store=!0),n.depthStencilOps.clearDepth||(r.depthStencilOps.storeDepth=!0),n.depthStencilOps.clearStencil||(r.depthStencilOps.storeStencil=!0)),e.set(s,n)}}for(var a=null,o=null,h=0;h<t.length;h++){var l=t[h],c=l.renderTarget,u=null==c?void 0:c.colorBuffer;null!=u&&u.cubemap?(a===u&&(o.colorOps.mipmaps=!1),a=c.colorBuffer,o=l):l.requiresCubemaps&&(a=null,o=null)}e.forEach((function(e,t){null===t&&(e.colorOps.store=!0,e.colorOps.resolve=!1,e.colorOps.mipmaps=!1)})),e.clear(),this.log()},t.render=function(){this.compile();for(var e=this.renderPasses,t=0;t<e.length;t++)e[t].render()},t.log=function(){},e}(),Nh=function(){function e(e,t){this.texture0=e,this.texture1=t}return e.prototype.destroy=function(){var e,t;null==(e=this.texture0)||e.destroy(),null==(t=this.texture1)||t.destroy()},e}(),Uh=new Ai,zh=function(){function e(){}return e.createTexture=function(e,t,i,n){return void 0===n&&(n=""),new wn(e,{width:i,height:i,format:t,addressU:1,addressV:1,type:Zt,magFilter:1,minFilter:0,anisotropy:1,name:"AreaLightLUT"+n})},e.applyTextures=function(e,t,i){Uh.remove(e),Uh.get(e,(function(){return new Nh(t,t===i?null:i)})),e.scope.resolve("areaLightsLutTex1").setValue(t),e.scope.resolve("areaLightsLutTex2").setValue(i)},e.createPlaceholder=function(t){var i=e.createTexture(t,7,2,"placeholder");i.lock().fill(0),i.unlock(),e.applyTextures(t,i,i)},e.set=function(t,i,n){function s(t,i,n){var s=e.createTexture(t,n,64);return s.lock().set(i),s.unlock(),s.upload(),s}function r(e,t,i){for(var n=e.length,s=new Float32Array(n),r=0;r<n;r++){var a=r%4;s[r]=(e[r]+t[a])*i[a]}return s}function a(e){for(var t=e.length,i=new Uint16Array(t),n=yn.float2Half,s=0;s<t;s++)i[s]=n(e[s]);return i}function o(e){for(var t=e.length,i=new Uint8ClampedArray(t),n=0;n<t;n++)i[n]=255*e[n];return i}var h,l,c=i,u=n,d=t.areaLightLutFormat;if(d===dt)h=c,l=u;else if(d===ct)h=a(c),l=a(u);else{h=o(r(c,[0,.2976,.01381,0],[.999,3.08737,1.6546,.603249])),l=o(r(u,[-.306897,0,0,0],[1.442787,1,1,1]))}var f=s(t,h,d),p=s(t,l,d);e.applyTextures(t,f,p)},e}(),Vh={generateKey:function(e){return"cubemap"===e.type?"skybox-"+e.type+"-"+e.encoding+"-"+e.useIntensity+"-"+e.gamma+"-"+e.toneMapping+"-"+e.fixSeams+"-"+e.mip:"skybox-"+e.type+"-"+e.encoding+"-"+e.useIntensity+"-"+e.gamma+"-"+e.toneMapping},createShaderDefinition:function(e,t){var i;if("cubemap"===t.type){i=Ki(e),i+=t.mip?Wi.fixCubemapSeamsStretchPS:Wi.fixCubemapSeamsNonePS,i+=t.useIntensity?Wi.envMultiplyPS:Wi.envConstPS,i+=Wi.decodePS,i+=Xi(t.gamma),i+=qi(t.toneMapping),i+=Wi.skyboxHDRPS.replace(/\$DECODE/g,mn.decodeFunc(t.encoding)).replace(/\$FIXCONST/g,1-1/[128,64,16,8,4,2][t.mip]+"")}else i=Ki(e),i+=t.useIntensity?Wi.envMultiplyPS:Wi.envConstPS,i+=Wi.decodePS,i+=Xi(t.gamma),i+=qi(t.toneMapping),i+=Wi.sphericalPS,i+=Wi.envAtlasPS,i+=Wi.skyboxEnvPS.replace(/\$DECODE/g,mn.decodeFunc(t.encoding));return{attributes:{aPosition:vt},vshader:Wi.skyboxVS,fshader:i}}},Gh=function(){function e(e,t,i){this.meshInstance=void 0,this._rotationMat3=void 0;var n=new Bs;n.getShaderVariant=function(n,s,r,a,o,h,l,c){var u=e.getProgramLibrary();return u.register("skybox",Vh),i.cubemap?u.getProgram("skybox",{type:"cubemap",encoding:i.encoding,useIntensity:1!==t.skyboxIntensity||t.physicalUnits,mip:i.fixCubemapSeams?t.skyboxMip:0,fixSeams:i.fixCubemapSeams,gamma:1===o?t.gammaCorrection?3:0:t.gammaCorrection,toneMapping:1===o?0:t.toneMapping}):u.getProgram("skybox",{type:"envAtlas",encoding:i.encoding,useIntensity:1!==t.skyboxIntensity||t.physicalUnits,gamma:1===o?t.gammaCorrection?3:0:t.gammaCorrection,toneMapping:1===o?0:t.toneMapping})},i.cubemap?n.setParameter("texture_cubeMap",i):(n.setParameter("texture_envAtlas",i),n.setParameter("mipLevel",t._skyboxMip)),t.skyboxRotation.equals(Pe.IDENTITY)?n.setParameter("cubeMapRotationMatrix",xe.IDENTITY.data):(lh=lh||new Ee,this._rotationMat3=this._rotationMat3||new xe,lh.setTRS(ye.ZERO,t._skyboxRotation,ye.ONE),lh.invertTo3x3(this._rotationMat3),n.setParameter("cubeMapRotationMatrix",this._rotationMat3.data)),n.cull=2,n.depthWrite=!1;var s=t.layers.getLayerById(2);if(s){var r=new Hn("Skybox"),a=pa(e),o=new ka(a,n,r);this.meshInstance=o,o.cull=!1,o._noDepthDrawGl1=!0,o.pick=!1,s.addMeshInstances([o]),this.skyLayer=s}}return e.prototype.destroy=function(){this.meshInstance&&(this.skyLayer&&this.skyLayer.removeMeshInstances([this.meshInstance]),this.meshInstance.destroy(),this.meshInstance=null)},e}(),Wh=new Hn;Wh.worldTransform=Ee.IDENTITY,Wh._dirtyWorld=Wh._dirtyNormal=!1;var Hh,Xh=function(){function e(e,t,i){this.material=t,this.layer=i,this.positions=[],this.colors=[],this.mesh=new ea(e),this.meshInstance=null}var t=e.prototype;return t.addLines=function(e,t){for(var i=this.positions,n=e.length,s=0;s<n;s++){var r=e[s];i.push(r.x,r.y,r.z)}var a=this.colors;if(t.length)for(var o=0;o<n;o++){var h=t[o];a.push(h.r,h.g,h.b,h.a)}else for(var l=0;l<n;l++)a.push(t.r,t.g,t.b,t.a)},t.addLinesArrays=function(e,t){for(var i=this.positions,n=0;n<e.length;n+=3)i.push(e[n],e[n+1],e[n+2]);var s=this.colors;if(t.length)for(var r=0;r<t.length;r+=4)s.push(t[r],t[r+1],t[r+2],t[r+3]);else for(var a=e.length/3,o=0;o<a;o++)s.push(t.r,t.g,t.b,t.a)},t.onPreRender=function(e,t){this.positions.length>0&&this.material.transparent===t&&(this.mesh.setPositions(this.positions),this.mesh.setColors(this.colors),this.mesh.update(1,!1),this.meshInstance||(this.meshInstance=new ka(this.mesh,this.material,Wh)),this.positions.length=0,this.colors.length=0,e.list.push(this.meshInstance),e.length++)},e}(),qh=function(){function e(e){this.device=e,this.map=new Map}var t=e.prototype;return t.getBatch=function(e,t){var i=this.map.get(e);return i||(i=new Xh(this.device,e,t),this.map.set(e,i)),i},t.onPreRender=function(e,t){this.map.forEach((function(i){i.onPreRender(e,t)}))},e}(),jh=[],Yh=function(){function e(e){this.device=e,this.quadMesh=null,this.textureShader=null,this.depthTextureShader=null,this.cubeLocalPos=null,this.cubeWorldPos=null,this.batchesMap=new Map,this.allBatches=new Set,this.updatedLayers=new Set,this._materialDepth=null,this._materialNoDepth=null,this.layerMeshInstances=new Map}var t=e.prototype;return t.createMaterial=function(e){var t=new ga;return t.vertexColors=!0,t.blend=!0,t.blendType=2,t.depthTest=e,t.update(),t},t.getBatch=function(e,t){var i=this.batchesMap.get(e);i||(i=new qh(this.device),this.batchesMap.set(e,i)),this.allBatches.add(i);var n=t?this.materialDepth:this.materialNoDepth;return i.getBatch(n,e)},e.getTextureVS=function(){return"\n attribute vec2 vertex_position;\n uniform mat4 matrix_model;\n varying vec2 uv0;\n void main(void) {\n gl_Position = matrix_model * vec4(vertex_position, 0, 1);\n uv0 = vertex_position.xy + 0.5;\n }\n "},t.getTextureShader=function(){if(!this.textureShader){this.textureShader=on(this.device,e.getTextureVS(),"\n varying vec2 uv0;\n uniform sampler2D colorMap;\n void main (void) {\n gl_FragColor = vec4(texture2D(colorMap, uv0).xyz, 1);\n }\n ","DebugTextureShader")}return this.textureShader},t.getDepthTextureShader=function(){if(!this.depthTextureShader){var t="\n "+Wi.screenDepthPS+"\n varying vec2 uv0;\n void main() {\n float depth = getLinearScreenDepth(uv0) * camera_params.x;\n gl_FragColor = vec4(vec3(depth), 1.0);\n }\n ";this.depthTextureShader=on(this.device,e.getTextureVS(),t,"DebugDepthTextureShader")}return this.depthTextureShader},t.getQuadMesh=function(){return this.quadMesh||(this.quadMesh=new ea(this.device),this.quadMesh.setPositions([-.5,-.5,0,.5,-.5,0,-.5,.5,0,.5,.5,0]),this.quadMesh.update(5)),this.quadMesh},t.drawMesh=function(e,t,i,n,s){if(!n){var r=this.getGraphNode(t);n=new ka(i,e,r)}var a=this.layerMeshInstances.get(s);a||(a=[],this.layerMeshInstances.set(s,a)),a.push(n)},t.drawWireAlignedBox=function(e,t,i,n,s){jh.push(e.x,e.y,e.z,e.x,t.y,e.z,e.x,t.y,e.z,t.x,t.y,e.z,t.x,t.y,e.z,t.x,e.y,e.z,t.x,e.y,e.z,e.x,e.y,e.z,e.x,e.y,t.z,e.x,t.y,t.z,e.x,t.y,t.z,t.x,t.y,t.z,t.x,t.y,t.z,t.x,e.y,t.z,t.x,e.y,t.z,e.x,e.y,t.z,e.x,e.y,e.z,e.x,e.y,t.z,e.x,t.y,e.z,e.x,t.y,t.z,t.x,t.y,e.z,t.x,t.y,t.z,t.x,e.y,e.z,t.x,e.y,t.z),this.getBatch(s,n).addLinesArrays(jh,i),jh.length=0},t.drawWireSphere=function(e,t,i,n,s,r){for(var a=2*Math.PI/n,o=0,h=0;h<n;h++){var l=Math.sin(o),c=Math.cos(o);o+=a;var u=Math.sin(o),d=Math.cos(o);jh.push(e.x+t*l,e.y,e.z+t*c),jh.push(e.x+t*u,e.y,e.z+t*d),jh.push(e.x+t*l,e.y+t*c,e.z),jh.push(e.x+t*u,e.y+t*d,e.z),jh.push(e.x,e.y+t*l,e.z+t*c),jh.push(e.x,e.y+t*u,e.z+t*d)}this.getBatch(r,s).addLinesArrays(jh,i),jh.length=0},t.getGraphNode=function(e){var t=new Hn("ImmediateDebug");return t.worldTransform=e,t._dirtyWorld=t._dirtyNormal=!1,t},t.onPreRenderLayer=function(e,t,i){if(this.batchesMap.forEach((function(n,s){s===e&&n.onPreRender(t,i)})),!this.updatedLayers.has(e)){this.updatedLayers.add(e);var n=this.layerMeshInstances.get(e);if(n){for(var s=0;s<n.length;s++)t.list[t.length+s]=n[s];t.length+=n.length,n.length=0}}},t.onPostRender=function(){this.allBatches.clear(),this.updatedLayers.clear()},$(e,[{key:"materialDepth",get:function(){return this._materialDepth||(this._materialDepth=this.createMaterial(!0)),this._materialDepth}},{key:"materialNoDepth",get:function(){return this._materialNoDepth||(this._materialNoDepth=this.createMaterial(!1)),this._materialNoDepth}}]),e}(),Kh=function(e){function t(t){var i;return(i=e.call(this)||this).ambientBake=!1,i.ambientBakeOcclusionBrightness=0,i.ambientBakeOcclusionContrast=0,i.ambientLight=new me(0,0,0),i.ambientLuminance=0,i.exposure=1,i.fogColor=new me(0,0,0),i.fogDensity=0,i.fogEnd=1e3,i.fogStart=1,i.lightmapSizeMultiplier=1,i.lightmapMaxResolution=2048,i.lightmapMode=1,i.lightmapFilterEnabled=!1,i.root=null,i.sky=null,i.physicalUnits=!1,i.device=t||Kr().graphicsDevice,i._gravity=new ye(0,-9.8,0),i._layers=null,i._fog=Ue,i._gammaCorrection=1,i._toneMapping=0,i._skyboxCubeMap=null,i._prefilteredCubemaps=[null,null,null,null,null,null],i._envAtlas=null,i._internalEnvAtlas=null,i._skyboxIntensity=1,i._skyboxLuminance=0,i._skyboxMip=0,i._skyboxRotation=new Pe,i._skyboxRotationMat3=null,i._skyboxRotationMat4=null,i._ambientBakeNumSamples=1,i._ambientBakeSpherePart=.4,i._lightmapFilterRange=10,i._lightmapFilterSmoothness=.2,i._clusteredLightingEnabled=!0,i._lightingParams=new Lh(i.device.supportsAreaLights,i.device.maxTextureSize,(function(){i._layers._dirtyLights=!0})),i._stats={meshInstances:0,lights:0,dynamicLights:0,bakedLights:0,lastStaticPrepareFullTime:0,lastStaticPrepareSearchTime:0,lastStaticPrepareWriteTime:0,lastStaticPrepareTriAabbTime:0,lastStaticPrepareCombineTime:0,updateShadersTime:0},i.updateShaders=!0,i._shaderVersion=0,i._statsUpdated=!1,i.immediate=new Yh(i.device),i}J(t,e);var i=t.prototype;return i.destroy=function(){this._resetSky(),this.root=null,this.off()},i.drawLine=function(e,t,i,n,s){void 0===i&&(i=me.WHITE),void 0===n&&(n=!0),void 0===s&&(s=this.defaultDrawLayer),this.immediate.getBatch(s,n).addLines([e,t],[i,i])},i.drawLines=function(e,t,i,n){void 0===i&&(i=!0),void 0===n&&(n=this.defaultDrawLayer),this.immediate.getBatch(n,i).addLines(e,t)},i.drawLineArrays=function(e,t,i,n){void 0===i&&(i=!0),void 0===n&&(n=this.defaultDrawLayer),this.immediate.getBatch(n,i).addLinesArrays(e,t)},i.applySettings=function(e){var t=this,i=e.physics,n=e.render;this._gravity.set(i.gravity[0],i.gravity[1],i.gravity[2]),this.ambientLight.set(n.global_ambient[0],n.global_ambient[1],n.global_ambient[2]),this.ambientLuminance=n.ambientLuminance,this._fog=n.fog,this.fogColor.set(n.fog_color[0],n.fog_color[1],n.fog_color[2]),this.fogStart=n.fog_start,this.fogEnd=n.fog_end,this.fogDensity=n.fog_density,this._gammaCorrection=n.gamma_correction,this._toneMapping=n.tonemapping,this.lightmapSizeMultiplier=n.lightmapSizeMultiplier,this.lightmapMaxResolution=n.lightmapMaxResolution,this.lightmapMode=n.lightmapMode,this.exposure=n.exposure,this._skyboxIntensity=void 0===n.skyboxIntensity?1:n.skyboxIntensity,this._skyboxLuminance=void 0===n.skyboxLuminance?2e4:n.skyboxLuminance,this._skyboxMip=void 0===n.skyboxMip?0:n.skyboxMip,n.skyboxRotation&&this._skyboxRotation.setFromEulerAngles(n.skyboxRotation[0],n.skyboxRotation[1],n.skyboxRotation[2]),this.clusteredLightingEnabled=n.clusteredLightingEnabled,this.lighting.applySettings(n),["lightmapFilterEnabled","lightmapFilterRange","lightmapFilterSmoothness","ambientBake","ambientBakeNumSamples","ambientBakeSpherePart","ambientBakeOcclusionBrightness","ambientBakeOcclusionContrast"].forEach((function(e){n.hasOwnProperty(e)&&(t[e]=n[e])})),this._resetSky()},i._getSkyboxTex=function(){var e=this._prefilteredCubemaps;if(this._skyboxMip){return e[[0,1,3,4,5,6][this._skyboxMip]]||this._envAtlas||e[0]||this._skyboxCubeMap}return this._skyboxCubeMap||e[0]||this._envAtlas},i._updateSky=function(e){if(!this.sky){var t=this._getSkyboxTex();t&&(this.sky=new Gh(e,this,t),this.fire("set:skybox",t))}},i._resetSky=function(){var e;null==(e=this.sky)||e.destroy(),this.sky=null,this.updateShaders=!0},i.setSkybox=function(e){e?(this.skybox=e[0]||null,this.prefilteredCubemaps=e.slice(1)):(this.skybox=null,this.prefilteredCubemaps=[null,null,null,null,null,null])},$(t,[{key:"defaultDrawLayer",get:function(){return this.layers.getLayerById(3)}},{key:"ambientBakeNumSamples",get:function(){return this._ambientBakeNumSamples},set:function(e){this._ambientBakeNumSamples=de.clamp(Math.floor(e),1,255)}},{key:"ambientBakeSpherePart",get:function(){return this._ambientBakeSpherePart},set:function(e){this._ambientBakeSpherePart=de.clamp(e,.001,1)}},{key:"clusteredLightingEnabled",get:function(){return this._clusteredLightingEnabled},set:function(e){this._clusteredLightingEnabled||!e?this._clusteredLightingEnabled=e:console.error("Turning on disabled clustered lighting is not currently supported")}},{key:"drawCalls",get:function(){var e=this.layers._meshInstances;return e.length||(this.layers._update(this.device,this.clusteredLightingEnabled),e=this.layers._meshInstances),e},set:function(e){}},{key:"envAtlas",get:function(){return this._envAtlas},set:function(e){e!==this._envAtlas&&(this._envAtlas=e,this.updateShaders=!0)}},{key:"fog",get:function(){return this._fog},set:function(e){e!==this._fog&&(this._fog=e,this.updateShaders=!0)}},{key:"gammaCorrection",get:function(){return this._gammaCorrection},set:function(e){e!==this._gammaCorrection&&(this._gammaCorrection=e,this.updateShaders=!0)}},{key:"layers",get:function(){return this._layers},set:function(e){var t=this._layers;this._layers=e,this.fire("set:layers",t,e)}},{key:"lighting",get:function(){return this._lightingParams}},{key:"lightmapFilterRange",get:function(){return this._lightmapFilterRange},set:function(e){this._lightmapFilterRange=Math.max(e,.001)}},{key:"lightmapFilterSmoothness",get:function(){return this._lightmapFilterSmoothness},set:function(e){this._lightmapFilterSmoothness=Math.max(e,.001)}},{key:"prefilteredCubemaps",get:function(){return this._prefilteredCubemaps},set:function(e){var t=this._prefilteredCubemaps;e=e||[];for(var i=!1,n=!0,s=0;s<6;++s){var r=e[s]||null;t[s]!==r&&(t[s]=r,i=!0),n=n&&!!t[s]}i&&(this._resetSky(),n?(this._internalEnvAtlas=Ls.generatePrefilteredAtlas(t,{target:this._internalEnvAtlas}),this._envAtlas||(this.envAtlas=this._internalEnvAtlas)):this._internalEnvAtlas&&(this._envAtlas===this._internalEnvAtlas&&(this.envAtlas=null),this._internalEnvAtlas.destroy(),this._internalEnvAtlas=null))}},{key:"skybox",get:function(){return this._skyboxCubeMap},set:function(e){e!==this._skyboxCubeMap&&(this._skyboxCubeMap=e,this._resetSky())}},{key:"skyboxIntensity",get:function(){return this._skyboxIntensity},set:function(e){e!==this._skyboxIntensity&&(this._skyboxIntensity=e,this._resetSky())}},{key:"skyboxLuminance",get:function(){return this._skyboxLuminance},set:function(e){e!==this._skyboxLuminance&&(this._skyboxLuminance=e,this._resetSky())}},{key:"skyboxMip",get:function(){return this._skyboxMip},set:function(e){e!==this._skyboxMip&&(this._skyboxMip=e,this._resetSky())}},{key:"skyboxRotation",get:function(){return this._skyboxRotation},set:function(e){this._skyboxRotation.equals(e)||(this._skyboxRotation.copy(e),this._resetSky())}},{key:"toneMapping",get:function(){return this._toneMapping},set:function(e){e!==this._toneMapping&&(this._toneMapping=e,this.updateShaders=!0)}}]),t}(m),Zh=function(){function e(e){this._blobUrls={};for(var t=0,i=e.length;t<i;t++)e[t].url&&(this._blobUrls[e[t].name]=e[t].url)}var t=e.prototype;return t.hasBlobUrl=function(e){return!!this._blobUrls[e]},t.getBlobUrl=function(e){return this._blobUrls[e]},t.destroy=function(){for(var e in this._blobUrls)URL.revokeObjectURL(this._blobUrls[e]);this._blobUrls=null},e}();function $h(e){var t,i;if("undefined"!=typeof TextDecoder)try{t=new TextDecoder("utf-8"),i=new TextDecoder("windows-1252")}catch(e){console.warn("TextDecoder not supported - pc.Untar module will not work")}else console.warn("TextDecoder not supported - pc.Untar module will not work");function n(e){this._fields=e}function s(e){this._arrayBuffer=e||new ArrayBuffer(0),this._bufferView=new DataView(this._arrayBuffer),this._globalPaxHeader=null,this._paxHeader=null,this._bytesRead=0}n.parse=function(e,i,s){for(var r=new Uint8Array(e,i,s),a=0,o=[];a<s;){var h=void 0;for(h=a;h<s&&32!==r[h];h++);if(h>=s)throw new Error("Invalid PAX header data format.");var l=parseInt(t.decode(new Uint8Array(e,i+a,h-a)),10),c=t.decode(new Uint8Array(e,i+h+1,l-(h-a)-2)).split("=");if(2!==c.length)throw new Error("Invalid PAX header data format.");0===c[1].length&&(c[1]=null),o.push({name:c[0],value:c[1]}),a+=l}return new n(o)},n.prototype.applyHeader=function(e){for(var t=0;t<this._fields.length;t++){var i=this._fields[t].name,n=this._fields[t].value;"path"===i&&(i="name"),null===n?delete e[i]:e[i]=n}},e||(Hh=s),s.prototype._hasNext=function(){return this._bytesRead+4<this._arrayBuffer.byteLength&&0!==this._bufferView.getUint32(this._bytesRead)},s.prototype._readNextFile=function(){var t=new DataView(this._arrayBuffer,this._bytesRead,512),s=i.decode(t);this._bytesRead+=512;var r=s.substring(0,100).replace(/\0/g,""),a=s.substring(257,263),o=parseInt(s.substring(124,136),8),h=s.substring(156,157),l=this._bytesRead,c=null,u=!1;switch(h){case"0":case"":if(u=!0,!e){var d=new Blob([this._arrayBuffer.slice(this._bytesRead,this._bytesRead+o)]);c=URL.createObjectURL(d)}break;case"g":this._globalPaxHeader=n.parse(this._arrayBuffer,this._bytesRead,o);break;case"x":this._paxHeader=n.parse(this._arrayBuffer,this._bytesRead,o)}this._bytesRead+=o;var f=o%512;if(0!==f&&(this._bytesRead+=512-f),!u)return null;if(-1!==a.indexOf("ustar")){var p=s.substring(345,500).replace(/\0/g,"");p.length>0&&(r=p.trim()+r.trim())}var m={name:r,start:l,size:o,url:c};return this._globalPaxHeader&&this._globalPaxHeader.applyHeader(m),this._paxHeader&&(this._paxHeader.applyHeader(m),this._paxHeader=null),m},s.prototype.untar=function(e){if(!t)return console.error("Cannot untar because TextDecoder interface is not available for this platform."),[];for(var i=[];this._hasNext();){var n=this._readNextFile();n&&(e&&n.name&&(n.name=e+n.name),i.push(n))}return i},e&&(self.onmessage=function(e){var t=e.data.id;try{var i=new s(e.data.arrayBuffer).untar(e.data.prefix);postMessage({id:t,files:i,arrayBuffer:e.data.arrayBuffer},[e.data.arrayBuffer])}catch(e){postMessage({id:t,error:e.toString()})}})}var Qh=null;var Jh=function(){function e(e){this._requestId=0,this._pendingRequests={},this._filenamePrefix=e,this._worker=new Worker(function(){if(!Qh){var e="("+$h.toString()+")(true)\n\n",t=new Blob([e],{type:"application/javascript"});Qh=URL.createObjectURL(t)}return Qh}()),this._worker.addEventListener("message",this._onMessage.bind(this))}var t=e.prototype;return t._onMessage=function(e){var t=e.data.id;if(this._pendingRequests[t]){var i=this._pendingRequests[t];if(delete this._pendingRequests[t],e.data.error)i(e.data.error);else{for(var n=e.data.arrayBuffer,s=0,r=e.data.files.length;s<r;s++){var a=e.data.files[s],o=new Blob([n.slice(a.start,a.start+a.size)]);a.url=URL.createObjectURL(o)}i(null,e.data.files)}}},t.untar=function(e,t){var i=this._requestId++;this._pendingRequests[i]=t,this._worker.postMessage({id:i,prefix:this._filenamePrefix,arrayBuffer:e},[e])},t.hasPendingRequests=function(){return Object.keys(this._pendingRequests).length>0},t.destroy=function(){this._worker&&(this._worker.terminate(),this._worker=null,this._pendingRequests=null)},e}();$h();var el=function(){function e(e){this.handlerType="bundle",this._assets=e.assets,this._worker=null,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i=this;pe.get(e.load,{responseType:fe.ResponseType.ARRAY_BUFFER,retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(n,s){if(n)t("Error loading bundle resource "+e.original+": "+n);else try{i._untar(s,t)}catch(i){t("Error loading bundle resource "+e.original+": "+i)}}))},t._untar=function(e,t){var i=this;if(L.workers)i._worker||(i._worker=new Jh(i._assets.prefix)),i._worker.untar(e,(function(e,n){t(e,n),i._worker.hasPendingRequests()||(i._worker.destroy(),i._worker=null)}));else{var n=new Hh(e).untar(i._assets.prefix);t(null,n)}},t.open=function(e,t){return new Zh(t)},t.patch=function(e,t){},e}(),tl=function(){function e(e){this._handlers={},this._requests={},this._cache={},this._app=e}var t=e.prototype;return t.addHandler=function(e,t){this._handlers[e]=t,t._loader=this},t.removeHandler=function(e){delete this._handlers[e]},t.getHandler=function(e){return this._handlers[e]},t.load=function(e,t,i,n){var s=this._handlers[t];if(s)if(e){var r=e+t;if(void 0!==this._cache[r])i(null,this._cache[r]);else if(this._requests[r])this._requests[r].push(i);else{this._requests[r]=[i];var a=this,o=function(e,t){e?a._onFailure(r,e):s.load(t,(function(e,i,o){if(a._requests[r])if(e)a._onFailure(r,e);else try{a._onSuccess(r,s.open(t.original,i,n),o)}catch(e){a._onFailure(r,e)}}),n)},h=e.split("?")[0];if(this._app.enableBundles&&this._app.bundles.hasUrl(h)){if(!this._app.bundles.canLoadUrl(h))return void o("Bundle for "+e+" not loaded yet");this._app.bundles.loadUrl(h,(function(e,t){o(e,{load:t,original:h})}))}else o(null,{load:e,original:n&&n.file.filename||e})}}else this._loadNull(s,i,n);else i("No resource handler for asset type: '"+t+"' when loading ["+e+"]")},t._loadNull=function(e,t,i){e.load(null,(function(n,s,r){if(n)t(n);else try{t(null,e.open(null,s,i),r)}catch(e){t(e)}}),i)},t._onSuccess=function(e,t,i){this._cache[e]=t;for(var n=0;n<this._requests[e].length;n++)this._requests[e][n](null,t,i);delete this._requests[e]},t._onFailure=function(e,t){if(console.error(t),this._requests[e]){for(var i=0;i<this._requests[e].length;i++)this._requests[e][i](t);delete this._requests[e]}},t.open=function(e,t){var i=this._handlers[e];return i?i.open(null,t):(console.warn("No resource handler found for: "+e),t)},t.patch=function(e,t){var i=this._handlers[e.type];i?i.patch&&i.patch(e,t):console.warn("No resource handler found for: "+e.type)},t.clearCache=function(e,t){delete this._cache[e+t]},t.getFromCache=function(e,t){if(this._cache[e+t])return this._cache[e+t]},t.enableRetry=function(e){for(var t in void 0===e&&(e=5),e=Math.max(0,e)||0,this._handlers)this._handlers[t].maxRetries=e},t.disableRetry=function(){for(var e in this._handlers)this._handlers[e].maxRetries=0},t.destroy=function(){this._handlers={},this._requests={},this._cache={}},e}(),il="en-US",nl={en:"en-US",es:"en-ES",zh:"zh-CN","zh-HK":"zh-TW","zh-TW":"zh-HK","zh-MO":"zh-HK",fr:"fr-FR",de:"de-DE",it:"it-IT",ru:"ru-RU",ja:"ja-JP"},sl={};function rl(e,t){for(var i=0,n=e.length;i<n;i++)sl[e[i]]=t}function al(e){var t=e.indexOf("-");return-1!==t?e.substring(0,t):e}function ol(e,t){if(t[e])return e;var i=nl[e];if(i&&t[i])return i;var n=al(e);return t[i=nl[n]]?i:t[n]?n:il}rl(["ja","ko","th","vi","zh","id"],(function(e){return 0})),rl(["fa","hi"],(function(e){return e>=0&&e<=1?0:1})),rl(["fr","pt"],(function(e){return e>=0&&e<2?0:1})),rl(["da"],(function(e){return 1===e||!Number.isInteger(e)&&e>=0&&e<=1?0:1})),rl(["de","en","it","el","es","tr","fi","sv","nb","no","ur"],(function(e){return 1===e?0:1})),rl(["ru","uk"],(function(e){if(Number.isInteger(e)){var t=e%10,i=e%100;if(1===t&&11!==i)return 0;if(t>=2&&t<=4&&(i<12||i>14))return 1;if(0===t||t>=5&&t<=9||i>=11&&i<=14)return 2}return 3})),rl(["pl"],(function(e){if(Number.isInteger(e)){if(1===e)return 0;var t=e%10,i=e%100;if(t>=2&&t<=4&&(i<12||i>14))return 1;if(t>=0&&t<=1||t>=5&&t<=9||i>=12&&i<=14)return 2}return 3})),rl(["ar"],(function(e){if(0===e)return 0;if(1===e)return 1;if(2===e)return 2;if(Number.isInteger(e)){var t=e%100;if(t>=3&&t<=10)return 3;if(t>=11&&t<=99)return 4}return 5}));var hl=sl[al(il)];function ll(e){return sl[e]||hl}var cl=new RegExp("^\\s*(?:(?:[a-z]+[a-z0-9\\-\\+\\.]*:)?//|data:|blob:)","i"),ul=function(){function e(e,t,i,n,s,r){this.url=e||"",this.filename=t||"",this.hash=void 0===i?null:i,this.size=void 0===n?null:n,this.opt=void 0===s?null:s,this.contents=r||null}return e.prototype.equals=function(e){return this.url===e.url&&this.filename===e.filename&&this.hash===e.hash&&this.size===e.size&&this.opt===e.opt&&this.contents===e.contents},e}(),dl=-1,fl={pvr:"extCompressedTexturePVRTC",dxt:"extCompressedTextureS3TC",etc2:"extCompressedTextureETC",etc1:"extCompressedTextureETC1",basis:"canvas"},pl=["pvr","dxt","etc2","etc1","basis"],ml=function(e){function t(t,i,n,s,r){var a;return(a=e.call(this)||this)._id=dl--,a.name=t||"",a.type=i,a.tags=new ae(te(a)),a._preload=!1,a._file=null,a._data=s||{},a.options=r||{},a._resources=[],a._i18n={},a.loaded=!1,a.loading=!1,a.registry=null,n&&(a.file=n),a}J(t,e);var i=t.prototype;return i.getFileUrl=function(){var e=this.file;if(!e||!e.url)return null;var t=e.url;if(this.registry&&this.registry.prefix&&!cl.test(t)&&(t=this.registry.prefix+t),"script"!==this.type&&e.hash){var i=-1!==t.indexOf("?")?"&":"?";t+=i+"t="+e.hash}return t},i.getAbsoluteUrl=function(e){if(e.startsWith("blob:")||e.startsWith("data:"))return e;var t=v.getDirectory(this.file.url);return v.join(t,e)},i.getLocalizedAssetId=function(e){return e=ol(e,this._i18n),this._i18n[e]||null},i.addLocalizedAssetId=function(e,t){this._i18n[e]=t,this.fire("add:localized",e,t)},i.removeLocalizedAssetId=function(e){var t=this._i18n[e];t&&(delete this._i18n[e],this.fire("remove:localized",e,t))},i.ready=function(e,t){t=t||this,this.loaded?e.call(t,this):this.once("load",(function(i){e.call(t,i)}))},i.reload=function(){this.loaded&&(this.loaded=!1,this.registry.load(this))},i.unload=function(){if(this.loaded||0!==this._resources.length){this.fire("unload",this),this.registry.fire("unload:"+this.id,this);var e=this._resources;this.resources=[],this.loaded=!1,this.file&&this.registry._loader.clearCache(this.getFileUrl(),this.type);for(var t=0;t<e.length;++t){var i=e[t];i&&i.destroy&&i.destroy()}}},t.fetchArrayBuffer=function(e,t,i,n){var s;void 0===n&&(n=0),null!=i&&null!=(s=i.file)&&s.contents?setTimeout((function(){t(null,i.file.contents)})):pe.get(e,{cache:!0,responseType:"arraybuffer",retry:n>0,maxRetries:n},t)},$(t,[{key:"id",get:function(){return this._id},set:function(e){this._id=e}},{key:"file",get:function(){return this._file},set:function(e){var t=this;if(e&&e.variants&&-1!==["texture","textureatlas","bundle"].indexOf(this.type)){var i,n,s=(null==(i=this.registry)||null==(n=i._loader)?void 0:n._app)||Kr(),r=null==s?void 0:s.graphicsDevice;if(r)for(var a=function(i,n){var a=pl[i];if(e.variants[a]&&r[fl[a]])return e=e.variants[a],"break";if(s.enableBundles){var o=s.bundles.listBundlesForAsset(t);if(o&&o.find((function(e){var t;return null==e||null==(t=e.file)?void 0:t.variants[a]})))return"break"}},o=0,h=pl.length;o<h;o++){if("break"===a(o))break}}var l=this._file,c=e?new ul(e.url,e.filename,e.hash,e.size,e.opt,e.contents):null;(!!c!=!!l||c&&!c.equals(l))&&(this._file=c,this.fire("change",this,"file",c,l),this.reload())}},{key:"data",get:function(){return this._data},set:function(e){var t=this._data;this._data=e,e!==t&&(this.fire("change",this,"data",e,t),this.loaded&&this.registry._loader.patch(this,this.registry))}},{key:"resource",get:function(){return this._resources[0]},set:function(e){var t=this._resources[0];this._resources[0]=e,this.fire("change",this,"resource",e,t)}},{key:"resources",get:function(){return this._resources},set:function(e){var t=this._resources;this._resources=e,this.fire("change",this,"resources",e,t)}},{key:"preload",get:function(){return this._preload},set:function(e){e=!!e,this._preload!==e&&(this._preload=e,this._preload&&!this.loaded&&!this.loading&&this.registry&&this.registry.load(this))}},{key:"loadFaces",get:function(){return this._loadFaces},set:function(e){e=!!e,this.hasOwnProperty("_loadFaces")&&e===this._loadFaces||(this._loadFaces=e,this.loaded&&this.registry._loader.patch(this,this.registry))}}]),t}(m),_l=function(){function e(e){void 0===e&&(e=null),this._index={},this._key=e}var t=e.prototype;return t.addItem=function(e){for(var t,i=ne(e.tags._list);!(t=i()).done;){var n=t.value;this.add(n,e)}},t.removeItem=function(e){for(var t,i=ne(e.tags._list);!(t=i()).done;){var n=t.value;this.remove(n,e)}},t.add=function(e,t){this._index[e]&&-1!==this._index[e].list.indexOf(t)||(this._index[e]||(this._index[e]={list:[]},this._key&&(this._index[e].keys={})),this._index[e].list.push(t),this._key&&(this._index[e].keys[t[this._key]]=t))},t.remove=function(e,t){if(this._index[e]&&(!this._key||this._index[e].keys[t[this._key]])){var i=this._index[e].list.indexOf(t);-1!==i&&(this._index[e].list.splice(i,1),this._key&&delete this._index[e].keys[t[this._key]],0===this._index[e].list.length&&delete this._index[e])}},t.find=function(e){for(var t,i,n,s,r,a=this,o={},h=[],l=function(e,t){return a._index[e].list.length-a._index[t].list.length},c=0;c<e.length;c++){if((i=e[c])instanceof Array){if(0===i.length)continue;if(1!==i.length){r=!1;for(var u=0;u<i.length;u++)if(!this._index[i[u]]){r=!0;break}if(r)continue;1===(s=(n=i.slice(0).sort(l)).slice(1)).length&&(s=s[0]);for(var d=0;d<this._index[n[0]].list.length;d++)t=this._index[n[0]].list[d],(this._key?!o[t[this._key]]:-1===h.indexOf(t))&&t.tags.has(s)&&(this._key&&(o[t[this._key]]=!0),h.push(t));continue}i=i[0]}if(i&&"string"==typeof i&&this._index[i])for(var f=0;f<this._index[i].list.length;f++)t=this._index[i].list[f],this._key?o[t[this._key]]||(o[t[this._key]]=!0,h.push(t)):-1===h.indexOf(t)&&h.push(t)}return h},e}(),gl=function(){function e(e){this.handlerType="script",this._app=e,this._scripts={},this._cache={}}e._push=function(t){xl.legacy&&e._types.length>0?console.assert("Script Ordering Error. Contact support@playcanvas.com"):e._types.push(t)};var t=e.prototype;return t.load=function(t,i){var n=this;"string"==typeof t&&(t={load:t,original:t});var s=this;xl.app=this._app,this._loadScript(t.load,(function(t,r,a){if(t)i(t);else if(xl.legacy){var o=null;e._types.length&&(o=e._types.pop()),o?n._scripts[r]=o:o=null,i(null,o,a)}else{for(var h={},l=0;l<e._types.length;l++)h[e._types[l].name]=e._types[l];e._types.length=0,i(null,h,a),delete s._loader._cache[r+"script"]}}))},t.open=function(e,t){return t},t.patch=function(e,t){},t._loadScript=function(e,t){var i=document.head,n=document.createElement("script");this._cache[e]=n,n.async=!1,n.addEventListener("error",(function(e){t("Script: "+e.target.src+" failed to load")}),!1);var s=!1;n.onload=n.onreadystatechange=function(){s||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState||(s=!0,t(null,e,n))},n.src=e,i.appendChild(n)},e}();gl._types=[];var vl=!1,yl=!1,xl={app:null,create:function(e,t){if(vl){var i=t(xl.app);i._pcScriptName=e,gl._push(i),this.fire("created",e,t)}},attribute:function(e,t,i,n){},createLoadingScreen:function(e){yl||(yl=!0,e(Kr()))}};Object.defineProperty(xl,"legacy",{get:function(){return vl},set:function(e){vl=e}}),_.attach(xl);var bl=function(e){function t(t){var i;return(i=e.call(this)||this)._loader=t,i._assets=[],i._cache={},i._names={},i._tags=new _l("_id"),i._urls={},i.prefix=null,i}J(t,e);var i=t.prototype;return i.list=function(e){return e=e||{},this._assets.filter((function(t){var i=!0;return void 0!==e.preload&&(i=t.preload===e.preload),i}))},i.add=function(e){var t,i=this._assets.push(e)-1;this._cache[e.id]=i,this._names[e.name]||(this._names[e.name]=[]),this._names[e.name].push(i),e.file&&(t=e.file.url,this._urls[t]=i),e.registry=this,this._tags.addItem(e),e.tags.on("add",this._onTagAdd,this),e.tags.on("remove",this._onTagRemove,this),this.fire("add",e),this.fire("add:"+e.id,e),t&&this.fire("add:url:"+t,e),e.preload&&this.load(e)},i.remove=function(e){var t=this._cache[e.id],i=e.file?e.file.url:null;if(void 0!==t){this._assets.splice(t,1),delete this._cache[e.id],this._names={},this._urls=[];for(var n=0,s=this._assets.length;n<s;n++){var r=this._assets[n];this._cache[r.id]=n,this._names[r.name]||(this._names[r.name]=[]),this._names[r.name].push(n),r.file&&(this._urls[r.file.url]=n)}return this._tags.removeItem(e),e.tags.off("add",this._onTagAdd,this),e.tags.off("remove",this._onTagRemove,this),e.fire("remove",e),this.fire("remove",e),this.fire("remove:"+e.id,e),i&&this.fire("remove:url:"+i,e),!0}return!1},i.get=function(e){var t=this._cache[e];return this._assets[t]},i.getByUrl=function(e){var t=this._urls[e];return this._assets[t]},i.load=function(e){var t=this;if(!e.loading&&!e.loaded){var i=e.file,n=function(n){n instanceof Array?e.resources=n:e.resource=n,t._loader.patch(e,t),t.fire("load",e),t.fire("load:"+e.id,e),i&&i.url&&t.fire("load:url:"+i.url,e),e.fire("load",e)};if(i||"cubemap"===e.type)this.fire("load:start",e),this.fire("load:"+e.id+":start",e),e.loading=!0,this._loader.load(e.getFileUrl(),e.type,(function(i,s,r){if(e.loaded=!0,e.loading=!1,i)t.fire("error",i,e),t.fire("error:"+e.id,i,e),e.fire("error",i,e);else{if(!xl.legacy&&"script"===e.type){var a=t._loader.getHandler("script");a._cache[e.id]&&a._cache[e.id].parentNode===document.head&&document.head.removeChild(a._cache[e.id]),a._cache[e.id]=r}n(s)}}),e);else{var s=this._loader.open(e.type,e.data);e.loaded=!0,n(s)}}},i.loadFromUrl=function(e,t,i){this.loadFromUrlAndFilename(e,null,t,i)},i.loadFromUrlAndFilename=function(e,t,i,n){var s=this,r=v.getBasename(t||e),a={filename:t||r,url:e},o=this.getByUrl(e);if(o){if(o.loaded)return void n(o.loadFromUrlError||null,o)}else o=new ml(r,i,a),this.add(o);var h=function(e){e.once("load",(function(e){"material"===i?s._loadTextures(e,(function(t,i){n(t,e)})):n(null,e)})),e.once("error",(function(t){t&&(s.loadFromUrlError=t),n(t,e)})),s.load(e)};o.resource?n(null,o):"model"===i?this._loadModel(o,h):h(o)},i._loadModel=function(e,t){var i=this,n=e.getFileUrl(),s=v.getExtension(n);if(".json"===s||".glb"===s){var r=v.getDirectory(n),a=v.getBasename(n),o=v.join(r,a.replace(s,".mapping.json"));this._loader.load(o,"json",(function(n,s){n?(e.data={mapping:[]},t(e)):i._loadMaterials(e,s,(function(i,n){e.data=s,t(e)}))}))}else t(e)},i._loadMaterials=function(e,t,i){for(var n=this,s=[],r=0,a=function(e,t){n._loadTextures(t,(function(e,n){s.push(t),s.length===r&&i(null,s)}))},o=0;o<t.mapping.length;o++){var h=t.mapping[o].path;if(h){r++;var l=e.getAbsoluteUrl(h);this.loadFromUrl(l,"material",a)}}0===r&&i(null,s)},i._loadTextures=function(e,t){var i=[],n=0,s=e.data;if("path"===s.mappingFormat){for(var r=function(e,s){e&&console.error(e),i.push(s),i.length===n&&t(null,i)},a=Gs,o=0;o<a.length;o++){var h=s[a[o]];if(h&&"string"==typeof h){n++;var l=e.getAbsoluteUrl(h);this.loadFromUrl(l,"texture",r)}}0===n&&t(null,i)}else t(null,i)},i.findAll=function(e,t){var i=this,n=this._names[e];if(n){var s=n.map((function(e){return i._assets[e]}));return t?s.filter((function(e){return e.type===t})):s}return[]},i._onTagAdd=function(e,t){this._tags.add(e,t)},i._onTagRemove=function(e,t){this._tags.remove(e,t)},i.findByTag=function(){return this._tags.find(arguments)},i.filter=function(e){return this._assets.filter((function(t){return e(t)}))},i.find=function(e,t){var i=this.findAll(e,t);return i.length>0?i[0]:null},t}(m),Sl=function(){function e(e){this._assets=e,this._bundleAssets={},this._assetsInBundles={},this._urlsInBundles={},this._fileRequests={},this._assets.on("add",this._onAssetAdded,this),this._assets.on("remove",this._onAssetRemoved,this)}var t=e.prototype;return t._onAssetAdded=function(e){if("bundle"===e.type){this._bundleAssets[e.id]=e,this._registerBundleEventListeners(e.id);for(var t=0,i=e.data.assets.length;t<i;t++)this._indexAssetInBundle(e.data.assets[t],e)}else this._assetsInBundles[e.id]&&this._indexAssetFileUrls(e)},t._registerBundleEventListeners=function(e){this._assets.on("load:"+e,this._onBundleLoaded,this),this._assets.on("error:"+e,this._onBundleError,this)},t._unregisterBundleEventListeners=function(e){this._assets.off("load:"+e,this._onBundleLoaded,this),this._assets.off("error:"+e,this._onBundleError,this)},t._indexAssetInBundle=function(e,t){if(this._assetsInBundles[e]){var i=this._assetsInBundles[e];-1===i.indexOf(t)&&i.push(t)}else this._assetsInBundles[e]=[t];var n=this._assets.get(e);n&&this._indexAssetFileUrls(n)},t._indexAssetFileUrls=function(e){var t=this._getAssetFileUrls(e);if(t)for(var i=0,n=t.length;i<n;i++){var s=t[i];this._urlsInBundles[s]=this._assetsInBundles[e.id]}},t._getAssetFileUrls=function(e){var t=e.getFileUrl();if(!t)return null;var i=[t=this._normalizeUrl(t)];if("font"===e.type)for(var n=e.data.info.maps.length,s=1;s<n;s++)i.push(t.replace(".png",s+".png"));return i},t._normalizeUrl=function(e){return e&&e.split("?")[0]},t._onAssetRemoved=function(e){if("bundle"===e.type){for(var t in delete this._bundleAssets[e.id],this._unregisterBundleEventListeners(e.id),this._assetsInBundles){var i=this._assetsInBundles[t],n=i.indexOf(e);if(-1!==n&&(i.splice(n,1),!i.length))for(var s in delete this._assetsInBundles[t],this._urlsInBundles)this._urlsInBundles[s]===i&&delete this._urlsInBundles[s]}this._onBundleError("Bundle "+e.id+" was removed",e)}else if(this._assetsInBundles[e.id]){delete this._assetsInBundles[e.id];for(var r=this._getAssetFileUrls(e),a=0,o=r.length;a<o;a++)delete this._urlsInBundles[r[a]]}},t._onBundleLoaded=function(e){var t=this;e.resource?requestAnimationFrame((function(){if(t._fileRequests)for(var i in t._fileRequests){var n=t._urlsInBundles[i];if(n&&-1!==n.indexOf(e)){var s=decodeURIComponent(i),r=null;e.resource.hasBlobUrl(s)||(r="Bundle "+e.id+" does not contain URL "+i);for(var a=t._fileRequests[i],o=0,h=a.length;o<h;o++)r?a[o](r):a[o](null,e.resource.getBlobUrl(s));delete t._fileRequests[i]}}})):this._onBundleError("Bundle "+e.id+" failed to load",e)},t._onBundleError=function(e,t){for(var i in this._fileRequests){if(!this._findLoadedOrLoadingBundleForUrl(i)){for(var n=this._fileRequests[i],s=0,r=n.length;s<r;s++)n[s](e);delete this._fileRequests[i]}}},t._findLoadedOrLoadingBundleForUrl=function(e){var t=this._urlsInBundles[e];if(!t)return null;for(var i=t.length,n=0;n<i;n++)if(t[n].loaded&&t[n].resource)return t[n];for(var s=0;s<i;s++)if(t[s].loading)return t[s];return null},t.listBundlesForAsset=function(e){return this._assetsInBundles[e.id]||null},t.list=function(){var e=[];for(var t in this._bundleAssets)e.push(this._bundleAssets[t]);return e},t.hasUrl=function(e){return!!this._urlsInBundles[e]},t.canLoadUrl=function(e){return!!this._findLoadedOrLoadingBundleForUrl(e)},t.loadUrl=function(e,t){var i=this._findLoadedOrLoadingBundleForUrl(e);if(i)if(i.loaded){var n=decodeURIComponent(e);if(!i.resource.hasBlobUrl(n))return void t("Bundle "+i.id+" does not contain URL "+e);t(null,i.resource.getBlobUrl(n))}else this._fileRequests.hasOwnProperty(e)?this._fileRequests[e].push(t):this._fileRequests[e]=[t];else t("URL "+e+" not found in any bundles")},t.destroy=function(){for(var e in this._assets.off("add",this._onAssetAdded,this),this._assets.off("remove",this._onAssetRemoved,this),this._bundleAssets)this._unregisterBundleEventListeners(e);this._assets=null,this._bundleAssets=null,this._assetsInBundles=null,this._urlsInBundles=null,this._fileRequests=null},e}(),wl=["x","y","z","w"],Tl=[void 0,void 0,be,ye,Se];function Al(e,t,i,n){switch(t.type){case"boolean":return!!i;case"number":if("number"==typeof i)return i;if("string"==typeof i){var s=parseInt(i,10);return isNaN(s)?null:s}return"boolean"==typeof i?0+i:null;case"json":var r={};if(Array.isArray(t.schema)){i&&"object"==typeof i||(i={});for(var a=0;a<t.schema.length;a++){var o=t.schema[a];if(o.name)if(o.array){r[o.name]=[];for(var h=Array.isArray(i[o.name])?i[o.name]:[],l=0;l<h.length;l++)r[o.name].push(Al(e,o,h[l]))}else{var c=i.hasOwnProperty(o.name)?i[o.name]:o.default;r[o.name]=Al(e,o,c)}}}return r;case"asset":return i instanceof ml?i:"number"==typeof i?e.assets.get(i)||null:"string"==typeof i&&e.assets.get(parseInt(i,10))||null;case"entity":return i instanceof Hn?i:"string"==typeof i?e.getEntityFromIndex(i):null;case"rgb":case"rgba":if(i instanceof me)return n instanceof me?(n.copy(i),n):i.clone();if(i instanceof Array&&i.length>=3&&i.length<=4){for(var u=0;u<i.length;u++)if("number"!=typeof i[u])return null;return n||(n=new me),n.r=i[0],n.g=i[1],n.b=i[2],n.a=3===i.length?1:i[3],n}return"string"==typeof i&&/#([0-9abcdef]{2}){3,4}/i.test(i)?(n||(n=new me),n.fromString(i),n):null;case"vec2":case"vec3":case"vec4":var d=parseInt(t.type.slice(3),10),f=Tl[d];if(i instanceof f)return n instanceof f?(n.copy(i),n):i.clone();if(i instanceof Array&&i.length===d){for(var p=0;p<i.length;p++)if("number"!=typeof i[p])return null;n||(n=new f);for(var m=0;m<d;m++)n[wl[m]]=i[m];return n}return null;case"curve":if(i){var _;if(i instanceof ge||i instanceof ve)_=i.clone();else(_=new(i.keys[0]instanceof Array?ve:ge)(i.keys)).type=i.type;return _}}return i}var Ml=function(){function e(e){this.scriptType=e,this.index={}}var t=e.prototype;return t.add=function(t,i){this.index[t]||e.reservedNames.has(t)||(this.index[t]=i,Object.defineProperty(this.scriptType.prototype,t,{get:function(){return this.__attributes[t]},set:function(e){var n="attr",s="attr:"+t,r=this.__attributes[t],a=r;if(r&&"json"!==i.type&&r.clone&&(this._callbacks.attr||this._callbacks[s])&&(a=r.clone()),i.array){if(this.__attributes[t]=[],e)for(var o=0,h=e.length;o<h;o++)this.__attributes[t].push(Al(this.app,i,e[o],r?r[o]:null))}else this.__attributes[t]=Al(this.app,i,e,r);this.fire(n,t,this.__attributes[t],a),this.fire(s,this.__attributes[t],a)}}))},t.remove=function(e){return!!this.index[e]&&(delete this.index[e],delete this.scriptType.prototype[e],!0)},t.has=function(e){return!!this.index[e]},t.get=function(e){return this.index[e]||null},e}();Ml.reservedNames=new Set(["app","entity","enabled","_enabled","_enabledOld","_destroyed","__attributes","__attributesRaw","__scriptType","__executionOrder","_callbacks","has","get","on","off","fire","once","hasEvent"]);var Cl=function(e){function t(t,i){var n;return(n=e.call(this)||this).system=void 0,n.entity=void 0,n.system=t,n.entity=i,n.system.schema&&!n._accessorsBuilt&&n.buildAccessors(n.system.schema),n.on("set",(function(e,t,i){this.fire("set_"+e,e,t,i)})),n.on("set_enabled",n.onSetEnabled,te(n)),n}J(t,e),t._buildAccessors=function(e,t){t.forEach((function(t){var i="object"==typeof t?t.name:t;Object.defineProperty(e,i,{get:function(){return this.data[i]},set:function(e){var t=this.data,n=t[i];t[i]=e,this.fire("set",i,n,e)},configurable:!0})})),e._accessorsBuilt=!0};var i=t.prototype;return i.buildAccessors=function(e){t._buildAccessors(this,e)},i.onSetEnabled=function(e,t,i){t!==i&&this.entity.enabled&&(i?this.onEnable():this.onDisable())},i.onEnable=function(){},i.onDisable=function(){},i.onPostStateChange=function(){},$(t,[{key:"data",get:function(){var e=this.system.store[this.entity.getGuid()];return e?e.data:null}}]),t}(m),El=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._scripts=[],n._updateList=new re({sortBy:"__executionOrder"}),n._postUpdateList=new re({sortBy:"__executionOrder"}),n._scriptsIndex={},n._destroyedScripts=[],n._destroyed=!1,n._scriptsData=null,n._oldState=!0,n._enabled=!0,n._beingEnabled=!1,n._isLoopingThroughScripts=!1,n._executionOrder=-1,n.on("set_enabled",n._onSetEnabled,te(n)),n}J(t,e);var i=t.prototype;return i.onEnable=function(){this._beingEnabled=!0,this._checkState(),this.entity._beingEnabled||this.onPostStateChange(),this._beingEnabled=!1},i.onDisable=function(){this._checkState()},i.onPostStateChange=function(){for(var e=this._beginLooping(),i=0,n=this.scripts.length;i<n;i++){var s=this.scripts[i];s._initialized&&!s._postInitialized&&s.enabled&&(s._postInitialized=!0,s.postInitialize&&this._scriptMethod(s,t.scriptMethods.postInitialize))}this._endLooping(e)},i._beginLooping=function(){var e=this._isLoopingThroughScripts;return this._isLoopingThroughScripts=!0,e},i._endLooping=function(e){this._isLoopingThroughScripts=e,this._isLoopingThroughScripts||this._removeDestroyedScripts()},i._onSetEnabled=function(e,t,i){this._beingEnabled=!0,this._checkState(),this._beingEnabled=!1},i._checkState=function(){var e=this.enabled&&this.entity.enabled;if(e!==this._oldState){this._oldState=e,this.fire(e?"enable":"disable"),this.fire("state",e),e?this.system._addComponentToEnabled(this):this.system._removeComponentFromEnabled(this);for(var t=this._beginLooping(),i=0,n=this.scripts.length;i<n;i++){var s=this.scripts[i];s.enabled=s._enabled}this._endLooping(t)}},i._onBeforeRemove=function(){this.fire("remove");for(var e=this._beginLooping(),t=0;t<this.scripts.length;t++){var i=this.scripts[t];i&&this.destroy(i.__scriptType.__name)}this._endLooping(e)},i._removeDestroyedScripts=function(){var e=this._destroyedScripts.length;if(e){for(var t=0;t<e;t++){var i=this._destroyedScripts[t];this._removeScriptInstance(i)}this._destroyedScripts.length=0,this._resetExecutionOrder(0,this._scripts.length)}},i._onInitializeAttributes=function(){for(var e=0,t=this.scripts.length;e<t;e++)this.scripts[e].__initializeAttributes()},i._scriptMethod=function(e,t,i){e[t](i)},i._onInitialize=function(){for(var e=this._scripts,i=this._beginLooping(),n=0,s=e.length;n<s;n++){var r=e[n];!r._initialized&&r.enabled&&(r._initialized=!0,r.initialize&&this._scriptMethod(r,t.scriptMethods.initialize))}this._endLooping(i)},i._onPostInitialize=function(){this.onPostStateChange()},i._onUpdate=function(e){var i=this._updateList;if(i.length){var n=this._beginLooping();for(i.loopIndex=0;i.loopIndex<i.length;i.loopIndex++){var s=i.items[i.loopIndex];s.enabled&&this._scriptMethod(s,t.scriptMethods.update,e)}this._endLooping(n)}},i._onPostUpdate=function(e){var i=this._postUpdateList;if(i.length){var n=this._beginLooping();for(i.loopIndex=0;i.loopIndex<i.length;i.loopIndex++){var s=i.items[i.loopIndex];s.enabled&&this._scriptMethod(s,t.scriptMethods.postUpdate,e)}this._endLooping(n)}},i._insertScriptInstance=function(e,t,i){-1===t?(this._scripts.push(e),e.__executionOrder=i,e.update&&this._updateList.append(e),e.postUpdate&&this._postUpdateList.append(e)):(this._scripts.splice(t,0,e),e.__executionOrder=t,this._resetExecutionOrder(t+1,i+1),e.update&&this._updateList.insert(e),e.postUpdate&&this._postUpdateList.insert(e))},i._removeScriptInstance=function(e){var t=this._scripts.indexOf(e);return-1===t||(this._scripts.splice(t,1),e.update&&this._updateList.remove(e),e.postUpdate&&this._postUpdateList.remove(e)),t},i._resetExecutionOrder=function(e,t){for(var i=e;i<t;i++)this._scripts[i].__executionOrder=i},i._resolveEntityScriptAttribute=function(e,t,i,n,s,r){if(e.array){var a=i.length;if(!a)return;for(var o=i.slice(),h=0;h<a;h++){var l=o[h]instanceof $l?o[h].getGuid():o[h];r[l]&&(o[h]=n?r[l].getGuid():r[l])}s[t]=o}else{if(i instanceof $l)i=i.getGuid();else if("string"!=typeof i)return;r[i]&&(s[t]=r[i])}},i.has=function(e){if("string"==typeof e)return!!this._scriptsIndex[e];if(!e)return!1;var t=e,i=t.__name,n=this._scriptsIndex[i];return(n&&n.instance)instanceof t},i.get=function(e){if("string"==typeof e){var t=this._scriptsIndex[e];return t?t.instance:null}if(!e)return null;var i=e,n=i.__name,s=this._scriptsIndex[n],r=s&&s.instance;return r instanceof i?r:null},i.create=function(e,i){void 0===i&&(i={});var n=this,s=e,r=e;if("string"==typeof s?s=this.system.app.scripts.get(s):s&&(r=s.__name),s){if(!this._scriptsIndex[r]||!this._scriptsIndex[r].instance){var a=new s({app:this.system.app,entity:this.entity,enabled:!i.hasOwnProperty("enabled")||i.enabled,attributes:i.attributes}),o=this._scripts.length,h=-1;return"number"==typeof i.ind&&-1!==i.ind&&o>i.ind&&(h=i.ind),this._insertScriptInstance(a,h,o),this._scriptsIndex[r]={instance:a,onSwap:function(){n.swap(r)}},this[r]=a,i.preloading||a.__initializeAttributes(),this.fire("create",r,a),this.fire("create:"+r,a),this.system.app.scripts.on("swap:"+r,this._scriptsIndex[r].onSwap),i.preloading||(a.enabled&&!a._initialized&&(a._initialized=!0,a.initialize&&this._scriptMethod(a,t.scriptMethods.initialize)),a.enabled&&!a._postInitialized&&(a._postInitialized=!0,a.postInitialize&&this._scriptMethod(a,t.scriptMethods.postInitialize))),a}}else this._scriptsIndex[r]={awaiting:!0,ind:this._scripts.length};return null},i.destroy=function(e){var t=e,i=e;"string"==typeof i?i=this.system.app.scripts.get(i):i&&(t=i.__name);var n=this._scriptsIndex[t];if(delete this._scriptsIndex[t],!n)return!1;var s=n.instance;if(s&&!s._destroyed)if(s.enabled=!1,s._destroyed=!0,this._isLoopingThroughScripts)this._destroyedScripts.push(s);else{var r=this._removeScriptInstance(s);r>=0&&this._resetExecutionOrder(r,this._scripts.length)}return this.system.app.scripts.off("swap:"+t,n.onSwap),delete this[t],this.fire("destroy",t,s||null),this.fire("destroy:"+t,s||null),s&&s.fire("destroy"),!0},i.swap=function(e){var i=e,n=e;"string"==typeof n?n=this.system.app.scripts.get(n):n&&(i=n.__name);var s=this._scriptsIndex[i];if(!s||!s.instance)return!1;var r=s.instance,a=this._scripts.indexOf(r),o=new n({app:this.system.app,entity:this.entity,enabled:r.enabled,attributes:r.__attributes});return!!o.swap&&(o.__initializeAttributes(),this._scripts[a]=o,this._scriptsIndex[i].instance=o,this[i]=o,o.__executionOrder=a,r.update&&this._updateList.remove(r),r.postUpdate&&this._postUpdateList.remove(r),o.update&&this._updateList.insert(o),o.postUpdate&&this._postUpdateList.insert(o),this._scriptMethod(o,t.scriptMethods.swap,r),this.fire("swap",i,o),this.fire("swap:"+i,o),!0)},i.resolveDuplicatedEntityReferenceProperties=function(e,t){var i=this.entity.script;for(var n in e._scriptsIndex){var s=this.system.app.scripts.get(n);if(s){var r=e._scriptsIndex[n];if(r&&r.instance){var a=i[n].__attributesRaw,o=i[n].__attributes;if(a||o){var h=!!a,l=r.instance.__attributes;for(var c in l)if(l[c]){var u=s.attributes.get(c);if(u)if("entity"===u.type)this._resolveEntityScriptAttribute(u,c,l[c],h,a||o,t);else if("json"===u.type&&Array.isArray(u.schema))for(var d=l[c],f=a?a[c]:o[c],p=0;p<u.schema.length;p++){var m=u.schema[p];if("entity"===m.type)if(u.array)for(var _=0;_<d.length;_++)this._resolveEntityScriptAttribute(m,m.name,d[_][m.name],h,f[_],t);else this._resolveEntityScriptAttribute(m,m.name,d[m.name],h,f,t)}}}}}}},i.move=function(e,t){var i=this._scripts.length;if(t>=i||t<0)return!1;var n=e,s=e;"string"!=typeof s?s=e.__name:n=null;var r=this._scriptsIndex[s];if(!r||!r.instance)return!1;var a=r.instance;if(n&&!(a instanceof n))return!1;var o=this._scripts.indexOf(a);return-1!==o&&o!==t&&(this._scripts.splice(t,0,this._scripts.splice(o,1)[0]),this._resetExecutionOrder(0,i),this._updateList.sort(),this._postUpdateList.sort(),this.fire("move",s,a,t,o),this.fire("move:"+s,a,t,o),!0)},$(t,[{key:"scripts",get:function(){return this._scripts},set:function(e){for(var t in this._scriptsData=e,e)if(e.hasOwnProperty(t)){var i=this._scriptsIndex[t];if(i){if("boolean"==typeof e[t].enabled&&(i.enabled=!!e[t].enabled),"object"==typeof e[t].attributes)for(var n in e[t].attributes)if(!Ml.reservedNames.has(n)){if(!i.__attributes.hasOwnProperty(n)){var s=this.system.app.scripts.get(t);s&&s.attributes.add(n,{})}i[n]=e[t].attributes[n]}}else console.log(this.order)}}},{key:"enabled",get:function(){return this._enabled},set:function(e){var t=this._enabled;this._enabled=e,this.fire("set","enabled",t,e)}}]),t}(Cl);El.scriptMethods={initialize:"initialize",postInitialize:"postInitialize",update:"update",postUpdate:"postUpdate",swap:"swap"};var Pl=new RegExp("^\\s*function(?:\\s|\\s*\\/\\*.*\\*\\/\\s*)+([^\\(\\s\\/]*)\\s*"),Rl=function(e){function t(t){var i;return(i=e.call(this)||this).app=void 0,i.entity=void 0,i._enabled=void 0,i._enabledOld=void 0,i._initialized=void 0,i._postInitialized=void 0,i.__destroyed=void 0,i.__attributes=void 0,i.__attributesRaw=void 0,i.__scriptType=void 0,i.__executionOrder=void 0,i.initScriptType(t),i}J(t,e);var i=t.prototype;return i.initScriptType=function(e){var t=this.constructor;this.app=e.app,this.entity=e.entity,this._enabled="boolean"!=typeof e.enabled||e.enabled,this._enabledOld=this.enabled,this.__destroyed=!1,this.__attributes={},this.__attributesRaw=e.attributes||{},this.__scriptType=t,this.__executionOrder=-1},t.__getScriptName=function(e){if("function"==typeof e){if("name"in Function.prototype)return e.name;if(e===Function||e===Function.prototype.constructor)return"Function";var t=(""+e).match(Pl);return t?t[1]:void 0}},i.__initializeAttributes=function(e){if(e||this.__attributesRaw){for(var t in this.__scriptType.attributes.index)this.__attributesRaw&&this.__attributesRaw.hasOwnProperty(t)?this[t]=this.__attributesRaw[t]:this.__attributes.hasOwnProperty(t)||(this.__scriptType.attributes.index[t].hasOwnProperty("default")?this[t]=this.__scriptType.attributes.index[t].default:this[t]=null);this.__attributesRaw=null}},t.extend=function(e){for(var t in e)e.hasOwnProperty(t)&&(this.prototype[t]=e[t])},$(t,[{key:"enabled",get:function(){return this._enabled&&!this._destroyed&&this.entity.script.enabled&&this.entity.enabled},set:function(e){this._enabled=!!e,this.enabled!==this._enabledOld&&(this._enabledOld=this.enabled,this.fire(this.enabled?"enable":"disable"),this.fire("state",this.enabled),!this._initialized&&this.enabled&&(this._initialized=!0,this.__initializeAttributes(!0),this.initialize&&this.entity.script._scriptMethod(this,El.scriptMethods.initialize)),this._initialized&&!this._postInitialized&&this.enabled&&!this.entity.script._beingEnabled&&(this._postInitialized=!0,this.postInitialize&&this.entity.script._scriptMethod(this,El.scriptMethods.postInitialize)))}}],[{key:"scriptName",get:function(){return this.__name}},{key:"attributes",get:function(){return this.hasOwnProperty("__attributes")||(this.__attributes=new Ml(this)),this.__attributes}}]),t}(m);Rl.__name=null;var Il=function(e){function t(t){var i;return(i=e.call(this)||this).app=t,i._scripts={},i._list=[],i}J(t,e);var i=t.prototype;return i.destroy=function(){this.app=null,this.off()},i.add=function(e){var t=this,i=e.__name;return this._scripts.hasOwnProperty(i)?(setTimeout((function(){if(e.prototype.swap){var n=t._scripts[i],s=t._list.indexOf(n);t._list[s]=e,t._scripts[i]=e,t.fire("swap",i,e),t.fire("swap:"+i,e)}else console.warn("script registry already has '"+i+"' script, define 'swap' method for new script type to enable code hot swapping")})),!1):(this._scripts[i]=e,this._list.push(e),this.fire("add",i,e),this.fire("add:"+i,e),setTimeout((function(){if(t._scripts.hasOwnProperty(i)&&t.app&&t.app.systems&&t.app.systems.script){var e,n=t.app.systems.script._components,s=[],r=[];for(n.loopIndex=0;n.loopIndex<n.length;n.loopIndex++){var a=n.items[n.loopIndex];if(a._scriptsIndex[i]&&a._scriptsIndex[i].awaiting){a._scriptsData&&a._scriptsData[i]&&(e=a._scriptsData[i].attributes);var o=a.create(i,{preloading:!0,ind:a._scriptsIndex[i].ind,attributes:e});o&&s.push(o)}}for(var h=0;h<s.length;h++)s[h].__initializeAttributes();for(var l=0;l<s.length;l++)s[l].enabled&&(s[l]._initialized=!0,r.push(s[l]),s[l].initialize&&s[l].initialize());for(var c=0;c<r.length;c++)r[c].enabled&&!r[c]._postInitialized&&(r[c]._postInitialized=!0,r[c].postInitialize&&r[c].postInitialize())}})),!0)},i.remove=function(e){var t=e,i=e;if("string"!=typeof i?i=t.__name:t=this.get(i),this.get(i)!==t)return!1;delete this._scripts[i];var n=this._list.indexOf(t);return this._list.splice(n,1),this.fire("remove",i,t),this.fire("remove:"+i,t),!0},i.get=function(e){return this._scripts[e]||null},i.has=function(e){if("string"==typeof e)return this._scripts.hasOwnProperty(e);if(!e)return!1;var t=e.__name;return this._scripts[t]===e},i.list=function(){return this._list},t}(m),Ll=function(){function e(){}var t=e.prototype;return t._validate=function(e){if(!e.header)throw new Error('pc.I18n#addData: Missing "header" field');if(!e.header.version)throw new Error('pc.I18n#addData: Missing "header.version" field');if(1!==e.header.version)throw new Error('pc.I18n#addData: Invalid "header.version" field');if(!e.data)throw new Error('pc.I18n#addData: Missing "data" field');if(!Array.isArray(e.data))throw new Error('pc.I18n#addData: "data" field must be an array');for(var t=0,i=e.data.length;t<i;t++){var n=e.data[t];if(!n.info)throw new Error('pc.I18n#addData: missing "data['+t+'].info" field');if(!n.info.locale)throw new Error('pc.I18n#addData: missing "data['+t+'].info.locale" field');if("string"!=typeof n.info.locale)throw new Error('pc.I18n#addData: "data['+t+'].info.locale" must be a string');if(!n.messages)throw new Error('pc.I18n#addData: missing "data['+t+'].messages" field')}},t.parse=function(e){return e.data},e}(),Dl=function(e){function t(t){var i;return(i=e.call(this)||this).locale=il,i._translations={},i._availableLangs={},i._app=t,i._assets=[],i._parser=new Ll,i}J(t,e),t.findAvailableLocale=function(e,t){return ol(e,t)};var i=t.prototype;return i.findAvailableLocale=function(e){if(this._translations[e])return e;var t=al(e);return this._findFallbackLocale(e,t)},i.getText=function(e,t){var i,n=e;t||(t=this._locale,i=this._lang);var s=this._translations[t];return s||(i||(i=al(t)),t=this._findFallbackLocale(t,i),s=this._translations[t]),s&&s.hasOwnProperty(e)&&(n=s[e],Array.isArray(n)&&(n=n[0]),null==n&&(n=e)),n},i.getPluralText=function(e,t,i){var n,s,r=e;i?s=ll(n=al(i)):(i=this._locale,n=this._lang,s=this._pluralFn);var a=this._translations[i];if(a||(s=ll(n=al(i=this._findFallbackLocale(i,n))),a=this._translations[i]),a&&a[e]&&s){var o=s(t);null==(r=a[e][o])&&(r=e)}return r},i.addData=function(e){var t;try{t=this._parser.parse(e)}catch(e){return void console.error(e)}for(var i=0,n=t.length;i<n;i++){var s=t[i],r=s.info.locale,a=s.messages;if(!this._translations[r]){this._translations[r]={};var o=al(r);this._availableLangs[o]||(this._availableLangs[o]=r)}Object.assign(this._translations[r],a),this.fire("data:add",r,a)}},i.removeData=function(e){var t;try{t=this._parser.parse(e)}catch(e){return void console.error(e)}for(var i=0,n=t.length;i<n;i++){var s=t[i],r=s.info.locale,a=this._translations[r];if(a){var o=s.messages;for(var h in o)delete a[h];0===Object.keys(a).length&&(delete this._translations[r],delete this._availableLangs[al(r)]),this.fire("data:remove",r,o)}}},i.destroy=function(){this._translations=null,this._availableLangs=null,this._assets=null,this._parser=null,this.off()},i._findFallbackLocale=function(e,t){var i=nl[e];return i&&this._translations[i]||(i=nl[t])&&this._translations[i]||(i=this._availableLangs[t])&&this._translations[i]?i:il},i._onAssetAdd=function(e){e.on("load",this._onAssetLoad,this),e.on("change",this._onAssetChange,this),e.on("remove",this._onAssetRemove,this),e.on("unload",this._onAssetUnload,this),e.resource&&this._onAssetLoad(e)},i._onAssetLoad=function(e){this.addData(e.resource)},i._onAssetChange=function(e){e.resource&&this.addData(e.resource)},i._onAssetRemove=function(e){e.off("load",this._onAssetLoad,this),e.off("change",this._onAssetChange,this),e.off("remove",this._onAssetRemove,this),e.off("unload",this._onAssetUnload,this),e.resource&&this.removeData(e.resource),this._app.assets.once("add:"+e.id,this._onAssetAdd,this)},i._onAssetUnload=function(e){e.resource&&this.removeData(e.resource)},$(t,[{key:"assets",get:function(){return this._assets},set:function(e){for(var t={},i=0,n=e.length;i<n;i++){t[e[i]instanceof ml?e[i].id:e[i]]=!0}for(var s=this._assets.length;s--;){var r=this._assets[s];if(!t[r]){this._app.assets.off("add:"+r,this._onAssetAdd,this);var a=this._app.assets.get(r);a&&this._onAssetRemove(a),this._assets.splice(s,1)}}for(var o in t){var h=parseInt(o,10);if(-1===this._assets.indexOf(h)){this._assets.push(h);var l=this._app.assets.get(h);l?this._onAssetAdd(l):this._app.assets.once("add:"+h,this._onAssetAdd,this)}}}},{key:"locale",get:function(){return this._locale},set:function(e){if(this._locale!==e){var t=al(e);if("in"!==t||(n=t="id",e=-1!==(s=(i=e).indexOf("-"))?n+i.substring(s):n,this._locale!==e)){var i,n,s,r=this._locale;this._locale=e,this._lang=t,this._pluralFn=ll(this._lang),this.fire("set:locale",e,r)}}}}]),t}(m),kl=function(e){function t(){var t;return(t=e.call(this)||this).anim=void 0,t.animation=void 0,t.audiolistener=void 0,t.audiosource=void 0,t.button=void 0,t.camera=void 0,t.collision=void 0,t.element=void 0,t.joint=void 0,t.layoutchild=void 0,t.layoutgroup=void 0,t.light=void 0,t.model=void 0,t.particlesystem=void 0,t.render=void 0,t.rigidbody=void 0,t.screen=void 0,t.script=void 0,t.scrollbar=void 0,t.scrollview=void 0,t.sound=void 0,t.sprite=void 0,t.zone=void 0,t.list=[],t}J(t,e);var i=t.prototype;return i.add=function(e){var t=e.id;if(this[t])throw new Error("ComponentSystem name '"+t+"' already registered or not allowed");this[t]=e,this.list.push(e)},i.remove=function(e){var t=e.id;if(!this[t])throw new Error("No ComponentSystem named '"+t+"' registered");delete this[t];var i=this.list.indexOf(this[t]);-1!==i&&this.list.splice(i,1)},i.destroy=function(){this.off();for(var e=0;e<this.list.length;e++)this.list[e].destroy()},t}(m),Ol=function(){function e(e){this.frame={fps:0,ms:0,dt:0,updateStart:0,updateTime:0,renderStart:0,renderTime:0,physicsStart:0,physicsTime:0,cullTime:0,sortTime:0,skinTime:0,morphTime:0,instancingTime:0,triangles:0,otherPrimitives:0,shaders:0,materials:0,cameras:0,shadowMapUpdates:0,shadowMapTime:0,depthMapTime:0,forwardTime:0,lightClustersTime:0,lightClusters:0,_timeToCountFrames:0,_fpsAccum:0},this.drawCalls={forward:0,depth:0,shadow:0,immediate:0,misc:0,total:0,skinned:0,instanced:0,removedByInstancing:0},this.misc={renderTargetCreationTime:0},this.particles={updatesPerFrame:0,_updatesPerFrame:0,frameTime:0,_frameTime:0},this.shaders=e._shaderStats,this.vram=e._vram,Object.defineProperty(this.vram,"totalUsed",{get:function(){return this.tex+this.vb+this.ib}}),Object.defineProperty(this.vram,"geom",{get:function(){return this.vb+this.ib}})}return $(e,[{key:"scene",get:function(){return Kr().scene._stats}},{key:"lightmapper",get:function(){var e;return null==(e=Kr().lightmapper)?void 0:e.stats}},{key:"batcher",get:function(){var e=Kr()._batcher;return e?e._stats:null}}]),e}(),Fl=function(){function e(e,t){this.name=e,this.url=t,this.data=null,this._loading=!1,this._onLoadedCallbacks=[]}return $(e,[{key:"loaded",get:function(){return!!this.data}},{key:"loading",get:function(){return this._loading}}]),e}(),Bl=function(){function e(e){this._app=e,this._list=[],this._index={},this._urlIndex={}}var t=e.prototype;return t.destroy=function(){this._app=null},t.list=function(){return this._list},t.add=function(e,t){if(this._index.hasOwnProperty(e))return!1;var i=new Fl(e,t),n=this._list.push(i);return this._index[i.name]=n-1,this._urlIndex[i.url]=n-1,!0},t.find=function(e){return this._index.hasOwnProperty(e)?this._list[this._index[e]]:null},t.findByUrl=function(e){return this._urlIndex.hasOwnProperty(e)?this._list[this._urlIndex[e]]:null},t.remove=function(e){if(this._index.hasOwnProperty(e)){var t=this._index[e],i=this._list[t];delete this._urlIndex[i.url],delete this._index[e],this._list.splice(t,1);for(var n=0;n<this._list.length;n++)i=this._list[n],this._index[i.name]=n,this._urlIndex[i.url]=n}},t._loadSceneData=function(e,t,i){var n=this._app,s=e;if("string"==typeof e&&(e=this.findByUrl(s)||this.find(s)||new Fl("Untitled",s)),s=e.url)if(e.loaded)i(null,e);else{if(n.assets&&n.assets.prefix&&!cl.test(s)&&(s=v.join(n.assets.prefix,s)),e._onLoadedCallbacks.push(i),!e._loading)n.loader.getHandler("hierarchy").load(s,(function(i,n){e.data=n,e._loading=!1;for(var s=0;s<e._onLoadedCallbacks.length;s++)e._onLoadedCallbacks[s](i,e);t||(e.data=null),e._onLoadedCallbacks.length=0}));e._loading=!0}else i("Cannot find scene to load")},t.loadSceneData=function(e,t){this._loadSceneData(e,!0,t)},t.unloadSceneData=function(e){"string"==typeof e&&(e=this.findByUrl(e)),e&&(e.data=null)},t._loadSceneHierarchy=function(e,t,i){var n=this;this._loadSceneData(e,!1,(function(e,s){if(e)i&&i(e);else{t&&t(s);var r=n._app;r._preloadScripts(s.data,(function(){var e=r.loader.getHandler("hierarchy");r.systems.script.preloading=!0;var t=e.open(s.url,s.data);r.systems.script.preloading=!1,r.loader.clearCache(s.url,"hierarchy"),r.root.addChild(t),r.systems.fire("initialize",t),r.systems.fire("postInitialize",t),r.systems.fire("postPostInitialize",t),i&&i(null,t)}))}}))},t.loadSceneHierarchy=function(e,t){this._loadSceneHierarchy(e,null,t)},t.loadSceneSettings=function(e,t){var i=this;this._loadSceneData(e,!1,(function(e,n){e?t&&t(e):(i._app.applySceneSettings(n.data.settings),t&&t(null))}))},t.changeScene=function(e,t){var i=this._app;this._loadSceneHierarchy(e,(function(e){for(var t=i.root.children;t.length>0;){var n=t[0];n.reparent(null),null==n.destroy||n.destroy()}i.applySceneSettings(e.data.settings)}),t)},t.loadScene=function(e,t){var i=this,n=this._app,s=n.loader.getHandler("scene");n.assets&&n.assets.prefix&&!cl.test(e)&&(e=v.join(n.assets.prefix,e)),s.load(e,(function(r,a){if(r)t&&t(r);else{n._preloadScripts(a,(function(){n.systems.script.preloading=!0;var r=s.open(e,a),o=i.findByUrl(e);o&&!o.loaded&&(o.data=a),n.systems.script.preloading=!1,n.loader.clearCache(e,"scene"),n.loader.patch({resource:r,type:"scene"},n.assets),n.root.addChild(r.root),n.systems.rigidbody&&"undefined"!=typeof Ammo&&n.systems.rigidbody.gravity.set(r._gravity.x,r._gravity.y,r._gravity.z),t&&t(null,r)}))}}))},e}(),Nl=["uSceneDepthMap","uDepthMap"],Ul=["uSceneColorMap","texture_grabPass"],zl=function(){function e(e){this.application=e,this.device=e.graphicsDevice,this.layer=null,this.colorFormat=this.device.defaultFramebufferAlpha?7:6,this.device.webgl2?this.initWebGl2():this.initWebGl1()}var t=e.prototype;return t.setupUniform=function(e,t,i){(t?Nl:Ul).forEach((function(t){return e.scope.resolve(t).setValue(i)}))},t.allocateTexture=function(e,t,i,n,s,r){return new wn(e,{name:i,format:n,width:t?t.colorBuffer.width:e.width,height:t?t.colorBuffer.height:e.height,mipmaps:r,minFilter:s?0:r?5:1,magFilter:s?0:1,addressU:1,addressV:1})},t.resizeCondition=function(e,t,i){var n=(null==t?void 0:t.width)||i.width,s=(null==t?void 0:t.height)||i.height;return!e||n!==e.width||s!==e.height},t.allocateRenderTarget=function(e,t,i,n,s,r,a){var o=a?Nl:Ul,h=this.allocateTexture(i,t,o[0],n,s,r);return e?(e.destroyFrameBuffers(),s?e._depthBuffer=h:e._colorBuffer=h):e=new cr({name:"renderTargetSceneGrab",colorBuffer:s?null:h,depthBuffer:s?h:null,depth:!s,stencil:i.supportsStencil,autoResolve:!1}),e},t.releaseRenderTarget=function(e){e&&(e.destroyTextureBuffers(),e.destroy())},t.initWebGl2=function(){var e=this.application,t=this;this.layer=new fh({enabled:!1,name:"Depth",id:1,onDisable:function(){t.releaseRenderTarget(this.depthRenderTarget),this.depthRenderTarget=null,t.releaseRenderTarget(this.colorRenderTarget),this.colorRenderTarget=null},onPreRenderOpaque:function(i){var n,s=e.graphicsDevice,r=this.cameras[i];if(r.renderSceneColorMap){var a;t.resizeCondition(this.colorRenderTarget,null==(a=r.renderTarget)?void 0:a.colorBuffer,s)&&(t.releaseRenderTarget(this.colorRenderTarget),this.colorRenderTarget=t.allocateRenderTarget(this.colorRenderTarget,r.renderTarget,s,this.colorFormat,!1,!0,!1)),s.copyRenderTarget(s.renderTarget,this.colorRenderTarget,!0,!1),s.activeTexture(s.maxCombinedTextures-1);var o=this.colorRenderTarget.colorBuffer;s.bindTexture(o),s.gl.generateMipmap(o.impl._glTarget),t.setupUniform(s,!1,o)}r.renderSceneDepthMap&&(t.resizeCondition(this.depthRenderTarget,null==(n=r.renderTarget)?void 0:n.depthBuffer,s)&&(t.releaseRenderTarget(this.depthRenderTarget),this.depthRenderTarget=t.allocateRenderTarget(this.depthRenderTarget,r.renderTarget,s,pt,!0,!1,!0)),s.copyRenderTarget(s.renderTarget,this.depthRenderTarget,!1,!0),t.setupUniform(s,!0,this.depthRenderTarget.depthBuffer))},onPostRenderOpaque:function(e){}})},t.initWebGl1=function(){var e=this.application,t=this;this.layer=new fh({enabled:!1,name:"Depth",id:1,shaderPass:2,onEnable:function(){this.depthRenderTarget=new cr({name:"depthRenderTarget-webgl1",depth:!0,stencil:e.graphicsDevice.supportsStencil,autoResolve:!1,graphicsDevice:e.graphicsDevice}),this.renderTarget=this.depthRenderTarget},onDisable:function(){this.depthRenderTarget.destroyTextureBuffers(),this.renderTarget=null,t.releaseRenderTarget(this.colorRenderTarget),this.colorRenderTarget=null},onPostCull:function(i){var n=e.graphicsDevice,s=this.cameras[i];if(s.renderSceneDepthMap){var r;t.resizeCondition(this.depthRenderTarget,null==(r=s.renderTarget)?void 0:r.depthBuffer,n)&&(this.depthRenderTarget.destroyTextureBuffers(),this.depthRenderTarget=t.allocateRenderTarget(this.depthRenderTarget,s.renderTarget,n,7,!1,!1,!0));for(var a=this.instances.visibleOpaque[i],o=a.list,h=e.scene.layers,l=h.subLayerEnabled,c=h.subLayerList,u=e.scene.layers.getLayerById(0).renderTarget,d=this.cameras[i],f=0,p=h.layerList,m=0;m<p.length;m++){var _=p[m];if(_===this)break;if(_.renderTarget===u&&_.enabled&&l[m]){var g=_.cameras.indexOf(d);if(!(g<0)){var v=c[m]?_.instances.visibleTransparent[g]:_.instances.visibleOpaque[g],y=v.length;v=v.list;for(var x=0;x<y;x++){var b=v[x];b.material&&b.material.depthWrite&&!b._noDepthDrawGl1&&(o[f]=b,f++)}}}}a.length=f}},onPreRenderOpaque:function(i){var n=e.graphicsDevice,s=this.cameras[i];if(s.renderSceneColorMap){var r;t.resizeCondition(this.colorRenderTarget,null==(r=s.renderTarget)?void 0:r.colorBuffer,n)&&(t.releaseRenderTarget(this.colorRenderTarget),this.colorRenderTarget=t.allocateRenderTarget(this.colorRenderTarget,s.renderTarget,n,this.colorFormat,!1,!1,!1));var a=this.colorRenderTarget._colorBuffer;a.impl._glTexture||a.impl.initialize(n,a),n.bindTexture(a);var o=n.gl;o.copyTexImage2D(o.TEXTURE_2D,0,a.impl._glFormat,0,0,a.width,a.height,0),a._needsUpload=!1,a._needsMipmapsUpload=!1,t.setupUniform(n,!1,a)}s.renderSceneDepthMap&&t.setupUniform(n,!0,this.depthRenderTarget.colorBuffer)},onDrawCall:function(){e.graphicsDevice.setColorWrite(!0,!0,!0,!0)},onPostRenderOpaque:function(e){this.cameras[e].renderSceneDepthMap&&(this.instances.visibleOpaque[e].length=0)}})},t.patch=function(e){e.onEnable=this.layer.onEnable,e.onDisable=this.layer.onDisable,e.onPreRenderOpaque=this.layer.onPreRenderOpaque,e.onPostRenderOpaque=this.layer.onPostRenderOpaque,e.shaderPass=this.layer.shaderPass,e.onPostCull=this.layer.onPostCull,e.onDrawCall=this.layer.onDrawCall},e}(),Vl="NONE",Gl="FILL_WINDOW",Wl="KEEP_ASPECT",Hl="AUTO",Xl="FIXED",ql=function(){function e(e){this.length=e,this.count=0}var t=e.prototype;return t.inc=function(){this.count++},t.done=function(){return this.count===this.length},e}();e.app=null;var jl=function(t){function i(n){var s;return s=t.call(this)||this,i._applications[n.id]=te(s),Zr(te(s)),e.app=te(s),s._destroyRequested=!1,s._inFrameUpdate=!1,s._time=0,s.timeScale=1,s.maxDeltaTime=.1,s.frame=0,s.autoRender=!0,s.renderNextFrame=!1,s.useLegacyScriptAttributeCloning=xl.legacy,s._librariesLoaded=!1,s._fillMode=Wl,s._resolutionMode=Xl,s._allowResize=!0,s.context=te(s),s}J(i,t);var n=i.prototype;return n.init=function(e){var t=this,i=e.graphicsDevice;this.graphicsDevice=i,this._initDefaultMaterial(),this.stats=new Ol(i),this._soundManager=e.soundManager,this.loader=new tl(this),ts.init(i),this._entityIndex={},this.scene=new Kh(i),this._registerSceneImmediate(this.scene),this.root=new $l,this.root._enabledInHierarchy=!0,this.assets=new bl(this.loader),e.assetPrefix&&(this.assets.prefix=e.assetPrefix),this.bundles=new Sl(this.assets),this.enableBundles="undefined"!=typeof TextDecoder,this.scriptsOrder=e.scriptsOrder||[],this.scripts=new Il(this),this.i18n=new Dl(this),this.scenes=new Bl(this);var n=this;this.defaultLayerWorld=new fh({name:"World",id:0}),this.sceneGrab=new zl(this),this.defaultLayerDepth=this.sceneGrab.layer,this.defaultLayerSkybox=new fh({enabled:!0,name:"Skybox",id:2,opaqueSortMode:0}),this.defaultLayerUi=new fh({enabled:!0,name:"UI",id:4,transparentSortMode:1,passThrough:!1}),this.defaultLayerImmediate=new fh({enabled:!0,name:"Immediate",id:3,opaqueSortMode:0,passThrough:!0});var s=new bh("default");s.pushOpaque(this.defaultLayerWorld),s.pushOpaque(this.defaultLayerDepth),s.pushOpaque(this.defaultLayerSkybox),s.pushTransparent(this.defaultLayerWorld),s.pushOpaque(this.defaultLayerImmediate),s.pushTransparent(this.defaultLayerImmediate),s.pushTransparent(this.defaultLayerUi),this.scene.layers=s,this.scene.on("set:layers",(function(e,t){for(var i,s=t.layerList,r=0;r<s.length;r++)switch((i=s[r]).id){case 1:n.sceneGrab.patch(i);break;case 4:i.passThrough=n.defaultLayerUi.passThrough;break;case 3:i.passThrough=n.defaultLayerImmediate.passThrough}})),zh.createPlaceholder(i),this.renderer=new ah(i),this.renderer.scene=this.scene,this.frameGraph=new Bh,this.lightmapper=null,e.lightmapper&&(this.lightmapper=new e.lightmapper(i,this.root,this.scene,this.renderer,this.assets),this.once("prerender",this._firstBake,this)),this._batcher=null,e.batchManager&&(this._batcher=new e.batchManager(i,this.root,this.scene),this.once("prerender",this._firstBatch,this)),this.keyboard=e.keyboard||null,this.mouse=e.mouse||null,this.touch=e.touch||null,this.gamepads=e.gamepads||null,this.elementInput=e.elementInput||null,this.elementInput&&(this.elementInput.app=this),this.xr=e.xr?new e.xr(this):null,this.elementInput&&this.elementInput.attachSelectEvents(),this._inTools=!1,this._skyboxAsset=null,this._scriptPrefix=e.scriptPrefix||"",this.enableBundles&&this.loader.addHandler("bundle",new el(this)),e.resourceHandlers.forEach((function(e){var i=new e(t);t.loader.addHandler(i.handlerType,i)})),this.systems=new kl,e.componentSystems.forEach((function(e){t.systems.add(new e(t))})),this._visibilityChangeHandler=this.onVisibilityChange.bind(this),"undefined"!=typeof document&&(void 0!==document.hidden?(this._hiddenAttr="hidden",document.addEventListener("visibilitychange",this._visibilityChangeHandler,!1)):void 0!==document.mozHidden?(this._hiddenAttr="mozHidden",document.addEventListener("mozvisibilitychange",this._visibilityChangeHandler,!1)):void 0!==document.msHidden?(this._hiddenAttr="msHidden",document.addEventListener("msvisibilitychange",this._visibilityChangeHandler,!1)):void 0!==document.webkitHidden&&(this._hiddenAttr="webkitHidden",document.addEventListener("webkitvisibilitychange",this._visibilityChangeHandler,!1))),this.tick=Kl(this)},i.getApplication=function(e){return e?i._applications[e]:Kr()},n._initDefaultMaterial=function(){var e=new Zs;e.name="Default Material",e.shadingModel=1,function(e,t){Ds.get(e,(function(){return t}))}(this.graphicsDevice,e)},n.configure=function(e,t){var i=this;pe.get(e,(function(e,n){if(e)t(e);else{var s=n.application_properties,r=n.scenes,a=n.assets;i._parseApplicationProperties(s,(function(e){i._parseScenes(r),i._parseAssets(a),t(e||null)}))}}))},n.preload=function(e){var t=this;this.fire("preload:start");var i=this.assets.list({preload:!0}),n=new ql(i.length),s=!1,r=function(){t.graphicsDevice&&!s&&n.done()&&(s=!0,t.fire("preload:end"),e())},a=i.length;if(n.length)for(var o=function(e){n.inc(),t.fire("preload:progress",n.count/a),n.done()&&r()},h=function(e,i){n.inc(),t.fire("preload:progress",n.count/a),n.done()&&r()},l=0;l<i.length;l++)i[l].loaded?(n.inc(),this.fire("preload:progress",n.count/a),n.done()&&r()):(i[l].once("load",o),i[l].once("error",h),this.assets.load(i[l]));else r()},n._preloadScripts=function(e,t){var i=this;if(xl.legacy){this.systems.script.preloading=!0;var n=this._getScriptReferences(e),s=n.length,r=new ql(s),a=/^http(s)?:\/\//;if(s)for(var o=function(e,n){e&&console.error(e),r.inc(),r.done()&&(i.systems.script.preloading=!1,t())},h=0;h<s;h++){var l=n[h];!a.test(l.toLowerCase())&&this._scriptPrefix&&(l=v.join(this._scriptPrefix,n[h])),this.loader.load(l,"script",o)}else this.systems.script.preloading=!1,t()}else t()},n._parseApplicationProperties=function(e,t){if("number"==typeof e.maxAssetRetries&&e.maxAssetRetries>0&&this.loader.enableRetry(e.maxAssetRetries),e.useDevicePixelRatio||(e.useDevicePixelRatio=e.use_device_pixel_ratio),e.resolutionMode||(e.resolutionMode=e.resolution_mode),e.fillMode||(e.fillMode=e.fill_mode),this._width=e.width,this._height=e.height,e.useDevicePixelRatio&&(this.graphicsDevice.maxPixelRatio=window.devicePixelRatio),this.setCanvasResolution(e.resolutionMode,this._width,this._height),this.setCanvasFillMode(e.fillMode,this._width,this._height),e.layers&&e.layerOrder){var i=new bh("application"),n={};for(var s in e.layers){var r=e.layers[s];r.id=parseInt(s,10),r.enabled=1!==r.id,n[s]=new fh(r)}for(var a=0,o=e.layerOrder.length;a<o;a++){var h=e.layerOrder[a],l=n[h.layer];l&&(h.transparent?i.pushTransparent(l):i.pushOpaque(l),i.subLayerEnabled[a]=h.enabled)}this.scene.layers=i}if(e.batchGroups){var c=this.batcher;if(c)for(var u=0,d=e.batchGroups.length;u<d;u++){var f=e.batchGroups[u];c.addGroup(f.name,f.dynamic,f.maxAabbSize,f.id,f.layers)}}e.i18nAssets&&(this.i18n.assets=e.i18nAssets),this._loadLibraries(e.libraries,t)},n._loadLibraries=function(e,t){var i=this,n=e.length,s=n,r=/^http(s)?:\/\//;if(n)for(var a=function(e,n){s--,e?t(e):0===s&&(i.onLibrariesLoaded(),t(null))},o=0;o<n;++o){var h=e[o];!r.test(h.toLowerCase())&&this._scriptPrefix&&(h=v.join(this._scriptPrefix,h)),this.loader.load(h,"script",a)}else this.onLibrariesLoaded(),t(null)},n._parseScenes=function(e){if(e)for(var t=0;t<e.length;t++)this.scenes.add(e[t].name,e[t].url)},n._parseAssets=function(e){var t=[],i={},n={};if(xl.legacy){if(this.enableBundles)for(var s in e)"bundle"===e[s].type&&(n[s]=!0,t.push(e[s]));for(var r in e)n[r]||t.push(e[r])}else{for(var a=0;a<this.scriptsOrder.length;a++){var o=this.scriptsOrder[a];e[o]&&(i[o]=!0,t.push(e[o]))}if(this.enableBundles)for(var h in e)"bundle"===e[h].type&&(n[h]=!0,t.push(e[h]));for(var l in e)i[l]||n[l]||t.push(e[l])}for(var c=0;c<t.length;c++){var u=t[c],d=new ml(u.name,u.type,u.file,u.data);if(d.id=parseInt(u.id,10),d.preload=!!u.preload&&u.preload,d.loaded="script"===u.type&&u.data&&u.data.loadingType>0,d.tags.add(u.tags),u.i18n)for(var f in u.i18n)d.addLocalizedAssetId(f,u.i18n[f]);this.assets.add(d)}},n._getScriptReferences=function(e){var t=[];e.settings.priority_scripts&&(t=e.settings.priority_scripts);for(var i=[],n={},s=0;s<t.length;s++)i.push(t[s]),n[t[s]]=!0;var r=e.entities;for(var a in r)if(r[a].components.script)for(var o=r[a].components.script.scripts,h=0;h<o.length;h++)n[o[h].url]||(i.push(o[h].url),n[o[h].url]=!0);return i},n.start=function(){this.frame=0,this.fire("start",{timestamp:oe(),target:this}),this._librariesLoaded||this.onLibrariesLoaded(),this.systems.fire("initialize",this.root),this.fire("initialize"),this.systems.fire("postInitialize",this.root),this.systems.fire("postPostInitialize",this.root),this.fire("postinitialize"),this.tick()},n.inputUpdate=function(e){this.controller&&this.controller.update(e),this.mouse&&this.mouse.update(),this.keyboard&&this.keyboard.update(),this.gamepads&&this.gamepads.update()},n.update=function(e){this.frame++,this.graphicsDevice.updateClientRect(),xl.legacy&&this.systems.fire("fixedUpdate",1/60),this.systems.fire(this._inTools?"toolsUpdate":"update",e),this.systems.fire("animationUpdate",e),this.systems.fire("postUpdate",e),this.fire("update",e),this.inputUpdate(e)},n.render=function(){this.fire("prerender"),this.root.syncHierarchy(),this._batcher&&this._batcher.updateAll(),this.renderComposition(this.scene.layers),this.fire("postrender")},n.renderComposition=function(e){this.renderer.buildFrameGraph(this.frameGraph,e),this.frameGraph.render()},n._fillFrameStatsBasic=function(e,t,i){var n=this.stats.frame;n.dt=t,n.ms=i,e>n._timeToCountFrames?(n.fps=n._fpsAccum,n._fpsAccum=0,n._timeToCountFrames=e+1e3):n._fpsAccum++,this.stats.drawCalls.total=this.graphicsDevice._drawCallsPerFrame,this.graphicsDevice._drawCallsPerFrame=0},n._fillFrameStats=function(){var e=this.stats.frame;e.cameras=this.renderer._camerasRendered,e.materials=this.renderer._materialSwitches,e.shaders=this.graphicsDevice._shaderSwitchesPerFrame,e.shadowMapUpdates=this.renderer._shadowMapUpdates,e.shadowMapTime=this.renderer._shadowMapTime,e.depthMapTime=this.renderer._depthMapTime,e.forwardTime=this.renderer._forwardTime;var t=this.graphicsDevice._primsPerFrame;e.triangles=t[4]/3+Math.max(t[5]-2,0)+Math.max(t[6]-2,0),e.cullTime=this.renderer._cullTime,e.sortTime=this.renderer._sortTime,e.skinTime=this.renderer._skinTime,e.morphTime=this.renderer._morphTime,e.lightClusters=this.renderer._lightClusters,e.lightClustersTime=this.renderer._lightClustersTime,e.otherPrimitives=0;for(var i=0;i<t.length;i++)i<4&&(e.otherPrimitives+=t[i]),t[i]=0;this.renderer._camerasRendered=0,this.renderer._materialSwitches=0,this.renderer._shadowMapUpdates=0,this.graphicsDevice._shaderSwitchesPerFrame=0,this.renderer._cullTime=0,this.renderer._layerCompositionUpdateTime=0,this.renderer._lightClustersTime=0,this.renderer._sortTime=0,this.renderer._skinTime=0,this.renderer._morphTime=0,this.renderer._shadowMapTime=0,this.renderer._depthMapTime=0,this.renderer._forwardTime=0,(e=this.stats.drawCalls).forward=this.renderer._forwardDrawCalls,e.culled=this.renderer._numDrawCallsCulled,e.depth=0,e.shadow=this.renderer._shadowDrawCalls,e.skinned=this.renderer._skinDrawCalls,e.immediate=0,e.instanced=0,e.removedByInstancing=0,e.misc=e.total-(e.forward+e.shadow),this.renderer._depthDrawCalls=0,this.renderer._shadowDrawCalls=0,this.renderer._forwardDrawCalls=0,this.renderer._numDrawCallsCulled=0,this.renderer._skinDrawCalls=0,this.renderer._immediateRendered=0,this.renderer._instancedDrawCalls=0,this.stats.misc.renderTargetCreationTime=this.graphicsDevice.renderTargetCreationTime,(e=this.stats.particles).updatesPerFrame=e._updatesPerFrame,e.frameTime=e._frameTime,e._updatesPerFrame=0,e._frameTime=0},n.setCanvasFillMode=function(e,t,i){this._fillMode=e,this.resizeCanvas(t,i)},n.setCanvasResolution=function(e,t,i){this._resolutionMode=e,e===Hl&&void 0===t&&(t=this.graphicsDevice.canvas.clientWidth,i=this.graphicsDevice.canvas.clientHeight),this.graphicsDevice.resizeCanvas(t,i)},n.isHidden=function(){return document[this._hiddenAttr]},n.onVisibilityChange=function(){this.isHidden()?this._soundManager&&this._soundManager.suspend():this._soundManager&&this._soundManager.resume()},n.resizeCanvas=function(e,t){if(this._allowResize&&(!this.xr||!this.xr.session)){var i=window.innerWidth,n=window.innerHeight;if(this._fillMode===Wl){var s=this.graphicsDevice.canvas.width/this.graphicsDevice.canvas.height;s>i/n?t=(e=i)/s:e=(t=n)*s}else this._fillMode===Gl&&(e=i,t=n);return this.graphicsDevice.canvas.style.width=e+"px",this.graphicsDevice.canvas.style.height=t+"px",this.updateCanvasSize(),{width:e,height:t}}},n.updateCanvasSize=function(){var e;if(this._allowResize&&(null==(e=this.xr)||!e.active)&&this._resolutionMode===Hl){var t=this.graphicsDevice.canvas;this.graphicsDevice.resizeCanvas(t.clientWidth,t.clientHeight)}},n.onLibrariesLoaded=function(){this._librariesLoaded=!0,this.systems.rigidbody&&this.systems.rigidbody.onLibraryLoaded()},n.applySceneSettings=function(e){var t;if(this.systems.rigidbody&&"undefined"!=typeof Ammo){var i=e.physics.gravity;this.systems.rigidbody.gravity.set(i[0],i[1],i[2])}this.scene.applySettings(e),e.render.hasOwnProperty("skybox")&&(e.render.skybox?(t=this.assets.get(e.render.skybox))?this.setSkybox(t):this.assets.once("add:"+e.render.skybox,this.setSkybox,this):this.setSkybox(null))},n.setAreaLightLuts=function(e,t){e&&t&&zh.set(this.graphicsDevice,e,t)},n.setSkybox=function(e){var t=this;if(e!==this._skyboxAsset){var i=function(){t.setSkybox(null)},n=function(){t.scene.setSkybox(t._skyboxAsset?t._skyboxAsset.resources:null)};this._skyboxAsset&&(this.assets.off("load:"+this._skyboxAsset.id,n,this),this.assets.off("remove:"+this._skyboxAsset.id,i,this),this._skyboxAsset.off("change",n,this)),this._skyboxAsset=e,this._skyboxAsset&&(this.assets.on("load:"+this._skyboxAsset.id,n,this),this.assets.once("remove:"+this._skyboxAsset.id,i,this),this._skyboxAsset.on("change",n,this),0!==this.scene.skyboxMip||this._skyboxAsset.loadFaces||(this._skyboxAsset.loadFaces=!0),this.assets.load(this._skyboxAsset)),n()}},n._firstBake=function(){var e;null==(e=this.lightmapper)||e.bake(null,this.scene.lightmapMode)},n._firstBatch=function(){var e;null==(e=this.batcher)||e.generate()},n._processTimestamp=function(e){return e},n.drawLine=function(e,t,i,n,s){this.scene.drawLine(e,t,i,n,s)},n.drawLines=function(e,t,i,n){void 0===i&&(i=!0),void 0===n&&(n=this.scene.defaultDrawLayer),this.scene.drawLines(e,t,i,n)},n.drawLineArrays=function(e,t,i,n){void 0===i&&(i=!0),void 0===n&&(n=this.scene.defaultDrawLayer),this.scene.drawLineArrays(e,t,i,n)},n.drawWireSphere=function(e,t,i,n,s,r){void 0===i&&(i=me.WHITE),void 0===n&&(n=20),void 0===s&&(s=!0),void 0===r&&(r=this.scene.defaultDrawLayer),this.scene.immediate.drawWireSphere(e,t,i,n,s,r)},n.drawWireAlignedBox=function(e,t,i,n,s){void 0===i&&(i=me.WHITE),void 0===n&&(n=!0),void 0===s&&(s=this.scene.defaultDrawLayer),this.scene.immediate.drawWireAlignedBox(e,t,i,n,s)},n.drawMeshInstance=function(e,t){void 0===t&&(t=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(null,null,null,e,t)},n.drawMesh=function(e,t,i,n){void 0===n&&(n=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(t,i,e,null,n)},n.drawQuad=function(e,t,i){void 0===i&&(i=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(t,e,this.scene.immediate.getQuadMesh(),null,i)},n.drawTexture=function(e,t,i,n,s,r,a){void 0===a&&(a=this.scene.defaultDrawLayer);var o=new Ee;o.setTRS(new ye(e,t,0),Pe.IDENTITY,new ye(i,n,0)),r||((r=new Bs).setParameter("colorMap",s),r.shader=this.scene.immediate.getTextureShader(),r.update()),this.drawQuad(o,r,a)},n.drawDepthTexture=function(e,t,i,n,s){void 0===s&&(s=this.scene.defaultDrawLayer);var r=new Bs;r.shader=this.scene.immediate.getDepthTextureShader(),r.update(),this.drawTexture(e,t,i,n,null,r,s)},n.destroy=function(){var e;if(this._inFrameUpdate)this._destroyRequested=!0;else{var t=this.graphicsDevice.canvas.id;this.off("librariesloaded"),"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this._visibilityChangeHandler,!1),document.removeEventListener("mozvisibilitychange",this._visibilityChangeHandler,!1),document.removeEventListener("msvisibilitychange",this._visibilityChangeHandler,!1),document.removeEventListener("webkitvisibilitychange",this._visibilityChangeHandler,!1)),this._visibilityChangeHandler=null,this.root.destroy(),this.root=null,this.mouse&&(this.mouse.off(),this.mouse.detach(),this.mouse=null),this.keyboard&&(this.keyboard.off(),this.keyboard.detach(),this.keyboard=null),this.touch&&(this.touch.off(),this.touch.detach(),this.touch=null),this.elementInput&&(this.elementInput.detach(),this.elementInput=null),this.controller&&(this.controller=null),this.systems.destroy(),this.scene.layers&&this.scene.layers.destroy();for(var n=this.assets.list(),s=0;s<n.length;s++)n[s].unload(),n[s].off();for(var r in this.assets.off(),this.bundles.destroy(),this.bundles=null,this.i18n.destroy(),this.i18n=null,this.loader.getHandler("script")._cache){var a=this.loader.getHandler("script")._cache[r],o=a.parentNode;o&&o.removeChild(a)}this.loader.getHandler("script")._cache={},this.loader.destroy(),this.loader=null,this.scene.destroy(),this.scene=null,this.systems=null,this.context=null,this.scripts.destroy(),this.scripts=null,this.scenes.destroy(),this.scenes=null,null==(e=this.lightmapper)||e.destroy(),this.lightmapper=null,this._batcher&&(this._batcher.destroy(),this._batcher=null),this._entityIndex={},this.defaultLayerDepth.onPreRenderOpaque=null,this.defaultLayerDepth.onPostRenderOpaque=null,this.defaultLayerDepth.onDisable=null,this.defaultLayerDepth.onEnable=null,this.defaultLayerDepth=null,this.defaultLayerWorld=null,null==this||this.xr.end(),null==this||this.xr.destroy(),this.renderer.destroy(),this.renderer=null,this.graphicsDevice.destroy(),this.graphicsDevice=null,this.tick=null,this.off(),this._soundManager&&(this._soundManager.destroy(),this._soundManager=null),xl.app=null,i._applications[t]=null,Kr()===this&&Zr(null)}},n.getEntityFromIndex=function(e){return this._entityIndex[e]},n._registerSceneImmediate=function(e){this.on("postrender",e.immediate.onPostRender,e.immediate)},$(i,[{key:"soundManager",get:function(){return this._soundManager}},{key:"batcher",get:function(){return this._batcher}},{key:"fillMode",get:function(){return this._fillMode}},{key:"resolutionMode",get:function(){return this._resolutionMode}}]),i}(m);jl._applications={};var Yl={},Kl=function(t){var i,n=t;return function(t,s){var r;if(n.graphicsDevice){Zr(n),i&&(window.cancelAnimationFrame(i),i=null),e.app=n;var a=n._processTimestamp(t)||oe(),o=a-(n._time||a),h=o/1e3;if(h=de.clamp(h,0,n.maxDeltaTime),h*=n.timeScale,n._time=a,i=null!=(r=n.xr)&&r.session?n.xr.session.requestAnimationFrame(n.tick):L.browser?window.requestAnimationFrame(n.tick):null,!n.graphicsDevice.contextLost){n._fillFrameStatsBasic(a,h,o),n._inFrameUpdate=!0,n.fire("frameupdate",o);var l,c=!0;if(s)c=null==(l=n.xr)?void 0:l.update(s),n.graphicsDevice.defaultFramebuffer=s.session.renderState.baseLayer.framebuffer;else n.graphicsDevice.defaultFramebuffer=null;c&&(n.update(h),n.fire("framerender"),(n.autoRender||n.renderNextFrame)&&(n.updateCanvasSize(),n.render(),n.renderNextFrame=!1),Yl.timestamp=oe(),Yl.target=n,n.fire("frameend",Yl)),n._inFrameUpdate=!1,n._destroyRequested&&n.destroy()}}}},Zl=[],$l=function(e){function t(t,i){var n;if((n=e.call(this,t)||this).anim=void 0,n.animation=void 0,n.audiolistener=void 0,n.button=void 0,n.camera=void 0,n.collision=void 0,n.element=void 0,n.layoutchild=void 0,n.layoutgroup=void 0,n.light=void 0,n.model=void 0,n.particlesystem=void 0,n.render=void 0,n.rigidbody=void 0,n.screen=void 0,n.script=void 0,n.scrollbar=void 0,n.scrollview=void 0,n.sound=void 0,n.sprite=void 0,n.c={},n._app=void 0,n._destroying=!1,n._guid=null,n._template=!1,t instanceof jl&&(i=t),!i&&!(i=jl.getApplication()))throw new Error("Couldn't find current application");return n._app=i,n}J(t,e);var i=t.prototype;return i.addComponent=function(e,t){var i=this._app.systems[e];return i?this.c[e]?null:i.addComponent(this,t):null},i.removeComponent=function(e){var t=this._app.systems[e];t&&this.c[e]&&t.removeComponent(this)},i.findComponent=function(e){var t=this.findOne((function(t){return t.c&&t.c[e]}));return t&&t.c[e]},i.findComponents=function(e){return this.find((function(t){return t.c&&t.c[e]})).map((function(t){return t.c[e]}))},i.getGuid=function(){return this._guid||this.setGuid(g.create()),this._guid},i.setGuid=function(e){var t=this._app._entityIndex;this._guid&&delete t[this._guid],this._guid=e,t[this._guid]=this},i._notifyHierarchyStateChanged=function(e,t){var i=!1;e===this&&0===Zl.length&&(i=!0),e._beingEnabled=!0,e._onHierarchyStateChanged(t),e._onHierarchyStatePostChanged&&Zl.push(e);for(var n=e._children,s=0,r=n.length;s<r;s++)n[s]._enabled&&this._notifyHierarchyStateChanged(n[s],t);if(e._beingEnabled=!1,i){for(var a=0;a<Zl.length;a++)Zl[a]._onHierarchyStatePostChanged();Zl.length=0}},i._onHierarchyStateChanged=function(t){e.prototype._onHierarchyStateChanged.call(this,t);var i=this.c;for(var n in i)if(i.hasOwnProperty(n)){var s=i[n];s.enabled&&(t?s.onEnable():s.onDisable())}},i._onHierarchyStatePostChanged=function(){var e=this.c;for(var t in e)e.hasOwnProperty(t)&&e[t].onPostStateChange()},i.findByGuid=function(e){if(this._guid===e)return this;var t=this._app._entityIndex[e];return t&&(t===this||t.isDescendantOf(this))?t:null},i.destroy=function(){for(var e in this._destroying=!0,this.c)this.c[e].enabled=!1;for(var i in this.c)this.c[i].system.removeComponent(this);this._parent&&this._parent.removeChild(this);for(var n=this._children;n.length;){var s=n.pop();s._parent=null,s instanceof t&&s.destroy()}this.fire("destroy",this),this.off(),this._guid&&delete this._app._entityIndex[this._guid],this._destroying=!1},i.clone=function(){var e={},t=this._cloneRecursively(e);return e[this.getGuid()]=t,Ql(this,this,t,e),t},i._cloneRecursively=function(i){var n=new this.constructor(this._app);for(var s in e.prototype._cloneInternal.call(this,n),this.c){this.c[s].system.cloneComponent(this,n)}for(var r=0;r<this._children.length;r++){var a=this._children[r];if(a instanceof t){var o=a._cloneRecursively(i);n.addChild(o),i[a.getGuid()]=o}}return n},t}(Hn);function Ql(e,t,i,n){if(t instanceof $l){var s=t.c;for(var r in s)for(var a=s[r],o=a.system.getPropertiesOfType("entity"),h=0,l=o.length;h<l;h++){var c=o[h].name,u=a[c];if(!!e.findByGuid(u)){var d=n[u].getGuid();d&&(i.c[r][c]=d)}}s.script&&!i._app.useLegacyScriptAttributeCloning&&i.script.resolveDuplicatedEntityReferenceProperties(s.script,n),s.render&&i.render.resolveDuplicatedEntityReferenceProperties(s.render,n),s.anim&&i.anim.resolveDuplicatedEntityReferenceProperties(s.anim,n);for(var f=t.children.filter((function(e){return e instanceof $l})),p=i.children.filter((function(e){return e instanceof $l})),m=0,_=f.length;m<_;m++)Ql(e,f[m],p[m],n)}}var Jl=new ye,ec=function(e){function t(t){var i=new $l("AmbientLight");return i.addComponent("light",{type:"directional",affectDynamic:!0,affectLightmapped:!1,bake:!0,bakeNumSamples:t.ambientBakeNumSamples,castShadows:!0,normalOffsetBias:.05,shadowBias:.2,shadowDistance:1,shadowResolution:2048,shadowType:0,color:me.WHITE,intensity:1,bakeDir:!1}),e.call(this,t,i.light.light)||this}return J(t,e),t.prototype.prepareVirtualLight=function(e,t){cs(Jl,e,t,0,this.scene.ambientBakeSpherePart),this.light._node.lookAt(Jl.mulScalar(-1)),this.light._node.rotateLocal(90,0,0);var i=this.scene.gammaCorrection?2.2:1,n=2*Math.PI*this.scene.ambientBakeSpherePart,s=Math.pow(n,i);this.light.intensity=Math.pow(s/t,1/i)},$(t,[{key:"numVirtualLights",get:function(){return this.light.bakeNumSamples}}]),t}(kh),tc=function(){function e(e,t){void 0===t&&(t=null),this.node=e,this.component=e.render||e.model,t=t||this.component.meshInstances,this.store(),this.meshInstances=t,this.bounds=null,this.renderTargets=[]}var t=e.prototype;return t.store=function(){this.castShadows=this.component.castShadows},t.restore=function(){this.component.castShadows=this.castShadows},e}(),ic=function(){function e(e){this.device=e,this.shaderDilate=on(e,Wi.fullscreenQuadVS,fr.dilatePS,"lmDilate"),this.constantTexSource=e.scope.resolve("source"),this.constantPixelOffset=e.scope.resolve("pixelOffset"),this.pixelOffset=new Float32Array(2),this.shaderDenoise=null,this.sigmas=null,this.constantSigmas=null,this.kernel=null}var t=e.prototype;return t.setSourceTexture=function(e){this.constantTexSource.setValue(e)},t.prepare=function(e,t){this.pixelOffset[0]=1/e,this.pixelOffset[1]=1/t,this.constantPixelOffset.setValue(this.pixelOffset)},t.prepareDenoise=function(e,t){this.shaderDenoise||(this.shaderDenoise=on(this.device,Wi.fullscreenQuadVS,fr.bilateralDeNoisePS,"lmBilateralDeNoise"),this.sigmas=new Float32Array(2),this.constantSigmas=this.device.scope.resolve("sigmas"),this.constantKernel=this.device.scope.resolve("kernel[0]"),this.bZnorm=this.device.scope.resolve("bZnorm")),this.sigmas[0]=e,this.sigmas[1]=t,this.constantSigmas.setValue(this.sigmas),this.evaluateDenoiseUniforms(e,t)},t.evaluateDenoiseUniforms=function(e,t){function i(e,t){return.39894*Math.exp(-.5*e*e/(t*t))/t}this.kernel=this.kernel||new Float32Array(15);for(var n=this.kernel,s=Math.floor(7),r=0;r<=s;++r){var a=i(r,e);n[s+r]=a,n[s-r]=a}this.constantKernel.setValue(this.kernel);var o=1/i(0,t);this.bZnorm.setValue(o)},e}(),nc=new ye,sc=function(){function e(e,t,i,n,s){this.device=e,this.root=t,this.scene=i,this.renderer=n,this.assets=s,this.shadowMapCache=n._shadowRenderer.shadowMapCache,this._tempSet=new Set,this._initCalled=!1,this.passMaterials=[],this.ambientAOMaterial=null,this.fog="",this.ambientLight=new me,this.renderTargets=new Map,this.stats={renderPasses:0,lightmapCount:0,totalRenderTime:0,forwardTime:0,fboTime:0,shadowMapTime:0,compileTime:0,shadersLinked:0}}var t=e.prototype;return t.destroy=function(){Ca.decRef(this.blackTex),this.blackTex=null,Ca.destroy(),this.device=null,this.root=null,this.scene=null,this.renderer=null,this.assets=null},t.initBake=function(e){if(!this._initCalled){this._initCalled=!0,this.lightmapFilters=new ic(e),this.constantBakeDir=e.scope.resolve("bakeDir"),this.materials=[],this.blackTex=new wn(this.device,{width:4,height:4,format:7,type:$t,name:"lightmapBlack"}),Ca.incRef(this.blackTex);var t=new En;t.clearColor.set(0,0,0,0),t.clearColorBuffer=!0,t.clearDepthBuffer=!1,t.clearStencilBuffer=!1,t.frustumCulling=!1,t.projection=1,t.aspectRatio=1,t.node=new Hn,this.camera=t}if(this.scene.clusteredLightingEnabled){var i=new Lh(e.supportsAreaLights,e.maxTextureSize,(function(){}));this.lightingParams=i;var n=this.scene.lighting;i.shadowsEnabled=n.shadowsEnabled,i.shadowAtlasResolution=n.shadowAtlasResolution,i.cookiesEnabled=n.cookiesEnabled,i.cookieAtlasResolution=n.cookieAtlasResolution,i.areaLightsEnabled=n.areaLightsEnabled,i.cells=new ye(3,3,3),i.maxLightsPerCell=4,this.worldClusters=new $a(e),this.worldClusters.name="ClusterLightmapper"}},t.finishBake=function(e){function t(e){Ca.decRef(e.colorBuffer),e.destroy()}this.materials=[],this.renderTargets.forEach((function(e){t(e)})),this.renderTargets.clear(),e.forEach((function(e){e.renderTargets.forEach((function(e){t(e)})),e.renderTargets.length=0})),this.ambientAOMaterial=null,this.worldClusters&&(this.worldClusters.destroy(),this.worldClusters=null)},t.createMaterialForPass=function(e,t,i,n){var s=new Zs;if(s.name="lmMaterial-pass:"+i+"-ambient:"+n,s.chunks.APIVersion=yi,s.chunks.transformVS="#define UV1LAYOUT\n"+Wi.transformVS,0===i){var r=fr.bakeLmEndPS;n?r="\n dDiffuseLight = ((dDiffuseLight - 0.5) * max("+t.ambientBakeOcclusionContrast.toFixed(1)+" + 1.0, 0.0)) + 0.5;\n dDiffuseLight += vec3("+t.ambientBakeOcclusionBrightness.toFixed(1)+");\n dDiffuseLight = saturate(dDiffuseLight);\n dDiffuseLight *= dAmbientLight;\n "+r:(s.ambient=new me(0,0,0),s.ambientTint=!0),s.chunks.endPS=r,s.lightMap=this.blackTex}else s.chunks.basePS=Wi.basePS+"\nuniform sampler2D texture_dirLightMap;\nuniform float bakeDir;\n",s.chunks.endPS=fr.bakeDirLmEndPS;return s.chunks.outputAlphaPS="\n",s.chunks.outputAlphaOpaquePS="\n",s.chunks.outputAlphaPremulPS="\n",s.cull=0,s.forceUv1=!0,s.update(),s},t.createMaterials=function(e,t,i){for(var n=0;n<i;n++)this.passMaterials[n]||(this.passMaterials[n]=this.createMaterialForPass(e,t,n,!1));this.ambientAOMaterial||(this.ambientAOMaterial=this.createMaterialForPass(e,t,0,!0),this.ambientAOMaterial.onUpdateShader=function(e){return e.lightMapWithoutAmbient=!0,e.separateAmbient=!0,e})},t.createTexture=function(e,t,i){return new wn(this.device,{width:e,height:e,format:7,mipmaps:!1,type:t,minFilter:0,magFilter:0,addressU:1,addressV:1,name:i})},t.collectModels=function(e,t,i){var n,s,r;if(e.enabled){var a;if(null!=(n=e.model)&&n.model&&null!=(s=e.model)&&s.enabled&&(i&&i.push(new tc(e)),e.model.lightmapped&&t&&(a=e.model.model.meshInstances)),null!=(r=e.render)&&r.enabled&&(i&&i.push(new tc(e)),e.render.lightmapped&&t&&(a=e.render.meshInstances)),a){for(var o=!0,h=0;h<a.length;h++)if(!a[h].mesh.vertexBuffer.format.hasUv1){o=!1;break}if(o){for(var l=[],c=0;c<a.length;c++){var u=a[c].mesh;this._tempSet.has(u)?t.push(new tc(e,[a[c]])):l.push(a[c]),this._tempSet.add(u)}this._tempSet.clear(),l.length>0&&t.push(new tc(e,l))}}for(var d=0;d<e._children.length;d++)this.collectModels(e._children[d],t,i)}},t.prepareShadowCasters=function(e){for(var t=[],i=0;i<e.length;i++){var n=e[i].component;if(n.castShadows=n.castShadowsLightmap,n.castShadowsLightmap)for(var s=e[i].meshInstances,r=0;r<s.length;r++)s[r].visibleThisFrame=!0,t.push(s[r])}return t},t.updateTransforms=function(e){for(var t=0;t<e.length;t++)for(var i=e[t].meshInstances,n=0;n<i.length;n++)i[n].node.getWorldTransform()},t.calculateLightmapSize=function(e){var t,i,n,s=this.scene.lightmapSizeMultiplier||16,r=nc;e.model?(n=e.model.lightmapSizeMultiplier,e.model.asset?(t=this.assets.get(e.model.asset).data).area&&(i=t.area):e.model._area&&(t=e.model)._area&&(i=t._area)):e.render&&(n=e.render.lightmapSizeMultiplier,"asset"!==e.render.type&&e.render._area&&(t=e.render)._area&&(i=t._area));var a={x:1,y:1,z:1,uv:1};i&&(a.x=i.x,a.y=i.y,a.z=i.z,a.uv=i.uv);var o=n||1;a.x*=o,a.y*=o,a.z*=o;var h=e.render||e.model,l=this.computeNodeBounds(h.meshInstances);r.copy(l.halfExtents);var c=a.x*r.y*r.z+a.y*r.x*r.z+a.z*r.x*r.y;return c/=a.uv,c=Math.sqrt(c),Math.min(de.nextPowerOfTwo(c*s),this.scene.lightmapMaxResolution||2048)},t.setLightmapping=function(e,t,i,n){for(var s=0;s<e.length;s++)for(var r=e[s],a=r.meshInstances,o=0;o<a.length;o++){var h=a[o];if(h.setLightmapped(t),t){n&&(h._shaderDefs|=n),h.mask=2;for(var l=0;l<i;l++){var c=r.renderTargets[l].colorBuffer;c.minFilter=1,c.magFilter=1,h.setRealtimeLightmap(ka.lightmapParamNames[l],c)}}}},t.bake=function(e,t){void 0===t&&(t=1);var i=this.device,n=oe();this.scene._updateSky(i),this.stats.renderPasses=0,this.stats.shadowMapTime=0,this.stats.forwardTime=0;var s=i._shaderStats.linked,r=i._renderTargetCreationTime,a=i._shaderStats.compileTime,o=[],h=[];if(e){for(var l=0;l<e.length;l++)this.collectModels(e[l],o,null);this.collectModels(this.root,null,h)}else this.collectModels(this.root,o,h);if(o.length>0){var c=1===t?2:1;this.setLightmapping(o,!1,c),this.initBake(i),this.bakeInternal(c,o,h);var u=64;1===t&&(u|=Ge),this.scene.ambientBake&&(u|=je),this.setLightmapping(o,!0,c,u),this.finishBake(o)}var d=oe();this.stats.totalRenderTime=d-n,this.stats.shadersLinked=i._shaderStats.linked-s,this.stats.compileTime=i._shaderStats.compileTime-a,this.stats.fboTime=i._renderTargetCreationTime-r,this.stats.lightmapCount=o.length},t.allocateTextures=function(e,t){for(var i=0;i<e.length;i++){for(var n=e[i],s=this.calculateLightmapSize(n.node),r=0;r<t;r++){var a=this.createTexture(s,Zt,"lightmapper_lightmap_"+i);Ca.incRef(a),n.renderTargets[r]=new cr({colorBuffer:a,depth:!1})}if(!this.renderTargets.has(s)){var o=this.createTexture(s,Zt,"lightmapper_temp_lightmap_"+s);Ca.incRef(o),this.renderTargets.set(s,new cr({colorBuffer:o,depth:!1}))}}},t.prepareLightsToBake=function(e,t,i){if(this.scene.ambientBake){var n=new ec(this.scene);i.push(n)}for(var s=e._lights,r=0;r<s.length;r++){var a=s[r],o=new Fh(this.scene,a);t.push(o),a.enabled&&0!=(4&a.mask)&&(a.isStatic=!1,a.mask=4294967295,a.shadowUpdateMode=0===a.type?2:1,i.push(o))}i.sort()},t.restoreLights=function(e){for(var t=0;t<e.length;t++)e[t].restore()},t.setupScene=function(){this.revertStatic=!1,this.scene._needsStaticPrepare&&(this.scene._needsStaticPrepare=!1,this.revertStatic=!0),this.fog=this.scene.fog,this.ambientLight.copy(this.scene.ambientLight),this.scene.fog=Ue,this.scene.ambientBake||this.scene.ambientLight.set(0,0,0),this.renderer.setSceneConstants()},t.restoreScene=function(){this.scene.fog=this.fog,this.scene.ambientLight.copy(this.ambientLight),this.revertStatic&&(this.scene._needsStaticPrepare=!0)},t.computeNodeBounds=function(e){var t=new Oe;if(e.length>0){t.copy(e[0].aabb);for(var i=1;i<e.length;i++)t.add(e[i].aabb)}return t},t.computeNodesBounds=function(e){for(var t=0;t<e.length;t++){var i=e[t].meshInstances;e[t].bounds=this.computeNodeBounds(i)}},t.computeBounds=function(e){for(var t=new Oe,i=0;i<e.length;i++){t.copy(e[0].aabb);for(var n=1;n<e.length;n++)t.add(e[n].aabb)}return t},t.backupMaterials=function(e){for(var t=0;t<e.length;t++)this.materials[t]=e[t].material},t.restoreMaterials=function(e){for(var t=0;t<e.length;t++)e[t].material=this.materials[t]},t.lightCameraPrepare=function(e,t){var i,n=t.light;2===n.type&&((i=n.getRenderData(null,0).shadowCamera)._node.setPosition(n._node.getPosition()),i._node.setRotation(n._node.getRotation()),i._node.rotateLocal(-90,0,0),i.projection=0,i.nearClip=n.attenuationEnd/1e3,i.farClip=n.attenuationEnd,i.aspectRatio=1,i.fov=2*n._outerConeAngle,this.renderer.updateCameraFrustum(i));return i},t.lightCameraPrepareAndCull=function(e,t,i,n){var s=e.light,r=!0;if(0===s.type){nc.copy(n.center),nc.y+=n.halfExtents.y,this.camera.node.setPosition(nc),this.camera.node.setEulerAngles(-90,0,0),this.camera.nearClip=0,this.camera.farClip=2*n.halfExtents.y;var a=Math.max(n.halfExtents.x,n.halfExtents.z);this.camera.orthoHeight=a}else e.lightBounds.intersects(t.bounds)||(r=!1);if(2===s.type){for(var o=!1,h=t.meshInstances,l=0;l<h.length;l++)if(h[l]._isVisible(i)){o=!0;break}o||(r=!1)}return r},t.setupLightArray=function(e,t){e[0].length=0,e[1].length=0,e[2].length=0,e[t.type][0]=t,t.visibleThisFrame=!0},t.renderShadowMap=function(e,t,i,n){var s=n.light;return!e&&s.castShadows&&(s.shadowMap||this.scene.clusteredLightingEnabled||(s.shadowMap=this.shadowMapCache.get(this.device,s)),0===s.type?this.renderer._shadowRenderer.cullDirectional(s,t,this.camera):this.renderer._shadowRenderer.cullLocal(s,t),this.renderer.renderShadows(i[s.type],this.camera)),!0},t.postprocessTextures=function(e,t,i){var n=this.lightmapFilters.shaderDilate,s=this.scene.lightmapFilterEnabled;s&&this.lightmapFilters.prepareDenoise(this.scene.lightmapFilterRange,this.scene.lightmapFilterSmoothness);for(var r=0;r<t.length;r++)for(var a=t[r],o=0;o<i;o++){var h=a.renderTargets[o],l=h.colorBuffer,c=this.renderTargets.get(l.width),u=c.colorBuffer;this.lightmapFilters.prepare(l.width,l.height);for(var d=0;d<1;d++){this.lightmapFilters.setSourceTexture(l),Ei(e,c,s&&0===o&&0===d?this.lightmapFilters.shaderDenoise:n),this.lightmapFilters.setSourceTexture(u),Ei(e,h,n)}}},t.bakeInternal=function(e,t,i){var n=this.scene,s=this.device,r=n.clusteredLightingEnabled;this.createMaterials(s,n,e),this.setupScene(),n.layers._update(),this.computeNodesBounds(t),this.allocateTextures(t,e);var a=[],o=[];this.prepareLightsToBake(n.layers,a,o),this.updateTransforms(i);var h=this.prepareShadowCasters(i);this.renderer.updateCpuSkinMatrices(h),this.renderer.gpuUpdate(h);var l,c,u,d,f=this.computeBounds(h);for(l=0;l<t.length;l++){for(u=t[l].meshInstances,c=0;c<u.length;c++)(d=u[c]).setLightmapped(!1),d.mask=4,d.setRealtimeLightmap(ka.lightmapParamNames[0],d.material.lightMap?d.material.lightMap:this.blackTex),d.setRealtimeLightmap(ka.lightmapParamNames[1],this.blackTex)}for(c=0;c<o.length;c++)o[c].light.enabled=!1;var p,m,_=[[],[],[]],g=!1;for(l=0;l<o.length;l++){var v=o[l],y=v instanceof ec,x=v.numVirtualLights;e>1&&x>1&&v.light.bakeDir&&(x=1);for(var b=0;b<x;b++){x>1&&v.prepareVirtualLight(b,x),v.startBake();var S=!1,w=this.lightCameraPrepare(s,v);for(m=0;m<t.length;m++){var T=t[m];if(u=T.meshInstances,this.lightCameraPrepareAndCull(v,T,w,f)){if(this.setupLightArray(_,v.light),r&&this.renderer.lightTextureAtlas.update(_[2],_[1],this.lightingParams),S=this.renderShadowMap(S,h,_,v),r){var A=_[2].concat(_[1]);this.worldClusters.update(A,this.scene.gammaCorrection,this.lightingParams)}for(this.backupMaterials(u),p=0;p<e&&!(p>0&&b>0)&&!(y&&p>0);p++){var M=T.renderTargets[p],C=T.renderTargets[p].colorBuffer.width,E=this.renderTargets.get(C),P=E.colorBuffer;0===p?g=n.updateShaders:g&&(n.updateShaders=!0);var R=this.passMaterials[p];for(y&&b+1===x&&0===p&&(R=this.ambientAOMaterial),c=0;c<u.length;c++)u[c].material=R;for(this.renderer.updateShaders(u),this.renderer.setCamera(this.camera,E,!0),1===p&&this.constantBakeDir.setValue(v.light.bakeDir?1:0),r&&this.worldClusters.activate(this.renderer.lightTextureAtlas),this.renderer._forwardTime=0,this.renderer._shadowMapTime=0,this.renderer.renderForward(this.camera,u,u.length,_,1),s.updateEnd(),T.renderTargets[p]=E,this.renderTargets.set(C,M),c=0;c<u.length;c++)(d=u[c]).setRealtimeLightmap(ka.lightmapParamNames[p],P),d._shaderDefs|=64}this.restoreMaterials(u)}}v.endBake(this.shadowMapCache)}}for(this.postprocessTextures(s,t,e),m=0;m<i.length;m++)i[m].restore();this.restoreLights(a),this.restoreScene(),r||this.shadowMapCache.clear()},e}(),rc=function(e){function t(i,n){var s;return s=e.call(this)||this,i.forEach((function(e){})),s.device=n||Kr().graphicsDevice,s._targets=i.slice(),s.device.supportsMorphTargetTexturesCore&&(s.device.extTextureHalfFloat&&s.device.textureHalfFloatRenderable?s._renderTextureFormat=t.FORMAT_HALF_FLOAT:s.device.extTextureFloat&&s.device.textureFloatRenderable&&(s._renderTextureFormat=t.FORMAT_FLOAT),s.device.extTextureHalfFloat&&s.device.textureHalfFloatUpdatable?s._textureFormat=t.FORMAT_HALF_FLOAT:s.device.extTextureFloat&&(s._textureFormat=t.FORMAT_FLOAT),void 0!==s._renderTextureFormat&&void 0!==s._textureFormat&&(s._useTextureMorph=!0)),s._init(),s._updateMorphFlags(),s._calculateAabb(),s}J(t,e);var i=t.prototype;return i._init=function(){if(this._useTextureMorph&&(this._useTextureMorph=this._initTextureBased()),!this._useTextureMorph)for(var e=0;e<this._targets.length;e++)this._targets[e]._initVertexBuffers(this.device);for(var t=0;t<this._targets.length;t++)this._targets[t]._postInit()},i._initTextureBased=function(){for(var e=[],i=[],n=0;n<this._targets.length;n++){var s=this._targets[n];s.options.deltaPositions&&(e.push(s.options.deltaPositions),i.push({target:s,name:"texturePositions"})),s.options.deltaNormals&&(e.push(s.options.deltaNormals),i.push({target:s,name:"textureNormals"}))}for(var r=[],a=[],o=1,h=e[0].length,l=0;l<h;l+=3){for(var c=!1,u=0;u<e.length;u++){var d=e[u];if(0!==d[l]||0!==d[l+1]||0!==d[l+2]){c=!0;break}}c?(r.push(o+.2),a.push(l/3),o++):r.push(.2)}var f=Math.min(this.device.maxTextureSize,4096),p=Math.ceil(Math.sqrt(o));p=Math.min(p,f);var m=Math.ceil(o/p);if(m>f)return!1;this.morphTextureWidth=p,this.morphTextureHeight=m;var _=!1,g=3,v=yn.float2Half;this._textureFormat===t.FORMAT_HALF_FLOAT&&(_=!0,g=4);for(var y=this.morphTextureWidth*this.morphTextureHeight*g,x=_?new Uint16Array(y):new Float32Array(y),b=0;b<e.length;b++){for(var S=e[b],w=0;w<a.length;w++){var T=a[w];_?(x[w*g+g]=v(S[3*T]),x[w*g+g+1]=v(S[3*T+1]),x[w*g+g+2]=v(S[3*T+2])):(x[w*g+g]=S[3*T],x[w*g+g+1]=S[3*T+1],x[w*g+g+2]=S[3*T+2])}var A=i[b].target,M=this._textureFormat===t.FORMAT_FLOAT?ut:ct;A._setTexture(i[b].name,this._createTexture("MorphTarget",M,x))}var C=[{semantic:Kt,components:1,type:6}];return this.vertexBufferIds=new Si(this.device,new Ti(this.device,C),r.length,0,new Float32Array(r)),!0},i.destroy=function(){var e;null==(e=this.vertexBufferIds)||e.destroy(),this.vertexBufferIds=null;for(var t=0;t<this._targets.length;t++)this._targets[t].destroy();this._targets.length=0},i._updateMorphFlags=function(){this._morphPositions=!1,this._morphNormals=!1;for(var e=0;e<this._targets.length;e++){var t=this._targets[e];t.morphPositions&&(this._morphPositions=!0),t.morphNormals&&(this._morphNormals=!0)}},i._calculateAabb=function(){for(var e=new ye,t=new ye,i=0;i<this._targets.length;i++){var n=this._targets[i].aabb;e.min(n.getMin()),t.max(n.getMax())}this.aabb=new Oe,this.aabb.setMinMax(e,t)},i._createTexture=function(e,t,i){var n=new wn(this.device,{width:this.morphTextureWidth,height:this.morphTextureHeight,format:t,cubemap:!1,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1,name:e});return i&&(n.lock().set(i),n.unlock()),n},$(t,[{key:"morphPositions",get:function(){return this._morphPositions}},{key:"morphNormals",get:function(){return this._morphNormals}},{key:"maxActiveTargets",get:function(){return this._useTextureMorph?this._targets.length:this._morphPositions&&this._morphNormals?4:8}},{key:"useTextureMorph",get:function(){return this._useTextureMorph}},{key:"targets",get:function(){return this._targets}}]),t}(Yr);rc.FORMAT_FLOAT=0,rc.FORMAT_HALF_FLOAT=1;var ac,oc=function(){function e(e){var t=this;this.morph=e,e.incRefCount(),this.device=e.device,this._weights=[],this._weightMap=new Map;for(var i=0;i<e._targets.length;i++){var n=e._targets[i];n.name&&this._weightMap.set(n.name,i),this.setWeight(i,n.defaultWeight)}if(this._activeTargets=[],e.useTextureMorph){this.shaderCache={},this.maxSubmitCount=this.device.maxTextures,this._shaderMorphWeights=new Float32Array(this.maxSubmitCount);var s=function(i,n){var s=e._renderTextureFormat===rc.FORMAT_FLOAT?dt:ct;return t[n]=e._createTexture(i,s),new cr({colorBuffer:t[n],depth:!1})};e.morphPositions&&(this.rtPositions=s("MorphRTPos","texturePositions")),e.morphNormals&&(this.rtNormals=s("MorphRTNrm","textureNormals")),this._textureParams=new Float32Array([e.morphTextureWidth,e.morphTextureHeight,1/e.morphTextureWidth,1/e.morphTextureHeight]);for(var r=0;r<this.maxSubmitCount;r++)this["morphBlendTex"+r]=this.device.scope.resolve("morphBlendTex"+r);this.morphFactor=this.device.scope.resolve("morphFactor[0]"),this.zeroTextures=!1}else this.maxSubmitCount=8,this._shaderMorphWeights=new Float32Array(this.maxSubmitCount),this._shaderMorphWeightsA=new Float32Array(this._shaderMorphWeights.buffer,0,4),this._shaderMorphWeightsB=new Float32Array(this._shaderMorphWeights.buffer,16,4),this._activeVertexBuffers=new Array(this.maxSubmitCount)}var t=e.prototype;return t.destroy=function(){this.shader=null;var e=this.morph;e&&(this.morph=null,e.decRefCount(),e.refCount<1&&e.destroy()),this.rtPositions&&(this.rtPositions.destroy(),this.rtPositions=null),this.texturePositions&&(this.texturePositions.destroy(),this.texturePositions=null),this.rtNormals&&(this.rtNormals.destroy(),this.rtNormals=null),this.textureNormals&&(this.textureNormals.destroy(),this.textureNormals=null)},t.clone=function(){return new e(this.morph)},t._getWeightIndex=function(e){return"string"==typeof e?this._weightMap.get(e):e},t.getWeight=function(e){var t=this._getWeightIndex(e);return this._weights[t]},t.setWeight=function(e,t){var i=this._getWeightIndex(e);this._weights[i]=t,this._dirty=!0},t._getFragmentShader=function(e){var t="";e>0&&(t+="varying vec2 uv0;\nuniform highp float morphFactor["+e+"];\n");for(var i=0;i<e;i++)t+="uniform highp sampler2D morphBlendTex"+i+";\n";t+="void main (void) {\n highp vec4 color = vec4(0, 0, 0, 1);\n";for(var n=0;n<e;n++)t+=" color.xyz += morphFactor["+n+"] * texture2D(morphBlendTex"+n+", uv0).xyz;\n";return t+=" gl_FragColor = color;\n}\n"},t._getShader=function(e){var t=this.shaderCache[e];if(!t){var i=this._getFragmentShader(e);t=on(this.device,"\n attribute vec2 vertex_position;\n varying vec2 uv0;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.5, 1.0);\n uv0 = vertex_position.xy * 0.5 + 0.5;\n }\n ",i,"textureMorph"+e),this.shaderCache[e]=t}return t},t._updateTextureRenderTarget=function(e,t){for(var i=this,n=this.device,s=function(t,s){i.morphFactor.setValue(i._shaderMorphWeights),n.setBlending(s),s&&(n.setBlendFunction(1,1),n.setBlendEquation(0));var r=i._getShader(t);Ei(n,e,r,void 0,void 0,s)},r=0,a=!1,o=this._activeTargets.length,h=0;h<o;h++){var l=this._activeTargets[h],c=l.target[t];c&&(this["morphBlendTex"+r].setValue(c),this._shaderMorphWeights[r]=l.weight,++r>=this.maxSubmitCount&&(s(r,a),r=0,a=!0))}(r>0||0===o&&!this.zeroTextures)&&s(r,a)},t._updateTextureMorph=function(){this.device,(this._activeTargets.length>0||!this.zeroTextures)&&(this._updateTextureRenderTarget(this.rtPositions,"texturePositions"),this._updateTextureRenderTarget(this.rtNormals,"textureNormals"),this.zeroTextures=0===this._activeTargets.length)},t._updateVertexMorph=function(){for(var e=this.maxSubmitCount,t=0;t<e;t++)this._shaderMorphWeights[t]=0,this._activeVertexBuffers[t]=null;for(var i=0,n=this.morph.morphPositions?4:0,s=0;s<this._activeTargets.length;s++){var r=this._activeTargets[s].target;r._vertexBufferPositions&&(this._activeVertexBuffers[i]=r._vertexBufferPositions,this._shaderMorphWeights[i]=this._activeTargets[s].weight,i++),r._vertexBufferNormals&&(this._activeVertexBuffers[n]=r._vertexBufferNormals,this._shaderMorphWeights[n]=this._activeTargets[s].weight,n++)}},t.update=function(){this._dirty=!1;for(var e=this.morph._targets,t=0,i=0;i<e.length;i++){var n=Math.abs(this.getWeight(i));if(n>1e-5){this._activeTargets.length<=t&&(this._activeTargets[t]={});var s=this._activeTargets[t++];s.absWeight=n,s.weight=this.getWeight(i),s.target=e[i]}}this._activeTargets.length=t;var r=this.morph.maxActiveTargets;this._activeTargets.length>r&&(this._activeTargets.sort((function(e,t){return e.absWeight<t.absWeight?1:t.absWeight<e.absWeight?-1:0})),this._activeTargets.length=r),this.morph.useTextureMorph?this._updateTextureMorph():this._updateVertexMorph()},e}(),hc=function(){function e(){this.graph=null,this.meshInstances=[],this.skinInstances=[],this.morphInstances=[],this.cameras=[],this.lights=[],this._shadersVersion=0,this._immutable=!1}var t=e.prototype;return t.getGraph=function(){return this.graph},t.setGraph=function(e){this.graph=e},t.getCameras=function(){return this.cameras},t.setCameras=function(e){this.cameras=e},t.getLights=function(){return this.lights},t.setLights=function(e){this.lights=e},t.getMaterials=function(){for(var e=[],t=0;t<this.meshInstances.length;t++){var i=this.meshInstances[t];-1===e.indexOf(i.material)&&e.push(i.material)}return e},t.clone=function(){for(var t=[],i=[],n=function e(n){var s=n.clone();t.push(n),i.push(s);for(var r=0;r<n._children.length;r++)s.addChild(e(n._children[r]));return s}(this.graph),s=[],r=[],a=[],o=0;o<this.skinInstances.length;o++){for(var h=this.skinInstances[o].skin,l=new ba(h),c=[],u=0;u<h.boneNames.length;u++){var d=h.boneNames[u],f=n.findByName(d);c.push(f)}l.bones=c,r.push(l)}for(var p=0;p<this.morphInstances.length;p++){var m=this.morphInstances[p].morph,_=new oc(m);a.push(_)}for(var g=0;g<this.meshInstances.length;g++){var v=this.meshInstances[g],y=t.indexOf(v.node),x=new ka(v.mesh,v.material,i[y]);if(v.skinInstance){var b=this.skinInstances.indexOf(v.skinInstance);x.skinInstance=r[b]}if(v.morphInstance){var S=this.morphInstances.indexOf(v.morphInstance);x.morphInstance=a[S]}s.push(x)}var w=new e;return w.graph=n,w.meshInstances=s,w.skinInstances=r,w.morphInstances=a,w.getGraph().syncHierarchy(),w},t.destroy=function(){for(var e=this.meshInstances,t=0;t<e.length;t++)e[t].destroy();this.meshInstances.length=0},t.generateWireframe=function(){ka._prepareRenderStyleForArray(this.meshInstances,1)},e}(),lc=function(){function e(e){this.used=!1,2===arguments.length&&(e=arguments[1]),this.options=e,this._name=e.name,this._defaultWeight=e.defaultWeight||0,this.aabb=e.aabb,this.aabb||(this.aabb=new Oe,e.deltaPositions&&this.aabb.compute(e.deltaPositions)),this.deltaPositions=e.deltaPositions}var t=e.prototype;return t.destroy=function(){var e,t,i,n;null==(e=this._vertexBufferPositions)||e.destroy(),this._vertexBufferPositions=null,null==(t=this._vertexBufferNormals)||t.destroy(),this._vertexBufferNormals=null,null==(i=this.texturePositions)||i.destroy(),this.texturePositions=null,null==(n=this.textureNormals)||n.destroy(),this.textureNormals=null},t.clone=function(){return new e(this.options)},t._postInit=function(){this.options.preserveData||(this.options=null),this.used=!0},t._initVertexBuffers=function(e){var t=this.options;this._vertexBufferPositions=this._createVertexBuffer(e,t.deltaPositions,t.deltaPositionsType),this._vertexBufferNormals=this._createVertexBuffer(e,t.deltaNormals,t.deltaNormalsType),this._vertexBufferPositions&&(this.deltaPositions=this._vertexBufferPositions.lock())},t._createVertexBuffer=function(e,t,i){return void 0===i&&(i=6),t?new Si(e,new Ti(e,[{semantic:kt,components:3,type:i}]),t.length/3,0,t):null},t._setTexture=function(e,t){this[e]=t},$(e,[{key:"name",get:function(){return this._name}},{key:"defaultWeight",get:function(){return this._defaultWeight}},{key:"morphPositions",get:function(){return!!this._vertexBufferPositions||!!this.texturePositions}},{key:"morphNormals",get:function(){return!!this._vertexBufferNormals||!!this.textureNormals}}]),e}(),cc={generateKey:function(e){var t="particle";for(var i in e)e.hasOwnProperty(i)&&(t+=e[i]);return t},_animTex:function(e){var t="";return t+=e.animTexLoop?Wi.particleAnimFrameLoopVS:Wi.particleAnimFrameClampVS,t+=Wi.particleAnimTexVS},createShaderDefinition:function(e,t){var i="",n=Ki(e)+"\n";n+="#define PARTICLE\n",e.webgl2&&(i+="#define GL2\n",n+="#define GL2\n"),i+="#define VERTEXSHADER\n",t.mesh&&(i+="#define USE_MESH\n"),t.localSpace&&(i+="#define LOCAL_SPACE\n"),t.screenSpace&&(i+="#define SCREEN_SPACE\n"),t.animTex&&(i+="\nuniform vec2 animTexTilesParams;\n"),t.animTex&&(i+="\nuniform vec4 animTexParams;\n"),t.animTex&&(i+="\nuniform vec2 animTexIndexParams;\n"),2===t.normal&&(i+="\nvarying mat3 ParticleMat;\n"),1===t.normal&&(i+="\nvarying vec3 Normal;\n"),t.soft&&(i+="\nvarying float vDepth;\n");var s=t.customFace?Wi.particle_customFaceVS:Wi.particle_billboardVS;return t.useCpu?(t.soft>0&&(i+=Wi.screenDepthPS),i+=Wi.particle_cpuVS,t.localSpace&&(i+=Wi.particle_localShiftVS),t.animTex&&(i+=this._animTex(t)),t.alignToMotion&&(i+=Wi.particle_pointAlongVS),i+=t.mesh?Wi.particle_meshVS:s,1===t.normal&&(i+=Wi.particle_normalVS),2===t.normal&&(i+=Wi.particle_TBNVS),t.stretch>0&&(i+=Wi.particle_stretchVS),i+=Wi.particle_cpu_endVS,t.soft>0&&(i+=Wi.particle_softVS)):(i+=Wi.particle_initVS,i+=t.pack8?Wi.particleInputRgba8PS:Wi.particleInputFloatPS,t.soft>0&&(i+=Wi.screenDepthPS),i+=Wi.particleVS,t.localSpace&&(i+=Wi.particle_localShiftVS),t.animTex&&(i+=this._animTex(t)),t.wrap&&(i+=Wi.particle_wrapVS),t.alignToMotion&&(i+=Wi.particle_pointAlongVS),i+=t.mesh?Wi.particle_meshVS:s,1===t.normal&&(i+=Wi.particle_normalVS),2===t.normal&&(i+=Wi.particle_TBNVS),t.stretch>0&&(i+=Wi.particle_stretchVS),i+=Wi.particle_endVS,t.soft>0&&(i+=Wi.particle_softVS)),i+="}\n",t.normal>0&&(1===t.normal?n+="\nvarying vec3 Normal;\n":2===t.normal&&(n+="\nvarying mat3 ParticleMat;\n"),n+="\nuniform vec3 lightCube[6];\n"),t.soft&&(n+="\nvarying float vDepth;\n"),0===t.normal&&"none"===t.fog&&(t.srgb=!1),n+=Wi.decodePS,n+=Xi(t.gamma),n+=qi(t.toneMap),"linear"===t.fog?n+=Wi.fogLinearPS:"exp"===t.fog?n+=Wi.fogExpPS:"exp2"===t.fog?n+=Wi.fogExp2PS:n+=Wi.fogNonePS,2===t.normal&&(n+="\nuniform sampler2D normalMap;\n"),t.soft>0&&(n+=Wi.screenDepthPS),n+=Wi.particlePS,t.soft>0&&(n+=Wi.particle_softPS),1===t.normal&&(n+="\nvec3 normal = Normal;\n"),2===t.normal&&(n+=Wi.particle_normalMapPS),t.normal>0&&(n+=t.halflambert?Wi.particle_halflambertPS:Wi.particle_lambertPS),t.normal>0&&(n+=Wi.particle_lightingPS),2===t.blend?n+=Wi.particle_blendNormalPS:1===t.blend?n+=Wi.particle_blendAddPS:5===t.blend&&(n+=Wi.particle_blendMultiplyPS),n+=Wi.particle_endPS,{attributes:rn(i),vshader:i,fshader:n}}},uc=1,dc=new Ee,fc=new Ee,mc=new ye,_c=new ye,gc=new ye,vc=new ye,yc=new ye,xc=new ye,bc=new ye,Sc=new ye,wc=new ye,Tc=new ye,Ac=new ye,Mc=new ye,Cc=new ye;function Ec(e){return e-Math.floor(e)}function Pc(e){return Math.max(Math.min(e,1),0)}function Rc(e,t){return e-t*Math.floor(e/t)}function Ic(e){var t=Ec(e),i=Ec(255*e);return[t-=i/255,i-=i/255]}var Lc=function(){function e(e){this._emitter=e}var t=e.prototype;return t.calcSpawnPosition=function(e,t,i,n,s){var r=this._emitter,a=Math.random(),o=Math.random(),h=Math.random(),l=Math.random();if(r.useCpu&&(e[4*s+0+2*r.numParticlesPot*4]=a,e[4*s+1+2*r.numParticlesPot*4]=o,e[4*s+2+2*r.numParticlesPot*4]=h),_c.x=a-.5,_c.y=o-.5,_c.z=h-.5,0===r.emitterShape){var c=Math.max(Math.abs(_c.x),Math.max(Math.abs(_c.y),Math.abs(_c.z))),u=c+(.5-c)*i[0],d=c+(.5-c)*i[1],f=c+(.5-c)*i[2];_c.x=u*(c===Math.abs(_c.x)?Math.sign(_c.x):2*_c.x),_c.y=d*(c===Math.abs(_c.y)?Math.sign(_c.y):2*_c.y),_c.z=f*(c===Math.abs(_c.z)?Math.sign(_c.z):2*_c.z),r.localSpace?mc.copy(t.transformPoint(_c)):mc.copy(n).add(t.transformPoint(_c))}else{_c.normalize();var p=0===r.emitterRadius?0:r.emitterRadiusInner/r.emitterRadius,m=l*(1-p)+p;r.localSpace?mc.copy(_c.mulScalar(m*r.emitterRadius)):mc.copy(n).add(_c.mulScalar(m*r.emitterRadius))}var _,g,v,y,x,b=-de.lerp(r.rate,r.rate2,a)*s;if(r.pack8){var S=(mc.x-r.worldBounds.center.x)/r.worldBoundsSize.x+.5,w=(mc.y-r.worldBounds.center.y)/r.worldBoundsSize.y+.5,T=(mc.z-r.worldBounds.center.z)/r.worldBoundsSize.z+.5,A=de.lerp(r.startAngle*de.DEG_TO_RAD,r.startAngle2*de.DEG_TO_RAD,a);A=A%(2*Math.PI)/(2*Math.PI);var M=Ic(S);e[4*s]=M[0],e[4*s+1]=M[1];var C=Ic(w);e[4*s+2]=C[0],e[4*s+3]=C[1];var E=Ic(T);e[4*s+0+4*r.numParticlesPot]=E[0],e[4*s+1+4*r.numParticlesPot]=E[1];var P=Ic(A);e[4*s+2+4*r.numParticlesPot]=P[0],e[4*s+3+4*r.numParticlesPot]=P[1];e[4*s+3+4*r.numParticlesPot*2]=1;var R=Math.max(r.lifetime,(r.numParticles-1)*Math.max(r.rate,r.rate2)),I=r.lifetime+1,L=(g=Ec(_=b=(b+R)/(R+I)),v=Ec(255*_),y=Ec(65025*_),x=Ec(160581375*_),[g-=v/255,v-=y/255,y-=x/255,x-=x/255]);e[4*s+0+4*r.numParticlesPot*3]=L[0],e[4*s+1+4*r.numParticlesPot*3]=L[1],e[4*s+2+4*r.numParticlesPot*3]=L[2],e[4*s+3+4*r.numParticlesPot*3]=L[3]}else e[4*s]=mc.x,e[4*s+1]=mc.y,e[4*s+2]=mc.z,e[4*s+3]=de.lerp(r.startAngle*de.DEG_TO_RAD,r.startAngle2*de.DEG_TO_RAD,a),e[4*s+3+4*r.numParticlesPot]=b},t.update=function(e,t,i,n,s,r,a,o){var h,l,c,u=this._emitter;if(u.meshInstance.node){for(var d=u.meshInstance.node.worldTransform,f=0;f<12;f++)dc.data[f]=d.data[f];fc.copy(dc),fc.invert(),ac=u.meshInstance.node.localScale,uc=Math.max(Math.max(ac.x,ac.y),ac.z)}r=null===u.meshInstance.node||u.localSpace?ye.ZERO:u.meshInstance.node.getPosition();for(var p,m,_,g,v,y,x,b,S=u.camera?u.camera._node.getPosition():ye.ZERO,w=u.useMesh?17:15,T=u.precision-1,A=0;A<u.numParticles;A++){var M=Math.floor(u.vbCPU[A*u.numParticleVerts*(u.useMesh?6:4)+3]),C=i[4*M+0+2*u.numParticlesPot*4];gc.x=C,gc.y=i[4*M+1+2*u.numParticlesPot*4],gc.z=i[4*M+2+2*u.numParticlesPot*4];var E=u.rate+(u.rate2-u.rate)*C,P=u.lifetime,R=i[4*M+3+4*u.numParticlesPot]+a,I=Pc(R/P),L=0,D=0;(R-a<=0||R>=P)&&this.calcSpawnPosition(i,n,s,r,M);var k=R>0&&R<P;k&&(c=I*T,p=Math.floor(c),m=Math.ceil(c),c%=1,_=(h=u.qRotSpeed[p])+((l=u.qRotSpeed[m])-h)*c,g=(h=u.qRotSpeed2[p])+((l=u.qRotSpeed2[m])-h)*c,L=(h=u.qScale[p])+((l=u.qScale[m])-h)*c,v=(h=u.qScale2[p])+((l=u.qScale2[m])-h)*c,y=(h=u.qAlpha[p])+((l=u.qAlpha[m])-h)*c,x=(h=u.qAlpha2[p])+((l=u.qAlpha2[m])-h)*c,b=(h=u.qRadialSpeed[p])+((l=u.qRadialSpeed[m])-h)*c,b+=100*C%1*((h=u.qRadialSpeed2[p])+((l=u.qRadialSpeed2[m])-h)*c-b),vc.x=i[4*M],vc.y=i[4*M+1],vc.z=i[4*M+2],u.localSpace?wc.copy(vc):wc.copy(vc).sub(r),wc.normalize().mulScalar(b),p*=3,m*=3,h=u.qLocalVelocity[p],l=u.qLocalVelocity[m],xc.x=h+(l-h)*c,h=u.qLocalVelocity[p+1],l=u.qLocalVelocity[m+1],xc.y=h+(l-h)*c,h=u.qLocalVelocity[p+2],l=u.qLocalVelocity[m+2],xc.z=h+(l-h)*c,h=u.qLocalVelocity2[p],l=u.qLocalVelocity2[m],Sc.x=h+(l-h)*c,h=u.qLocalVelocity2[p+1],l=u.qLocalVelocity2[m+1],Sc.y=h+(l-h)*c,h=u.qLocalVelocity2[p+2],l=u.qLocalVelocity2[m+2],Sc.z=h+(l-h)*c,h=u.qVelocity[p],l=u.qVelocity[m],yc.x=h+(l-h)*c,h=u.qVelocity[p+1],l=u.qVelocity[m+1],yc.y=h+(l-h)*c,h=u.qVelocity[p+2],l=u.qVelocity[m+2],yc.z=h+(l-h)*c,h=u.qVelocity2[p],l=u.qVelocity2[m],bc.x=h+(l-h)*c,h=u.qVelocity2[p+1],l=u.qVelocity2[m+1],bc.y=h+(l-h)*c,h=u.qVelocity2[p+2],l=u.qVelocity2[m+2],bc.z=h+(l-h)*c,xc.x+=(Sc.x-xc.x)*gc.x,xc.y+=(Sc.y-xc.y)*gc.y,xc.z+=(Sc.z-xc.z)*gc.z,u.initialVelocity>0&&(1===u.emitterShape?(_c.copy(gc).mulScalar(2).sub(ye.ONE).normalize(),xc.add(_c.mulScalar(u.initialVelocity))):xc.add(ye.FORWARD.mulScalar(u.initialVelocity))),yc.x+=(bc.x-yc.x)*gc.x,yc.y+=(bc.y-yc.y)*gc.y,yc.z+=(bc.z-yc.z)*gc.z,_+=(g-_)*gc.y,L=(L+1e4*C%1*(v-L))*uc,D=1e3*C%1*(x-y),u.meshInstance.node&&(u.localSpace?(xc.x/=ac.x,xc.y/=ac.y,xc.z/=ac.z):dc.transformPoint(xc,xc)),u.localSpace?(fc.transformPoint(yc,yc),xc.add(yc).add(wc)):(xc.add(yc.mul(ac)),xc.add(wc.mul(ac))),Mc.copy(xc),Tc.copy(vc).add(xc.mulScalar(a)),Ac.copy(Tc),i[4*M]=Ac.x,i[4*M+1]=Ac.y,i[4*M+2]=Ac.z,i[4*M+3]+=_*a,u.wrap&&u.wrapBounds&&(u.localSpace||Ac.sub(r),Ac.x=Rc(Ac.x,u.wrapBounds.x)-.5*u.wrapBounds.x,Ac.y=Rc(Ac.y,u.wrapBounds.y)-.5*u.wrapBounds.y,Ac.z=Rc(Ac.z,u.wrapBounds.z)-.5*u.wrapBounds.z,u.localSpace||Ac.add(r)),u.sort>0&&(1===u.sort?(Cc.copy(Ac).sub(S),u.particleDistance[M]=-(Cc.x*Cc.x+Cc.y*Cc.y+Cc.z*Cc.z)):2===u.sort?u.particleDistance[M]=R:3===u.sort&&(u.particleDistance[M]=-R))),o?R<0&&(i[4*M+3+2*u.numParticlesPot*4]=-1):(R>=P&&(R-=Math.max(P,(u.numParticles-1)*E),i[4*M+3+2*u.numParticlesPot*4]=u.loop?1:-1),R<0&&u.loop&&(i[4*M+3+2*u.numParticlesPot*4]=1)),i[4*M+3+2*u.numParticlesPot*4]<0&&(k=!1),i[4*M+3+4*u.numParticlesPot]=R;for(var O=0;O<u.numParticleVerts;O++){var F=(A*u.numParticleVerts+O)*(u.useMesh?6:4),B=u.vbCPU[F],N=u.vbCPU[F+1],U=u.vbCPU[F+2];k||(B=N=U=0);var z=A*u.numParticleVerts*w+O*w;e[z]=Ac.x,e[z+1]=Ac.y,e[z+2]=Ac.z,e[z+3]=I,e[z+4]=u.alignToMotion?0:i[4*M+3],e[z+5]=L,e[z+6]=D,e[z+7]=Mc.x,e[z+8]=B,e[z+9]=N,e[z+10]=U,e[z+11]=Mc.y,e[z+12]=M,e[z+13]=Mc.z,e[z+14]=u.vbCPU[F+3],u.useMesh&&(e[z+15]=u.vbCPU[F+4],e[z+16]=u.vbCPU[F+5])}}if(u.sort>0&&u.camera){for(var V=u.useMesh?6:4,G=u.particleDistance,W=0;W<u.numParticles;W++)t[W][0]=W,t[W][1]=G[Math.floor(u.vbCPU[W*u.numParticleVerts*V+3])];u.vbOld.set(u.vbCPU),t.sort((function(e,t){return e[1]-t[1]}));for(var H=0;H<u.numParticles;H++)for(var X=t[H][0]*u.numParticleVerts*V,q=H*u.numParticleVerts*V,j=0;j<u.numParticleVerts*V;j++)u.vbCPU[q+j]=u.vbOld[X+j]}},e}(),Dc=new xe,kc=new xe,Oc=new xe,Fc=function(){function e(e,t){this._emitter=e,this.frameRandomUniform=new Float32Array(3),this.emitterPosUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),this.worldBoundsMulUniform=new Float32Array(3),this.worldBoundsAddUniform=new Float32Array(3),this.inBoundsSizeUniform=new Float32Array(3),this.inBoundsCenterUniform=new Float32Array(3),this.constantParticleTexIN=t.scope.resolve("particleTexIN"),this.constantParticleTexOUT=t.scope.resolve("particleTexOUT"),this.constantEmitterPos=t.scope.resolve("emitterPos"),this.constantEmitterScale=t.scope.resolve("emitterScale"),this.constantSpawnBounds=t.scope.resolve("spawnBounds"),this.constantSpawnPosInnerRatio=t.scope.resolve("spawnPosInnerRatio"),this.constantSpawnBoundsSphere=t.scope.resolve("spawnBoundsSphere"),this.constantSpawnBoundsSphereInnerRatio=t.scope.resolve("spawnBoundsSphereInnerRatio"),this.constantInitialVelocity=t.scope.resolve("initialVelocity"),this.constantFrameRandom=t.scope.resolve("frameRandom"),this.constantDelta=t.scope.resolve("delta"),this.constantRate=t.scope.resolve("rate"),this.constantRateDiv=t.scope.resolve("rateDiv"),this.constantLifetime=t.scope.resolve("lifetime"),this.constantGraphSampleSize=t.scope.resolve("graphSampleSize"),this.constantGraphNumSamples=t.scope.resolve("graphNumSamples"),this.constantInternalTex0=t.scope.resolve("internalTex0"),this.constantInternalTex1=t.scope.resolve("internalTex1"),this.constantInternalTex2=t.scope.resolve("internalTex2"),this.constantInternalTex3=t.scope.resolve("internalTex3"),this.constantEmitterMatrix=t.scope.resolve("emitterMatrix"),this.constantEmitterMatrixInv=t.scope.resolve("emitterMatrixInv"),this.constantNumParticles=t.scope.resolve("numParticles"),this.constantNumParticlesPot=t.scope.resolve("numParticlesPot"),this.constantLocalVelocityDivMult=t.scope.resolve("localVelocityDivMult"),this.constantVelocityDivMult=t.scope.resolve("velocityDivMult"),this.constantRotSpeedDivMult=t.scope.resolve("rotSpeedDivMult"),this.constantSeed=t.scope.resolve("seed"),this.constantStartAngle=t.scope.resolve("startAngle"),this.constantStartAngle2=t.scope.resolve("startAngle2"),this.constantOutBoundsMul=t.scope.resolve("outBoundsMul"),this.constantOutBoundsAdd=t.scope.resolve("outBoundsAdd"),this.constantInBoundsSize=t.scope.resolve("inBoundsSize"),this.constantInBoundsCenter=t.scope.resolve("inBoundsCenter"),this.constantMaxVel=t.scope.resolve("maxVel"),this.constantFaceTangent=t.scope.resolve("faceTangent"),this.constantFaceBinorm=t.scope.resolve("faceBinorm")}var t=e.prototype;return t._setInputBounds=function(){this.inBoundsSizeUniform[0]=this._emitter.prevWorldBoundsSize.x,this.inBoundsSizeUniform[1]=this._emitter.prevWorldBoundsSize.y,this.inBoundsSizeUniform[2]=this._emitter.prevWorldBoundsSize.z,this.constantInBoundsSize.setValue(this.inBoundsSizeUniform),this.inBoundsCenterUniform[0]=this._emitter.prevWorldBoundsCenter.x,this.inBoundsCenterUniform[1]=this._emitter.prevWorldBoundsCenter.y,this.inBoundsCenterUniform[2]=this._emitter.prevWorldBoundsCenter.z,this.constantInBoundsCenter.setValue(this.inBoundsCenterUniform)},t.randomize=function(){this.frameRandomUniform[0]=Math.random(),this.frameRandomUniform[1]=Math.random(),this.frameRandomUniform[2]=Math.random()},t.update=function(e,t,i,n,s){var r=this._emitter;e.setBlending(!1),e.setColorWrite(!0,!0,!0,!0),e.setCullMode(0),e.setDepthTest(!1),e.setDepthWrite(!1),this.randomize(),this.constantGraphSampleSize.setValue(1/r.precision),this.constantGraphNumSamples.setValue(r.precision),this.constantNumParticles.setValue(r.numParticles),this.constantNumParticlesPot.setValue(r.numParticlesPot),this.constantInternalTex0.setValue(r.internalTex0),this.constantInternalTex1.setValue(r.internalTex1),this.constantInternalTex2.setValue(r.internalTex2),this.constantInternalTex3.setValue(r.internalTex3);var a=r.meshInstance.node,o=null===a?ye.ONE:a.localScale;if(r.pack8){this.worldBoundsMulUniform[0]=r.worldBoundsMul.x,this.worldBoundsMulUniform[1]=r.worldBoundsMul.y,this.worldBoundsMulUniform[2]=r.worldBoundsMul.z,this.constantOutBoundsMul.setValue(this.worldBoundsMulUniform),this.worldBoundsAddUniform[0]=r.worldBoundsAdd.x,this.worldBoundsAddUniform[1]=r.worldBoundsAdd.y,this.worldBoundsAddUniform[2]=r.worldBoundsAdd.z,this.constantOutBoundsAdd.setValue(this.worldBoundsAddUniform),this._setInputBounds();var h=r.maxVel*Math.max(Math.max(o.x,o.y),o.z);h=Math.max(h,1),this.constantMaxVel.setValue(h)}var l=null===a||r.localSpace?ye.ZERO:a.getPosition(),c=null===a?Ee.IDENTITY:a.getWorldTransform();0===r.emitterShape?(Dc.setFromMat4(t),this.constantSpawnBounds.setValue(Dc.data),this.constantSpawnPosInnerRatio.setValue(i)):(this.constantSpawnBoundsSphere.setValue(r.emitterRadius),this.constantSpawnBoundsSphereInnerRatio.setValue(0===r.emitterRadius?0:r.emitterRadiusInner/r.emitterRadius)),this.constantInitialVelocity.setValue(r.initialVelocity),kc.setFromMat4(c),c.invertTo3x3(Oc),this.emitterPosUniform[0]=l.x,this.emitterPosUniform[1]=l.y,this.emitterPosUniform[2]=l.z,this.constantEmitterPos.setValue(this.emitterPosUniform),this.constantFrameRandom.setValue(this.frameRandomUniform),this.constantDelta.setValue(n),this.constantRate.setValue(r.rate),this.constantRateDiv.setValue(r.rate2-r.rate),this.constantStartAngle.setValue(r.startAngle*de.DEG_TO_RAD),this.constantStartAngle2.setValue(r.startAngle2*de.DEG_TO_RAD),this.constantSeed.setValue(r.seed),this.constantLifetime.setValue(r.lifetime),this.emitterScaleUniform[0]=o.x,this.emitterScaleUniform[1]=o.y,this.emitterScaleUniform[2]=o.z,this.constantEmitterScale.setValue(this.emitterScaleUniform),this.constantEmitterMatrix.setValue(kc.data),this.constantEmitterMatrixInv.setValue(Oc.data),this.constantLocalVelocityDivMult.setValue(r.localVelocityUMax),this.constantVelocityDivMult.setValue(r.velocityUMax),this.constantRotSpeedDivMult.setValue(r.rotSpeedUMax[0]);var u=r.swapTex?r.particleTexOUT:r.particleTexIN;u=r.beenReset?r.particleTexStart:u;var d=r.swapTex?r.particleTexIN:r.particleTexOUT;this.constantParticleTexIN.setValue(u),Ei(e,r.swapTex?r.rtParticleTexIN:r.rtParticleTexOUT,s?r.shaderParticleUpdateOnStop:r.loop?r.shaderParticleUpdateRespawn:r.shaderParticleUpdateNoRespawn),r.material.setParameter("particleTexOUT",u),r.material.setParameter("particleTexIN",d),r.beenReset=!1,r.swapTex=!r.swapTex,e.setDepthTest(!0),e.setDepthWrite(!0),r.prevWorldBoundsSize.copy(r.worldBoundsSize),r.prevWorldBoundsCenter.copy(r.worldBounds.center),r.pack8&&this._setInputBounds()},e}(),Bc=[[-1,-1],[1,-1],[1,1],[-1,1]];function Nc(e,t,i,n,s,r,a){void 0===s&&(s=dt);var o=0;a&&7===s&&(o=1);var h=new wn(e,{width:t,height:i,format:s,cubemap:!1,mipmaps:!1,minFilter:o,magFilter:o,addressU:1,addressV:1,name:"ParticleSystemTexture"}),l=h.lock();if(7===s){for(var c=new Uint8Array(n.length),u=0;u<n.length;u++)c[u]=n[u]*r*255;n=c}return l.set(n),h.unlock(),h}function Uc(e){return Math.max(Math.min(e,1),0)}var zc,Vc,Gc=new ge([0,0,1,0]),Wc=new ge([0,1,1,1]),Hc=new ve([0,0,1,0],[0,0,1,0],[0,0,1,0]),Xc=new ve([0,1,1,1],[0,1,1,1],[0,1,1,1]),qc=2,jc=new Float32Array(3),Yc=new Ee,Kc=new ye,Zc=new ye,$c=new ye;function Qc(e,t){void 0!==Vc[e]&&null!==Vc[e]?zc[e]=Vc[e]:zc[e]=t}function Jc(e,t,i){return(255*e<<16|255*t<<8|255*i)/(1<<24)}function eu(e,t){for(var i=e.length/3,n=new Array(4*i),s=0;s<i;s++)n[4*s]=e[3*s],n[4*s+1]=e[3*s+1],n[4*s+2]=e[3*s+2],n[4*s+3]=Jc(t[3*s],t[3*s+1],t[3*s+2]);return n}function tu(e,t){for(var i=t.length,n=e.length/i,s=0;s<n;s++)for(var r=0;r<i;r++){var a=Math.abs(e[s*i+r]);t[r]=Math.max(t[r],a)}}function iu(e,t,i){var n=function(e,t){for(var i=new Float32Array(e.length),n=0;n<e.length;n++)i[n]=e[n]-t[n];return i}(t,e);return tu(n,i),function(e,t){for(var i=t.length,n=e.length/i,s=0;s<n;s++)for(var r=0;r<i;r++)e[s*i+r]/=0===t[r]?1:t[r],e[s*i+r]*=.5,e[s*i+r]+=.5}(n,i),n}var nu=new Ai,su=function(){function e(e,t){this.graphicsDevice=e;var i=e;this.precision=32,this._addTimeTime=0,zc=this,Vc=t,Qc("numParticles",1),this.numParticles>e.maxTextureSize&&(this.numParticles=e.maxTextureSize),Qc("rate",1),Qc("rate2",this.rate),Qc("lifetime",50),Qc("emitterExtents",new ye(0,0,0)),Qc("emitterExtentsInner",new ye(0,0,0)),Qc("emitterRadius",0),Qc("emitterRadiusInner",0),Qc("emitterShape",0),Qc("initialVelocity",1),Qc("wrap",!1),Qc("localSpace",!1),Qc("screenSpace",!1),Qc("wrapBounds",null),Qc("colorMap",this.defaultParamTexture),Qc("normalMap",null),Qc("loop",!0),Qc("preWarm",!1),Qc("sort",0),Qc("mode",0),Qc("scene",null),Qc("lighting",!1),Qc("halfLambert",!1),Qc("intensity",1),Qc("stretch",0),Qc("alignToMotion",!1),Qc("depthSoftening",0),Qc("mesh",null),Qc("particleNormal",new ye(0,1,0)),Qc("orientation",0),Qc("depthWrite",!1),Qc("noFog",!1),Qc("blendType",2),Qc("node",null),Qc("startAngle",0),Qc("startAngle2",this.startAngle),Qc("animTilesX",1),Qc("animTilesY",1),Qc("animStartFrame",0),Qc("animNumFrames",1),Qc("animNumAnimations",1),Qc("animIndex",0),Qc("randomizeAnimIndex",!1),Qc("animSpeed",1),Qc("animLoop",!0),this._gpuUpdater=new Fc(this,i),this._cpuUpdater=new Lc(this),this.constantLightCube=i.scope.resolve("lightCube[0]"),this.emitterPosUniform=new Float32Array(3),this.wrapBoundsUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),Qc("colorGraph",Xc),Qc("colorGraph2",this.colorGraph),Qc("scaleGraph",Wc),Qc("scaleGraph2",this.scaleGraph),Qc("alphaGraph",Wc),Qc("alphaGraph2",this.alphaGraph),Qc("localVelocityGraph",Hc),Qc("localVelocityGraph2",this.localVelocityGraph),Qc("velocityGraph",Hc),Qc("velocityGraph2",this.velocityGraph),Qc("rotationSpeedGraph",Gc),Qc("rotationSpeedGraph2",this.rotationSpeedGraph),Qc("radialSpeedGraph",Gc),Qc("radialSpeedGraph2",this.radialSpeedGraph),this.lightCube=new Float32Array(18),this.lightCubeDir=new Array(6),this.lightCubeDir[0]=new ye(-1,0,0),this.lightCubeDir[1]=new ye(1,0,0),this.lightCubeDir[2]=new ye(0,-1,0),this.lightCubeDir[3]=new ye(0,1,0),this.lightCubeDir[4]=new ye(0,0,-1),this.lightCubeDir[5]=new ye(0,0,1),this.animTilesParams=new Float32Array(2),this.animParams=new Float32Array(4),this.animIndexParams=new Float32Array(2),this.internalTex0=null,this.internalTex1=null,this.internalTex2=null,this.colorParam=null,this.vbToSort=null,this.vbOld=null,this.particleDistance=null,this.camera=null,this.swapTex=!1,this.useMesh=!0,this.useCpu=!e.supportsGpuParticles,this.pack8=!0,this.localBounds=new Oe,this.worldBoundsNoTrail=new Oe,this.worldBoundsTrail=[new Oe,new Oe],this.worldBounds=new Oe,this.worldBoundsSize=new ye,this.prevWorldBoundsSize=new ye,this.prevWorldBoundsCenter=new ye,this.prevEmitterExtents=this.emitterExtents,this.prevEmitterRadius=this.emitterRadius,this.worldBoundsMul=new ye,this.worldBoundsAdd=new ye,this.timeToSwitchBounds=0,this.shaderParticleUpdateRespawn=null,this.shaderParticleUpdateNoRespawn=null,this.shaderParticleUpdateOnStop=null,this.numParticleVerts=0,this.numParticleIndices=0,this.material=null,this.meshInstance=null,this.drawOrder=0,this.seed=Math.random(),this.fixedTimeStep=1/60,this.maxSubSteps=10,this.simTime=0,this.simTimeTotal=0,this.beenReset=!1,this._layer=null,this.rebuild()}var t=e.prototype;return t.onChangeCamera=function(){this.regenShader(),this.resetMaterial()},t.calculateBoundsMad=function(){this.worldBoundsMul.x=1/this.worldBoundsSize.x,this.worldBoundsMul.y=1/this.worldBoundsSize.y,this.worldBoundsMul.z=1/this.worldBoundsSize.z,this.worldBoundsAdd.copy(this.worldBounds.center).mul(this.worldBoundsMul).mulScalar(-1),this.worldBoundsAdd.x+=.5,this.worldBoundsAdd.y+=.5,this.worldBoundsAdd.z+=.5},t.calculateWorldBounds=function(){if(this.node){if(this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),!this.useCpu){(0===this.emitterShape?!this.emitterExtents.equals(this.prevEmitterExtents):!(this.emitterRadius===this.prevEmitterRadius))&&this.calculateLocalBounds()}var e=this.node.getWorldTransform();this.localSpace?this.worldBoundsNoTrail.copy(this.localBounds):this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,e),this.worldBoundsTrail[0].add(this.worldBoundsNoTrail),this.worldBoundsTrail[1].add(this.worldBoundsNoTrail);var t=this.simTimeTotal;t>=this.timeToSwitchBounds&&(this.worldBoundsTrail[0].copy(this.worldBoundsTrail[1]),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.timeToSwitchBounds=t+this.lifetime),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.localSpace?(this.meshInstance.aabb.setFromTransformedAabb(this.worldBounds,e),this.meshInstance.mesh.aabb.setFromTransformedAabb(this.worldBounds,e)):(this.meshInstance.aabb.copy(this.worldBounds),this.meshInstance.mesh.aabb.copy(this.worldBounds)),this.meshInstance._aabbVer=1-this.meshInstance._aabbVer,this.pack8&&this.calculateBoundsMad()}},t.resetWorldBounds=function(){this.node&&(this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,this.localSpace?Ee.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBoundsNoTrail),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.simTimeTotal=0,this.timeToSwitchBounds=0)},t.calculateLocalBounds=function(){for(var e,t,i,n=Number.MAX_VALUE,s=Number.MAX_VALUE,r=Number.MAX_VALUE,a=-Number.MAX_VALUE,o=-Number.MAX_VALUE,h=-Number.MAX_VALUE,l=0,c=0,u=this.lifetime/this.precision,d=[this.qVelocity,this.qVelocity2],f=[this.qLocalVelocity,this.qLocalVelocity2],p=[0,0],m=[0,0],_=[0,0],g=[0,0],v=[0,0],y=0;y<this.precision+1;y++){for(var x=Math.min(y,this.precision-1),b=0;b<2;b++)e=f[b][3*x+0]*u+p[b],t=f[b][3*x+1]*u+m[b],i=f[b][3*x+2]*u+_[b],n=Math.min(e,n),s=Math.min(t,s),r=Math.min(i,r),a=Math.max(e,a),o=Math.max(t,o),h=Math.max(i,h),p[b]=e,m[b]=t,_[b]=i;for(var S=0;S<2;S++)v[S]+=u*Math.sqrt(d[S][3*x+0]*d[S][3*x+0]+d[S][3*x+1]*d[S][3*x+1]+d[S][3*x+2]*d[S][3*x+2]);g[0]+=this.qRadialSpeed[x]*u,g[1]+=this.qRadialSpeed2[x]*u,l=Math.max(l,Math.max(Math.abs(g[0]),Math.abs(g[1]))),c=Math.max(c,this.qScale[x])}0===this.emitterShape?(e=.5*this.emitterExtents.x,t=.5*this.emitterExtents.y,i=.5*this.emitterExtents.z):(e=this.emitterRadius,t=this.emitterRadius,i=this.emitterRadius);var w=Math.max(v[0],v[1]);Zc.x=n-c-e-l-w,Zc.y=s-c-t-l-w,Zc.z=r-c-i-l-w,$c.x=a+c+e+l+w,$c.y=o+c+t+l+w,$c.z=h+c+i+l+w,this.localBounds.setMinMax(Zc,$c)},t.rebuild=function(){var e=this.graphicsDevice;(null===this.colorMap&&(this.colorMap=this.defaultParamTexture),this.spawnBounds=0===this.emitterShape?this.emitterExtents:this.emitterRadius,this.useCpu=this.useCpu||this.sort>0||e.maxVertexTextures<=1||e.fragmentUniformsCount<64||e.forceCpuParticles||!e.extTextureFloat,this._destroyResources(),this.pack8=(this.pack8||!e.textureFloatRenderable)&&!this.useCpu,qc=this.useCpu||this.pack8?4:2,this.useMesh=!1,this.mesh)&&(this.numParticles*this.mesh.vertexBuffer.numVertices>65535||(this.useMesh=!0));this.numParticlesPot=de.nextPowerOfTwo(this.numParticles),this.rebuildGraphs(),this.calculateLocalBounds(),this.resetWorldBounds(),this.node&&(this.worldBounds.setFromTransformedAabb(this.localBounds,this.localSpace?Ee.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBounds),this.worldBoundsTrail[1].copy(this.worldBounds),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.pack8&&this.calculateBoundsMad()),this.vbToSort=new Array(this.numParticles);for(var t=0;t<this.numParticles;t++)this.vbToSort[t]=[0,0];this.particleDistance=new Float32Array(this.numParticles),this._gpuUpdater.randomize(),this.particleTex=new Float32Array(this.numParticlesPot*qc*4);var i=null===this.node||this.localSpace?ye.ZERO:this.node.getPosition();0===this.emitterShape&&(null===this.node||this.localSpace?Yc.setTRS(ye.ZERO,Pe.IDENTITY,this.spawnBounds):Yc.setTRS(ye.ZERO,this.node.getRotation(),Kc.copy(this.spawnBounds).mul(this.node.localScale)),jc[0]=0!==this.emitterExtents.x?this.emitterExtentsInner.x/this.emitterExtents.x:0,jc[1]=0!==this.emitterExtents.y?this.emitterExtentsInner.y/this.emitterExtents.y:0,jc[2]=0!==this.emitterExtents.z?this.emitterExtentsInner.z/this.emitterExtents.z:0);for(var n=0;n<this.numParticles;n++)this._cpuUpdater.calcSpawnPosition(this.particleTex,Yc,jc,i,n),this.useCpu&&(this.particleTex[4*n+3+2*this.numParticlesPot*4]=1);this.particleTexStart=new Float32Array(this.numParticlesPot*qc*4);for(var s=0;s<this.particleTexStart.length;s++)this.particleTexStart[s]=this.particleTex[s];this.useCpu||(this.pack8?(this.particleTexIN=Nc(e,this.numParticlesPot,qc,this.particleTex,7,1,!1),this.particleTexOUT=Nc(e,this.numParticlesPot,qc,this.particleTex,7,1,!1),this.particleTexStart=Nc(e,this.numParticlesPot,qc,this.particleTexStart,7,1,!1)):(this.particleTexIN=Nc(e,this.numParticlesPot,qc,this.particleTex),this.particleTexOUT=Nc(e,this.numParticlesPot,qc,this.particleTex),this.particleTexStart=Nc(e,this.numParticlesPot,qc,this.particleTexStart)),this.rtParticleTexIN=new cr({colorBuffer:this.particleTexIN,depth:!1}),this.rtParticleTexOUT=new cr({colorBuffer:this.particleTexOUT,depth:!1}),this.swapTex=!1);var r=(this.localSpace?"#define LOCAL_SPACE\n":"")+Wi.particleUpdaterInitPS+(this.pack8?Wi.particleInputRgba8PS+Wi.particleOutputRgba8PS:Wi.particleInputFloatPS+Wi.particleOutputFloatPS)+(0===this.emitterShape?Wi.particleUpdaterAABBPS:Wi.particleUpdaterSpherePS)+Wi.particleUpdaterStartPS,a=r+Wi.particleUpdaterRespawnPS+Wi.particleUpdaterEndPS,o=r+Wi.particleUpdaterNoRespawnPS+Wi.particleUpdaterEndPS,h=r+Wi.particleUpdaterOnStopPS+Wi.particleUpdaterEndPS,l=this.emitterShape+""+this.pack8+this.localSpace;this.shaderParticleUpdateRespawn=on(e,Wi.fullscreenQuadVS,a,"fsQuad0"+l),this.shaderParticleUpdateNoRespawn=on(e,Wi.fullscreenQuadVS,o,"fsQuad1"+l),this.shaderParticleUpdateOnStop=on(e,Wi.fullscreenQuadVS,h,"fsQuad2"+l),this.numParticleVerts=this.useMesh?this.mesh.vertexBuffer.numVertices:4,this.numParticleIndices=this.useMesh?this.mesh.indexBuffer[0].numIndices:6,this._allocate(this.numParticles);var c=new ea(e);c.vertexBuffer=this.vertexBuffer,c.indexBuffer[0]=this.indexBuffer,c.primitive[0].type=4,c.primitive[0].base=0,c.primitive[0].count=this.numParticles*this.numParticleIndices,c.primitive[0].indexed=!0,this.material=new Bs,this.material.name=this.node.name,this.material.cull=0,this.material.alphaWrite=!1,this.material.blend=!0,this.material.blendType=this.blendType,this.material.depthWrite=this.depthWrite,this.material.emitter=this,this.regenShader(),this.resetMaterial();var u=!this.meshInstance||this.meshInstance.visible;this.meshInstance=new ka(c,this.material,this.node),this.meshInstance.pick=!1,this.meshInstance.updateKey(),this.meshInstance.cull=!0,this.meshInstance._noDepthDrawGl1=!0,this.localSpace?this.meshInstance.aabb.setFromTransformedAabb(this.worldBounds,this.node.getWorldTransform()):this.meshInstance.aabb.copy(this.worldBounds),this.meshInstance._updateAabb=!1,this.meshInstance.visible=u,this._initializeTextures(),this.resetTime(),this.addTime(0,!1),this.preWarm&&this.prewarm(this.lifetime)},t._isAnimated=function(){return this.animNumFrames>=1&&(this.animTilesX>1||this.animTilesY>1)&&(this.colorMap&&this.colorMap!==this.defaultParamTexture||this.normalMap)},t.rebuildGraphs=function(){var e=this.precision,t=this.graphicsDevice;this.qLocalVelocity=this.localVelocityGraph.quantize(e),this.qVelocity=this.velocityGraph.quantize(e),this.qColor=this.colorGraph.quantizeClamped(e,0,1),this.qRotSpeed=this.rotationSpeedGraph.quantize(e),this.qScale=this.scaleGraph.quantize(e),this.qAlpha=this.alphaGraph.quantize(e),this.qRadialSpeed=this.radialSpeedGraph.quantize(e),this.qLocalVelocity2=this.localVelocityGraph2.quantize(e),this.qVelocity2=this.velocityGraph2.quantize(e),this.qColor2=this.colorGraph2.quantizeClamped(e,0,1),this.qRotSpeed2=this.rotationSpeedGraph2.quantize(e),this.qScale2=this.scaleGraph2.quantize(e),this.qAlpha2=this.alphaGraph2.quantize(e),this.qRadialSpeed2=this.radialSpeedGraph2.quantize(e);for(var i=0;i<e;i++)this.qRotSpeed[i]*=de.DEG_TO_RAD,this.qRotSpeed2[i]*=de.DEG_TO_RAD;if(this.localVelocityUMax=new Float32Array(3),this.velocityUMax=new Float32Array(3),this.colorUMax=new Float32Array(3),this.rotSpeedUMax=[0],this.scaleUMax=[0],this.alphaUMax=[0],this.radialSpeedUMax=[0],this.qLocalVelocityDiv=iu(this.qLocalVelocity,this.qLocalVelocity2,this.localVelocityUMax),this.qVelocityDiv=iu(this.qVelocity,this.qVelocity2,this.velocityUMax),this.qColorDiv=iu(this.qColor,this.qColor2,this.colorUMax),this.qRotSpeedDiv=iu(this.qRotSpeed,this.qRotSpeed2,this.rotSpeedUMax),this.qScaleDiv=iu(this.qScale,this.qScale2,this.scaleUMax),this.qAlphaDiv=iu(this.qAlpha,this.qAlpha2,this.alphaUMax),this.qRadialSpeedDiv=iu(this.qRadialSpeed,this.qRadialSpeed2,this.radialSpeedUMax),this.pack8){var n=[0,0,0];tu(this.qVelocity,n);var s=[0,0,0];tu(this.qVelocity2,s);var r=[0,0,0];tu(this.qLocalVelocity,r);var a=[0,0,0];tu(this.qLocalVelocity2,a);var o=[0];tu(this.qRadialSpeed,o);var h=[0];tu(this.qRadialSpeed2,h);var l=Math.max(n[0],s[0]);l=Math.max(l,n[1]),l=Math.max(l,s[1]),l=Math.max(l,n[2]),l=Math.max(l,s[2]);var c=Math.max(r[0],a[0]);c=Math.max(c,r[1]),c=Math.max(c,a[1]),c=Math.max(c,r[2]),c=Math.max(c,a[2]);var u=Math.max(o[0],h[0]);this.maxVel=l+c+u}this.useCpu||(this.internalTex0=Nc(t,e,1,eu(this.qLocalVelocity,this.qLocalVelocityDiv)),this.internalTex1=Nc(t,e,1,eu(this.qVelocity,this.qVelocityDiv)),this.internalTex2=Nc(t,e,1,function(e,t,i,n,s){for(var r=new Array(4*e.length),a=0;a<e.length;a++)r[4*a]=e[a],r[4*a+1]=t[a],r[4*a+2]=0,r[4*a+3]=Jc(i[a],n[a],s[a]);return r}(this.qRotSpeed,this.qScale,this.qScaleDiv,this.qRotSpeedDiv,this.qAlphaDiv)),this.internalTex3=Nc(t,e,1,function(e,t){for(var i=new Array(4*e.length),n=0;n<e.length;n++)i[4*n]=e[n],i[4*n+1]=t[n],i[4*n+2]=0,i[4*n+3]=0;return i}(this.qRadialSpeed,this.qRadialSpeedDiv))),this.colorParam=Nc(t,e,1,function(e,t){for(var i=new Array(4*t.length),n=0;n<t.length;n++)i[4*n]=e[3*n],i[4*n+1]=e[3*n+1],i[4*n+2]=e[3*n+2],i[4*n+3]=t[n];return i}(this.qColor,this.qAlpha),7,1,!0)},t._initializeTextures=function(){this.colorMap&&(this.material.setParameter("colorMap",this.colorMap),this.lighting&&this.normalMap&&this.material.setParameter("normalMap",this.normalMap))},t.regenShader=function(){var e=this.graphicsDevice.getProgramLibrary();this.graphicsDevice.programLib.register("particle",cc);var t=null!==this.normalMap;this.normalOption=0,this.lighting&&(this.normalOption=t?2:1),this.material.getShaderVariant=function(t,i,n,s,r,a,o,h){this.emitter.scene&&this.emitter.camera!==this.emitter.scene._activeCamera&&(this.emitter.camera=this.emitter.scene._activeCamera,this.emitter.onChangeCamera());var l=this.emitter.inTools;return e.getProgram("particle",{useCpu:this.emitter.useCpu,normal:this.emitter.normalOption,halflambert:this.emitter.halfLambert,stretch:this.emitter.stretch,alignToMotion:this.emitter.alignToMotion,soft:this.emitter.depthSoftening,mesh:this.emitter.useMesh,gamma:this.emitter.scene?this.emitter.scene.gammaCorrection:0,toneMap:this.emitter.scene?this.emitter.scene.toneMapping:0,fog:this.emitter.scene&&!this.emitter.noFog?this.emitter.scene.fog:"none",wrap:this.emitter.wrap&&this.emitter.wrapBounds,localSpace:this.emitter.localSpace,screenSpace:!l&&this.emitter.screenSpace,blend:this.blendType,animTex:this.emitter._isAnimated(),animTexLoop:this.emitter.animLoop,pack8:this.emitter.pack8,customFace:0!==this.emitter.orientation})},this.material.shader=this.material.getShaderVariant()},t.resetMaterial=function(){var e=this.material;e.setParameter("stretch",this.stretch),this._isAnimated()&&(e.setParameter("animTexTilesParams",this.animTilesParams),e.setParameter("animTexParams",this.animParams),e.setParameter("animTexIndexParams",this.animIndexParams)),e.setParameter("colorMult",this.intensity),this.useCpu||(e.setParameter("internalTex0",this.internalTex0),e.setParameter("internalTex1",this.internalTex1),e.setParameter("internalTex2",this.internalTex2),e.setParameter("internalTex3",this.internalTex3)),e.setParameter("colorParam",this.colorParam),e.setParameter("numParticles",this.numParticles),e.setParameter("numParticlesPot",this.numParticlesPot),e.setParameter("lifetime",this.lifetime),e.setParameter("rate",this.rate),e.setParameter("rateDiv",this.rate2-this.rate),e.setParameter("seed",this.seed),e.setParameter("scaleDivMult",this.scaleUMax[0]),e.setParameter("alphaDivMult",this.alphaUMax[0]),e.setParameter("radialSpeedDivMult",this.radialSpeedUMax[0]),e.setParameter("graphNumSamples",this.precision),e.setParameter("graphSampleSize",1/this.precision),e.setParameter("emitterScale",new Float32Array([1,1,1])),this.pack8&&(this._gpuUpdater._setInputBounds(),e.setParameter("inBoundsSize",this._gpuUpdater.inBoundsSizeUniform),e.setParameter("inBoundsCenter",this._gpuUpdater.inBoundsCenterUniform),e.setParameter("maxVel",this.maxVel)),this.wrap&&this.wrapBounds&&(this.wrapBoundsUniform[0]=this.wrapBounds.x,this.wrapBoundsUniform[1]=this.wrapBounds.y,this.wrapBoundsUniform[2]=this.wrapBounds.z,e.setParameter("wrapBounds",this.wrapBoundsUniform)),this.colorMap&&e.setParameter("colorMap",this.colorMap),this.lighting&&this.normalMap&&e.setParameter("normalMap",this.normalMap),this.depthSoftening>0&&e.setParameter("softening",1/(this.depthSoftening*this.depthSoftening*100)),this.stretch>0&&(e.cull=0),this._compParticleFaceParams()},t._compParticleFaceParams=function(){var e,t;if(0===this.orientation)e=new Float32Array([1,0,0]),t=new Float32Array([0,0,1]);else{var i;if(1===this.orientation)i=this.particleNormal.normalize();else i=(null===this.node?Ee.IDENTITY:this.node.getWorldTransform()).transformVector(this.particleNormal).normalize();var n=new ye(1,0,0);1===Math.abs(n.dot(i))&&n.set(0,0,1);var s=(new ye).cross(i,n).normalize();n.cross(s,i).normalize(),e=new Float32Array([n.x,n.y,n.z]),t=new Float32Array([s.x,s.y,s.z])}this.material.setParameter("faceTangent",e),this.material.setParameter("faceBinorm",t)},t._allocate=function(e){var t=e*this.numParticleVerts,i=e*this.numParticleIndices;if(void 0===this.vertexBuffer||this.vertexBuffer.getNumVertices()!==t){if(this.useCpu){var n=[{semantic:kt,components:4,type:6},{semantic:Ot,components:4,type:6},{semantic:Ft,components:4,type:6},{semantic:Bt,components:1,type:6},{semantic:Nt,components:this.useMesh?4:2,type:6}],s=new Ti(this.graphicsDevice,n);this.vertexBuffer=new Si(this.graphicsDevice,s,t,1),this.indexBuffer=new mr(this.graphicsDevice,1,i)}else{var r=[{semantic:kt,components:4,type:6}];this.useMesh&&r.push({semantic:Ot,components:2,type:6});var a=new Ti(this.graphicsDevice,r);this.vertexBuffer=new Si(this.graphicsDevice,a,t,1),this.indexBuffer=new mr(this.graphicsDevice,1,i)}var o,h,l,c=new Float32Array(this.vertexBuffer.lock());if(this.useMesh){h=(o=new Float32Array(this.mesh.vertexBuffer.lock())).length/this.mesh.vertexBuffer.numVertices;for(var u=0;u<this.mesh.vertexBuffer.format.elements.length;u++)if(this.mesh.vertexBuffer.format.elements[u].name===At){l=this.mesh.vertexBuffer.format.elements[u].offset/4;break}}for(var d=0;d<t;d++){var f=Math.floor(d/this.numParticleVerts);if(this.useMesh){var p=d%this.numParticleVerts;c[6*d]=o[p*h],c[6*d+1]=o[p*h+1],c[6*d+2]=o[p*h+2],c[6*d+3]=f,c[6*d+4]=o[p*h+l+0],c[6*d+5]=1-o[p*h+l+1]}else{var m=d%4;c[4*d]=Bc[m][0],c[4*d+1]=Bc[m][1],c[4*d+2]=0,c[4*d+3]=f}}this.useCpu&&(this.vbCPU=new Float32Array(c),this.vbOld=new Float32Array(this.vbCPU.length)),this.vertexBuffer.unlock(),this.useMesh&&this.mesh.vertexBuffer.unlock();var _=0,g=new Uint16Array(this.indexBuffer.lock());this.useMesh&&(o=new Uint16Array(this.mesh.indexBuffer[0].lock()));for(var v=0;v<e;v++)if(this.useMesh)for(var y=0;y<this.numParticleIndices;y++)g[v*this.numParticleIndices+y]=o[y]+v*this.numParticleVerts;else{var x=4*v;g[_++]=x,g[_++]=x+1,g[_++]=x+2,g[_++]=x,g[_++]=x+2,g[_++]=x+3}this.indexBuffer.unlock(),this.useMesh&&this.mesh.indexBuffer[0].unlock()}},t.reset=function(){if(this.beenReset=!0,this.seed=Math.random(),this.material.setParameter("seed",this.seed),this.useCpu)for(var e=0;e<this.particleTexStart.length;e++)this.particleTex[e]=this.particleTexStart[e];else this._initializeTextures();this.resetWorldBounds(),this.resetTime();var t=this.loop;this.loop=!0,this.addTime(0,!1),this.loop=t,this.preWarm&&this.prewarm(this.lifetime)},t.prewarm=function(e){for(var t=e/this.lifetime,i=Math.min(Math.floor(t*this.precision),this.precision),n=e/i,s=0;s<i;s++)this.addTime(n,!1)},t.resetTime=function(){var e,t;this.endTime=(e=this,t=Math.max(e.rate,e.rate2)*e.numParticles+e.lifetime,Date.now()+1e3*t)},t.finishFrame=function(){this.useCpu&&this.vertexBuffer.unlock()},t.addTime=function(e,t){var i,n=this.graphicsDevice;if(this.simTimeTotal+=e,this.calculateWorldBounds(),this._isAnimated()){var s=this.animTilesParams;s[0]=1/this.animTilesX,s[1]=1/this.animTilesY;var r=this.animParams;r[0]=this.animStartFrame,r[1]=this.animNumFrames*this.animSpeed,r[2]=this.animNumFrames-1,r[3]=this.animNumAnimations-1;var a=this.animIndexParams;a[0]=this.animIndex,a[1]=this.randomizeAnimIndex}this.scene&&this.camera!==this.scene._activeCamera&&(this.camera=this.scene._activeCamera,this.onChangeCamera()),0===this.emitterShape&&(jc[0]=0!==this.emitterExtents.x?this.emitterExtentsInner.x/this.emitterExtents.x:0,jc[1]=0!==this.emitterExtents.y?this.emitterExtentsInner.y/this.emitterExtents.y:0,jc[2]=0!==this.emitterExtents.z?this.emitterExtentsInner.z/this.emitterExtents.z:0,null===this.meshInstance.node?Yc.setTRS(ye.ZERO,Pe.IDENTITY,this.emitterExtents):Yc.setTRS(ye.ZERO,this.meshInstance.node.getRotation(),Kc.copy(this.emitterExtents).mul(this.meshInstance.node.localScale)));var o=null===this.meshInstance.node?ye.ONE:this.meshInstance.node.localScale;if(this.emitterScaleUniform[0]=o.x,this.emitterScaleUniform[1]=o.y,this.emitterScaleUniform[2]=o.z,this.material.setParameter("emitterScale",this.emitterScaleUniform),this.localSpace&&this.meshInstance.node&&(i=this.meshInstance.node.getPosition(),this.emitterPosUniform[0]=i.x,this.emitterPosUniform[1]=i.y,this.emitterPosUniform[2]=i.z,this.material.setParameter("emitterPos",this.emitterPosUniform)),this._compParticleFaceParams(),this.useCpu){var h=new Float32Array(this.vertexBuffer.lock());this._cpuUpdater.update(h,this.vbToSort,this.particleTex,Yc,jc,i,e,t)}else this._gpuUpdater.update(n,Yc,jc,e,t);this.loop||Date.now()>this.endTime&&(this.onFinished&&this.onFinished(),this.meshInstance.visible=!1),this.meshInstance&&(this.meshInstance.drawOrder=this.drawOrder)},t._destroyResources=function(){this.particleTexIN&&(this.particleTexIN.destroy(),this.particleTexIN=null),this.particleTexOUT&&(this.particleTexOUT.destroy(),this.particleTexOUT=null),this.particleTexStart&&this.particleTexStart.destroy&&(this.particleTexStart.destroy(),this.particleTexStart=null),this.rtParticleTexIN&&(this.rtParticleTexIN.destroy(),this.rtParticleTexIN=null),this.rtParticleTexOUT&&(this.rtParticleTexOUT.destroy(),this.rtParticleTexOUT=null),this.internalTex0&&(this.internalTex0.destroy(),this.internalTex0=null),this.internalTex1&&(this.internalTex1.destroy(),this.internalTex1=null),this.internalTex2&&(this.internalTex2.destroy(),this.internalTex2=null),this.internalTex3&&(this.internalTex3.destroy(),this.internalTex3=null),this.colorParam&&(this.colorParam.destroy(),this.colorParam=null),this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=void 0),this.indexBuffer&&(this.indexBuffer.destroy(),this.indexBuffer=void 0),this.material&&(this.material.destroy(),this.material=null)},t.destroy=function(){this.camera=null,this._destroyResources()},$(e,[{key:"defaultParamTexture",get:function(){var e=this;return nu.get(this.graphicsDevice,(function(){for(var t=16,i=new Float32Array(1024),n=0;n<t;n++)for(var s=0;s<t;s++){var r=s+1-8.5,a=n+1-8.5,o=Uc(1-Uc(Math.sqrt(r*r+a*a)/t)-.5),h=n*t+s;i[4*h]=1,i[4*h+1]=1,i[4*h+2]=1,i[4*h+3]=o}var l=Nc(e.graphicsDevice,t,t,i,7,1,!0);return l.minFilter=1,l.magFilter=1,l}))}}]),e}(),ru=new Set,au={depth:1,flags:2},ou=function(){function e(e,t,i){e instanceof or&&(e=Kr()),this.app=e,this.device=e.graphicsDevice,this.pickColor=new Float32Array(4),this.pickColor[3]=1,this.mapping=[],this.cameraEntity=null,this.layer=null,this.layerComp=null,this.initLayerComposition(),this._renderTarget=null;var n=this.device;this.clearDepthCommand=new Da(0,0,(function(){n.clear(au)})),this.width=0,this.height=0,this.resize(t,i)}var t=e.prototype;return t.getSelection=function(e,t,i,n){var s=this.device;if("object"==typeof e){var r=e;e=r.x,t=r.y,i=r.width,n=r.height}else t=this.renderTarget.height-(t+(n||1));e=Math.floor(e),t=Math.floor(t),i=Math.floor(Math.max(i||1,1)),n=Math.floor(Math.max(n||1,1));var a=s.renderTarget;s.setRenderTarget(this.renderTarget),s.updateBegin();var o=new Uint8Array(4*i*n);s.readPixels(e,t,i,n,o),s.updateEnd(),s.setRenderTarget(a);for(var h=this.mapping,l=0;l<i*n;l++){var c=o[4*l+0]<<16|o[4*l+1]<<8|o[4*l+2];16777215!==c&&ru.add(h[c])}var u=[];return ru.forEach((function(e){return u.push(e)})),ru.clear(),u},t.allocateRenderTarget=function(){var e=new wn(this.device,{format:7,width:this.width,height:this.height,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1,name:"pick"});this.renderTarget=new cr({colorBuffer:e,depth:!0})},t.releaseRenderTarget=function(){this.cameraEntity.camera.renderTarget=null,this._renderTarget&&(this._renderTarget.destroyTextureBuffers(),this._renderTarget.destroy(),this._renderTarget=null)},t.initLayerComposition=function(){var e=this.device,t=this,i=e.scope.resolve("uColor");this.cameraEntity=new $l,this.cameraEntity.addComponent("camera"),this.layer=new fh({name:"Picker",shaderPass:3,opaqueSortMode:0,onDrawCall:function(n,s){t.pickColor[0]=(s>>16&255)/255,t.pickColor[1]=(s>>8&255)/255,t.pickColor[2]=(255&s)/255,i.setValue(t.pickColor),e.setBlending(!1),t.mapping[s]=n}}),this.layer.addCamera(this.cameraEntity.camera),this.layerComp=new bh("picker"),this.layerComp.pushOpaque(this.layer)},t.prepare=function(e,t,i){e instanceof En&&(e=e.node.camera),i instanceof fh&&(i=[i]),this.layer.clearMeshInstances();for(var n=this.layer.opaqueMeshInstances,s=t.layers.layerList,r=t.layers.subLayerEnabled,a=t.layers.subLayerList,o=0;o<s.length;o++){var h=s[o];if(!(i&&i.indexOf(h)<0))if(h.enabled&&r[o])if(h.cameras.indexOf(e)>=0){h._clearDepthBuffer&&n.push(this.clearDepthCommand);for(var l=a[o]?h.instances.transparentMeshInstances:h.instances.opaqueMeshInstances,c=0;c<l.length;c++){var u=l[c];u.pick&&n.push(u)}}}this.renderTarget&&this.width===this.renderTarget.width&&this.height===this.renderTarget.height||(this.releaseRenderTarget(),this.allocateRenderTarget()),this.updateCamera(e),this.mapping.length=0,this.app.renderComposition(this.layerComp)},t.updateCamera=function(e){this.cameraEntity.copy(e.entity),this.cameraEntity.name="PickerCamera";var t=this.cameraEntity.camera;t.copy(e),t.clearColorBuffer=!0,t.clearDepthBuffer=!0,t.clearStencilBuffer=!0,t.clearColor=me.WHITE,t.renderTarget=this.renderTarget,this.layer.clearCameras(),this.layer.addCamera(t),t.layers=[this.layer.id]},t.resize=function(e,t){this.width=Math.floor(e),this.height=Math.floor(t)},e}(),hu=function(e,t,i){this.device=e,this.inverseBindPose=t,this.boneNames=i},lu=[0,0,1,0,0,1,0,0,1,0,0,1],cu=[0,1,3,2,3,1],uu=function(e){function t(t,i){var n;return(n=e.call(this)||this)._device=t,n._pixelsPerUnit=i&&void 0!==i.pixelsPerUnit?i.pixelsPerUnit:1,n._renderMode=i&&void 0!==i.renderMode?i.renderMode:0,n._atlas=i&&void 0!==i.atlas?i.atlas:null,n._frameKeys=i&&void 0!==i.frameKeys?i.frameKeys:null,n._meshes=[],n._updatingProperties=!1,n._meshesDirty=!1,n._atlas&&n._frameKeys&&n._createMeshes(),n}J(t,e);var i=t.prototype;return i._createMeshes=function(){for(var e=this._meshes.length,t=0;t<e;t++){var i=this._meshes[t];i&&i.destroy()}var n=this._frameKeys.length;this._meshes=new Array(n);for(var s=1===this.renderMode||2===this._renderMode?this._create9SliceMesh:this._createSimpleMesh,r=0;r<n;r++){var a=this._atlas.frames[this._frameKeys[r]];this._meshes[r]=a?s.call(this,a):null}this.fire("set:meshes")},i._createSimpleMesh=function(e){var t=e.rect,i=this._atlas.texture.width,n=this._atlas.texture.height,s=t.z/this._pixelsPerUnit,r=t.w/this._pixelsPerUnit,a=e.pivot.x,o=e.pivot.y,h=[-a*s,-o*r,0,(1-a)*s,-o*r,0,(1-a)*s,(1-o)*r,0,-a*s,(1-o)*r,0],l=t.x/i,c=1-t.y/n,u=(t.x+t.z)/i,d=1-(t.y+t.w)/n,f=[l,c,u,c,u,d,l,d];return aa(this._device,h,{uvs:f,normals:lu,indices:cu})},i._create9SliceMesh=function(){for(var e=be.ONE,t=[],i=[],n=[],s=[],r=0,a=0;a<=3;a++)for(var o=0===a||3===a?0:1,h=0;h<=3;h++){var l=-e.x+2*e.x*(a<=1?0:3)/3,c=-(-e.y+2*e.y*(h<=1?0:3)/3),u=0===h||3===h?0:1;t.push(-l,0,c),i.push(0,1,0),n.push(o,u),a<3&&h<3&&(s.push(r+3+1,r+1,r),s.push(r+3+1,r+3+2,r+1)),r++}var d={normals:i,uvs:n,indices:s};return aa(this._device,t,d)},i._onSetFrames=function(e){this._updatingProperties?this._meshesDirty=!0:this._createMeshes()},i._onFrameChanged=function(e,t){var i=this._frameKeys.indexOf(e);i<0||(t?0===this.renderMode&&(this._meshes[i]=this._createSimpleMesh(t)):this._meshes[i]=null,this.fire("set:meshes"))},i._onFrameRemoved=function(e){var t=this._frameKeys.indexOf(e);t<0||(this._meshes[t]=null,this.fire("set:meshes"))},i.startUpdate=function(){this._updatingProperties=!0,this._meshesDirty=!1},i.endUpdate=function(){this._updatingProperties=!1,this._meshesDirty&&this._atlas&&this._frameKeys&&this._createMeshes(),this._meshesDirty=!1},i.destroy=function(){for(var e,t=ne(this._meshes);!(e=t()).done;){var i=e.value;i&&i.destroy()}this._meshes.length=0},$(t,[{key:"frameKeys",get:function(){return this._frameKeys},set:function(e){this._frameKeys=e,this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes()),this.fire("set:frameKeys",e)}},{key:"atlas",get:function(){return this._atlas},set:function(e){e!==this._atlas&&(this._atlas&&(this._atlas.off("set:frames",this._onSetFrames,this),this._atlas.off("set:frame",this._onFrameChanged,this),this._atlas.off("remove:frame",this._onFrameRemoved,this)),this._atlas=e,this._atlas&&this._frameKeys&&(this._atlas.on("set:frames",this._onSetFrames,this),this._atlas.on("set:frame",this._onFrameChanged,this),this._atlas.on("remove:frame",this._onFrameRemoved,this),this._updatingProperties?this._meshesDirty=!0:this._createMeshes()),this.fire("set:atlas",e))}},{key:"pixelsPerUnit",get:function(){return this._pixelsPerUnit},set:function(e){this._pixelsPerUnit!==e&&(this._pixelsPerUnit=e,this.fire("set:pixelsPerUnit",e),this._atlas&&this._frameKeys&&0===this.renderMode&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes()))}},{key:"renderMode",get:function(){return this._renderMode},set:function(e){if(this._renderMode!==e){var t=this._renderMode;this._renderMode=e,this.fire("set:renderMode",e),0!==t&&0!==e||this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes())}}},{key:"meshes",get:function(){return this._meshes}}]),t}(m),du=function(){function e(e){this.func=void 0===e.func?7:e.func,this.ref=e.ref||0,this.readMask=void 0===e.readMask?255:e.readMask,this.writeMask=void 0===e.writeMask?255:e.writeMask,this.fail=e.fail||0,this.zfail=e.zfail||0,this.zpass=e.zpass||0}return e.prototype.clone=function(){return new e({func:this.func,ref:this.ref,readMask:this.readMask,writeMask:this.writeMask,fail:this.fail,zfail:this.zfail,zpass:this.zpass})},e}(),fu=function(e){function t(){var t;return(t=e.call(this)||this)._texture=null,t._frames=null,t}J(t,e);var i=t.prototype;return i.setFrame=function(e,t){var i=this._frames[e];i?(i.rect.copy(t.rect),i.pivot.copy(t.pivot),i.border.copy(t.border)):(i={rect:t.rect.clone(),pivot:t.pivot.clone(),border:t.border.clone()},this._frames[e]=i),this.fire("set:frame",e.toString(),i)},i.removeFrame=function(e){var t=this._frames[e];t&&(delete this._frames[e],this.fire("remove:frame",e.toString(),t))},i.destroy=function(){this._texture&&this._texture.destroy()},$(t,[{key:"texture",get:function(){return this._texture},set:function(e){this._texture=e,this.fire("set:texture",e)}},{key:"frames",get:function(){return this._frames},set:function(e){this._frames=e,this.fire("set:frames",e)}}]),t}(m),pu=function(e,t,i,n){this.time=e,this.position=t,this.rotation=i,this.scale=n},mu=function(){this._name="",this._keys=[]},_u=function(){function e(){this.name="",this.duration=0,this._nodes=[],this._nodeDict={}}var t=e.prototype;return t.getNode=function(e){return this._nodeDict[e]},t.addNode=function(e){this._nodes.push(e),this._nodeDict[e._name]=e},$(e,[{key:"nodes",get:function(){return this._nodes}}]),e}(),gu=function(){function e(){this._written=!1,this._name="",this._keyFrames=[],this._quat=new Pe,this._pos=new ye,this._scale=new ye,this._targetNode=null}var t=e.prototype;return t.getTarget=function(){return this._targetNode},t.setTarget=function(e){this._targetNode=e},e}(),vu=function(){function e(e){var t=this;this.looping=!0,this._animation=null,this._time=0,this._interpolatedKeys=[],this._interpolatedKeyDict={},this._currKeyIndices={},this.graph=null;!function e(i){var n=new gu;n._name=i.name,t._interpolatedKeys.push(n),t._interpolatedKeyDict[i.name]=n,t._currKeyIndices[i.name]=0;for(var s=0;s<i._children.length;s++)e(i._children[s])}(e)}var t=e.prototype;return t.addTime=function(e){if(null!==this._animation){var t=this._animation._nodes,i=this._animation.duration;if(this._time===i&&!this.looping)return;if(this._time+=e,this._time>i){this._time=this.looping?0:i;for(var n=0;n<t.length;n++){var s=t[n]._name;this._currKeyIndices[s]=0}}else if(this._time<0){this._time=this.looping?i:0;for(var r=0;r<t.length;r++){var a=t[r],o=a._name;this._currKeyIndices[o]=a._keys.length-2}}for(var h=e>=0?1:-1,l=0;l<t.length;l++){var c=t[l],u=c._name,d=c._keys,f=this._interpolatedKeyDict[u];if(void 0!==f){var p=!1;if(1!==d.length)for(var m=this._currKeyIndices[u];m<d.length-1&&m>=0;m+=h){var _=d[m],g=d[m+1];if(_.time<=this._time&&g.time>=this._time){var v=(this._time-_.time)/(g.time-_.time);f._pos.lerp(_.position,g.position,v),f._quat.slerp(_.rotation,g.rotation,v),f._scale.lerp(_.scale,g.scale,v),f._written=!0,this._currKeyIndices[u]=m,p=!0;break}}(1===d.length||!p&&0===this._time&&this.looping)&&(f._pos.copy(d[0].position),f._quat.copy(d[0].rotation),f._scale.copy(d[0].scale),f._written=!0)}}}},t.blend=function(e,t,i){for(var n=this._interpolatedKeys.length,s=0;s<n;s++){var r=e._interpolatedKeys[s],a=t._interpolatedKeys[s],o=this._interpolatedKeys[s];r._written&&a._written?(o._quat.slerp(r._quat,t._interpolatedKeys[s]._quat,i),o._pos.lerp(r._pos,t._interpolatedKeys[s]._pos,i),o._scale.lerp(r._scale,a._scale,i),o._written=!0):r._written?(o._quat.copy(r._quat),o._pos.copy(r._pos),o._scale.copy(r._scale),o._written=!0):a._written&&(o._quat.copy(a._quat),o._pos.copy(a._pos),o._scale.copy(a._scale),o._written=!0)}},t.setGraph=function(e){if(this.graph=e,e)for(var t=0;t<this._interpolatedKeys.length;t++){var i=this._interpolatedKeys[t],n=e.findByName(i._name);this._interpolatedKeys[t].setTarget(n)}else for(var s=0;s<this._interpolatedKeys.length;s++)this._interpolatedKeys[s].setTarget(null)},t.updateGraph=function(){if(this.graph)for(var e=0;e<this._interpolatedKeys.length;e++){var t=this._interpolatedKeys[e];if(t._written){var i=t.getTarget();i.localPosition.copy(t._pos),i.localRotation.copy(t._quat),i.localScale.copy(t._scale),i._dirtyLocal||i._dirtifyLocal(),t._written=!1}}},$(e,[{key:"animation",get:function(){return this._animation},set:function(e){this._animation=e,this.currentTime=0}},{key:"currentTime",get:function(){return this._time},set:function(e){this._time=e;for(var t=this._interpolatedKeys.length,i=0;i<t;i++){var n=this._interpolatedKeys[i]._name;this._currKeyIndices[n]=0}this.addTime(0),this.updateGraph()}},{key:"numNodes",get:function(){return this._interpolatedKeys.length}}]),e}(),yu=function(){function e(){}e.joinPath=function(e,t){t=t||".";return e.map((function(e){return e.replace(/\\/g,"\\\\").replace(new RegExp("\\"+t,"g"),"\\"+t)})).join(t)},e.splitPath=function(e,t){t=t||".";for(var i=[],n="",s=0;s<e.length;){var r=e[s++];"\\"===r&&s<e.length?n+="\\"===(r=e[s++])||r===t?r:"\\"+r:r===t?(i.push(n),n=""):n+=r}return n.length>0&&i.push(n),i},e.encode=function(e,t,i){return(Array.isArray(e)?e.join("/"):e)+"/"+t+"/"+(Array.isArray(i)?i.join("/"):i)};var t=e.prototype;return t.resolve=function(e){return null},t.unresolve=function(e){},t.update=function(e){},e}(),xu=function(){function e(){this._left=1/0,this._right=-1/0,this._len=0,this._recip=0,this._p0=0,this._p1=0,this._t=0,this._hermite={valid:!1,p0:0,m0:0,p1:0,m1:0}}var t=e.prototype;return t.update=function(e,t){if(e<this._left||e>=this._right){var i=t.length;if(i)if(e<t[0])this._left=-1/0,this._right=t[0],this._len=0,this._recip=0,this._p0=this._p1=0;else if(e>=t[i-1])this._left=t[i-1],this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=i-1;else{var n=this._findKey(e,t);this._left=t[n],this._right=t[n+1],this._len=this._right-this._left;var s=1/this._len;this._recip=isFinite(s)?s:0,this._p0=n,this._p1=n+1}else this._left=-1/0,this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=0}this._t=0===this._recip?0:(e-this._left)*this._recip,this._hermite.valid=!1},t._findKey=function(e,t){for(var i=0;e>=t[i+1];)i++;return i},t.eval=function(e,t,i){var n=i._data,s=i._components,r=this._p0*s;if(0===t)for(var a=0;a<s;++a)e[a]=n[r+a];else{var o=this._t,h=this._p1*s;switch(t){case 1:for(var l=0;l<s;++l)e[l]=de.lerp(n[r+l],n[h+l],o);break;case 2:var c=this._hermite;if(!c.valid){var u=o*o,d=o+o,f=1-o,p=f*f;c.valid=!0,c.p0=(1+d)*p,c.m0=o*p,c.p1=u*(3-d),c.m1=u*(o-1)}for(var m=(3*this._p0+1)*s,_=(3*this._p0+2)*s,g=(3*this._p1+1)*s,v=(3*this._p1+0)*s,y=0;y<s;++y)e[y]=c.p0*n[m+y]+c.m0*n[_+y]*this._len+c.p1*n[g+y]+c.m1*n[v+y]*this._len}}},e}(),bu=function(e){this._name=e.name+"Snapshot",this._time=-1,this._cache=[],this._results=[];for(var t=0;t<e._inputs.length;++t)this._cache[t]=new xu;for(var i=e._curves,n=e._outputs,s=0;s<i.length;++s){for(var r=n[i[s]._output],a=[],o=0;o<r._components;++o)a[o]=0;this._results[s]=a}},Su=function(){function e(e,t,i,n,s,r){for(this._name=e.name,this._track=e,this._snapshot=new bu(e),this._playing=n,this._time=t,this._speed=i,this._loop=s,this._blendWeight=1,this._blendOrder=0,this._eventHandler=r,this._eventCursor=0;this._track.events[this._eventCursor]&&this._track.events[this._eventCursor].time<this.time;)this._eventCursor++}var t=e.prototype;return t.activeEventsForFrame=function(e,t){var i;for(0===e&&(this.eventCursor=0),t>this.track.duration&&(i=t-this.track.duration,t=this.track.duration);this.track.events[this.eventCursor]&&this.track.events[this.eventCursor].time>=e&&(t===this.track.duration?this.track.events[this.eventCursor].time<=t:this.track.events[this.eventCursor].time<t);){var n=this.track.events[this.eventCursor];this._eventHandler.fire(n.name,Q({track:this.track},n)),this.eventCursor++}Number.isFinite(i)&&this.activeEventsForFrame(0,i)},t._update=function(e){if(this._playing){var t=this._time,i=this._track.duration,n=this._speed,s=this._loop;this._track.events.length>0&&i>0&&this.activeEventsForFrame(t,t+n*e),t+=n*e,n>=0?t>i&&(s?t=t%i||0:(t=this._track.duration,this.pause())):t<0&&(s?t=i+(t%i||0):(t=0,this.pause())),this._time=t}this._time!==this._snapshot._time&&this._track.eval(this._time,this._snapshot)},t.play=function(){this._playing=!0,this._time=0},t.stop=function(){this._playing=!1,this._time=0},t.pause=function(){this._playing=!1},t.resume=function(){this._playing=!0},t.reset=function(){this._time=0},$(e,[{key:"name",get:function(){return this._name},set:function(e){this._name=e}},{key:"track",get:function(){return this._track}},{key:"snapshot",get:function(){return this._snapshot}},{key:"time",get:function(){return this._time},set:function(e){this._time=e}},{key:"speed",get:function(){return this._speed},set:function(e){this._speed=e}},{key:"loop",get:function(){return this._loop},set:function(e){this._loop=e}},{key:"blendWeight",get:function(){return this._blendWeight},set:function(e){this._blendWeight=e}},{key:"blendOrder",get:function(){return this._blendOrder},set:function(e){this._blendOrder=e}},{key:"eventCursor",get:function(){return this._eventCursor},set:function(e){this._eventCursor=e}}]),e}(),wu=function(){function e(e,t,i,n){this._paths=e,this._input=t,this._output=i,this._interpolation=n}return $(e,[{key:"paths",get:function(){return this._paths}},{key:"input",get:function(){return this._input}},{key:"output",get:function(){return this._output}},{key:"interpolation",get:function(){return this._interpolation}}]),e}(),Tu=function(){function e(e,t){this._components=e,this._data=t}return $(e,[{key:"components",get:function(){return this._components}},{key:"data",get:function(){return this._data}}]),e}(),Au="NONE",Mu="PREV_STATE",Cu="NEXT_STATE",Eu="PREV_STATE_NEXT_STATE",Pu="NEXT_STATE_PREV_STATE",Ru="GREATER_THAN",Iu="LESS_THAN",Lu="GREATER_THAN_EQUAL_TO",Du="LESS_THAN_EQUAL_TO",ku="EQUAL_TO",Ou="NOT_EQUAL_TO",Fu="INTEGER",Bu="FLOAT",Nu="BOOLEAN",Uu="TRIGGER",zu="2D_DIRECTIONAL",Vu="2D_CARTESIAN",Gu="DIRECT",Wu="START",Hu="END",Xu="ANY",qu=[Wu,Hu,Xu],ju="OVERWRITE",Yu="ADDITIVE",Ku=function(){function e(t,i){this._component=t,this.mask=new Int8Array(t.layers.length),this.weights=new Float32Array(t.layers.length),this.totalWeight=0,this.counter=0,this.layerCounter=0,this.valueType=i,this.dirty=!0,this.value=i===e.TYPE_QUAT?[0,0,0,1]:[0,0,0],this.baseValue=null,this.setter=null}var t=e.prototype;return t.getWeight=function(e){return this.dirty&&this.updateWeights(),this._normalizeWeights&&0===this.totalWeight||!this.mask[e]?0:this._normalizeWeights?this.weights[e]/this.totalWeight:de.clamp(this.weights[e],0,1)},t._layerBlendType=function(e){return this._component.layers[e].blendType},t.setMask=function(e,t){this.mask[e]=t,this._normalizeWeights&&(this._component.layers[e].blendType===ju&&(this.mask=this.mask.fill(0,0,e)),this.dirty=!0)},t.updateWeights=function(){this.totalWeight=0;for(var e=0;e<this.weights.length;e++)this.weights[e]=this._component.layers[e].weight,this.totalWeight+=this.mask[e]*this.weights[e];this.dirty=!1},t.updateValue=function(t,i){if(0===this.counter&&(Zu._set(this.value,e.IDENTITY_QUAT_ARR,this.valueType),this._normalizeWeights||Zu._blend(this.value,this.baseValue,1,this.valueType)),this.mask[t]&&0!==this.getWeight(t)){if(this._layerBlendType(t)!==Yu||this._normalizeWeights)Zu._blend(this.value,i,this.getWeight(t),this.valueType);else if(this.valueType===e.TYPE_QUAT){var n=e.q1.set(this.value[0],this.value[1],this.value[2],this.value[3]),s=e.q2.set(this.baseValue[0],this.baseValue[1],this.baseValue[2],this.baseValue[3]),r=e.q3.set(i[0],i[1],i[2],i[3]),a=s.invert().mul(r);a.slerp(Pe.IDENTITY,a,this.getWeight(t)),n.mul(a),e.quatArr[0]=n.x,e.quatArr[1]=n.y,e.quatArr[2]=n.z,e.quatArr[3]=n.w,Zu._set(this.value,e.quatArr,this.valueType)}else e.vecArr[0]=i[0]-this.baseValue[0],e.vecArr[1]=i[1]-this.baseValue[1],e.vecArr[2]=i[2]-this.baseValue[2],Zu._blend(this.value,e.vecArr,this.getWeight(t),this.valueType,!0);this.setter&&this.setter(this.value)}},t.unbind=function(){this.setter&&this.setter(this.baseValue)},$(e,[{key:"_normalizeWeights",get:function(){return this._component.normalizeWeights}}]),e}();Ku.TYPE_QUAT="quaternion",Ku.TYPE_VEC3="vector3",Ku.q1=new Pe,Ku.q2=new Pe,Ku.q3=new Pe,Ku.quatArr=[0,0,0,1],Ku.vecArr=[0,0,0],Ku.IDENTITY_QUAT_ARR=[0,0,0,1];var Zu=function(){function e(e){this._binder=e,this._clips=[],this._inputs=[],this._outputs=[],this._targets={}}e._dot=function(e,t){for(var i=e.length,n=0,s=0;s<i;++s)n+=e[s]*t[s];return n},e._normalize=function(t){var i=e._dot(t,t);if(i>0){i=1/Math.sqrt(i);for(var n=t.length,s=0;s<n;++s)t[s]*=i}},e._set=function(t,i,n){var s=t.length;if("quaternion"===n){var r=e._dot(i,i);r>0&&(r=1/Math.sqrt(r));for(var a=0;a<s;++a)t[a]=i[a]*r}else for(var o=0;o<s;++o)t[o]=i[o]},e._blendVec=function(e,t,i,n){for(var s=n?1:1-i,r=e.length,a=0;a<r;++a)e[a]=e[a]*s+t[a]*i},e._blendQuat=function(t,i,n,s){var r=t.length,a=s?1:1-n;e._dot(t,i)<0&&(n=-n);for(var o=0;o<r;++o)t[o]=t[o]*a+i[o]*n;s||e._normalize(t)},e._blend=function(t,i,n,s,r){"quaternion"===s?e._blendQuat(t,i,n,r):e._blendVec(t,i,n,r)},e._stableSort=function(e,t){for(var i=e.length,n=0;n<i-1;++n)for(var s=n+1;s<i;++s)if(t(e[s],e[n])){var r=e[n];e[n]=e[s],e[s]=r}};var t=e.prototype;return t.addClip=function(e){for(var t=this._targets,i=this._binder,n=e.track.curves,s=e.snapshot,r=[],a=[],o=0;o<n.length;++o)for(var h=n[o].paths,l=0;l<h.length;++l){var c=h[l],u=i.resolve(c),d=t[u&&u.targetPath||null];if(!d&&u){d={target:u,value:[],curves:0,blendCounter:0};for(var f=0;f<d.target.components;++f)d.value.push(0);if(t[u.targetPath]=d,i.animComponent){if(!i.animComponent.targets[u.targetPath]){var p=void 0;p="localRotation"===u.targetPath.substring(u.targetPath.length-13)?Ku.TYPE_QUAT:Ku.TYPE_VEC3,i.animComponent.targets[u.targetPath]=new Ku(i.animComponent,p)}i.animComponent.targets[u.targetPath].layerCounter++,i.animComponent.targets[u.targetPath].setMask(i.layerIndex,1)}}d&&(d.curves++,r.push(s._results[o]),a.push(d))}this._clips.push(e),this._inputs.push(r),this._outputs.push(a)},t.removeClip=function(e){for(var t=this._targets,i=this._binder,n=this._clips,s=n[e].track.curves,r=0;r<s.length;++r)for(var a=s[r].paths,o=0;o<a.length;++o){var h=a[o],l=this._binder.resolve(h);l&&(l.curves--,0===l.curves&&(i.unresolve(h),delete t[l.targetPath],i.animComponent&&i.animComponent.targets[l.targetPath].layerCounter--))}n.splice(e,1),this._inputs.splice(e,1),this._outputs.splice(e,1)},t.removeClips=function(){for(;this._clips.length>0;)this.removeClip(0)},t.findClip=function(e){for(var t=this._clips,i=0;i<t.length;++i){var n=t[i];if(n.name===e)return n}return null},t.rebind=function(){var e=this;this._binder.rebind(),this._targets={};var t=[].concat(this.clips);this.removeClips(),t.forEach((function(t){e.addClip(t)}))},t.assignMask=function(e){return this._binder.assignMask(e)},t.update=function(t){var i=this._clips,n=i.map((function(e,t){return t}));e._stableSort(n,(function(e,t){return i[e].blendOrder<i[t].blendOrder}));for(var s=0;s<n.length;++s){var r=n[s],a=i[r],o=this._inputs[r],h=this._outputs[r],l=a.blendWeight;l>0&&a._update(t);var c=void 0,u=void 0,d=void 0;if(l>=1)for(var f=0;f<o.length;++f)c=o[f],d=(u=h[f]).value,e._set(d,c,u.target.type),u.blendCounter++;else if(l>0)for(var p=0;p<o.length;++p)c=o[p],d=(u=h[p]).value,0===u.blendCounter?e._set(d,c,u.target.type):e._blend(d,c,l,u.target.type),u.blendCounter++}var m=this._targets,_=this._binder;for(var g in m)if(m.hasOwnProperty(g)){var v=m[g];if(_.animComponent&&v.target.isTransform){var y=_.animComponent.targets[g];y.counter===y.layerCounter&&(y.counter=0),y.path||(y.path=g,y.baseValue=v.target.get(),y.setter=v.target.set),y.updateValue(_.layerIndex,v.value),y.counter++}else v.target.set(v.value);v.blendCounter=0}_.update(t)},$(e,[{key:"clips",get:function(){return this._clips}}]),e}(),$u=function(){function e(e,t,i,n){e.set?(this._set=e.set,this._get=e.get):this._set=e,this._type=t,this._components=i,this._targetPath=n,this._isTransform="localRotation"===this._targetPath.substring(this._targetPath.length-13)||"localPosition"===this._targetPath.substring(this._targetPath.length-13)||"localScale"===this._targetPath.substring(this._targetPath.length-10)}return $(e,[{key:"set",get:function(){return this._set}},{key:"get",get:function(){return this._get}},{key:"type",get:function(){return this._type}},{key:"components",get:function(){return this._components}},{key:"targetPath",get:function(){return this._targetPath}},{key:"isTransform",get:function(){return this._isTransform}}]),e}(),Qu=function(){function e(e){this._events=[].concat(e),this._events.sort((function(e,t){return e.time-t.time}))}return $(e,[{key:"events",get:function(){return this._events}}]),e}(),Ju=function(){function e(e,t,i,n,s,r){void 0===r&&(r=new Qu([])),this._name=e,this._duration=t,this._inputs=i,this._outputs=n,this._curves=s,this._animEvents=r}return e.prototype.eval=function(e,t){t._time=e;for(var i=this._inputs,n=this._outputs,s=this._curves,r=t._cache,a=t._results,o=0;o<i.length;++o)r[o].update(e,i[o]._data);for(var h=0;h<s.length;++h){var l=s[h],c=n[l._output],u=a[h];r[l._input].eval(u,l._interpolation,c)}},$(e,[{key:"name",get:function(){return this._name}},{key:"duration",get:function(){return this._duration}},{key:"inputs",get:function(){return this._inputs}},{key:"outputs",get:function(){return this._outputs}},{key:"curves",get:function(){return this._curves}},{key:"events",get:function(){return this._animEvents.events},set:function(e){this._animEvents=e}}]),e}(),ed=function(){function e(t){var i=this;if(this._isPathInMask=function(e,t){var n=i._mask[e];return!!n&&!!(n.children||t&&!1!==n.value)},this.graph=t,t){this._mask=null;var n={};!function e(t){n[t.name]=t;for(var i=0;i<t.children.length;++i)e(t.children[i])}(t),this.nodes=n,this.targetCache={};var s=function(e){for(var t,i=e;i&&!(i instanceof $l);)i=i.parent;return i&&(i.render?t=i.render.meshInstances:i.model&&(t=i.model.meshInstances)),t};this.nodeCounts={},this.activeNodes=[],this.handlers={localPosition:function(t){var i=t.localPosition;return e.createAnimTarget((function(e){i.set.apply(i,e)}),"vector",3,t,"localPosition")},localRotation:function(t){var i=t.localRotation;return e.createAnimTarget((function(e){i.set.apply(i,e)}),"quaternion",4,t,"localRotation")},localScale:function(t){var i=t.localScale;return e.createAnimTarget((function(e){i.set.apply(i,e)}),"vector",3,t,"localScale")},weight:function(t,i){i=0===i.indexOf("name.")?i.replace("name.",""):Number(i);var n=s(t);if(n)for(var r=0;r<n.length;++r)if(n[r].node.name===t.name&&n[r].morphInstance){var a=function(){var s=n[r].morphInstance;return{v:e.createAnimTarget((function(e){s.setWeight(i,e[0])}),"number",1,t,"weight."+i)}}();if("object"==typeof a)return a.v}return null},materialTexture:function(t,n){var r=s(t);if(r){for(var a,o=0;o<r.length;++o)if(r[o].node.name===t.name){a=r[o];break}if(a){return e.createAnimTarget((function(e){var t=i.animComponent.system.app.assets.get(e[0]);t&&t.resource&&"texture"===t.type&&(a.material[n]=t.resource,a.material.update())}),"vector",1,t,"materialTexture","material")}}return null}}}}var t=e.prototype;return t._isPathActive=function(e){if(!this._mask)return!0;for(var t=[e.entityPath[0],this.graph.name],i=0;i<t.length;++i){var n=t[i];if(this._isPathInMask(n,1===e.entityPath.length))return!0;for(var s=1;s<e.entityPath.length;s++)if(n+="/"+e.entityPath[s],this._isPathInMask(n,s===e.entityPath.length-1))return!0}return!1},t.findNode=function(e){return this._isPathActive(e)?(this.graph&&((t=this.graph.findByPath(e.entityPath))||(t=this.graph.findByPath(e.entityPath.slice(1)))),t||(t=this.nodes[e.entityPath[e.entityPath.length-1]||""]),t):null;var t},e.createAnimTarget=function(e,t,i,n,s,r){var a=yu.encode(n.path,r||"entity",s);return new $u(e,t,i,a)},t.resolve=function(e){var t=yu.encode(e.entityPath,e.component,e.propertyPath),i=this.targetCache[t];if(i)return i;var n=this.findNode(e);if(!n)return null;var s=this.handlers[e.propertyPath];return s&&(i=s(n))?(this.targetCache[t]=i,this.nodeCounts[n.path]?this.nodeCounts[n.path]++:(this.activeNodes.push(n),this.nodeCounts[n.path]=1),i):null},t.unresolve=function(e){if("graph"===e.component){var t=this.nodes[e.entityPath[e.entityPath.length-1]||""];if(this.nodeCounts[t.path]--,0===this.nodeCounts[t.path]){var i=this.activeNodes,n=i.indexOf(t.node),s=i.length;n<s-1&&(i[n]=i[s-1]),i.pop()}}},t.update=function(e){for(var t=this.activeNodes,i=0;i<t.length;++i)t[i]._dirtifyLocal()},t.assignMask=function(e){return e!==this._mask&&(this._mask=e,!0)},e}(),td=function(){function e(e,t,i,n,s){void 0===s&&(s=1),this._state=e,this._parent=t,this._name=i,Array.isArray(n)?(this._point=new be(n[0],n[1]),this._pointLength=this._point.length()):(this._point=n,this._pointLength=n),this._speed=s,this._weightedSpeed=1,this._weight=1,this._animTrack=null}return $(e,[{key:"parent",get:function(){return this._parent}},{key:"name",get:function(){return this._name}},{key:"path",get:function(){return this._parent?this._parent.path+"."+this._name:this._name}},{key:"point",get:function(){return this._point}},{key:"pointLength",get:function(){return this._pointLength}},{key:"weight",get:function(){return this._parent?this._parent.weight*this._weight:this._weight},set:function(e){this._weight=e}},{key:"normalizedWeight",get:function(){var e=this._state.totalWeight;return 0===e?0:this.weight/e}},{key:"speed",get:function(){return this._weightedSpeed*this._speed}},{key:"absoluteSpeed",get:function(){return Math.abs(this._speed)}},{key:"weightedSpeed",get:function(){return this._weightedSpeed},set:function(e){this._weightedSpeed=e}},{key:"animTrack",get:function(){return this._animTrack},set:function(e){this._animTrack=e}}]),e}(),id=function(e){function t(t,i,n,s,r,a,o,h,l){var c;(c=e.call(this,t,i,n,s)||this)._parameters=r,c._parameterValues=new Array(r.length),c._children=[],c._findParameter=l,c._syncAnimations=!1!==o,c._pointCache={};for(var u=0;u<a.length;u++){var d=a[u];d.children?c._children.push(h(d.type,te(c),null,n,1,d.parameter?[d.parameter]:d.parameters,d.children,h,l)):c._children.push(new td(t,te(c),d.name,d.point,d.speed))}return c}J(t,e);var i=t.prototype;return i.getChild=function(e){for(var t=0;t<this._children.length;t++)if(this._children[t].name===e)return this._children[t];return null},i.updateParameterValues=function(){for(var e=!0,t=0;t<this._parameterValues.length;t++){var i=this._findParameter(this._parameters[t]).value;this._parameterValues[t]!==i&&(this._parameterValues[t]=i,e=!1)}return e},i.getNodeWeightedDuration=function(e){return this._children[e].animTrack.duration/this._children[e].speedMultiplier*this._children[e].weight},i.getNodeCount=function(){for(var e=0,i=0;i<this._children.length;i++){this._children[i].constructor===t?e+=this._children[i].getNodeCount():e++}return e},$(t,[{key:"weight",get:function(){return this.calculateWeights(),this._parent?this._parent.weight*this._weight:this._weight}},{key:"syncAnimations",get:function(){return this._syncAnimations}}]),t}(td),nd=function(e){function t(t,i,n,s,r,a,o,h,l){return a.sort((function(e,t){return e.point-t.point})),e.call(this,t,i,n,s,r,a,o,h,l)||this}return J(t,e),t.prototype.calculateWeights=function(){if(!this.updateParameterValues()){var e=0;this._children[0].weight=0;for(var t=0;t<this._children.length;t++){var i=this._children[t];if(t!==this._children.length-1){var n=this._children[t+1];if(i.point===n.point)i.weight=.5,n.weight=.5;else if(de.between(this._parameterValues[0],i.point,n.point,!0)){var s=Math.abs(i.point-n.point),r=(s-Math.abs(i.point-this._parameterValues[0]))/s;i.weight=r,n.weight=1-r}else n.weight=0}this._syncAnimations&&(e+=i.animTrack.duration/i.absoluteSpeed*i.weight)}if(this._syncAnimations)for(var a=0;a<this._children.length;a++){var o=this._children[a];o.weightedSpeed=o.animTrack.duration/o.absoluteSpeed/e}}},t}(id),sd=function(e){function t(){return e.apply(this,arguments)||this}J(t,e);var i=t.prototype;return i.pointDistanceCache=function(e,t){var i=""+e+t;return this._pointCache[i]||(this._pointCache[i]=this._children[t].point.clone().sub(this._children[e].point)),this._pointCache[i]},i.calculateWeights=function(){var e;if(!this.updateParameterValues()){var i,n;(e=t._p).set.apply(e,this._parameterValues),i=0,n=0;for(var s=0;s<this._children.length;s++){var r=this._children[s],a=r.point;t._pip.set(t._p.x,t._p.y).sub(a);for(var o=Number.MAX_VALUE,h=0;h<this._children.length;h++)if(s!==h){var l=this.pointDistanceCache(s,h),c=de.clamp(1-t._pip.dot(l)/l.lengthSq(),0,1);c<o&&(o=c)}r.weight=o,i+=o,this._syncAnimations&&(n+=r.animTrack.duration/r.absoluteSpeed*r.weight)}for(var u=0;u<this._children.length;u++){var d=this._children[u];d.weight=d._weight/i,this._syncAnimations&&(d.weightedSpeed=d.animTrack.duration/d.absoluteSpeed/n)}}},t}(id);sd._p=new be,sd._pip=new be;var rd=function(e){function t(){return e.apply(this,arguments)||this}J(t,e);var i=t.prototype;return i.pointCache=function(e,t){var i=""+e+t;return this._pointCache[i]||(this._pointCache[i]=new be((this._children[t].pointLength-this._children[e].pointLength)/((this._children[t].pointLength+this._children[e].pointLength)/2),2*be.angleRad(this._children[e].point,this._children[t].point))),this._pointCache[i]},i.calculateWeights=function(){var e;if(!this.updateParameterValues()){var i,n;(e=t._p).set.apply(e,this._parameterValues);var s=t._p.length();i=0,n=0;for(var r=0;r<this._children.length;r++){for(var a=this._children[r],o=a.point,h=a.pointLength,l=Number.MAX_VALUE,c=0;c<this._children.length;c++)if(r!==c){var u=this.pointCache(r,c),d=this._children[c].pointLength;t._pip.set((s-h)/((d+h)/2),2*be.angleRad(o,t._p));var f=de.clamp(1-Math.abs(t._pip.dot(u)/u.lengthSq()),0,1);f<l&&(l=f)}a.weight=l,i+=l,this._syncAnimations&&(n+=a.animTrack.duration/a.absoluteSpeed*a.weight)}for(var p=0;p<this._children.length;p++){var m=this._children[p];if(m.weight=m._weight/i,this._syncAnimations){var _=m.animTrack.duration/n*i;m.weightedSpeed=m.absoluteSpeed*_}}}},t}(id);rd._p=new be,rd._pip=new be;var ad=function(e){function t(){return e.apply(this,arguments)||this}return J(t,e),t.prototype.calculateWeights=function(){if(!this.updateParameterValues()){for(var e=0,t=0,i=0;i<this._children.length;i++)if(e+=Math.max(this._parameterValues[i],0),this._syncAnimations){var n=this._children[i];t+=n.animTrack.duration/n.absoluteSpeed*n.weight}for(var s=0;s<this._children.length;s++){var r=this._children[s],a=Math.max(this._parameterValues[s],0);e?(r.weight=a/e,this._syncAnimations&&(r.weightedSpeed=r.animTrack.duration/r.absoluteSpeed/t)):(r.weight=0,this._syncAnimations&&(r.weightedSpeed=0))}}},t}(id),od=function(){function e(e,t,i,n,s){this._controller=e,this._name=t,this._animations={},this._animationList=[],this._speed=i||1,this._loop=void 0===n||n;var r=this._controller.findParameter.bind(this._controller);this._blendTree=s?this._createTree(s.type,this,null,t,1,s.parameter?[s.parameter]:s.parameters,s.children,s.syncAnimations,this._createTree,r):new td(this,null,t,1,i)}var t=e.prototype;return t._createTree=function(e,t,i,n,s,r,a,o,h,l){switch(e){case"1D":return new nd(t,i,n,s,r,a,o,h,l);case Vu:return new sd(t,i,n,s,r,a,o,h,l);case zu:return new rd(t,i,n,s,r,a,o,h,l);case Gu:return new ad(t,i,n,s,r,a,o,h,l)}},t._getNodeFromPath=function(e){for(var t=this._blendTree,i=1;i<e.length;i++)t=t.getChild(e[i]);return t},t.addAnimation=function(e,t){var i=e.join("."),n=this._animationList.findIndex((function(e){return e.path===i}));if(n>=0)this._animationList[n].animTrack=t;else{var s=this._getNodeFromPath(e);s.animTrack=t,this._animationList.push(s)}},$(e,[{key:"name",get:function(){return this._name}},{key:"animations",get:function(){return this._animationList},set:function(e){this._animationList=e}},{key:"speed",get:function(){return this._speed},set:function(e){this._speed=e}},{key:"loop",get:function(){return this._loop},set:function(e){this._loop=e}},{key:"nodeCount",get:function(){return this._blendTree&&this._blendTree.constructor!==td?this._blendTree.getNodeCount():1}},{key:"playable",get:function(){return-1!==qu.indexOf(this.name)||this.animations.length===this.nodeCount}},{key:"looping",get:function(){if(this.animations.length>0){var e=this.name+"."+this.animations[0].animTrack.name,t=this._controller.animEvaluator.findClip(e);if(t)return t.loop}return!1}},{key:"totalWeight",get:function(){for(var e=0,t=0;t<this.animations.length;t++)e+=this.animations[t].weight;return e}},{key:"timelineDuration",get:function(){for(var e=0,t=0;t<this.animations.length;t++){var i=this.animations[t];i.animTrack.duration>e&&(e=i.animTrack.duration)}return e}}]),e}(),hd=function(){function e(e){var t=e.from,i=e.to,n=e.time,s=void 0===n?0:n,r=e.priority,a=void 0===r?0:r,o=e.conditions,h=void 0===o?[]:o,l=e.exitTime,c=void 0===l?null:l,u=e.transitionOffset,d=void 0===u?null:u,f=e.interruptionSource,p=void 0===f?Au:f;this._from=t,this._to=i,this._time=s,this._priority=a,this._conditions=h,this._exitTime=c,this._transitionOffset=d,this._interruptionSource=p}return $(e,[{key:"from",get:function(){return this._from}},{key:"to",get:function(){return this._to},set:function(e){this._to=e}},{key:"time",get:function(){return this._time}},{key:"priority",get:function(){return this._priority}},{key:"conditions",get:function(){return this._conditions}},{key:"exitTime",get:function(){return this._exitTime}},{key:"transitionOffset",get:function(){return this._transitionOffset}},{key:"interruptionSource",get:function(){return this._interruptionSource}},{key:"hasExitTime",get:function(){return!!this.exitTime}}]),e}(),ld=function(){function e(e,t,i,n,s,r,a){this._animEvaluator=e,this._states={},this._stateNames=[],this._eventHandler=r,this._consumedTriggers=a;for(var o=0;o<t.length;o++)this._states[t[o].name]=new od(this,t[o].name,t[o].speed,t[o].loop,t[o].blendTree),this._stateNames.push(t[o].name);this._transitions=i.map((function(e){return new hd(Q({},e))})),this._findTransitionsFromStateCache={},this._findTransitionsBetweenStatesCache={},this._parameters=n,this._previousStateName=null,this._activeStateName=Wu,this._playing=!1,this._activate=s,this._currTransitionTime=1,this._totalTransitionTime=1,this._isTransitioning=!1,this._transitionInterruptionSource=Au,this._transitionPreviousStates=[],this._timeInState=0,this._timeInStateBefore=0}var t=e.prototype;return t.assignMask=function(e){return this._animEvaluator.assignMask(e)},t._findState=function(e){return this._states[e]},t._getActiveStateProgressForTime=function(e){if(this.activeStateName===Wu||this.activeStateName===Hu||this.activeStateName===Xu)return 1;var t=this._animEvaluator.findClip(this.activeStateAnimations[0].name);return t?e/t.track.duration:null},t._findTransitionsFromState=function(e){var t=this._findTransitionsFromStateCache[e];return t||(t=this._transitions.filter((function(t){return t.from===e})),_h(t),this._findTransitionsFromStateCache[e]=t),t},t._findTransitionsBetweenStates=function(e,t){var i=this._findTransitionsBetweenStatesCache[e+"->"+t];return i||(i=this._transitions.filter((function(i){return i.from===e&&i.to===t})),_h(i),this._findTransitionsBetweenStatesCache[e+"->"+t]=i),i},t._transitionHasConditionsMet=function(e){for(var t=e.conditions,i=0;i<t.length;i++){var n=t[i],s=this.findParameter(n.parameterName);switch(n.predicate){case Ru:if(!(s.value>n.value))return!1;break;case Iu:if(!(s.value<n.value))return!1;break;case Lu:if(!(s.value>=n.value))return!1;break;case Du:if(!(s.value<=n.value))return!1;break;case ku:if(s.value!==n.value)return!1;break;case Ou:if(s.value===n.value)return!1}}return!0},t._findTransition=function(e,t){var i=this,n=[];if(e&&t)n=n.concat(this._findTransitionsBetweenStates(e,t));else if(this._isTransitioning)switch(this._transitionInterruptionSource){case Mu:n=(n=n.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(Xu));break;case Cu:n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Xu));break;case Eu:n=(n=(n=n.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Xu));break;case Pu:n=(n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(Xu))}else n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Xu));if(n=n.filter((function(e){if(e.to===i.activeStateName)return!1;if(e.hasExitTime){var t=i._getActiveStateProgressForTime(i._timeInStateBefore),n=i._getActiveStateProgressForTime(i._timeInState);if(e.exitTime<1&&i.activeState.loop&&(t-=Math.floor(t),n-=Math.floor(n)),!(e.exitTime>t&&e.exitTime<=n))return null}return i._transitionHasConditionsMet(e)})),n.length>0){var s=n[0];if(s.to===Hu){var r=this._findTransitionsFromState(Wu)[0];s.to=r.to}return s}return null},t.updateStateFromTransition=function(e){var t,i,n;this.previousState=e.from?this.activeStateName:null,this.activeState=e.to;for(var s=0;s<e.conditions.length;s++){var r=e.conditions[s];this.findParameter(r.parameterName).type===Uu&&this._consumedTriggers.add(r.parameterName)}if(this.previousState){this._isTransitioning||(this._transitionPreviousStates=[]),this._transitionPreviousStates.push({name:this._previousStateName,weight:1});for(var a=Math.min(0!==this._totalTransitionTime?this._currTransitionTime/this._totalTransitionTime:1,1),o=0;o<this._transitionPreviousStates.length;o++){this._isTransitioning?o!==this._transitionPreviousStates.length-1?this._transitionPreviousStates[o].weight*=1-a:this._transitionPreviousStates[o].weight=a:this._transitionPreviousStates[o].weight=1,t=this._findState(this._transitionPreviousStates[o].name);for(var h=0;h<t.animations.length;h++)i=t.animations[h],(n=this._animEvaluator.findClip(i.name+".previous."+o))||((n=this._animEvaluator.findClip(i.name)).name=i.name+".previous."+o),o!==this._transitionPreviousStates.length-1&&n.pause()}}this._isTransitioning=!0,this._totalTransitionTime=e.time,this._currTransitionTime=0,this._transitionInterruptionSource=e.interruptionSource;var l=this.activeState,c=e.transitionOffset&&e.transitionOffset>0&&e.transitionOffset<1,u=0,d=0;if(c){var f=l.timelineDuration*e.transitionOffset;u=f,d=f}this._timeInState=u,this._timeInStateBefore=d;for(var p=0;p<l.animations.length;p++){if(n=this._animEvaluator.findClip(l.animations[p].name))n.reset();else{var m=Number.isFinite(l.animations[p].speed)?l.animations[p].speed:l.speed;(n=new Su(l.animations[p].animTrack,this._timeInState,m,!0,l.loop,this._eventHandler)).name=l.animations[p].name,this._animEvaluator.addClip(n)}if(e.time>0?n.blendWeight=0:n.blendWeight=l.animations[p].normalizedWeight,n.play(),c)n.time=l.timelineDuration*e.transitionOffset;else{var _=l.speed>=0?0:this.activeStateDuration;n.time=_}}},t._transitionToState=function(e){if(this._findState(e)){var t=this._findTransition(this._activeStateName,e);t||(this._animEvaluator.removeClips(),t=new hd({from:null,to:e})),this.updateStateFromTransition(t)}},t.assignAnimation=function(e,t,i,n){var s=e.split("."),r=this._findState(s[0]);r||(r=new od(this,s[0],1),this._states[s[0]]=r,this._stateNames.push(s[0])),r.addAnimation(s,t),void 0!==i&&(r.speed=i),void 0!==n&&(r.loop=n),!this._playing&&this._activate&&this.playable&&this.play()},t.removeNodeAnimations=function(e){if(-1!==qu.indexOf(e))return!1;var t=this._findState(e);return!!t&&(t.animations=[],!0)},t.play=function(e){e&&this._transitionToState(e),this._playing=!0},t.pause=function(){this._playing=!1},t.reset=function(){this._previousStateName=null,this._activeStateName=Wu,this._playing=!1,this._currTransitionTime=1,this._totalTransitionTime=1,this._isTransitioning=!1,this._timeInState=0,this._timeInStateBefore=0,this._animEvaluator.removeClips()},t.rebind=function(){this._animEvaluator.rebind()},t.update=function(e){if(this._playing){var t,i,n;this._timeInStateBefore=this._timeInState,this._timeInState+=e;var s=this._findTransition(this._activeStateName);if(s&&this.updateStateFromTransition(s),this._isTransitioning)if(this._currTransitionTime+=e,this._currTransitionTime<=this._totalTransitionTime){for(var r=0!==this._totalTransitionTime?this._currTransitionTime/this._totalTransitionTime:1,a=0;a<this._transitionPreviousStates.length;a++){t=this._findState(this._transitionPreviousStates[a].name);for(var o=this._transitionPreviousStates[a].weight,h=0;h<t.animations.length;h++)i=t.animations[h],(n=this._animEvaluator.findClip(i.name+".previous."+a))&&(n.blendWeight=(1-r)*i.normalizedWeight*o)}t=this.activeState;for(var l=0;l<t.animations.length;l++)i=t.animations[l],this._animEvaluator.findClip(i.name).blendWeight=r*i.normalizedWeight}else{this._isTransitioning=!1;for(var c=this.activeStateAnimations.length,u=this._animEvaluator.clips.length,d=0;d<u-c;d++)this._animEvaluator.removeClip(0);this._transitionPreviousStates=[],t=this.activeState;for(var f=0;f<t.animations.length;f++)i=t.animations[f],(n=this._animEvaluator.findClip(i.name))&&(n.blendWeight=i.normalizedWeight)}else if(this.activeState._blendTree.constructor!==td){t=this.activeState;for(var p=0;p<t.animations.length;p++)i=t.animations[p],(n=this._animEvaluator.findClip(i.name))&&(n.blendWeight=i.normalizedWeight,i.parent.syncAnimations&&(n.speed=i.speed))}this._animEvaluator.update(e)}},t.findParameter=function(e){return this._parameters[e]},$(e,[{key:"animEvaluator",get:function(){return this._animEvaluator}},{key:"activeState",get:function(){return this._findState(this._activeStateName)},set:function(e){this._activeStateName=e}},{key:"activeStateName",get:function(){return this._activeStateName}},{key:"activeStateAnimations",get:function(){return this.activeState.animations}},{key:"previousState",get:function(){return this._findState(this._previousStateName)},set:function(e){this._previousStateName=e}},{key:"previousStateName",get:function(){return this._previousStateName}},{key:"playable",get:function(){for(var e=!0,t=0;t<this._stateNames.length;t++)this._states[this._stateNames[t]].playable||(e=!1);return e}},{key:"playing",get:function(){return this._playing},set:function(e){this._playing=e}},{key:"activeStateProgress",get:function(){return this._getActiveStateProgressForTime(this._timeInState)}},{key:"activeStateDuration",get:function(){if(this.activeStateName===Wu||this.activeStateName===Hu)return 0;for(var e=0,t=0;t<this.activeStateAnimations.length;t++){var i=this._animEvaluator.findClip(this.activeStateAnimations[t].name);i&&(e=Math.max(e,i.track.duration))}return e}},{key:"activeStateCurrentTime",get:function(){return this._timeInState},set:function(e){this._timeInStateBefore=e,this._timeInState=e;for(var t=0;t<this.activeStateAnimations.length;t++){var i=this.animEvaluator.findClip(this.activeStateAnimations[t].name);i&&(i.time=e)}}},{key:"transitioning",get:function(){return this._isTransitioning}},{key:"transitionProgress",get:function(){return this._currTransitionTime/this._totalTransitionTime}},{key:"states",get:function(){return this._stateNames}}]),e}(),cd=function(){function e(e){if(this._layers=[],this._parameters={},Array.isArray(e.layers))this._layers=e.layers;else for(var t in e.layers){for(var i=e.layers[t],n={name:i.name,blendType:i.blendType,weight:i.weight,states:[],transitions:[]},s=0;s<i.states.length;s++)n.states.push(e.states[i.states[s]]);for(var r=0;r<i.transitions.length;r++){var a=e.transitions[i.transitions[r]];if(a.conditions&&!Array.isArray(a.conditions)){for(var o=Object.keys(a.conditions),h=[],l=0;l<o.length;l++){var c=a.conditions[o[l]];c.parameterName&&h.push(c)}a.conditions=h}Number.isInteger(a.from)&&(a.from=e.states[a.from].name),Number.isInteger(a.to)&&(a.to=e.states[a.to].name),n.transitions.push(a)}this._layers.push(n)}for(var u in e.parameters){var d=e.parameters[u];this._parameters[d.name]={type:d.type,value:d.value}}}return $(e,[{key:"parameters",get:function(){return Object.assign({},this._parameters)}},{key:"layers",get:function(){return this._layers}}]),e}(),ud="msdf",dd="bitmap",fd=function(){function e(e,t){this.type=t&&t.type||ud,this.em=1,this.textures=e,this.intensity=0,this._data=null,this.data=t}return $(e,[{key:"data",get:function(){return this._data},set:function(e){if(this._data=e,e&&(void 0!==this._data.intensity&&(this.intensity=this._data.intensity),this._data.info||(this._data.info={}),(!this._data.version||this._data.version<2)&&(this._data.info.maps=[{width:this._data.info.width,height:this._data.info.height}],this._data.chars)))for(var t in this._data.chars)this._data.chars[t].map=0}}]),e}(),pd=4096,md=function(e){function t(t,i){var n;void 0===i&&(i={}),(n=e.call(this)||this).type="bitmap",n.app=t,n.intensity=0,n.fontWeight=i.fontWeight||"normal",n.fontSize=parseInt(i.fontSize,10),n.glyphSize=n.fontSize,n.fontName=i.fontName||"Arial",n.color=i.color||new me(1,1,1),n.padding=i.padding||0;var s=i.width>pd?pd:i.width||512,r=i.height>pd?pd:i.height||512,a=document.createElement("canvas");a.height=r,a.width=s;var o=new wn(n.app.graphicsDevice,{name:"font",format:7,minFilter:5,magFilter:1,addressU:1,addressV:1,mipmaps:!0});return o.setSource(a),n.textures=[o],n.chars="",n.data={},n}J(t,e);var i=t.prototype;return i.createTextures=function(e){var t=this._normalizeCharsSet(e);if(t.length===this.chars.length){for(var i=0;i<t.length;i++)if(t[i]!==this.chars[i])return void this._renderAtlas(t)}else this._renderAtlas(t)},i.updateTextures=function(e){for(var t=this._normalizeCharsSet(e),i=[],n=0;n<t.length;n++){var s=t[n];this.data.chars[s]||i.push(s)}i.length>0&&this._renderAtlas(this.chars.concat(i))},i.destroy=function(){for(var e=0;e<this.textures.length;e++)this.textures[e].destroy();this.chars=null,this.color=null,this.data=null,this.fontName=null,this.fontSize=null,this.glyphSize=null,this.intensity=null,this.textures=null,this.type=null,this.fontWeight=null},i._getAndClearContext=function(e,t){var i=e.width,n=e.height,s=e.getContext("2d",{alpha:!0});return s.clearRect(0,0,i,n),s.fillStyle=t,s.fillRect(0,0,i,n),s},i._colorToRgbString=function(e,t){var i=Math.round(255*e.r),n=Math.round(255*e.g),s=Math.round(255*e.b);return t?"rgba("+i+", "+n+", "+s+", "+e.a+")":"rgb("+i+", "+n+", "+s+")"},i.renderCharacter=function(e,t,i,n,s){e.fillStyle=s,e.fillText(t,i,n)},i._renderAtlas=function(e){this.chars=e;var t=1,i=this.textures[t-1].getSource(),n=i.width,s=i.height,r=this._colorToRgbString(this.color,!1),a=this.color.a;this.color.a=1/255;var o=this._colorToRgbString(this.color,!0);this.color.a=a;var h="center",l="alphabetic",c=this._getAndClearContext(i,o);c.font=this.fontWeight+" "+this.fontSize.toString()+"px "+this.fontName,c.textAlign=h,c.textBaseline=l,this.data=this._createJson(this.chars,this.fontName,n,s);for(var u=q.getSymbols(this.chars.join("")),d=this.textures.length,f=0,p=0,m={},_=0;_<u.length;_++){var g=u[_];m[g]=this._getTextMetrics(g),f=Math.max(f,m[g].height),p=Math.max(p,m[g].descent)}this.glyphSize=Math.max(this.glyphSize,f);for(var v=this.glyphSize+2*this.padding,y=this.glyphSize+2*this.padding,x=this.glyphSize/2+this.padding,b=y-p-this.padding,S=0,w=0,T=0;T<u.length;T++){var A=u[T],M=q.getCodePoint(u[T]),C=this.fontSize;c.font=this.fontWeight+" "+C.toString()+"px "+this.fontName,c.textAlign=h,c.textBaseline=l;var E=c.measureText(A).width;E>C&&(C=this.fontSize*this.fontSize/E,c.font=this.fontWeight+" "+C.toString()+"px "+this.fontName,E=this.fontSize),this.renderCharacter(c,A,S+x,w+b,r);var P=this.padding+(this.glyphSize-E)/2,R=-this.padding+m[A].descent-p,I=E;if(this._addChar(this.data,A,M,S,w,v,y,P,R,I,t-1,n,s),(S+=v)+v>n&&(S=0,(w+=y)+y>s))if(this.textures[t-1].upload(),w=0,++t>d){(i=document.createElement("canvas")).height=s,i.width=n,c=this._getAndClearContext(i,o);var L=new wn(this.app.graphicsDevice,{format:7,mipmaps:!0,name:"font-atlas"});L.setSource(i),L.minFilter=5,L.magFilter=1,L.addressU=1,L.addressV=1,this.textures.push(L)}else i=this.textures[t-1].getSource(),c=this._getAndClearContext(i,o)}if(this.textures[t-1].upload(),t<d){for(var D=t;D<d;D++)this.textures[D].destroy();this.textures.splice(t)}this.fire("render")},i._createJson=function(e,t,i,n){return{version:3,intensity:this.intensity,info:{face:t,width:i,height:n,maps:[{width:i,height:n}]},chars:{}}},i._addChar=function(e,t,i,n,s,r,a,o,h,l,c,u,d){e.info.maps.length<c+1&&e.info.maps.push({width:u,height:d});var f=this.fontSize/32;e.chars[t]={id:i,letter:t,x:n,y:s,width:r,height:a,xadvance:l/f,xoffset:o/f,yoffset:(h+this.padding)/f,scale:f,range:1,map:c,bounds:[0,0,r/f,a/f]}},i._normalizeCharsSet=function(e){var t=this.app.systems.element.getUnicodeConverter();t&&(e=t(e));for(var i={},n=q.getSymbols(e),s=0;s<n.length;s++){var r=n[s];i[r]||(i[r]=r)}return Object.keys(i).sort()},i._getTextMetrics=function(e){var t=document.createElement("span");t.id="content-span",t.innerHTML=e;var i=document.createElement("div");i.id="content-block",i.style.display="inline-block",i.style.width="1px",i.style.height="0px";var n=document.createElement("div");n.appendChild(t),n.appendChild(i),n.style.font=this.fontSize+"px "+this.fontName,document.body.appendChild(n);var s=-1,r=-1,a=-1;try{i.style["vertical-align"]="baseline",s=i.offsetTop-t.offsetTop,i.style["vertical-align"]="bottom",r=(a=i.offsetTop-t.offsetTop)-s}finally{document.body.removeChild(n)}return{ascent:s,descent:r,height:a}},t}(m),_d="linear",gd="inverse",vd="exponential";function yd(){return!("undefined"==typeof AudioContext&&"undefined"==typeof webkitAudioContext)}var xd=function(){function e(e,t,i){if(void 0===i&&(i={}),this.volume=void 0===i.volume?1:i.volume,this.loop=void 0!==i.loop&&i.loop,this.pitch=void 0===i.pitch?1:i.pitch,this.sound=t,this.paused=!1,this.suspended=!1,this.manager=e,this.source=null,yd()){this.startTime=0,this.startOffset=0;var n=e.context;this.gain=n.createGain()}else t.audio&&(this.source=t.audio.cloneNode(!1),this.source.pause())}var t=e.prototype;return t.getVolume=function(){return this.volume},t.getLoop=function(){return this.loop},t.setLoop=function(e){this.loop=e,this.source&&(this.source.loop=e)},t.getPitch=function(){return this.pitch},t.onManagerVolumeChange=function(){this.setVolume(this.getVolume())},t.onManagerSuspend=function(){this.isPlaying()&&!this.suspended&&(this.suspended=!0,this.pause())},t.onManagerResume=function(){this.suspended&&(this.suspended=!1,this.unpause())},t.play=function(){if(this.source)throw new Error("Call stop() before calling play()");this._createSource(),this.source&&(this.startTime=this.manager.context.currentTime,this.source.start(0,this.startOffset%this.source.buffer.duration),this.setVolume(this.volume),this.setLoop(this.loop),this.setPitch(this.pitch),this.manager.on("volumechange",this.onManagerVolumeChange,this),this.manager.on("suspend",this.onManagerSuspend,this),this.manager.on("resume",this.onManagerResume,this),this.manager.suspended&&this.onManagerSuspend())},t.pause=function(){this.source&&(this.paused=!0,this.startOffset+=this.manager.context.currentTime-this.startTime,this.source.stop(0),this.source=null)},t.unpause=function(){!this.source&&this.paused?(this._createSource(),this.source&&(this.startTime=this.manager.context.currentTime,this.source.start(0,this.startOffset%this.source.buffer.duration),this.setVolume(this.volume),this.setLoop(this.loop),this.setPitch(this.pitch),this.paused=!1)):console.warn("Call pause() before unpausing.")},t.stop=function(){this.source&&(this.source.stop(0),this.source=null),this.manager.off("volumechange",this.onManagerVolumeChange,this),this.manager.off("suspend",this.onManagerSuspend,this),this.manager.off("resume",this.onManagerResume,this)},t.setVolume=function(e){e=de.clamp(e,0,1),this.volume=e,this.gain&&(this.gain.gain.value=e*this.manager.volume)},t.setPitch=function(e){this.pitch=e,this.source&&(this.source.playbackRate.value=e)},t.isPlaying=function(){return!this.paused&&this.source.playbackState===this.source.PLAYING_STATE},t.getDuration=function(){return this.source?this.source.buffer.duration:0},t._createSource=function(){var e=this.manager.context;this.sound.buffer&&(this.source=e.createBufferSource(),this.source.buffer=this.sound.buffer,this.source.connect(this.gain),this.gain.connect(e.destination),this.loop||(this.source.onended=this.pause.bind(this)))},e}();yd()||Object.assign(xd.prototype,{play:function(){this.source&&(this.paused=!1,this.setVolume(this.volume),this.setLoop(this.loop),this.setPitch(this.pitch),this.source.play()),this.manager.on("volumechange",this.onManagerVolumeChange,this),this.manager.on("suspend",this.onManagerSuspend,this),this.manager.on("resume",this.onManagerResume,this),this.manager.suspended&&this.onManagerSuspend()},pause:function(){this.source&&(this.paused=!0,this.source.pause())},unpause:function(){this.source&&(this.paused=!1,this.source.play())},stop:function(){this.source&&this.source.pause(),this.manager.off("volumechange",this.onManagerVolumeChange,this),this.manager.off("suspend",this.onManagerSuspend,this),this.manager.off("resume",this.onManagerResume,this)},setVolume:function(e){e=de.clamp(e,0,1),this.volume=e,this.source&&(this.source.volume=e*this.manager.volume)},setPitch:function(e){this.pitch=e,this.source&&(this.source.playbackRate=e)},getDuration:function(){return this.source&&!isNaN(this.source.duration)?this.source.duration:0},isPlaying:function(){return!this.source.paused}});var bd=function(e){function t(t,i,n){var s;return(s=e.call(this,t,i,n)||this).position=new ye,s.velocity=new ye,yd()?s.panner=t.context.createPanner():(s.maxDistance=1e4,s.minDistance=1,s.rollOffFactor=1,s.distanceModel=gd),s}J(t,e);var i=t.prototype;return i.getPosition=function(){return this.position},i.setPosition=function(e){this.position.copy(e);var t=this.panner;"positionX"in t?(t.positionX.value=e.x,t.positionY.value=e.y,t.positionZ.value=e.z):t.setPosition&&t.setPosition(e.x,e.y,e.z)},i.getVelocity=function(){return this.velocity},i.setVelocity=function(e){this.velocity.copy(e)},i.getMaxDistance=function(){return this.panner.maxDistance},i.setMaxDistance=function(e){this.panner.maxDistance=e},i.getMinDistance=function(){return this.panner.refDistance},i.setMinDistance=function(e){this.panner.refDistance=e},i.getRollOffFactor=function(){return this.panner.rolloffFactor},i.setRollOffFactor=function(e){this.panner.rolloffFactor=e},i.getDistanceModel=function(){return this.panner.distanceModel},i.setDistanceModel=function(e){this.panner.distanceModel=e},i._createSource=function(){var e=this.manager.context;this.source=e.createBufferSource(),this.source.buffer=this.sound.buffer,this.source.connect(this.panner),this.panner.connect(this.gain),this.gain.connect(e.destination),this.loop||(this.source.onended=this.pause.bind(this))},t}(xd);if(!yd()){var Sd=new ye;Object.assign(bd.prototype,{setPosition:function(e){if(this.position.copy(e),this.source){var t=function(e,t,i,n,s,r){var a=(Sd=Sd.sub2(e,t)).length();if(a<i)return 1;if(a>n)return 0;var o=0;return r===_d?o=1-s*(a-i)/(n-i):r===gd?o=i/(i+s*(a-i)):r===vd&&(o=Math.pow(a/i,-s)),de.clamp(o,0,1)}(this.manager.listener.getPosition(),this.position,this.minDistance,this.maxDistance,this.rollOffFactor,this.distanceModel),i=this.getVolume();this.source.volume=i*t}},getMaxDistance:function(){return this.maxDistance},setMaxDistance:function(e){this.maxDistance=e},getMinDistance:function(){return this.minDistance},setMinDistance:function(e){this.minDistance=e},getRollOffFactor:function(){return this.rollOffFactor},setRollOffFactor:function(e){this.rollOffFactor=e},getDistanceModel:function(){return this.distanceModel},setDistanceModel:function(e){this.distanceModel=e}})}var wd=function(){function e(e){this._manager=e,this.position=new ye,this.velocity=new ye,this.orientation=new Ee}var t=e.prototype;return t.getPosition=function(){return this.position},t.setPosition=function(e){this.position.copy(e);var t=this.listener;t&&("positionX"in t?(t.positionX.value=e.x,t.positionY.value=e.y,t.positionZ.value=e.z):t.setPosition&&t.setPosition(e.x,e.y,e.z))},t.getVelocity=function(){return this.velocity},t.setVelocity=function(e){},t.setOrientation=function(e){this.orientation.copy(e);var t=this.listener;if(t){var i=e.data;"forwardX"in t?(t.forwardX.value=-i[8],t.forwardY.value=-i[9],t.forwardZ.value=-i[10],t.upX.value=i[4],t.upY.value=i[5],t.upZ.value=i[6]):t.setOrientation&&t.setOrientation(-i[8],-i[9],-i[10],i[4],i[5],i[6])}},t.getOrientation=function(){return this.orientation},$(e,[{key:"listener",get:function(){var e=this._manager.context;return e?e.listener:null}}]),e}(),Td="running",Ad=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","pointerup","touchend","keydown","keyup"],Md=function(e){function t(t){var i;return(i=e.call(this)||this)._context=null,i._forceWebAudioApi=t.forceWebAudioApi,i._resumeContextCallback=null,i._selfSuspended=!1,i._unlocked=!1,i._unlocking=!1,!yd()&&i._forceWebAudioApi,i.listener=new wd(te(i)),i._volume=1,i}J(t,e);var i=t.prototype;return i.suspend=function(){this._selfSuspended=!0,this.suspended||this.fire("suspend")},i.resume=function(){var e=this;this._selfSuspended=!1,this._context&&(this._unlocked||this._unlocking)&&("interrupted"===this._context.state?this._context.resume().then((function(){e.fire("resume")}),(function(e){})).catch((function(e){})):this.fire("resume"))},i.destroy=function(){this._removeUserInputListeners(),this.fire("destroy"),this._context&&this._context.close&&(this._context.close(),this._context=null)},i.playSound=function(e,t){void 0===t&&(t={});var i=null;return xd&&(i=new xd(this,e,t)).play(),i},i.playSound3d=function(e,t,i){void 0===i&&(i={});var n=null;return bd&&((n=new bd(this,e,i)).setPosition(t),i.volume&&n.setVolume(i.volume),i.loop&&n.setLoop(i.loop),i.maxDistance&&n.setMaxDistance(i.maxDistance),i.minDistance&&n.setMinDistance(i.minDistance),i.rollOffFactor&&n.setRollOffFactor(i.rollOffFactor),i.distanceModel&&n.setDistanceModel(i.distanceModel),n.play()),n},i._addContextUnlockListeners=function(){var e=this;this._unlocking=!1,this._resumeContextCallback||(this._resumeContextCallback=function(){if(e._context&&!e._unlocked&&!e._unlocking){e._unlocking=!0,e.resume();var t=e._context.createBuffer(1,1,e._context.sampleRate),i=e._context.createBufferSource();i.buffer=t,i.connect(e._context.destination),i.start(0),i.onended=function(t){i.disconnect(0),e._unlocked=!0,e._unlocking=!1,e._removeUserInputListeners()}}}),Ad.forEach((function(t){window.addEventListener(t,e._resumeContextCallback,!1)}))},i._removeUserInputListeners=function(){var e=this;this._resumeContextCallback&&(Ad.forEach((function(t){window.removeEventListener(t,e._resumeContextCallback,!1)})),this._resumeContextCallback=null)},$(t,[{key:"volume",get:function(){return this._volume},set:function(e){e=de.clamp(e,0,1),this._volume=e,this.fire("volumechange",e)}},{key:"suspended",get:function(){return!this._context||!this._unlocked||this._context.state!==Td}},{key:"context",get:function(){if(!this._context&&(yd()||this._forceWebAudioApi)&&("undefined"!=typeof AudioContext?this._context=new AudioContext:"undefined"!=typeof webkitAudioContext&&(this._context=new webkitAudioContext),this._context)){this._unlocked=this._context.state===Td,this._unlocked||this._addContextUnlockListeners();var e=this;this._context.onstatechange=function(){e._unlocked&&!e._selfSuspended&&e._context.state!==Td&&e._context.resume().then((function(){}),(function(e){})).catch((function(e){}))}}return this._context}}]),t}(m),Cd=function(){function e(e){this.audio=void 0,this.buffer=void 0,e instanceof Audio?this.audio=e:this.buffer=e}return $(e,[{key:"duration",get:function(){var e=0;return this.buffer?e=this.buffer.duration:this.audio&&(e=this.audio.duration),e||0}}]),e}();function Ed(e,t){return e%t||0}var Pd=function(e){function t(t,i,n){var s;return(s=e.call(this)||this).source=null,s._manager=t,s._volume=void 0!==n.volume?de.clamp(Number(n.volume)||0,0,1):1,s._pitch=void 0!==n.pitch?Math.max(.01,Number(n.pitch)||0):1,s._loop=!(void 0===n.loop||!n.loop),s._sound=i,s._state=2,s._suspended=!1,s._suspendEndEvent=0,s._suspendInstanceEvents=!1,s._playWhenLoaded=!0,s._startTime=Math.max(0,Number(n.startTime)||0),s._duration=Math.max(0,Number(n.duration)||0),s._startOffset=null,s._onPlayCallback=n.onPlay,s._onPauseCallback=n.onPause,s._onResumeCallback=n.onResume,s._onStopCallback=n.onStop,s._onEndCallback=n.onEnd,yd()?(s._startedAt=0,s._currentTime=0,s._currentOffset=0,s._inputNode=null,s._connectorNode=null,s._firstNode=null,s._lastNode=null,s._waitingContextSuspension=!1,s._initializeNodes(),s._endedHandler=s._onEnded.bind(te(s))):(s._isReady=!1,s._loadedMetadataHandler=s._onLoadedMetadata.bind(te(s)),s._timeUpdateHandler=s._onTimeUpdate.bind(te(s)),s._endedHandler=s._onEnded.bind(te(s)),s._createSource()),s}J(t,e);var i=t.prototype;return i._onPlay=function(){this.fire("play"),this._onPlayCallback&&this._onPlayCallback(this)},i._onPause=function(){this.fire("pause"),this._onPauseCallback&&this._onPauseCallback(this)},i._onResume=function(){this.fire("resume"),this._onResumeCallback&&this._onResumeCallback(this)},i._onStop=function(){this.fire("stop"),this._onStopCallback&&this._onStopCallback(this)},i._onEnded=function(){this._suspendEndEvent>0?this._suspendEndEvent--:(this.fire("end"),this._onEndCallback&&this._onEndCallback(this),this.stop())},i._onManagerVolumeChange=function(){this.volume=this._volume},i._onManagerSuspend=function(){0!==this._state||this._suspended||(this._suspended=!0,this.pause())},i._onManagerResume=function(){this._suspended&&(this._suspended=!1,this.resume())},i._initializeNodes=function(){this.gain=this._manager.context.createGain(),this._inputNode=this.gain,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination)},i.play=function(){return 2!==this._state&&this.stop(),this._state=0,this._playWhenLoaded=!1,!this._waitingContextSuspension&&(this._manager.suspended?(this._manager.once("resume",this._playAudioImmediate,this),this._waitingContextSuspension=!0,!1):(this._playAudioImmediate(),!0))},i._playAudioImmediate=function(){if(this._waitingContextSuspension=!1,0===this._state){this.source||this._createSource();var e=Ed(this._startOffset,this.duration);e=Ed(this._startTime+e,this._sound.duration),this._startOffset=null,this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentTime=0,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._manager.on("volumechange",this._onManagerVolumeChange,this),this._manager.on("suspend",this._onManagerSuspend,this),this._manager.on("resume",this._onManagerResume,this),this._manager.on("destroy",this._onManagerDestroy,this),this._suspendInstanceEvents||this._onPlay()}},i.pause=function(){return this._playWhenLoaded=!1,0===this._state&&(this._state=1,this._waitingContextSuspension||(this._updateCurrentTime(),this._suspendEndEvent++,this.source.stop(0),this.source=null,this._startOffset=null,this._suspendInstanceEvents||this._onPause()),!0)},i.resume=function(){if(1!==this._state)return!1;if(this._state=0,this._waitingContextSuspension)return!0;this.source||this._createSource();var e=this.currentTime;return null!==this._startOffset&&(e=Ed(this._startOffset,this.duration),e=Ed(this._startTime+e,this._sound.duration),this._startOffset=null),this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._playWhenLoaded=!1,this._suspendInstanceEvents||this._onResume(),!0},i.stop=function(){if(this._playWhenLoaded=!1,2===this._state)return!1;var e=0===this._state;return this._state=2,this._waitingContextSuspension||(this._manager.off("volumechange",this._onManagerVolumeChange,this),this._manager.off("suspend",this._onManagerSuspend,this),this._manager.off("resume",this._onManagerResume,this),this._manager.off("destroy",this._onManagerDestroy,this),this._startedAt=0,this._currentTime=0,this._currentOffset=0,this._startOffset=null,this._suspendEndEvent++,e&&this.source&&this.source.stop(0),this.source=null,this._suspendInstanceEvents||this._onStop()),!0},i.setExternalNodes=function(e,t){if(e){t||(t=e);var i=this._manager.context.destination;this._firstNode!==e&&(this._firstNode?this._connectorNode.disconnect(this._firstNode):this._connectorNode.disconnect(i),this._firstNode=e,this._connectorNode.connect(e)),this._lastNode!==t&&(this._lastNode&&this._lastNode.disconnect(i),this._lastNode=t,this._lastNode.connect(i))}else console.error("The firstNode must be a valid Audio Node")},i.clearExternalNodes=function(){var e=this._manager.context.destination;this._firstNode&&(this._connectorNode.disconnect(this._firstNode),this._firstNode=null),this._lastNode&&(this._lastNode.disconnect(e),this._lastNode=null),this._connectorNode.connect(e)},i.getExternalNodes=function(){return[this._firstNode,this._lastNode]},i._createSource=function(){if(!this._sound)return null;var e=this._manager.context;return this._sound.buffer&&(this.source=e.createBufferSource(),this.source.buffer=this._sound.buffer,this.source.connect(this._inputNode),this.source.onended=this._endedHandler,this.source.loopStart=Ed(this._startTime,this.source.buffer.duration),this._duration&&(this.source.loopEnd=Math.max(this.source.loopStart,Ed(this._startTime+this._duration,this.source.buffer.duration)))),this.source},i._updateCurrentTime=function(){this._currentTime=Ed((this._manager.context.currentTime-this._startedAt)*this._pitch+this._currentOffset,this.duration)},i._onManagerDestroy=function(){this.source&&0===this._state&&(this.source.stop(0),this.source=null)},$(t,[{key:"currentTime",get:function(){return null!==this._startOffset?this._startOffset:1===this._state?this._currentTime:2!==this._state&&this.source?(this._updateCurrentTime(),this._currentTime):0},set:function(e){if(!(e<0))if(0===this._state){var t=this._suspendInstanceEvents;this._suspendInstanceEvents=!0,this.stop(),this._startOffset=e,this.play(),this._suspendInstanceEvents=t}else this._startOffset=e,this._currentTime=e}},{key:"duration",get:function(){return this._sound?this._duration?Ed(this._duration,this._sound.duration):this._sound.duration:0},set:function(e){this._duration=Math.max(0,Number(e)||0);var t=0===this._state;this.stop(),t&&this.play()}},{key:"isPaused",get:function(){return 1===this._state}},{key:"isPlaying",get:function(){return 0===this._state}},{key:"isStopped",get:function(){return 2===this._state}},{key:"isSuspended",get:function(){return this._suspended}},{key:"loop",get:function(){return this._loop},set:function(e){this._loop=!!e,this.source&&(this.source.loop=this._loop)}},{key:"pitch",get:function(){return this._pitch},set:function(e){this._currentOffset=this.currentTime,this._startedAt=this._manager.context.currentTime,this._pitch=Math.max(Number(e)||0,.01),this.source&&(this.source.playbackRate.value=this._pitch)}},{key:"sound",get:function(){return this._sound},set:function(e){this._sound=e,2!==this._state?this.stop():this._createSource()}},{key:"startTime",get:function(){return this._startTime},set:function(e){this._startTime=Math.max(0,Number(e)||0);var t=0===this._state;this.stop(),t&&this.play()}},{key:"volume",get:function(){return this._volume},set:function(e){e=de.clamp(e,0,1),this._volume=e,this.gain&&(this.gain.gain.value=e*this._manager.volume)}}]),t}(m);yd()||(Object.assign(Pd.prototype,{play:function(){return 2!==this._state&&this.stop(),!(!this.source&&!this._createSource())&&(this.volume=this._volume,this.pitch=this._pitch,this.loop=this._loop,this.source.play(),this._state=0,this._playWhenLoaded=!1,this._manager.on("volumechange",this._onManagerVolumeChange,this),this._manager.on("suspend",this._onManagerSuspend,this),this._manager.on("resume",this._onManagerResume,this),this._manager.on("destroy",this._onManagerDestroy,this),this._manager.suspended&&this._onManagerSuspend(),this._suspendInstanceEvents||this._onPlay(),!0)},pause:function(){return!(!this.source||0!==this._state)&&(this._suspendEndEvent++,this.source.pause(),this._playWhenLoaded=!1,this._state=1,this._startOffset=null,this._suspendInstanceEvents||this._onPause(),!0)},resume:function(){return!(!this.source||1!==this._state)&&(this._state=0,this._playWhenLoaded=!1,this.source.paused&&(this.source.play(),this._suspendInstanceEvents||this._onResume()),!0)},stop:function(){return!(!this.source||2===this._state)&&(this._manager.off("volumechange",this._onManagerVolumeChange,this),this._manager.off("suspend",this._onManagerSuspend,this),this._manager.off("resume",this._onManagerResume,this),this._manager.off("destroy",this._onManagerDestroy,this),this._suspendEndEvent++,this.source.pause(),this._playWhenLoaded=!1,this._state=2,this._startOffset=null,this._suspendInstanceEvents||this._onStop(),!0)},setExternalNodes:function(){},clearExternalNodes:function(){},getExternalNodes:function(){return[null,null]},_onLoadedMetadata:function(){this.source.removeEventListener("loadedmetadata",this._loadedMetadataHandler),this._isReady=!0;var e=Ed(this._startOffset,this.duration);e=Ed(this._startTime+e,this._sound.duration),this._startOffset=null,this.source.currentTime=e},_createSource:function(){return this._sound&&this._sound.audio&&(this._isReady=!1,this.source=this._sound.audio.cloneNode(!0),this.source.addEventListener("loadedmetadata",this._loadedMetadataHandler),this.source.addEventListener("timeupdate",this._timeUpdateHandler),this.source.onended=this._endedHandler),this.source},_onTimeUpdate:function(){this._duration&&this.source.currentTime>Ed(this._startTime+this._duration,this.source.duration)&&(this.loop?this.source.currentTime=Ed(this._startTime,this.source.duration):(this.source.removeEventListener("timeupdate",this._timeUpdateHandler),this.source.pause(),this._onEnded()))},_onManagerDestroy:function(){this.source&&this.source.pause()}}),Object.defineProperty(Pd.prototype,"volume",{get:function(){return this._volume},set:function(e){e=de.clamp(e,0,1),this._volume=e,this.source&&(this.source.volume=e*this._manager.volume)}}),Object.defineProperty(Pd.prototype,"pitch",{get:function(){return this._pitch},set:function(e){this._pitch=Math.max(Number(e)||0,.01),this.source&&(this.source.playbackRate=this._pitch)}}),Object.defineProperty(Pd.prototype,"sound",{get:function(){return this._sound},set:function(e){this.stop(),this._sound=e}}),Object.defineProperty(Pd.prototype,"currentTime",{get:function(){return null!==this._startOffset?this._startOffset:2!==this._state&&this.source?this.source.currentTime-this._startTime:0},set:function(e){e<0||(this._startOffset=e,this.source&&this._isReady&&(this.source.currentTime=Ed(this._startTime+Ed(e,this.duration),this._sound.duration),this._startOffset=null))}}));var Rd=function(e){function t(t,i,n){var s;return void 0===n&&(n={}),(s=e.call(this,t,i,n)||this)._position=new ye,s._velocity=new ye,n.position&&(s.position=n.position),s.maxDistance=void 0!==n.maxDistance?Number(n.maxDistance):1e4,s.refDistance=void 0!==n.refDistance?Number(n.refDistance):1,s.rollOffFactor=void 0!==n.rollOffFactor?Number(n.rollOffFactor):1,s.distanceModel=void 0!==n.distanceModel?n.distanceModel:_d,s}return J(t,e),t.prototype._initializeNodes=function(){this.gain=this._manager.context.createGain(),this.panner=this._manager.context.createPanner(),this.panner.connect(this.gain),this._inputNode=this.panner,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination)},$(t,[{key:"position",get:function(){return this._position},set:function(e){this._position.copy(e);var t=this.panner;"positionX"in t?(t.positionX.value=e.x,t.positionY.value=e.y,t.positionZ.value=e.z):t.setPosition&&t.setPosition(e.x,e.y,e.z)}},{key:"velocity",get:function(){return this._velocity},set:function(e){this._velocity.copy(e)}},{key:"maxDistance",get:function(){return this.panner.maxDistance},set:function(e){this.panner.maxDistance=e}},{key:"refDistance",get:function(){return this.panner.refDistance},set:function(e){this.panner.refDistance=e}},{key:"rollOffFactor",get:function(){return this.panner.rolloffFactor},set:function(e){this.panner.rolloffFactor=e}},{key:"distanceModel",get:function(){return this.panner.distanceModel},set:function(e){this.panner.distanceModel=e}}]),t}(Pd);if(!yd()){var Id=new ye;Object.defineProperty(Rd.prototype,"position",{get:function(){return this._position},set:function(e){if(this._position.copy(e),this.source){var t=function(e,t,i,n,s,r){var a=(Id=Id.sub2(e,t)).length();if(a<i)return 1;if(a>n)return 0;var o=0;return r===_d?o=1-s*(a-i)/(n-i):r===gd?o=i/(i+s*(a-i)):r===vd&&(o=Math.pow(a/i,-s)),de.clamp(o,0,1)}(this._manager.listener.getPosition(),this._position,this.refDistance,this.maxDistance,this.rollOffFactor,this.distanceModel),i=this.volume;this.source.volume=i*t*this._manager.volume}}}),Object.defineProperty(Rd.prototype,"maxDistance",{get:function(){return this._maxDistance},set:function(e){this._maxDistance=e}}),Object.defineProperty(Rd.prototype,"refDistance",{get:function(){return this._refDistance},set:function(e){this._refDistance=e}}),Object.defineProperty(Rd.prototype,"rollOffFactor",{get:function(){return this._rollOffFactor},set:function(e){this._rollOffFactor=e}}),Object.defineProperty(Rd.prototype,"distanceModel",{get:function(){return this._distanceModel},set:function(e){this._distanceModel=e}})}function Ld(){var e,t,i,n=0,s=1,r=2,a=3,o=8,h=9,l=10,c=11,u=12,d=13,f=14,p=16,m={astc:l,dxt:r,etc1:n,etc2:n,pvr:o,atc:c,none:f},_={astc:l,dxt:a,etc1:p,etc2:s,pvr:h,atc:u,none:p},g=21,v=22,y=23,x=8,b=10,S=26,w=27,T=28,A=29,M=30,C=7,E=3,P=5,R=function(e,t){switch(e){case n:return t.formats.etc1?g:v;case s:return y;case r:return x;case a:return b;case o:return S;case h:return w;case l:return T;case c:return A;case u:return M;case d:return C;case f:return E;case p:return P}},I=function(e){for(var t=function(e,t){var i=e*(2/255)-1,n=t*(2/255)-1,s=Math.sqrt(1-Math.min(1,i*i+n*n));return Math.max(0,Math.min(255,Math.floor(.5*(s+1)*255)))},i=0;i<e.length;i+=4){var n=e[i+3],s=e[i+1];e[i+0]=n,e[i+2]=t(n,s),e[i+3]=255}return e},L=function(e){for(var t=new Uint16Array(e.length/4),i=0;i<e.length;i+=4){var n=e[i+0],s=e[i+1],r=e[i+2];t[i/4]=(248&n)<<8|(252&s)<<3|r>>3}return t},D=function(){return"undefined"!=typeof performance?performance.now():0},k=function(e,n,s){if(s){if(e.formats.astc)return"astc"}else if(n){if(e.formats.etc2)return"etc2"}else if(e.formats.etc1||e.formats.etc2)return"etc1";return function(t){for(var i=0;i<t.length;++i){var n=t[i];if(e.formats[n])return n}return"none"}(n?i:t)},O=function(e,t,i,d){switch(i){case n:case s:return!0;case r:case a:return 0==(3&e)&&0==(3&t);case o:case h:return function(e,t){return 0==(e&e-1)&&0==(t&t-1)}(e,t)&&(e===t||d);case l:case c:case u:return!0}},F=function(t,i,n){return n.isKTX2?function(t,i,n){if(!e.KTX2File)throw new Error("Basis transcoder module does not include support for KTX2.");var s=D(),r=new e.KTX2File(new Uint8Array(i)),a=r.getWidth(),o=r.getHeight(),h=r.getLevels(),l=!!r.getHasAlpha(),c=r.isUASTC&&r.isUASTC();if(!a||!o||!h)throw r.close(),r.delete(),new Error("Invalid image dimensions url="+t+" width="+a+" height="+o+" levels="+h);var u,g,v=k(n.deviceDetails,l,c),y=!!n.isGGGR&&"pvr"===v;if(y?u=d:O(a,o,u=l?_[v]:m[v],n.deviceDetails.webgl2)||(u=l?d:f),!r.startTranscoding())throw r.close(),r.delete(),new Error("Failed to start transcoding url="+t);for(var x=[],b=0;b<h;++b){var S=r.getImageTranscodedSizeInBytes(b,0,0,u),w=new Uint8Array(S);if(!r.transcodeImage(w,b,0,0,u,0,-1,-1))throw r.close(),r.delete(),new Error("Failed to transcode image url="+t);var T=u===f||u===p;x.push(T?new Uint16Array(w.buffer):w)}if(r.close(),r.delete(),y)for(u=f,g=0;g<x.length;++g)x[g]=L(I(x[g]));return{format:R(u,n.deviceDetails),width:a,height:o,levels:x,cubemap:!1,transcodeTime:D()-s,url:t,unswizzledGGGR:y}}(t,i,n):function(t,i,n){var s=D(),r=new e.BasisFile(new Uint8Array(i)),a=r.getImageWidth(0,0),o=r.getImageHeight(0,0),h=r.getNumImages(),l=r.getNumLevels(0),c=!!r.getHasAlpha(),u=r.isUASTC&&r.isUASTC();if(!(a&&o&&h&&l))throw r.close(),r.delete(),new Error("Invalid image dimensions url="+t+" width="+a+" height="+o+" images="+h+" levels="+l);var g,v,y=k(n.deviceDetails,c,u),x=!!n.isGGGR&&"pvr"===y;if(x?g=d:O(a,o,g=c?_[y]:m[y],n.deviceDetails.webgl2)||(g=c?d:f),!r.startTranscoding())throw r.close(),r.delete(),new Error("Failed to start transcoding url="+t);for(var b=[],S=0;S<l;++S){var w=r.getImageTranscodedSizeInBytes(0,S,g),T=new Uint8Array(w);if(!r.transcodeImage(T,0,S,g,0,0))throw r.close(),r.delete(),new Error("Failed to transcode image url="+t);var A=g===f||g===p;b.push(A?new Uint16Array(T.buffer):T)}if(r.close(),r.delete(),x)for(g=f,v=0;v<b.length;++v)b[v]=L(I(b[v]));return{format:R(g,n.deviceDetails),width:a,height:o,levels:b,cubemap:!1,transcodeTime:D()-s,url:t,unswizzledGGGR:x}}(t,i,n)},B=function(e,t,i){try{var n=F(e,t,i);n.levels=n.levels.map((function(e){return e.buffer})),self.postMessage({url:e,data:n},n.levels)}catch(t){self.postMessage({url:e,err:t},null)}},N=[];self.onmessage=function(n){var s=n.data;switch(s.type){case"init":!function(n,s){self.importScripts(n.basisUrl),self.BASIS(n.module?{instantiateWasm:function(e,t){return WebAssembly.instantiate(n.module,e).then((function(e){t(e)})).catch((function(e){console.error("instantiate failed + "+e)})),{}}}:null).then((function(r){r.initializeBasis(),e=r,t=n.rgbPriority,i=n.rgbaPriority,s(null)}))}(s.config,(function(){for(var e=0;e<N.length;++e)B(N[e].url,N[e].data,N[e].options);N.length=0}));break;case"transcode":e?B(s.url,s.data,s.options):N.push(s)}}}var Dd=function(e){return{astc:!!e.extCompressedTextureASTC,atc:!!e.extCompressedTextureATC,dxt:!!e.extCompressedTextureS3TC,etc1:!!e.extCompressedTextureETC1,etc2:!!e.extCompressedTextureETC,pvr:!!e.extCompressedTexturePVRTC}},kd=function(){function e(){this.callbacks={},this.queue=[],this.clients=[]}var t=e.prototype;return t.enqueueJob=function(e,t,i,n){if(this.callbacks.hasOwnProperty(e))this.callbacks[e].push(i);else{this.callbacks[e]=[i];var s={url:e,data:t,options:n};this.clients.length>0?this.clients.shift().run(s):this.queue.push(s)}},t.enqueueClient=function(e){this.queue.length>0?e.run(this.queue.shift()):this.clients.push(e)},t.handleResponse=function(e,t,i){var n=this.callbacks[e];if(t)for(var s=0;s<n.length;++s)n[s](t);else{3===i.format||5===i.format?i.levels=i.levels.map((function(e){return new Uint16Array(e)})):i.levels=i.levels.map((function(e){return new Uint8Array(e)}));for(var r=0;r<n.length;++r)n[r](null,i)}delete this.callbacks[e]},e}(),Od=function(){function e(e,t,i){var n=this;this.queue=e,this.worker=new Worker(t.workerUrl),this.worker.addEventListener("message",(function(e){var t=e.data;n.queue.handleResponse(t.url,t.err,t.data),n.eager||n.queue.enqueueClient(n)})),this.worker.postMessage({type:"init",config:t}),this.eager=i}return e.prototype.run=function(e){var t=[];e.data instanceof ArrayBuffer&&t.push(e.data),this.worker.postMessage({type:"transcode",url:e.url,format:e.format,data:e.data,options:e.options},t),this.eager&&this.queue.enqueueClient(this)},e}(),Fd=["etc1","etc2","astc","dxt","pvr","atc"],Bd=["astc","dxt","etc2","pvr","atc"],Nd=new kd,Ud=null,zd=!1;function Vd(e){if(!zd){if(e){if(e.lazyInit)return void(Ud=e)}else e=Ud||{};if(!e.glueUrl||!e.wasmUrl||!e.fallbackUrl){var t=((window.config?window.config.wasmModules:window.PRELOAD_MODULES)||[]).find((function(e){return"BASIS"===e.moduleName}));if(t){var i=window.ASSET_PREFIX||"";e.glueUrl||(e.glueUrl=i+t.glueUrl),e.wasmUrl||(e.wasmUrl=i+t.wasmUrl),e.fallbackUrl||(e.fallbackUrl=i+t.fallbackUrl)}}if(e.glueUrl||e.wasmUrl||e.fallbackUrl){zd=!0;var n=Math.max(1,Math.min(16,e.numWorkers||1)),s=1===e.numWorkers||!e.hasOwnProperty("eagerWorkers")||e.eagerWorkers;e.rgbPriority=e.rgbPriority||Fd,e.rgbaPriority=e.rgbaPriority||Bd,e.maxRetries=e.hasOwnProperty("maxRetries")?e.maxRetries:5,function(e,t){var i=function(i,n){var s;t(null,{workerUrl:URL.createObjectURL((s="("+Ld.toString()+")()\n\n",new Blob([s],{type:"application/javascript"}))),basisUrl:URL.createObjectURL(i),module:n,rgbPriority:e.rgbPriority,rgbaPriority:e.rgbaPriority})},n={responseType:"blob",retry:e.maxRetries>0,maxRetries:e.maxRetries};if(e.glueUrl&&e.wasmUrl&&function(){try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){var e=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(e instanceof WebAssembly.Module)return new WebAssembly.Instance(e)instanceof WebAssembly.Instance}}catch(e){}return!1}()){var s=null,r=null;pe.get(e.glueUrl,n,(function(e,n){e?t(e):r?i(n,r):s=n}));var a=fetch(e.wasmUrl),o=function(){a.then((function(e){return e.arrayBuffer()})).then((function(e){return WebAssembly.compile(e)})).then((function(e){s?i(s,e):r=e})).catch((function(e){t(e,null)}))};WebAssembly.compileStreaming?WebAssembly.compileStreaming(a).then((function(e){s?i(s,e):r=e})).catch((function(e){o()})):o()}else pe.get(e.fallbackUrl,n,(function(e,n){e?t(e,null):i(n,null)}))}(e,(function(e,t){if(e)console.error("failed to initialize basis worker: "+e);else for(var i=0;i<n;++i)Nd.enqueueClient(new Od(Nd,t,s))}))}}}var Gd=null;function Wd(e,t,i,n,s){return Vd(),Gd||(Gd={webgl2:e.webgl2,formats:Dd(e)}),Nd.enqueueJob(t,i,n,{deviceDetails:Gd,isGGGR:!(null==s||!s.isGGGR),isKTX2:!(null==s||!s.isKTX2)}),zd}var Hd=function(){function e(e){this.handlerType="animclip",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=fe.ResponseType.JSON),pe.get(e.load,i,(function(i,n){i?t("Error loading animation clip resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){var i=t.name,n=t.duration,s=t.inputs.map((function(e){return new Tu(1,e)})),r=t.outputs.map((function(e){return new Tu(e.components,e.data)})),a=t.curves.map((function(e){return new wu([e.path],e.inputIndex,e.outputIndex,e.interpolation)}));return new Ju(i,n,s,r,a)},t.patch=function(e,t){},e}(),Xd=function(){function e(e){this.handlerType="animstategraph",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=fe.ResponseType.JSON),pe.get(e.load,i,(function(i,n){i?t("Error loading animation state graph resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return new cd(t)},t.patch=function(e,t){},e}(),qd=function(e){function t(){var t;return(t=e.call(this)||this)._meshes=null,t}J(t,e);var i=t.prototype;return i.destroy=function(){this.meshes=null},i.decRefMeshes=function(){if(this._meshes)for(var e=this._meshes.length,t=0;t<e;t++){var i=this._meshes[t];i&&(i.decRefCount(),i.refCount<1&&(i.destroy(),this._meshes[t]=null))}},i.incRefMeshes=function(){if(this._meshes)for(var e=this._meshes.length,t=0;t<e;t++)this._meshes[t]&&this._meshes[t].incRefCount()},$(t,[{key:"meshes",get:function(){return this._meshes},set:function(e){this.decRefMeshes(),this._meshes=e,this.incRefMeshes(),this.fire("set:meshes",e)}}]),t}(m),jd=function(e){function t(t,i){var n;return(n=e.call(this)||this).skin=t,n.skinInstance=i,n}return J(t,e),t}(Yr),Yd=function(){function e(){}return e.createCachedSkinInstance=function(t,i,n){var s=e.getCachedSkinInstance(t,i);return s||((s=new ba(t)).resolve(i,n),e.addCachedSkinInstance(t,i,s)),s},e.getCachedSkinInstance=function(t,i){var n=null,s=e._skinInstanceCache.get(i);if(s){var r=s.find((function(e){return e.skin===t}));r&&(r.incRefCount(),n=r.skinInstance)}return n},e.addCachedSkinInstance=function(t,i,n){var s=e._skinInstanceCache.get(i);s||(s=[],e._skinInstanceCache.set(i,s));var r=s.find((function(e){return e.skin===t}));r||(r=new jd(t,n),s.push(r)),r.incRefCount()},e.removeCachedSkinInstance=function(t){if(t){var i=t.rootBone;if(i){var n=e._skinInstanceCache.get(i);if(n){var s=n.findIndex((function(e){return e.skinInstance===t}));if(s>=0){var r=n[s];r.decRefCount(),0===r.refCount&&(n.splice(s,1),n.length||e._skinInstanceCache.delete(i),t&&(t.destroy(),r.skinInstance=null))}}}}},e}();Yd._skinInstanceCache=new Map;var Kd=function(){function e(t,i,n,s){for(var r=function(t,s,r){var a=e.createAsset(i.name,t,s,r);return n.add(a),a},a=[],o=0;o<t.renders.length;++o)a.push(r("render",t.renders[o],o));for(var h=[],l=0;l<t.materials.length;++l)h.push(r("material",t.materials[l],l));for(var c=[],u=0;u<t.animations.length;++u)c.push(r("animation",t.animations[u],u));this.data=t,this._model=null,this._assetName=i.name,this._assets=n,this._defaultMaterial=s,this.renders=a,this.materials=h,this.textures=t.textures,this.animations=c}e.createAsset=function(e,t,i,n){var s=new ml(e+"/"+t+"/"+n,t,{url:""});return s.resource=i,s.loaded=!0,s};var t=e.prototype;return t.instantiateModelEntity=function(e){var t=new $l;return t.addComponent("model",Object.assign({type:"asset",asset:this.model},e)),t},t.instantiateRenderEntity=function(t){for(var i,n=this,s=this._defaultMaterial,r=[],a=function(e,t,i,n,a,o,h){var l=a[i.id],c=void 0===l?s:n[l],u=new ka(i,c);return i.morph&&(u.morphInstance=new oc(i.morph)),h.hasOwnProperty("skin")&&r.push({meshInstance:u,rootBone:e,entity:t}),u},o=function e(i,s,r){var o=new $l;s._cloneInternal(o),i||(i=o);for(var h=null,l=null,c=0;c<r.nodes.length;c++){if(r.nodes[c]===s){var u=r.gltf.nodes[c];if(u.hasOwnProperty("mesh")){var d=r.renders[u.mesh].meshes;l=n.renders[u.mesh];for(var f=0;f<d.length;f++){var p=d[f];if(p){var m=a(i,o,p,r.materials,r.meshDefaultMaterials,r.skins,u);h||(h=[]),h.push(m)}}}if(r.lights){var _=r.lights.get(u);_&&o.addChild(_.clone())}if(r.cameras){var g=r.cameras.get(u);g&&g.camera.system.cloneComponent(g,o)}}}h&&(o.addComponent("render",Object.assign({type:"asset",meshInstances:h,rootBone:i},t)),o.render.assignAsset(l));for(var v=s.children,y=0;y<v.length;y++){var x=e(i,v[y],r);o.addChild(x)}return o},h=[],l=ne(this.data.scenes);!(i=l()).done;){var c=i.value;h.push(o(null,c,this.data))}return r.forEach((function(e){e.meshInstance.skinInstance=Yd.createCachedSkinInstance(e.meshInstance.mesh.skin,e.rootBone,e.entity)})),e.createSceneHierarchy(h,"Entity")},t.getMaterialVariants=function(){return this.data.variants?Object.keys(this.data.variants):[]},t.applyMaterialVariant=function(e,t){var i=t?this.data.variants[t]:null;if(void 0!==i)for(var n=e.findComponents("render"),s=0;s<n.length;s++){var r=n[s];this._applyMaterialVariant(i,r.meshInstances)}},t.applyMaterialVariantInstances=function(e,t){var i=t?this.data.variants[t]:null;void 0!==i&&this._applyMaterialVariant(i,e)},t._applyMaterialVariant=function(e,t){var i=this;t.forEach((function(t){if(null===e)t.material=i._defaultMaterial;else{var n=i.data.meshVariants[t.mesh.id];n&&(t.material=i.data.materials[n[e]])}}))},e.createSceneHierarchy=function(e,t){var i=null;if(1===e.length)i=e[0];else{i=new t("SceneGroup");for(var n,s=ne(e);!(n=s()).done;){var r=n.value;i.addChild(r)}}return i},e.createModel=function(t,i){for(var n,s=function(e,n,s,r,a,o,h){var l=t.meshDefaultMaterials[n.id],c=void 0===l?i:a[l],u=new ka(n,c,o);if(n.morph){var d=new oc(n.morph);u.morphInstance=d,e.morphInstances.push(d)}if(h.hasOwnProperty("skin")){var f=h.skin,p=s[f];n.skin=p;var m=r[f];u.skinInstance=m,e.skinInstances.push(m)}e.meshInstances.push(u)},r=new hc,a=[],o=ne(t.skins);!(n=o()).done;){var h=n.value,l=new ba(h);l.bones=h.bones,a.push(l)}r.graph=e.createSceneHierarchy(t.scenes,"GraphNode");for(var c=0;c<t.nodes.length;c++){var u=t.nodes[c];if(u.root===r.graph){var d=t.gltf.nodes[c];if(d.hasOwnProperty("mesh"))for(var f=t.renders[d.mesh].meshes,p=0;p<f.length;p++){var m=f[p];m&&s(r,m,t.skins,a,t.materials,u,d)}}}return r},t.destroy=function(){var e=this._assets,t=function(t){e.remove(t),t.unload()},i=function(e){e.forEach((function(e){t(e)}))};this.animations&&(i(this.animations),this.animations=null),this.textures&&(i(this.textures),this.textures=null),this.materials&&(i(this.materials),this.materials=null),this.renders&&(i(this.renders),this.renders=null),this._model&&(t(this._model),this._model=null),this.data=null,this.assets=null},$(e,[{key:"model",get:function(){if(!this._model){var t=e.createModel(this.data,this._defaultMaterial),i=e.createAsset(this._assetName,"model",t,0);this._assets.add(i),this._model=i}return this._model}}]),e}(),Zd=null,$d=function(){return"undefined"!=typeof window&&window.DracoDecoderModule},Qd=function(){function e(e){this.gltf=e,this.nodes=null,this.scenes=null,this.animations=null,this.textures=null,this.materials=null,this.variants=null,this.meshVariants=null,this.meshDefaultMaterials=null,this.renders=null,this.skins=null,this.lights=null,this.cameras=null}return e.prototype.destroy=function(){this.renders&&this.renders.forEach((function(e){e.meshes=null}))},e}(),Jd=function(e){return/^data:.*,.*$/i.test(e)},ef=function(e){switch(e){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":default:return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}},tf=function(e){switch(e){case 5120:default:return 0;case 5121:return 1;case 5122:return 2;case 5123:return 3;case 5124:return 4;case 5125:return 5;case 5126:return 6}},nf=function(e){switch(e){case 5120:case 5121:return 1;case 5122:case 5123:return 2;case 5124:case 5125:case 5126:return 4;default:return 0}},sf={POSITION:vt,NORMAL:yt,TANGENT:xt,COLOR_0:wt,JOINTS_0:St,WEIGHTS_0:bt,TEXCOORD_0:At,TEXCOORD_1:Mt,TEXCOORD_2:Ct,TEXCOORD_3:Et,TEXCOORD_4:Pt,TEXCOORD_5:Rt,TEXCOORD_6:It,TEXCOORD_7:Lt},rf=function(e,t,i){for(var n=function(e){switch(e){case 0:return function(e){return Math.max(e/127,-1)};case 1:return function(e){return e/255};case 2:return function(e){return Math.max(e/32767,-1)};case 3:return function(e){return e/65535};default:return function(e){return e}}}(i),s=t.length,r=0;r<s;++r)e[r]=n(t[r]);return e},af=function e(t,i,n){void 0===n&&(n=!1);var s=ef(t.type),r=function(e){switch(e){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5124:return Int32Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:return null}}(t.componentType);if(!r)return null;var a,o=i[t.bufferView];if(t.sparse){var h=t.sparse,l={count:h.count,type:"SCALAR"},c=e(Object.assign(l,h.indices),i,!0),u={count:h.count,type:t.scalar,componentType:t.componentType},d=e(Object.assign(u,h.values),i,!0);if(t.hasOwnProperty("bufferView"))a=e({bufferView:t.bufferView,byteOffset:t.byteOffset,componentType:t.componentType,count:t.count,type:t.type},i,!0).slice();else a=new r(t.count*s);for(var f=0;f<h.count;++f)for(var p=c[f],m=0;m<s;++m)a[p*s+m]=d[f*s+m]}else if(n&&o.hasOwnProperty("byteStride")){for(var _=s*r.BYTES_PER_ELEMENT,g=new ArrayBuffer(t.count*_),v=new Uint8Array(g),y=0,x=0;x<t.count;++x)for(var b=(t.byteOffset||0)+x*o.byteStride,S=0;S<_;++S)v[y++]=o[b++];a=new r(g)}else a=new r(o.buffer,o.byteOffset+(t.byteOffset||0),t.count*s);return a},of=function(e,t){var i=af(e,t,!0);if(i instanceof Float32Array||!e.normalized)return i;var n=new Float32Array(i.length);return rf(n,i,tf(e.componentType)),n},hf=function(e){var t=e.min,i=e.max;if(!t||!i)return null;if(e.normalized){var n=tf(e.componentType);t=rf([],t,n),i=rf([],i,n)}return new Oe(new ye(.5*(i[0]+t[0]),.5*(i[1]+t[1]),.5*(i[2]+t[2])),new ye(.5*(i[0]-t[0]),.5*(i[1]-t[1]),.5*(i[2]-t[2])))},lf=function(e,t){var i=e.POSITION;if(i&&3===i.components){var n;if(i.size!==i.stride){var s=i.stride/pi[i.type],r=new fi[i.type](i.buffer,i.offset,i.count*s);n=new fi[i.type](3*i.count);for(var a=0;a<i.count;++a)n[3*a+0]=r[a*s+0],n[3*a+1]=r[a*s+1],n[3*a+2]=r[a*s+2]}else n=new fi[i.type](i.buffer,i.offset,3*i.count);var o=i.count;t||(t=function(e){for(var t=new Uint16Array(e),i=0;i<e;i++)t[i]=i;return t}(o));var h=sa(n,t),l=new Float32Array(h.length);l.set(h),e.NORMAL={buffer:l.buffer,size:12,offset:0,stride:12,count:o,components:3,type:6}}},cf=function(e){var t=new ml(e.name+"_clone",e.type,e.file,e.data,e.options);return t.loaded=!0,t.resource=function(e){var t=new wn(e.device,e);return t._levels=function(e){for(var t=[],i=0;i<e._levels.length;++i){var n=[];if(e.cubemap)for(var s=0;s<6;++s)n.push(e._levels[i][s]);else n=e._levels[i];t.push(n)}return t}(e),t}(e.resource),e.registry.add(t),t},uf=function(e,t,i){var n=t.POSITION;if(!n)return null;var s=n.count,r=[];for(var a in t)t.hasOwnProperty(a)&&r.push({semantic:a,components:t[a].components,type:t[a].type,normalize:!!t[a].normalize});var o,h,l,c,u,d,f=[vt,yt,xt,wt,St,bt,At,Mt];r.sort((function(e,t){var i=f.indexOf(e.semantic),n=f.indexOf(t.semantic);return i<n?-1:n<i?1:0}));var p=new Ti(e,r),m=!0;for(o=0;o<p.elements.length;++o)if(d=(c=t[(u=p.elements[o]).name]).offset-n.offset,c.buffer!==n.buffer||c.stride!==u.stride||c.size!==u.size||d!==u.offset){m=!1;break}var _,g,v,y=new Si(e,p,s,0),x=y.lock(),b=new Uint32Array(x);if(m)_=new Uint32Array(n.buffer,n.offset,s*y.format.size/4),b.set(_);else for(o=0;o<y.format.elements.length;++o){g=(u=y.format.elements[o]).stride/4,v=(c=t[u.name]).stride/4,_=new Uint32Array(c.buffer,c.offset,(c.count-1)*v+(c.size+3)/4);var S=0,w=u.offset/4,T=Math.floor((c.size+3)/4);for(h=0;h<s;++h){for(l=0;l<T;++l)b[w+l]=_[S+l];S+=v,w+=g}}return i&&function(e){var t,i,n=[],s=[],r=[];for(t=0;t<e.format.elements.length;++t){var a=e.format.elements[t];if(a.name===At||a.name===Mt)switch(a.dataType){case 6:n.push({offset:a.offset/4+1,stride:a.stride/4});break;case 3:s.push({offset:a.offset/2+1,stride:a.stride/2});break;case 1:r.push({offset:a.offset+1,stride:a.stride})}}var o=function(n,s,r){var a=new s(e.storage);for(t=0;t<n.length;++t){var o=n[t].offset,h=n[t].stride;for(i=0;i<e.numVertices;++i)a[o]=r-a[o],o+=h}};n.length>0&&o(n,Float32Array,1),s.length>0&&o(s,Uint16Array,65535),r.length>0&&o(r,Uint8Array,255)}(y),y.unlock(),y},df=new Ee,ff=new ye,pf=function(e,t,i,n,s,r,a,o,h,l){var c=[];return t.primitives.forEach((function(u){var d,f,p,m=null,_=!0;if(u.hasOwnProperty("extensions")){var g=u.extensions;if(g.hasOwnProperty("KHR_draco_mesh_compression")){var v=Zd||$d();if(v){var y=g.KHR_draco_mesh_compression;if(y.hasOwnProperty("attributes")){var x=n[y.bufferView],b=new v.DecoderBuffer;b.Init(x,x.length);var S,w,T=new v.Decoder,A=T.GetEncodedGeometryType(b);switch(A){case v.POINT_CLOUD:d=0,S=new v.PointCloud,w=T.DecodeBufferToPointCloud(b,S);break;case v.TRIANGULAR_MESH:d=4,S=new v.Mesh,w=T.DecodeBufferToMesh(b,S);case v.INVALID_GEOMETRY_TYPE:}if(!w||!w.ok()||0===S.ptr)return void s("Failed to decode draco compressed asset: "+(w?w.error_msg():"Mesh asset - invalid draco compressed geometry type: "+A));var M=S.num_faces();if(A===v.TRIANGULAR_MESH){var C=S.num_points()>65535,E=(p=3*M)*(C?4:2),P=v._malloc(E);C?(T.GetTrianglesUInt32Array(S,E,P),m=new Uint32Array(v.HEAPU32.buffer,P,p).slice()):(T.GetTrianglesUInt16Array(S,E,P),m=new Uint16Array(v.HEAPU16.buffer,P,p).slice()),v._free(P)}f=function(e,t,i,n,s,r,a){var o=t.num_points(),h=function(e,i){var r,a,h,l,c=n.GetAttributeByUniqueId(t,e),u=o*c.num_components();switch(c.data_type()){case s.DT_UINT8:l=1,h=1,r=s._malloc(u*h),n.GetAttributeDataArrayForAllPoints(t,c,s.DT_UINT8,u*h,r),a=new Uint8Array(s.HEAPU8.buffer,r,u).slice();break;case s.DT_UINT16:l=3,h=2,r=s._malloc(u*h),n.GetAttributeDataArrayForAllPoints(t,c,s.DT_UINT16,u*h,r),a=new Uint16Array(s.HEAPU16.buffer,r,u).slice();break;case s.DT_FLOAT32:default:l=6,h=4,r=s._malloc(u*h),n.GetAttributeDataArrayForAllPoints(t,c,s.DT_FLOAT32,u*h,r),a=new Float32Array(s.HEAPF32.buffer,r,u).slice()}return s._free(r),{values:a,numComponents:c.num_components(),componentSizeInBytes:h,storageType:l,normalized:i===wt&&1===l||c.normalized()}},l={},c=i.attributes;for(var u in c)if(c.hasOwnProperty(u)&&sf.hasOwnProperty(u)){var d=sf[u],f=h(c[u],d),p=f.numComponents*f.componentSizeInBytes;l[d]={values:f.values,buffer:f.values.buffer,size:p,offset:0,stride:p,count:o,components:f.numComponents,type:f.storageType,normalize:f.normalized}}return l.hasOwnProperty(yt)||lf(l,r),uf(e,l,a)}(e,S,y,T,v,m,r),v.destroy(S),v.destroy(T),v.destroy(b),_=!1}}}}f||(m=u.hasOwnProperty("indices")?af(i[u.indices],n,!0):null,f=function(e,t,i,n,s,r,a){var o={},h=[];for(var l in t)t.hasOwnProperty(l)&&sf.hasOwnProperty(l)&&(o[l]=t[l],h.push(l+":"+t[l]));h.sort();var c=h.join(),u=a[c];if(!u){var d={};for(var f in o){var p=n[t[f]],m=af(p,s),_=s[p.bufferView],g=sf[f],v=ef(p.type)*nf(p.componentType),y=_.hasOwnProperty("byteStride")?_.byteStride:v;d[g]={buffer:m.buffer,size:v,offset:m.byteOffset,stride:y,count:p.count,components:ef(p.type),type:tf(p.componentType),normalize:p.normalized}}d.hasOwnProperty(yt)||lf(d,i),u=uf(e,d,r),a[c]=u}return u}(e,u.attributes,m,i,n,r,a),d=function(e){if(!e.hasOwnProperty("mode"))return 4;switch(e.mode){case 0:return 0;case 1:return 1;case 2:return 2;case 3:return 3;case 4:default:return 4;case 5:return 5;case 6:return 6}}(u));var R=null;if(f){if((R=new ea(e)).vertexBuffer=f,R.primitive[0].type=d,R.primitive[0].base=0,R.primitive[0].indexed=null!==m,null!==m){var I;2!==(I=m instanceof Uint8Array?0:m instanceof Uint16Array?1:2)||e.extUintElement||(I=1,m=new Uint16Array(m));var L=new mr(e,I,m.length,0,m);R.indexBuffer[0]=L,R.primitive[0].count=m.length}else R.primitive[0].count=f.numVertices;if(u.hasOwnProperty("extensions")&&u.extensions.hasOwnProperty("KHR_materials_variants")){var D=u.extensions.KHR_materials_variants,k={};D.mappings.forEach((function(e){e.variants.forEach((function(t){k[t]=e.material}))})),o[R.id]=k}h[R.id]=u.material;var O=i[u.attributes.POSITION];if(R.aabb=hf(O),_&&u.hasOwnProperty("targets")){var F=[];u.targets.forEach((function(e,s){var r={};e.hasOwnProperty("POSITION")&&(O=i[e.POSITION],r.deltaPositions=of(O,n),r.deltaPositionsType=6,r.aabb=hf(O)),e.hasOwnProperty("NORMAL")&&(O=i[e.NORMAL],r.deltaNormals=of(O,n),r.deltaNormalsType=6),t.hasOwnProperty("extras")&&t.extras.hasOwnProperty("targetNames")?r.name=t.extras.targetNames[s]:r.name=s.toString(10),t.hasOwnProperty("weights")&&(r.defaultWeight=t.weights[s]),r.preserveData=l.morphPreserveData,F.push(new lc(r))})),R.morph=new rc(F,e)}}c.push(R)})),c},mf=function(e,t,i){var n,s,r=e.texCoord;if(r)for(s=0;s<i.length;++s)t[i[s]+"MapUv"]=r;var a=null==(n=e.extensions)?void 0:n.KHR_texture_transform;if(a){var o=a.offset||[0,0],h=a.scale||[1,1],l=a.rotation?-a.rotation*de.RAD_TO_DEG:0,c=new be(h[0],h[1]),u=new be(o[0],1-h[1]-o[1]);for(s=0;s<i.length;++s)t[i[s]+"MapTiling"]=c,t[i[s]+"MapOffset"]=u,t[i[s]+"MapRotation"]=l}},_f=function(e,t,i){var n,s;if(e.hasOwnProperty("diffuseFactor")?(n=e.diffuseFactor,t.diffuse.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2)),t.opacity=n[3]):(t.diffuse.set(1,1,1),t.opacity=1),e.hasOwnProperty("diffuseTexture")){var r=e.diffuseTexture;s=i[r.index],t.diffuseMap=s,t.diffuseMapChannel="rgb",t.opacityMap=s,t.opacityMapChannel="a",mf(r,t,["diffuse","opacity"])}if(t.useMetalness=!1,e.hasOwnProperty("specularFactor")?(n=e.specularFactor,t.specular.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2))):t.specular.set(1,1,1),e.hasOwnProperty("glossinessFactor")?t.shininess=100*e.glossinessFactor:t.shininess=100,e.hasOwnProperty("specularGlossinessTexture")){var a=e.specularGlossinessTexture;t.specularEncoding="srgb",t.specularMap=t.glossMap=i[a.index],t.specularMapChannel="rgb",t.glossMapChannel="a",mf(a,t,["gloss","metalness"])}},gf=function(e,t,i){if(e.hasOwnProperty("clearcoatFactor")?t.clearCoat=.25*e.clearcoatFactor:t.clearCoat=0,e.hasOwnProperty("clearcoatTexture")){var n=e.clearcoatTexture;t.clearCoatMap=i[n.index],t.clearCoatMapChannel="r",mf(n,t,["clearCoat"])}if(e.hasOwnProperty("clearcoatRoughnessFactor")?t.clearCoatGlossiness=e.clearcoatRoughnessFactor:t.clearCoatGlossiness=0,e.hasOwnProperty("clearcoatRoughnessTexture")){var s=e.clearcoatRoughnessTexture;t.clearCoatGlossMap=i[s.index],t.clearCoatGlossMapChannel="g",mf(s,t,["clearCoatGloss"])}if(e.hasOwnProperty("clearcoatNormalTexture")){var r=e.clearcoatNormalTexture;t.clearCoatNormalMap=i[r.index],mf(r,t,["clearCoatNormal"]),r.hasOwnProperty("scale")&&(t.clearCoatBumpiness=r.scale)}t.chunks.clearCoatGlossPS="\n #ifdef MAPFLOAT\n uniform float material_clearCoatGlossiness;\n #endif\n \n void getClearCoatGlossiness() {\n ccGlossiness = 1.0;\n \n #ifdef MAPFLOAT\n ccGlossiness *= material_clearCoatGlossiness;\n #endif\n \n #ifdef MAPTEXTURE\n ccGlossiness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n \n #ifdef MAPVERTEX\n ccGlossiness *= saturate(vVertexColor.$VC);\n #endif\n \n ccGlossiness = 1.0 - ccGlossiness;\n \n ccGlossiness += 0.0000001;\n }\n "},vf=function(e,t,i){t.useLighting=!1,t.emissive.copy(t.diffuse),t.emissiveTint=t.diffuseTint,t.emissiveMap=t.diffuseMap,t.emissiveMapUv=t.diffuseMapUv,t.emissiveMapTiling.copy(t.diffuseMapTiling),t.emissiveMapOffset.copy(t.diffuseMapOffset),t.emissiveMapRotation=t.diffuseMapRotation,t.emissiveMapChannel=t.diffuseMapChannel,t.emissiveVertexColor=t.diffuseVertexColor,t.emissiveVertexColorChannel=t.diffuseVertexColorChannel,t.diffuse.set(0,0,0),t.diffuseTint=!1,t.diffuseMap=null,t.diffuseVertexColor=!1},yf=function(e,t,i){if(t.useMetalnessSpecularColor=!0,e.hasOwnProperty("specularColorTexture")&&(t.specularEncoding="srgb",t.specularMap=i[e.specularColorTexture.index],t.specularMapChannel="rgb",mf(e.specularColorTexture,t,["specular"])),e.hasOwnProperty("specularColorFactor")){var n=e.specularColorFactor;t.specular.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2))}else t.specular.set(1,1,1);e.hasOwnProperty("specularFactor")?t.specularityFactor=e.specularFactor:t.specularityFactor=1,e.hasOwnProperty("specularTexture")&&(t.specularityFactorMapChannel="a",t.specularityFactorMap=i[e.specularTexture.index],mf(e.specularTexture,t,["specularityFactor"]))},xf=function(e,t,i){e.hasOwnProperty("ior")&&(t.refractionIndex=1/e.ior)},bf=function(e,t,i){t.blendType=2,t.useDynamicRefraction=!0,e.hasOwnProperty("transmissionFactor")&&(t.refraction=e.transmissionFactor),e.hasOwnProperty("transmissionTexture")&&(t.refractionMapChannel="r",t.refractionMap=i[e.transmissionTexture.index],mf(e.transmissionTexture,t,["refraction"]))},Sf=function(e,t,i){if(t.useSheen=!0,e.hasOwnProperty("sheenColorFactor")){var n=e.sheenColorFactor;t.sheen.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2))}else t.sheen.set(1,1,1);e.hasOwnProperty("sheenColorTexture")&&(t.sheenMap=i[e.sheenColorTexture.index],t.sheenEncoding="srgb",mf(e.sheenColorTexture,t,["sheen"])),e.hasOwnProperty("sheenRoughnessFactor")?t.sheenGlossiness=e.sheenRoughnessFactor:t.sheenGlossiness=0,e.hasOwnProperty("sheenRoughnessTexture")&&(t.sheenGlossinessMap=i[e.sheenRoughnessTexture.index],t.sheenGlossinessMapChannel="a",mf(e.sheenRoughnessTexture,t,["sheenGlossiness"]));t.chunks.sheenGlossPS="\n #ifdef MAPFLOAT\n uniform float material_sheenGlossiness;\n #endif\n\n #ifdef MAPTEXTURE\n uniform sampler2D texture_sheenGlossinessMap;\n #endif\n\n void getSheenGlossiness() {\n float sheenGlossiness = 1.0;\n\n #ifdef MAPFLOAT\n sheenGlossiness *= material_sheenGlossiness;\n #endif\n\n #ifdef MAPTEXTURE\n sheenGlossiness *= texture2DBias(texture_sheenGlossinessMap, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n sheenGlossiness *= saturate(vVertexColor.$VC);\n #endif\n\n sheenGlossiness = 1.0 - sheenGlossiness;\n sheenGlossiness += 0.0000001;\n sGlossiness = sheenGlossiness;\n }\n "},wf=function(e,t,i){if(t.blendType=2,t.useDynamicRefraction=!0,e.hasOwnProperty("thicknessFactor")&&(t.thickness=e.thicknessFactor),e.hasOwnProperty("thicknessTexture")&&(t.thicknessMap=i[e.thicknessTexture.index],mf(e.thicknessTexture,t,["thickness"])),e.hasOwnProperty("attenuationDistance")&&(t.attenuationDistance=e.attenuationDistance),e.hasOwnProperty("attenuationColor")){var n=e.attenuationColor;t.attenuation.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2))}},Tf=function(e,t,i){e.hasOwnProperty("emissiveStrength")&&(t.emissiveIntensity=e.emissiveStrength)},Af=function(e,t,i){t.useIridescence=!0,e.hasOwnProperty("iridescenceFactor")&&(t.iridescence=e.iridescenceFactor),e.hasOwnProperty("iridescenceTexture")&&(t.iridescenceMapChannel="r",t.iridescenceMap=i[e.iridescenceTexture.index],mf(e.iridescenceTexture,t,["iridescence"])),e.hasOwnProperty("iridescenceIor")&&(t.iridescenceRefractionIndex=e.iridescenceIor),e.hasOwnProperty("iridescenceThicknessMinimum")&&(t.iridescenceThicknessMin=e.iridescenceThicknessMinimum),e.hasOwnProperty("iridescenceThicknessMaximum")&&(t.iridescenceThicknessMax=e.iridescenceThicknessMaximum),e.hasOwnProperty("iridescenceThicknessTexture")&&(t.iridescenceThicknessMapChannel="g",t.iridescenceThicknessMap=i[e.iridescenceThicknessTexture.index],mf(e.iridescenceThicknessTexture,t,["iridescenceThickness"]))},Mf=function(e,t,i){var n,s,r=new Zs;if(r.occludeSpecular=1,r.diffuseTint=!0,r.diffuseVertexColor=!0,r.specularTint=!0,r.specularVertexColor=!0,r.chunks.APIVersion=xi,e.hasOwnProperty("name")&&(r.name=e.name),e.hasOwnProperty("pbrMetallicRoughness")){var a=e.pbrMetallicRoughness;if(a.hasOwnProperty("baseColorFactor")?(n=a.baseColorFactor,r.diffuse.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2)),r.opacity=n[3]):(r.diffuse.set(1,1,1),r.opacity=1),a.hasOwnProperty("baseColorTexture")){var o=a.baseColorTexture;s=t[o.index],r.diffuseMap=s,r.diffuseMapChannel="rgb",r.opacityMap=s,r.opacityMapChannel="a",mf(o,r,["diffuse","opacity"])}if(r.useMetalness=!0,r.specular.set(1,1,1),a.hasOwnProperty("metallicFactor")?r.metalness=a.metallicFactor:r.metalness=1,a.hasOwnProperty("roughnessFactor")?r.shininess=100*a.roughnessFactor:r.shininess=100,a.hasOwnProperty("metallicRoughnessTexture")){var h=a.metallicRoughnessTexture;r.metalnessMap=r.glossMap=t[h.index],r.metalnessMapChannel="b",r.glossMapChannel="g",mf(h,r,["gloss","metalness"])}r.chunks.glossPS="\n #ifdef MAPFLOAT\n uniform float material_shininess;\n #endif\n \n void getGlossiness() {\n dGlossiness = 1.0;\n \n #ifdef MAPFLOAT\n dGlossiness *= material_shininess;\n #endif\n \n #ifdef MAPTEXTURE\n dGlossiness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n \n #ifdef MAPVERTEX\n dGlossiness *= saturate(vVertexColor.$VC);\n #endif\n \n dGlossiness = 1.0 - dGlossiness;\n \n dGlossiness += 0.0000001;\n }\n "}if(e.hasOwnProperty("normalTexture")){var l=e.normalTexture;r.normalMap=t[l.index],mf(l,r,["normal"]),l.hasOwnProperty("scale")&&(r.bumpiness=l.scale)}if(e.hasOwnProperty("occlusionTexture")){var c=e.occlusionTexture;r.aoMap=t[c.index],r.aoMapChannel="r",mf(c,r,["ao"])}if(e.hasOwnProperty("emissiveFactor")?(n=e.emissiveFactor,r.emissive.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2)),r.emissiveTint=!0):(r.emissive.set(0,0,0),r.emissiveTint=!1),e.hasOwnProperty("emissiveTexture")){var u=e.emissiveTexture;r.emissiveMap=t[u.index],mf(u,r,["emissive"])}if(e.hasOwnProperty("alphaMode"))switch(e.alphaMode){case"MASK":r.blendType=3,e.hasOwnProperty("alphaCutoff")?r.alphaTest=e.alphaCutoff:r.alphaTest=.5;break;case"BLEND":r.blendType=2,r.depthWrite=!1;break;default:r.blendType=3}else r.blendType=3;e.hasOwnProperty("doubleSided")?(r.twoSidedLighting=e.doubleSided,r.cull=e.doubleSided?0:1):(r.twoSidedLighting=!1,r.cull=1);var d={KHR_materials_clearcoat:gf,KHR_materials_emissive_strength:Tf,KHR_materials_ior:xf,KHR_materials_iridescence:Af,KHR_materials_pbrSpecularGlossiness:_f,KHR_materials_sheen:Sf,KHR_materials_specular:yf,KHR_materials_transmission:bf,KHR_materials_unlit:vf,KHR_materials_volume:wf};if(e.hasOwnProperty("extensions"))for(var f in e.extensions){var p=d[f];void 0!==p&&p(e.extensions[f],r,t)}return r.update(),r},Cf=function(e,t){var i=new Hn;if(e.hasOwnProperty("name")&&e.name.length>0?i.name=e.name:i.name="node_"+t,e.hasOwnProperty("matrix")&&(df.data.set(e.matrix),df.getTranslation(ff),i.setLocalPosition(ff),df.getEulerAngles(ff),i.setLocalEulerAngles(ff),df.getScale(ff),i.setLocalScale(ff)),e.hasOwnProperty("rotation")){var n=e.rotation;i.setLocalRotation(n[0],n[1],n[2],n[3])}if(e.hasOwnProperty("translation")){var s=e.translation;i.setLocalPosition(s[0],s[1],s[2])}if(e.hasOwnProperty("scale")){var r=e.scale;i.setLocalScale(r[0],r[1],r[2])}return i},Ef=function(e,t){var i="orthographic"===e.type?1:0,n=1===i?e.orthographic:e.perspective,s={enabled:!1,projection:i,nearClip:n.znear,aspectRatioMode:0};n.zfar&&(s.farClip=n.zfar),1===i?(s.orthoHeight=.5*n.ymag,n.ymag&&(s.aspectRatioMode=1,s.aspectRatio=n.xmag/n.ymag)):(s.fov=n.yfov*de.RAD_TO_DEG,n.aspectRatio&&(s.aspectRatioMode=1,s.aspectRatio=n.aspectRatio));var r=new $l(e.name);return r.addComponent("camera",s),r},Pf=function(e,t){var i={enabled:!1,type:"point"===e.type?"omni":e.type,color:e.hasOwnProperty("color")?new me(e.color):me.WHITE,range:e.hasOwnProperty("range")?e.range:9999,falloffMode:1,intensity:e.hasOwnProperty("intensity")?de.clamp(e.intensity,0,2):1};e.hasOwnProperty("spot")&&(i.innerConeAngle=e.spot.hasOwnProperty("innerConeAngle")?e.spot.innerConeAngle*de.RAD_TO_DEG:0,i.outerConeAngle=e.spot.hasOwnProperty("outerConeAngle")?e.spot.outerConeAngle*de.RAD_TO_DEG:Math.PI/4),e.hasOwnProperty("intensity")&&(i.luminance=e.intensity*Ih.getLightUnitConversion(Ch[i.type],i.outerConeAngle,i.innerConeAngle));var n=new $l(t.name);return n.rotateLocal(90,0,0),n.addComponent("light",i),n},Rf=function(e,t,i,n){if(!t.hasOwnProperty("skins")||0===t.skins.length)return[];var s=new Map;return t.skins.map((function(r){return function(e,t,i,n,s,r){var a,o,h,l=t.joints,c=l.length,u=[];if(t.hasOwnProperty("inverseBindMatrices")){var d=t.inverseBindMatrices,f=af(i[d],n,!0),p=[];for(a=0;a<c;a++){for(o=0;o<16;o++)p[o]=f[16*a+o];(h=new Ee).set(p),u.push(h)}}else for(a=0;a<c;a++)h=new Ee,u.push(h);var m=[];for(a=0;a<c;a++)m[a]=s[l[a]].name;var _=m.join("#"),g=r.get(_);return g||(g=new hu(e,u,m),r.set(_,g)),g}(e,r,t.accessors,n,i,s)}))},If=function(e,t,i,n){if(!e.hasOwnProperty("animations")||0===e.animations.length)return[];var s=n&&n.animation&&n.animation.preprocess,r=n&&n.animation&&n.animation.postprocess;return e.animations.map((function(n,a){s&&s(n);var o=function(e,t,i,n,s,r){var a,o=function(e){return new Tu(ef(e.type),of(e,n))},h={STEP:0,LINEAR:1,CUBICSPLINE:2},l={},c={},u={},d=1;for(a=0;a<e.samplers.length;++a){var f=e.samplers[a];l.hasOwnProperty(f.input)||(l[f.input]=o(i[f.input])),c.hasOwnProperty(f.output)||(c[f.output]=o(i[f.output]));var p=f.hasOwnProperty("interpolation")&&h.hasOwnProperty(f.interpolation)?h[f.interpolation]:1,m={paths:[],input:f.input,output:f.output,interpolation:p};u[a]=m}var _=[],g={translation:"localPosition",rotation:"localRotation",scale:"localScale"},v=function(e){for(var t=[];e;)t.unshift(e.name),e=e.parent;return t},y=function(e,t){if(!r)return t;for(var i=0;i<r.length;i++){var n=r[i];if(n.name===e&&n.hasOwnProperty("extras")&&n.extras.hasOwnProperty("targetNames")&&n.extras.targetNames[t])return"name."+n.extras.targetNames[t]}return t},x=function(e,t,i){if(c[e.output])for(var n=c[e.output].data.length/l[e.input].data.length,s=c[e.output].data.length/n,r=0;r<n;r++){for(var o=new Float32Array(s),h=0;h<s;h++)o[h]=c[e.output].data[h*n+r];var f=new Tu(1,o);c[-d]=f;var p={paths:[{entityPath:i,component:"graph",propertyPath:["weight."+y(t.name,r)]}],input:e.input,output:-d,interpolation:e.interpolation};d++,u["morphCurve-"+a+"-"+r]=p}};for(a=0;a<e.channels.length;++a){var b=e.channels[a],S=b.target,w=u[b.sampler],T=s[S.node],A=v(T);S.path.startsWith("weights")?(x(w,T,A),delete u[b.sampler],delete c[w.output]):w.paths.push({entityPath:A,component:"graph",propertyPath:[g[S.path]]})}var M=[],C=[],E=[];for(var P in l)M.push(l[P]),l[P]=M.length-1;for(var R in c)C.push(c[R]),c[R]=C.length-1;for(var I in u){var L=u[I];E.push(new wu(L.paths,l[L.input],c[L.output],L.interpolation)),L.paths.length>0&&"localRotation"===L.paths[0].propertyPath[0]&&2!==L.interpolation&&_.push(E[E.length-1].output)}_.sort();var D,k=null;for(a=0;a<_.length;++a){var O=_[a];if(0===a||O!==k){if(4===(D=C[O]).components)for(var F=D.data,B=F.length-4,N=0;N<B;N+=4)F[N+0]*F[N+4]+F[N+1]*F[N+5]+F[N+2]*F[N+6]+F[N+3]*F[N+7]<0&&(F[N+4]*=-1,F[N+5]*=-1,F[N+6]*=-1,F[N+7]*=-1);k=O}}var U=0;for(a=0;a<M.length;a++)D=M[a]._data,U=Math.max(U,0===D.length?0:D[D.length-1]);return new Ju(e.hasOwnProperty("name")?e.name:"animation_"+t,U,M,C,E)}(n,a,e.accessors,i,t,e.meshes);return r&&r(n,o),o}))},Lf=function(e,t,i,n,s,r){var a=s&&s.global&&s.global.preprocess,o=s&&s.global&&s.global.postprocess;a&&a(t);for(var h=t.asset&&"PlayCanvas"===t.asset.generator,l=function(e,t){if(!e.hasOwnProperty("nodes")||0===e.nodes.length)return[];for(var i=t&&t.node&&t.node.preprocess,n=t&&t.node&&t.node.process||Cf,s=t&&t.node&&t.node.postprocess,r=e.nodes.map((function(e,t){i&&i(e);var r=n(e,t);return s&&s(e,r),r})),a=0;a<e.nodes.length;++a){var o=e.nodes[a];if(o.hasOwnProperty("children"))for(var h=r[a],l={},c=0;c<o.children.length;++c){var u=r[o.children[c]];u.parent||(l.hasOwnProperty(u.name)?u.name+=l[u.name]++:l[u.name]=1,h.addChild(u))}}return r}(t,s),c=function(e,t){var i,n=[],s=e.scenes.length;if(1===s&&1===(null==(i=e.scenes[0].nodes)?void 0:i.length)){var r=e.scenes[0].nodes[0];n.push(t[r])}else for(var a=0;a<s;a++){var o=e.scenes[a];if(o.nodes){for(var h=new Hn(o.name),l=0;l<o.nodes.length;l++){var c=t[o.nodes[l]];h.addChild(c)}n.push(h)}}return n}(t,l),u=function(e,t,i){var n=null;if(e.hasOwnProperty("nodes")&&e.hasOwnProperty("extensions")&&e.extensions.hasOwnProperty("KHR_lights_punctual")&&e.extensions.KHR_lights_punctual.hasOwnProperty("lights")){var s=e.extensions.KHR_lights_punctual.lights;if(s.length){var r=i&&i.light&&i.light.preprocess,a=i&&i.light&&i.light.process||Pf,o=i&&i.light&&i.light.postprocess;e.nodes.forEach((function(e,i){if(e.hasOwnProperty("extensions")&&e.extensions.hasOwnProperty("KHR_lights_punctual")&&e.extensions.KHR_lights_punctual.hasOwnProperty("light")){var h=e.extensions.KHR_lights_punctual.light,l=s[h];if(l){r&&r(l);var c=a(l,t[i]);o&&o(l,c),c&&(n||(n=new Map),n.set(e,c))}}}))}}return n}(t,l,s),d=function(e,t,i){var n=null;if(e.hasOwnProperty("nodes")&&e.hasOwnProperty("cameras")&&e.cameras.length>0){var s=i&&i.camera&&i.camera.preprocess,r=i&&i.camera&&i.camera.process||Ef,a=i&&i.camera&&i.camera.postprocess;e.nodes.forEach((function(i,o){if(i.hasOwnProperty("camera")){var h=e.cameras[i.camera];if(h){s&&s(h);var l=r(h,t[o]);a&&a(h,l),l&&(n||(n=new Map),n.set(i,l))}}}))}return n}(t,l,s),f=If(t,l,i,s),p=function(e,t,i,n){if(!e.hasOwnProperty("materials")||0===e.materials.length)return[];var s=i&&i.material&&i.material.preprocess,r=i&&i.material&&i.material.process||Mf,a=i&&i.material&&i.material.postprocess;return e.materials.map((function(e){s&&s(e);var i=r(e,t,n);return a&&a(e,i),i}))}(t,n.map((function(e){return e.resource})),s,h),m=function(e){if(!e.hasOwnProperty("extensions")||!e.extensions.hasOwnProperty("KHR_materials_variants"))return null;for(var t=e.extensions.KHR_materials_variants.variants,i={},n=0;n<t.length;n++)i[t[n].name]=n;return i}(t),_={},g={},v=function(e,t,i,n,s,r,a,o){if(!t.hasOwnProperty("meshes")||0===t.meshes.length||!t.hasOwnProperty("accessors")||0===t.accessors.length||!t.hasOwnProperty("bufferViews")||0===t.bufferViews.length)return[];var h={};return t.meshes.map((function(l){return pf(e,l,t.accessors,i,n,s,h,r,a,o)}))}(e,t,i,r,h,_,g,s),y=Rf(e,t,l,i),x=[],b=0;b<v.length;b++)x[b]=new qd,x[b].meshes=v[b];!function(e,t,i){e.nodes.forEach((function(e){e.hasOwnProperty("mesh")&&e.hasOwnProperty("skin")&&t[e.mesh].meshes.forEach((function(t){t.skin=i[e.skin]}))}))}(t,x,y);var S=new Qd(t);S.nodes=l,S.scenes=c,S.animations=f,S.textures=n,S.materials=p,S.variants=m,S.meshVariants=_,S.meshDefaultMaterials=g,S.renders=x,S.skins=y,S.lights=u,S.cameras=d,o&&o(t,S),r(null,S)},Df=0,kf=function(e,t,i,n,s,r,a){var o=r&&r.image&&r.image.preprocess,h=r&&r.image&&r.image.processAsync||function(e,t){t(null,null)},l=r&&r.image&&r.image.postprocess,c=function(t){l&&l(e,t),a(null,t)},u={"image/png":"png","image/jpeg":"jpg","image/basis":"basis","image/ktx":"ktx","image/ktx2":"ktx2","image/vnd-ms.dds":"dds"},d=function(t,i,n,r){var o=(e.name||"gltf-texture")+"-"+Df++,h={url:t||o};if(i&&(h.contents=i.slice(0).buffer),n){var l=u[n];l&&(h.filename=h.url+"."+l)}var d=new ml(o,"texture",h,null,r);d.on("load",c),d.on("error",a),s.add(d),s.load(d)};o&&o(e),h(e,(function(s,r){var o;s?a(s):r?c(r):e.hasOwnProperty("uri")?Jd(e.uri)?d(e.uri,null,(o=e.uri).substring(o.indexOf(":")+1,o.indexOf(";")),null):d(v.join(n,e.uri),null,null,{crossOrigin:"anonymous"}):e.hasOwnProperty("bufferView")&&e.hasOwnProperty("mimeType")?d(null,i[e.bufferView],e.mimeType,null):a("Invalid image found in gltf (neither uri or bufferView found). index="+t)}))},Of=function(e,t){var i=JSON.parse(function(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);for(var t="",i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return decodeURIComponent(escape(t))}(e));if(i.asset&&i.asset.version&&parseFloat(i.asset.version)<2)t("Invalid gltf version. Expected version 2.0 or above but found version '"+i.asset.version+"'.");else{var n=(null==i?void 0:i.extensionsRequired)||[];Zd||$d()||-1===n.indexOf("KHR_draco_mesh_compression")?t(null,i):K.getInstance("DracoDecoderModule",(function(e){Zd=e,t(null,i)}))}},Ff=function(e,t,i){e&&e.toLowerCase().endsWith(".glb")?function(e,t){var i=e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),n=i.getUint32(0,!0),s=i.getUint32(4,!0),r=i.getUint32(8,!0);if(1179937895===n)if(2===s)if(r<=0||r>i.byteLength)t("Invalid length found in glb header. Found "+r);else{for(var a=[],o=12;o<r;){var h=i.getUint32(o,!0);if(o+h+8>i.byteLength)throw new Error("Invalid chunk length found in glb. Found "+h);var l=i.getUint32(o+4,!0),c=new Uint8Array(i.buffer,i.byteOffset+o+8,h);a.push({length:h,type:l,data:c}),o+=h+8}1===a.length||2===a.length?1313821514===a[0].type?a.length>1&&5130562!==a[1].type?t("Invalid chunk type found in glb file. Expected 0x004E4942, found 0x"+a[1].type.toString(16)):t(null,{gltfChunk:a[0].data,binaryChunk:2===a.length?a[1].data:null}):t("Invalid chunk type found in glb file. Expected 0x4E4F534A, found 0x"+a[0].type.toString(16)):t("Invalid number of chunks found in glb file.")}else t("Invalid version number found in glb header. Expected 2, found "+s);else t("Invalid magic number found in glb header. Expected 0x46546C67, found 0x"+n.toString(16))}(t,i):i(null,{gltfChunk:t,binaryChunk:null})},Bf=function(e,t,i,n){var s=[],r=i&&i.bufferView&&i.bufferView.preprocess,a=i&&i.bufferView&&i.bufferView.processAsync||function(e,t,i){i(null,null)},o=i&&i.bufferView&&i.bufferView.postprocess,h=e.bufferViews?e.bufferViews.length:0;if(h)for(var l=function(t,i){var r=e.bufferViews[t];r.hasOwnProperty("byteStride")&&(i.byteStride=r.byteStride),s[t]=i,o&&o(r,i),0==--h&&n(null,s)},c=0;c<e.bufferViews.length;++c){var u=e.bufferViews[c];r&&r(u),a(u,t,function(e,i,s,r){if(s)n(s);else if(r)l(e,r);else{var a=t[i.buffer],o=new Uint8Array(a.buffer,a.byteOffset+(i.byteOffset||0),i.byteLength);l(e,o)}}.bind(null,c,u))}else n(null,null)},Nf=function(){function e(e,t,i){this._device=e,this._assets=t,this._defaultMaterial=Mf({name:"defaultGlbMaterial"},[]),this.maxRetries=i}e.parseAsync=function(e,t,i,n,s,r,a){Ff(e,i,(function(e,i){e?a(e):Of(i.gltfChunk,(function(e,o){e?a(e):function(e,t,i,n,s){var r=[];if(e.buffers&&0!==e.buffers.length)for(var a=n&&n.buffer&&n.buffer.preprocess,o=n&&n.buffer&&n.buffer.processAsync||function(e,t){t(null,null)},h=n&&n.buffer&&n.buffer.postprocess,l=e.buffers.length,c=function(t,i){r[t]=i,h&&h(e.buffers[t],i),0==--l&&s(null,r)},u=0;u<e.buffers.length;++u){var d=e.buffers[u];a&&a(d),o(d,function(e,n,r,a){if(r)s(r);else if(a)c(e,new Uint8Array(a));else if(n.hasOwnProperty("uri"))if(Jd(n.uri)){for(var o=atob(n.uri.split(",")[1]),h=new Uint8Array(o.length),l=0;l<o.length;l++)h[l]=o.charCodeAt(l);c(e,h)}else pe.get(v.join(i,n.uri),{cache:!0,responseType:"arraybuffer",retry:!1},function(e,t,i){t?s(t):c(e,new Uint8Array(i))}.bind(null,e));else c(e,t)}.bind(null,u,d))}else s(null,r)}(o,i.binaryChunk,t,r,(function(e,i){e?a(e):Bf(o,i,r,(function(e,i){e?a(e):function(e,t,i,n,s,r){if(e.hasOwnProperty("images")&&0!==e.images.length&&e.hasOwnProperty("textures")&&0!==e.textures.length)for(var a=s&&s.texture&&s.texture.preprocess,o=s&&s.texture&&s.texture.processAsync||function(e,t,i){i(null,null)},h=s&&s.texture&&s.texture.postprocess,l=[],c=[],u=e.textures.length,d=function(t,i){if(c[i]||(c[i]=[]),c[i].push(t),0==--u){var n=[];c.forEach((function(t,i){t.forEach((function(t,s){var r,a,o,c,u=0===s?l[i]:cf(l[i]);r=u.resource,a=(e.samplers||[])[e.textures[t].sampler],o=function(e,t){switch(e){case 9728:return 0;case 9729:return 1;case 9984:return 2;case 9985:return 4;case 9986:return 3;case 9987:return 5;default:return t}},c=function(e,t){switch(e){case 33071:return 1;case 33648:return 2;case 10497:return 0;default:return t}},r&&(a=a||{},r.minFilter=o(a.minFilter,5),r.magFilter=o(a.magFilter,1),r.addressU=c(a.wrapS,0),r.addressV=c(a.wrapT,0)),n[t]=u,h&&h(e.textures[t],u)}))})),r(null,n)}},f=0;f<e.textures.length;++f){var p=e.textures[f];a&&a(p),o(p,e.images,function(a,o,h,c){var u,f;if(h)r(h);else if(null==c&&void 0===(c=null==o||null==(u=o.extensions)||null==(f=u.KHR_texture_basisu)?void 0:f.source)&&(c=o.source),l[c])d(a,c);else{var p=e.images[c];kf(p,a,t,i,n,s,(function(e,t){e?r(e):(l[c]=t,d(a,c))}))}}.bind(null,f,p))}else r(null,[])}(o,i,t,s,r,(function(e,t){e?a(e):Lf(n,o,i,t,r,a)}))}))}))}))}))},e.parse=function(e,t,i,n){var s=null;return n=n||{},Ff(e,t,(function(e,t){e?console.error(e):Of(t.gltfChunk,(function(e,r){e?console.error(e):Bf(r,[t.binaryChunk],n,(function(e,t){e?console.error(e):Lf(i,r,t,[],n,(function(e,t){e?console.error(e):s=t}))}))}))})),s};var t=e.prototype;return t._getUrlWithoutParams=function(e){return e.indexOf("?")>=0?e.split("?")[0]:e},t.load=function(t,i,n){var s=this;ml.fetchArrayBuffer(t.load,(function(r,a){r?i(r):e.parseAsync(s._getUrlWithoutParams(t.original),v.extractPath(t.load),a,s._device,n.registry,n.options,(function(e,t){e?i(e):i(null,new Kd(t,n,s._assets,s._defaultMaterial))}))}),n,this.maxRetries)},t.open=function(e,t,i){return t},t.patch=function(e,t){},e}(),Uf=function(){function e(e){this.handlerType="animation",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};(e.load.startsWith("blob:")||e.load.startsWith("data:"))&&(".glb"===v.getExtension(e.original).toLowerCase()?i.responseType=fe.ResponseType.ARRAY_BUFFER:i.responseType=fe.ResponseType.JSON),pe.get(e.load,i,(function(i,n){i?t("Error loading animation resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t,i){if(".glb"===v.getExtension(e).toLowerCase()){var n=Nf.parse("filename.glb",t,null);if(n){var s,r=n.animations;if(null!=i&&null!=(s=i.data)&&s.events)for(var a=0;a<r.length;a++)r[a].events=new Qu(Object.values(i.data.events));return n.destroy(),r}return null}return this["_parseAnimationV"+t.animation.version](t)},t.patch=function(e,t){},t._parseAnimationV3=function(e){var t=e.animation,i=new _u;i.name=t.name,i.duration=t.duration;for(var n=0;n<t.nodes.length;n++){var s=new mu,r=t.nodes[n];s._name=r.name;for(var a=0;a<r.keys.length;a++){var o=r.keys[a],h=o.time,l=o.pos,c=o.rot,u=o.scale,d=new ye(l[0],l[1],l[2]),f=(new Pe).setFromEulerAngles(c[0],c[1],c[2]),p=new ye(u[0],u[1],u[2]),m=new pu(h,d,f,p);s._keys.push(m)}i.addNode(s)}return i},t._parseAnimationV4=function(e){var t=e.animation,i=new _u;i.name=t.name,i.duration=t.duration;for(var n=0;n<t.nodes.length;n++){var s=new mu,r=t.nodes[n];s._name=r.name;for(var a=r.defaults.p,o=r.defaults.r,h=r.defaults.s,l=0;l<r.keys.length;l++){var c=r.keys[l],u=c.t,d=a||c.p,f=o||c.r,p=h||c.s,m=new ye(d[0],d[1],d[2]),_=(new Pe).setFromEulerAngles(f[0],f[1],f[2]),g=new ye(p[0],p[1],p[2]),v=new pu(u,m,_,g);s._keys.push(v)}i.addNode(s)}return i},e}(),zf=function(){if("undefined"==typeof window)return!1;var e=window.navigator.userAgent,t=e.indexOf("MSIE ");if(t>0)return parseInt(e.substring(t+5,e.indexOf(".",t)),10);if(e.indexOf("Trident/")>0){var i=e.indexOf("rv:");return parseInt(e.substring(i+3,e.indexOf(".",i)),10)}return!1}(),Vf=[".ogg",".mp3",".wav",".mp4a",".m4a",".mp4",".aac",".opus"],Gf=function(){function e(e){this.handlerType="audio",this.manager=e.soundManager,this.maxRetries=0}var t=e.prototype;return t._isSupported=function(e){var t=v.getExtension(e);return Vf.indexOf(t)>-1},t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i=function(i){var n="Error loading audio url: "+e.original;i&&(n+=": "+(i.message||i)),console.warn(n),t(n)};if(this._createSound){if(!this._isSupported(e.original))return void i("Audio format for "+e.original+" not supported");this._createSound(e.load,(function(e){t(null,new Cd(e))}),i)}else i(null)},t.open=function(e,t){return t},t.patch=function(e,t){},t._createSound=function(e,t,i){if(yd()){var n=this.manager;if(!n.context)return void i("Audio manager has no audio context");var s={retry:this.maxRetries>0,maxRetries:this.maxRetries};(e.startsWith("blob:")||e.startsWith("data:"))&&(s.responseType=fe.ResponseType.ARRAY_BUFFER),pe.get(e,s,(function(e,s){e?i(e):n.context.decodeAudioData(s,t,i)}))}else{var r=null;try{r=new Audio}catch(e){return void i("No support for Audio element")}zf&&document.body.appendChild(r);r.onerror=function(){r.onerror=null,zf&&document.body.removeChild(r),i()},r.addEventListener("canplaythrough",(function e(){r.removeEventListener("canplaythrough",e),zf&&document.body.removeChild(r),t(r)})),r.src=e}},e}(),Wf=function(){function e(e){this.handlerType="binary",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),pe.get(e.load,{responseType:fe.ResponseType.ARRAY_BUFFER,retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?t("Error loading binary resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}(),Hf=function(){function e(){}var t=e.prototype;return t.instantiateModelEntity=function(e){return null},t.instantiateRenderEntity=function(e){return null},t.getMaterialVariants=function(){return null},t.applyMaterialVariant=function(e,t){},t.applyMaterialVariantInstances=function(e,t){},e}(),Xf=function(){function e(e){this.handlerType="container",this.glbParser=new Nf(e.graphicsDevice,e.assets,0),this.parsers={}}var t=e.prototype;return t._getUrlWithoutParams=function(e){return e.indexOf("?")>=0?e.split("?")[0]:e},t._getParser=function(e){var t=e?v.getExtension(this._getUrlWithoutParams(e)).toLowerCase().replace(".",""):null;return this.parsers[t]||this.glbParser},t.load=function(e,t,i){"string"==typeof e&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,i)},t.open=function(e,t,i){return this._getParser(e).open(e,t,i)},t.patch=function(e,t){},$(e,[{key:"maxRetries",get:function(){return this.glbParser.maxRetries},set:function(e){for(var t in this.glbParser.maxRetries=e,this.parsers)this.parsers.hasOwnProperty(t)&&(this.parsers[t].maxRetries=e)}}]),e}(),qf=function(){function e(e){this.handlerType="css",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),pe.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?t("Error loading css resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}();var jf=function(){function e(e){this.handlerType="cubemap",this._device=e.graphicsDevice,this._registry=e.assets,this._loader=e.loader}var t=e.prototype;return t.load=function(e,t,i){this.loadAssets(i,t)},t.open=function(e,t,i){return i?i.resource:null},t.patch=function(e,t){this.loadAssets(e,(function(i,n){i&&(t.fire("error",e),t.fire("error:"+e.id,i,e),e.fire("error",e))}))},t.getAssetIds=function(e){var t=[];if(t[0]=e.file,(e.loadFaces||!e.file)&&e.data&&e.data.textures)for(var i=0;i<6;++i)t[i+1]=e.data.textures[i];else t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=null;return t},t.compareAssetIds=function(e,t){return e&&t?parseInt(e,10)===e||"string"==typeof e?e===t:e.url===t.url:null!==e==(null!==t)},t.update=function(e,t,i){var n,s,r,a=e.data||{},o=e._handlerState.assets,h=e._resources,l=[null,null,null,null,null,null,null],c=function(){return a.hasOwnProperty("type")?a.type:a.hasOwnProperty("rgbm")?a.rgbm?$t:Zt:null};if(e.loaded&&i[0]===o[0])l[1]=h[1]||null,l[2]=h[2]||null,l[3]=h[3]||null,l[4]=h[4]||null,l[5]=h[5]||null,l[6]=h[6]||null;else if(i[0])for(n=i[0].resource,r=0;r<6;++r)l[r+1]=new wn(this._device,{name:e.name+"_prelitCubemap"+(n.width>>r),cubemap:!0,type:c()||n.type,width:n.width>>r,height:n.height>>r,format:n.format,levels:[n._levels[r]],fixCubemapSeams:!0,addressU:1,addressV:1,mipmaps:0===r});var u=i.slice(1);if(e.loaded&&this.cmpArrays(u,o.slice(1)))l[0]=h[0]||null;else if(-1===u.indexOf(null)){var d=u.map((function(e){return e.resource})),f=[];for(s=0;s<d[0]._levels.length;++s)f.push(d.map((function(e){return e._levels[s]})));var p=d[0].format,m=new wn(this._device,{name:e.name+"_faces",cubemap:!0,type:c()||d[0].type,width:d[0].width,height:d[0].height,format:6===p?7:p,levels:f,minFilter:a.hasOwnProperty("minFilter")?a.minFilter:d[0].minFilter,magFilter:a.hasOwnProperty("magFilter")?a.magFilter:d[0].magFilter,anisotropy:a.hasOwnProperty("anisotropy")?a.anisotropy:1,addressU:1,addressV:1,fixCubemapSeams:!!i[0]});l[0]=m}if(!this.cmpArrays(l,h))for(e.resources=l,e._handlerState.assetIds=t,e._handlerState.assets=i,r=0;r<h.length;++r)null!==h[r]&&-1===l.indexOf(h[r])&&h[r].destroy();for(r=0;r<o.length;++r)null!==o[r]&&-1===i.indexOf(o[r])&&o[r].unload()},t.cmpArrays=function(e,t){if(e.length!==t.length)return!1;for(var i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0},t.resolveId=function(e){var t=parseInt(e,10);return t===e||t.toString()===e?t:e},t.loadAssets=function(e,t){e.hasOwnProperty("_handlerState")||(e._handlerState={assetIds:[null,null,null,null,null,null,null],assets:[null,null,null,null,null,null,null]});for(var i,n=this,s=n.getAssetIds(e),r=[null,null,null,null,null,null,null],a=e._handlerState.assetIds,o=e._handlerState.assets,h=n._registry,l=7,c=function(i,a){r[i]=a,0===--l&&(n.update(e,s,r),t(null,e.resources))},u=function(e,i,n){t(i)},d=function(e,t){t.loaded?c(e,t):(h.once("load:"+t.id,c.bind(n,e)),h.once("error:"+t.id,u.bind(n,e)),t.loading||h.load(t))},f=0;f<7;++f){var p=this.resolveId(s[f]);if(p)if(n.compareAssetIds(p,a[f]))c(f,o[f]);else if(parseInt(p,10)===p)(i=h.get(p))?d(f,i):setTimeout(function(e,t){var i=h.get(t);i?d(e,i):u(0,"failed to find dependent cubemap asset="+t)}.bind(null,f,p));else{var m="string"==typeof p?{url:p,filename:p}:p;i=new ml(e.name+"_part_"+f,"texture",m),h.add(i),h.once("load:"+i.id,c.bind(n,f)),h.once("error:"+i.id,u.bind(n,f)),h.load(i)}else c(f,null)}},e}(),Yf=function(){function e(){this.handlerType="folder"}var t=e.prototype;return t.load=function(e,t){t(null,null)},t.open=function(e,t){return t},e}();function Kf(e){return e.version<3&&(e.version<2&&(e.info.maps=e.info.maps||[{width:e.info.width,height:e.info.height}]),e.chars=Object.keys(e.chars||{}).reduce((function(t,i){var n=e.chars[i],s=void 0!==n.letter?n.letter:q.fromCodePoint(i);return e.version<2&&(n.map=n.map||0),t[s]=n,t}),{}),e.version=3),e}var Zf=function(){function e(e){this.handlerType="font",this._loader=e.loader,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t,i){"string"==typeof e&&(e={load:e,original:e});var n=this;".json"===v.getExtension(e.original)?pe.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,s){if(i)t("Error loading font resource: "+e.original+" ["+i+"]");else{var r=Kf(s);n._loadTextures(e.load.replace(".json",".png"),r,(function(e,i){if(e)return t(e);t(null,{data:r,textures:i})}))}})):(i&&i.data&&(i.data=Kf(i.data)),this._loadTextures(e.load,i&&i.data,t))},t._loadTextures=function(e,t,i){for(var n=t.info.maps.length,s=0,r=null,a=new Array(n),o=this._loader,h=function(t){var h=function(e,o){if(!r){if(e)return r=e,i(e);o.upload(),a[t]=o,++s===n&&i(null,a)}};0===t?o.load(e,"texture",h):o.load(e.replace(".png",t+".png"),"texture",h)},l=0;l<n;l++)h(l)},t.open=function(e,t,i){return t.textures?new fd(t.textures,t.data):new fd(t,null)},t.patch=function(e,t){var i=e.resource;!i.data&&e.data?i.data=e.data:!e.data&&i.data&&(e.data=i.data),e.data&&(e.data=Kf(e.data))},e}(),$f=function(e,t,i){var n,s,r=i.singleVecs,a=t.___1;a||(n=i.tripleVecs,s=t.___2);var o=a?a[0]:n[s];e.setLocalPosition(r[o],r[o+1],r[o+2]),o=a?a[1]:n[s+1],e.setLocalEulerAngles(r[o],r[o+1],r[o+2]),o=a?a[2]:n[s+2],e.setLocalScale(r[o],r[o+1],r[o+2])},Qf=function(e,t){var i=e.charCodeAt(0)-t.fieldFirstCode;return t.fieldArray[i]},Jf=function(e,t){for(var i=0,n=0;n<e.length;n++)i=i*t.fieldCodeBase+e.charCodeAt(n)-t.fieldFirstCode;return t.fieldArray[i]},ep=function(){function e(e,t){this._node=e,this._data=t}var t=e.prototype;return t.run=function(){var e=Object.prototype.toString.call(this._node);return"[object Object]"===e?this._handleMap():"[object Array]"===e?this._handleArray():this._result=this._node,this._result},t._handleMap=function(){this._result={},Object.keys(this._node).forEach(this._handleKey,this)},t._handleKey=function(t){var i=t,n=t.length;1===n?i=Qf(t,this._data):2===n&&(i=Jf(t,this._data)),this._result[i]=new e(this._node[t],this._data).run()},t._handleArray=function(){this._result=[],this._node.forEach(this._handleArElt,this)},t._handleArElt=function(t){var i=new e(t,this._data).run();this._result.push(i)},e}(),tp=function(){function e(e,t){this._app=e,this._isTemplate=t}var t=e.prototype;return t.parse=function(e){var t={},i=null,n=e.compressedFormat;for(var s in n&&!e.entDecompressed&&(e.entDecompressed=!0,e.entities=new ep(e.entities,n).run()),e.entities){var r=e.entities[s],a=this._createEntity(r,n);t[s]=a,null===r.parent&&(i=a)}for(var o in e.entities)for(var h=t[o],l=e.entities[o].children,c=l.length,u=0;u<c;u++){var d=t[l[u]];d&&h.addChild(d)}return this._openComponentData(i,e.entities),i},t._createEntity=function(e,t){var i=new $l(e.name,this._app);if(i.setGuid(e.resource_id),this._setPosRotScale(i,e,t),i._enabled=void 0===e.enabled||e.enabled,this._isTemplate?i._template=!0:i._enabledInHierarchy=i._enabled,i.template=e.template,e.tags)for(var n=0;n<e.tags.length;n++)i.tags.add(e.tags[n]);return e.labels&&e.labels.forEach((function(e){i.addLabel(e)})),i},t._setPosRotScale=function(e,t,i){if(i)$f(e,t,i);else{var n=t.position,s=t.rotation,r=t.scale;e.setLocalPosition(n[0],n[1],n[2]),e.setLocalEulerAngles(s[0],s[1],s[2]),e.setLocalScale(r[0],r[1],r[2])}},t._openComponentData=function(e,t){for(var i=this._app.systems.list,n=i.length,s=t[e.getGuid()],r=0;r<n;r++){var a=i[r],o=s.components[a.id];o&&a.addComponent(e,o)}n=s.children.length;for(var h=e._children,l=0;l<n;l++)h[l]=this._openComponentData(h[l],t);return e},e}(),ip=function(e,t,i){"string"==typeof e&&(e={load:e,original:e}),pe.get(e.load,{retry:t>0,maxRetries:t},(function(t,n){if(t){var s="Error while loading scene JSON "+e.original;t.message?(s+=": "+t.message,t.stack&&(s+="\n"+t.stack)):s+=": "+t,i(s)}else i(t,n)}))},np=function(){function e(e){this.handlerType="hierarchy",this._app=e,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){ip(e,this.maxRetries,t)},t.open=function(e,t){this._app.systems.script.preloading=!0;var i=new tp(this._app,!1).parse(t);return this._app.systems.script.preloading=!1,i},e}(),sp=function(){function e(e){this.handlerType="html",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),pe.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?t("Error loading html resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}(),rp=function(){function e(e){this.handlerType="json",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=fe.ResponseType.JSON),pe.get(e.load,i,(function(i,n){i?t("Error loading JSON resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}(),ap=function(){function e(){this.removeInvalid=!0,this.valid=!0,this.enumValidators={occludeSpecular:this._createEnumValidator([0,1,2]),cull:this._createEnumValidator([0,1,2,3]),blendType:this._createEnumValidator([0,1,2,3,4,5,6,7,8,9,10]),depthFunc:this._createEnumValidator([0,1,2,3,4,5,6,7]),shadingModel:this._createEnumValidator([0,1])}}var t=e.prototype;return t.setInvalid=function(e,t){this.valid=!1,this.removeInvalid&&delete t[e]},t.validate=function(e){var t=Vs,i=qs,n="path"===e.mappingFormat;for(var s in e){var r=t[s];if(r)if(r.startsWith("enum")){var a=r.split(":")[1];this.enumValidators[a]&&(this.enumValidators[a](e[s])||this.setInvalid(s,e))}else if("number"===r)"number"!=typeof e[s]&&this.setInvalid(s,e);else if("boolean"===r)"boolean"!=typeof e[s]&&this.setInvalid(s,e);else if("string"===r)"string"!=typeof e[s]&&this.setInvalid(s,e);else if("vec2"===r)e[s]instanceof Array&&2===e[s].length||this.setInvalid(s,e);else if("rgb"===r)e[s]instanceof Array&&3===e[s].length||this.setInvalid(s,e);else if("texture"===r)n?"string"!=typeof e[s]&&null!==e[s]&&(e[s]instanceof wn||this.setInvalid(s,e)):"number"!=typeof e[s]&&null!==e[s]&&(e[s]instanceof wn||this.setInvalid(s,e));else if("boundingbox"===r)e[s].center&&e[s].center instanceof Array&&3===e[s].center.length||this.setInvalid(s,e),e[s].halfExtents&&e[s].halfExtents instanceof Array&&3===e[s].halfExtents.length||this.setInvalid(s,e);else if("cubemap"===r)"number"!=typeof e[s]&&null!==e[s]&&void 0!==e[s]&&(e[s]instanceof wn&&e[s].cubemap||this.setInvalid(s,e));else if("chunks"===r)for(var o=Object.keys(e[s]),h=0;h<o.length;h++)"string"!=typeof e[s][o[h]]&&this.setInvalid(o[h],e[s]);else console.error("Unknown material type: "+r);else i[s]?delete e[s]:this.valid=!1}return e.validated=!0,this.valid},t._createEnumValidator=function(e){return function(t){return e.indexOf(t)>=0}},e}(),op=function(){function e(){this._validator=null}var t=e.prototype;return t.parse=function(e){var t=this.migrate(e),i=this._validate(t),n=new Zs;return this.initialize(n,i),n},t.initialize=function(e,t){for(var i in t.validated||(t=this._validate(t)),t.chunks&&(e.chunks=Q({},t.chunks)),t){var n=Vs[i],s=t[i];if("vec2"===n)e[i]=new be(s[0],s[1]);else if("rgb"===n)e[i]=new me(s[0],s[1],s[2]);else if("texture"===n)s instanceof wn?e[i]=s:e[i]instanceof wn&&"number"==typeof s&&s>0||(e[i]=null);else if("cubemap"===n)s instanceof wn?e[i]=s:e[i]instanceof wn&&"number"==typeof s&&s>0||(e[i]=null),"cubeMap"!==i||s||(e.prefilteredCubemaps=null);else if("boundingbox"===n){var r=new ye(s.center[0],s.center[1],s.center[2]),a=new ye(s.halfExtents[0],s.halfExtents[1],s.halfExtents[2]);e[i]=new Oe(r,a)}else e[i]=t[i]}e.update()},t.migrate=function(e){var t;void 0===e.shadingModel&&("blinn"===e.shader?e.shadingModel=1:e.shadingModel=0),e.shader&&delete e.shader,e.mapping_format&&(e.mappingFormat=e.mapping_format,delete e.mapping_format);var i=[["bumpMapFactor","bumpiness"],["aoUvSet","aoMapUv"],["aoMapVertexColor","aoVertexColor"],["diffuseMapVertexColor","diffuseVertexColor"],["emissiveMapVertexColor","emissiveVertexColor"],["specularMapVertexColor","specularVertexColor"],["metalnessMapVertexColor","metalnessVertexColor"],["opacityMapVertexColor","opacityVertexColor"],["glossMapVertexColor","glossVertexColor"],["lightMapVertexColor","lightVertexColor"],["diffuseMapTint","diffuseTint"],["specularMapTint","specularTint"],["emissiveMapTint","emissiveTint"],["metalnessMapTint","metalnessTint"]];for(t=0;t<i.length;t++){var n=i[t][0],s=i[t][1];void 0!==e[n]&&void 0===e[s]&&(e[s]=e[n],delete e[n])}var r=["fresnelFactor","shadowSampleType"];for(t=0;t<r.length;t++){var a=r[t];e.hasOwnProperty(a)&&delete e[a]}return e},t._validate=function(e){return e.validated||(this._validator||(this._validator=new ap),this._validator.validate(e)),e},e}(),hp=function(){function e(e,t,i,n,s){this.propertyName=e,this.parent=t,this._scope=s,this._registry=i,this.id=null,this.url=null,this.asset=null,this._onAssetLoad=n.load,this._onAssetAdd=n.add,this._onAssetRemove=n.remove,this._onAssetUnload=n.unload}var t=e.prototype;return t._bind=function(){this.id&&(this._onAssetLoad&&this._registry.on("load:"+this.id,this._onLoad,this),this._onAssetAdd&&this._registry.once("add:"+this.id,this._onAdd,this),this._onAssetRemove&&this._registry.on("remove:"+this.id,this._onRemove,this),this._onAssetUnload&&this._registry.on("unload:"+this.id,this._onUnload,this)),this.url&&(this._onAssetLoad&&this._registry.on("load:url:"+this.url,this._onLoad,this),this._onAssetAdd&&this._registry.once("add:url:"+this.url,this._onAdd,this),this._onAssetRemove&&this._registry.on("remove:url:"+this.url,this._onRemove,this))},t._unbind=function(){this.id&&(this._onAssetLoad&&this._registry.off("load:"+this.id,this._onLoad,this),this._onAssetAdd&&this._registry.off("add:"+this.id,this._onAdd,this),this._onAssetRemove&&this._registry.off("remove:"+this.id,this._onRemove,this),this._onAssetUnload&&this._registry.off("unload:"+this.id,this._onUnload,this)),this.url&&(this._onAssetLoad&&this._registry.off("load:"+this.url,this._onLoad,this),this._onAssetAdd&&this._registry.off("add:"+this.url,this._onAdd,this),this._onAssetRemove&&this._registry.off("remove:"+this.url,this._onRemove,this))},t._onLoad=function(e){this._onAssetLoad.call(this._scope,this.propertyName,this.parent,e)},t._onAdd=function(e){this.asset=e,this._onAssetAdd.call(this._scope,this.propertyName,this.parent,e)},t._onRemove=function(e){this._onAssetRemove.call(this._scope,this.propertyName,this.parent,e),this.asset=null},t._onUnload=function(e){this._onAssetUnload.call(this._scope,this.propertyName,this.parent,e)},$(e,[{key:"id",get:function(){return this._id},set:function(e){if(this.url)throw Error("Can't set id and url");this._unbind(),this._id=e,this.asset=this._registry.get(this._id),this._bind()}},{key:"url",get:function(){return this._url},set:function(e){if(this.id)throw Error("Can't set id and url");this._unbind(),this._url=e,this.asset=this._registry.getByUrl(this._url),this._bind()}}]),e}(),lp={aoMap:"white",diffuseMap:"gray",specularMap:"gray",specularityFactorMap:"white",metalnessMap:"black",glossMap:"gray",sheenMap:"black",sheenGlossinessMap:"gray",clearCoatMap:"black",clearCoatGlossMap:"gray",clearCoatNormalMap:"normal",refractionMap:"white",emissiveMap:"gray",normalMap:"normal",heightMap:"gray",opacityMap:"gray",sphereMap:"gray",lightMap:"white"},cp=function(){function e(e){this.handlerType="material",this._assets=e.assets,this._device=e.graphicsDevice,this._placeholderTextures=null,this._parser=new op,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),pe.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?t&&t("Error loading material: "+e.original+" ["+i+"]"):t&&(n._engine=!0,t(null,n))}))},t.open=function(e,t){var i=this._parser.parse(t);return t._engine&&(i._data=t,delete t._engine),i},t._createPlaceholders=function(){this._placeholderTextures={};var e={white:[255,255,255,255],gray:[128,128,128,255],black:[0,0,0,255],normal:[128,128,255,255]};for(var t in e)if(e.hasOwnProperty(t)){this._placeholderTextures[t]=new wn(this._device,{width:2,height:2,format:7,name:"material_placeholder"});for(var i=this._placeholderTextures[t].lock(),n=0;n<4;n++)for(var s=0;s<4;s++)i[4*n+s]=e[t][s];this._placeholderTextures[t].unlock()}},t.patch=function(e,t){e.resource._data&&(e._data=e.resource._data,delete e.resource._data),e.data.name=e.name,e.resource.name=e.name,this._bindAndAssignAssets(e,t),e.off("unload",this._onAssetUnload,this),e.on("unload",this._onAssetUnload,this)},t._onAssetUnload=function(e){delete e.data.parameters,delete e.data.chunks,delete e.data.name},t._assignTexture=function(e,t,i){t.resource[e]=i},t._getPlaceholderTexture=function(e){this._placeholderTextures||this._createPlaceholders();var t=lp[e];return this._placeholderTextures[t]},t._assignPlaceholderTexture=function(e,t){t.resource[e]=this._getPlaceholderTexture(e)},t._onTextureLoad=function(e,t,i){this._assignTexture(e,t,i.resource),t.resource.update()},t._onTextureAdd=function(e,t,i){this._assets.load(i)},t._onTextureRemoveOrUnload=function(e,t,i){var n=t.resource;n&&t.resource[e]===i.resource&&(this._assignPlaceholderTexture(e,t),n.update())},t._assignCubemap=function(e,t,i){t.resource[e]=i[0],"cubeMap"===e&&(t.resource.prefilteredCubemaps=i.slice(1))},t._onCubemapLoad=function(e,t,i){this._assignCubemap(e,t,i.resources),this._parser.initialize(t.resource,t.data)},t._onCubemapAdd=function(e,t,i){0===t.data.shadingModel&&(t.loadFaces=!0),this._assets.load(i)},t._onCubemapRemoveOrUnload=function(e,t,i){var n=t.resource;t.data.prefilteredCubeMap128===i.resources[1]&&(this._assignCubemap(e,t,[null,null,null,null,null,null,null]),n.update())},t._bindAndAssignAssets=function(e,t){var i,n,s,r=this._parser.migrate(e.data),a=e.resource,o="path"===r.mappingFormat,h=Gs;for(i=0;i<h.length;i++){n=h[i],s=a._assetReferences[n];var l=r[n],c=a[n],u=c===this._getPlaceholderTexture(n),d=r.validated;!l||c&&d&&!u?s&&(o?s.url=null:s.id=null):(s||(s=new hp(n,e,t,{load:this._onTextureLoad,add:this._onTextureAdd,remove:this._onTextureRemoveOrUnload,unload:this._onTextureRemoveOrUnload},this),a._assetReferences[n]=s),o?s.url=e.getAbsoluteUrl(l):s.id=l,s.asset&&(s.asset.resource?this._assignTexture(n,e,s.asset.resource):this._assignPlaceholderTexture(n,e),t.load(s.asset)))}var f=Hs;for(i=0;i<f.length;i++)n=f[i],s=a._assetReferences[n],r[n]&&!e.data.prefilteredCubeMap128&&(s||(s=new hp(n,e,t,{load:this._onCubemapLoad,add:this._onCubemapAdd,remove:this._onCubemapRemoveOrUnload,unload:this._onCubemapRemoveOrUnload},this),a._assetReferences[n]=s),o?s.url=r[n]:s.id=r[n],s.asset&&(s.asset.loaded&&this._assignCubemap(n,e,s.asset.resources),t.load(s.asset)));this._parser.initialize(a,r)},e}(),up=function(){function e(e,t){this._device=e,this._defaultMaterial=t}return e.prototype.parse=function(e){var t=Nf.parse("filename.glb",e,this._device);if(t){var i=Kd.createModel(t,this._defaultMaterial);return t.destroy(),i}return null},e}(),dp=function(){this.index=0,this.boneIndices=[0,0,0,0]},fp=function(){function e(){this.partition=0,this.vertexStart=0,this.vertexCount=0,this.indexStart=0,this.indexCount=0,this.boneIndices=[],this.vertices=[],this.indices=[],this.indexMap={},this.originalMesh=null}var t=e.prototype;return t.addVertex=function(e,t,i){var n=-1;if(void 0!==this.indexMap[t])n=this.indexMap[t],this.indices.push(n);else{for(var s=0;s<4;s++)if(0!==i.blendWeight.data[4*t+s]){var r=i.blendIndices.data[4*e.index+s];e.boneIndices[s]=this.getBoneRemap(r)}n=this.vertices.length,this.indices.push(n),this.vertices.push(e),this.indexMap[t]=n}},t.addPrimitive=function(e,t,i,n){for(var s=[],r=0,a=e.length,o=0;o<a;o++)for(var h=e[o].index,l=0;l<4;l++)if(i.blendWeight.data[4*h+l]>0){for(var c=i.blendIndices.data[4*h+l],u=!0,d=0;d<r;d++)if(s[d]===c){u=!1;break}if(u)s[r]=c,r+=-1===this.getBoneRemap(c)?1:0}if(this.boneIndices.length+r>n)return!1;for(var f=0;f<r;f++)this.boneIndices.push(s[f]);for(var p=0;p<a;p++)this.addVertex(e[p],t[p],i);return!0},t.getBoneRemap=function(e){for(var t=0;t<this.boneIndices.length;t++)if(this.boneIndices[t]===e)return t;return-1},e}();function pp(e,t,i){var n,s,r,a;!function(e){for(var t=e.vertices,i=e.skins,n=e.meshes,s=e.meshInstances,r=0;r<n.length;r++)n[r].vertices=t[n[r].vertices],void 0!==n[r].skin&&(n[r].skin=i[n[r].skin]);for(var a=0;a<s.length;a++)s[a].mesh=n[s[a].mesh]}(e);var o,h=e.vertices,l=e.skins,c=e.meshes,u=e.meshInstances,d=function(e){var t=new dp;return t.index=e,t};for(n=l.length-1;n>=0;n--)if(l[n].boneNames.length>i){var f=l.splice(n,1)[0],p=[];for(s=0;s<c.length;s++)c[s].skin===f&&p.push(c[s]);for(s=0;s<p.length;s++)-1!==(a=c.indexOf(p[s]))&&c.splice(a,1);if(0===p.length)throw new Error("partitionSkin: There should be at least one mesh that references a skin");var m=p[0].vertices;for(s=1;s<p.length;s++)if(p[s].vertices!==m)throw new Error("partitionSkin: All meshes that share a skin should also share the same vertex buffer");var _=void 0,g=[],v=[],y=[],x=0;for(s=0;s<p.length;s++){for(var b=(o=p[s]).indices,S=o.base;S<o.base+o.count;){a=b[S++],v[0]=d(a),y[0]=a,a=b[S++],v[1]=d(a),y[1]=a,a=b[S++],v[2]=d(a),y[2]=a;for(var w=!1,T=x;T<g.length;T++)if((_=g[T]).addPrimitive(v,y,m,i)){w=!0;break}w||((_=new fp).originalMesh=o,_.addPrimitive(v,y,m,i),g.push(_))}x=g.length}var A=[],M=[];for(s=0;s<g.length;s++)if((_=g[s]).vertices.length&&_.indices.length){var C=A.length,E=_.vertices.length,P=M.length,R=_.indices.length;_.partition=s,_.vertexStart=C,_.vertexCount=E,_.indexStart=P,_.indexCount=R;var I=void 0,L=void 0;for(I=0,L=C;I<E;)A[L++]=_.vertices[I++];for(I=0,L=P;I<R;)M[L++]=_.indices[I++]+C}var D=[];for(s=0;s<g.length;s++){_=g[s];var k=[],O=[];for(r=0;r<_.boneIndices.length;r++)k.push(f.inverseBindMatrices[_.boneIndices[r]]),O.push(f.boneNames[_.boneIndices[r]]);var F={inverseBindMatrices:k,boneNames:O};D.push(F),l.push(F)}var B=void 0,N=void 0,U=void 0,z=void 0,V={};for(N in m)V[N]={components:m[N].components,data:[],type:m[N].type};for(N in m)if("blendIndices"===N){var G=V[N].data;for(s=0;s<A.length;s++){var W=A[s].boneIndices;G.push(W[0],W[1],W[2],W[3])}}else for(U=(B=m[N]).data,z=B.components,s=0;s<A.length;s++)for(a=A[s].index,r=0;r<z;r++)V[N].data.push(U[a*z+r]);for(h[h.indexOf(m)]=V,s=0;s<g.length;s++)for(_=g[s],o={aabb:{min:[0,0,0],max:[0,0,0]},vertices:V,skin:D[s],indices:M.splice(0,_.indexCount),type:"triangles",base:0,count:_.indexCount},c.push(o),r=u.length-1;r>=0;r--)u[r].mesh===_.originalMesh&&(u.push({mesh:o,node:u[r].node}),t&&t.push({material:t[r].material,path:t[r].path}));for(s=0;s<g.length;s++)for(_=g[s],r=u.length-1;r>=0;r--)u[r].mesh===_.originalMesh&&(u.splice(r,1),t&&t.splice(r,1))}!function(e){for(var t=e.vertices,i=e.skins,n=e.meshes,s=e.meshInstances,r=0;r<n.length;r++)n[r].vertices=t.indexOf(n[r].vertices),void 0!==n[r].skin&&(n[r].skin=i.indexOf(n[r].skin));for(var a=0;a<s.length;a++)s[a].mesh=n.indexOf(s[a].mesh)}(e)}var mp={points:0,lines:1,lineloop:2,linestrip:3,triangles:4,trianglestrip:5,trianglefan:6},_p={int8:0,uint8:1,int16:2,uint16:3,int32:4,uint32:5,float32:6},gp=function(){function e(e,t){this._device=e,this._defaultMaterial=t}var t=e.prototype;return t.parse=function(e){var t=e.model;if(!t)return null;if(t.version<=1)return null;var i=this._parseNodes(e),n=this._parseSkins(e,i),s=this._parseVertexBuffers(e),r=this._parseIndexBuffers(e,s),a=this._parseMorphs(e,i,s),o=this._parseMeshes(e,n.skins,a.morphs,s,r.buffer,r.data),h=this._parseMeshInstances(e,i,o,n.skins,n.instances,a.morphs,a.instances),l=new hc;return l.graph=i[0],l.meshInstances=h,l.skinInstances=n.instances,l.morphInstances=a.instances,l.getGraph().syncHierarchy(),l},t._parseNodes=function(e){var t,i=e.model,n=[];for(t=0;t<i.nodes.length;t++){var s=i.nodes[t],r=new Hn(s.name);r.setLocalPosition(s.position[0],s.position[1],s.position[2]),r.setLocalEulerAngles(s.rotation[0],s.rotation[1],s.rotation[2]),r.setLocalScale(s.scale[0],s.scale[1],s.scale[2]),r.scaleCompensation=!!s.scaleCompensation,n.push(r)}for(t=1;t<i.parents.length;t++)n[i.parents[t]].addChild(n[t]);return n},t._parseSkins=function(e,t){var i,n,s=e.model,r=[],a=[];!this._device.supportsBoneTextures&&s.skins.length>0&&pp(s,null,this._device.getBoneLimit());for(i=0;i<s.skins.length;i++){var o=s.skins[i],h=[];for(n=0;n<o.inverseBindMatrices.length;n++){var l=o.inverseBindMatrices[n];h[n]=(new Ee).set(l)}var c=new hu(this._device,h,o.boneNames);r.push(c);var u=new ba(c),d=[];for(n=0;n<c.boneNames.length;n++){var f=c.boneNames[n],p=t[0].findByName(f);d.push(p)}u.bones=d,a.push(u)}return{skins:r,instances:a}},t._getMorphVertexCount=function(e,t,i){for(var n=0;n<e.meshes.length;n++){var s=e.meshes[n];if(s.morph===t)return i[s.vertices].numVertices}},t._parseMorphs=function(e,t,i){var n,s,r,a,o,h,l=e.model,c=[],u=[];if(l.morphs){var d=function(e,t,i){for(var n=new Float32Array(3*i),s=0;s<t.length;s++){var r=3*t[s];n[r]=e[3*s],n[r+1]=e[3*s+1],n[r+2]=e[3*s+2]}return n};for(n=0;n<l.morphs.length;n++){for(a=l.morphs[n].targets,h=[],r=this._getMorphVertexCount(l,n,i),s=0;s<a.length;s++){var f=a[s].aabb,p=f.min,m=f.max,_=new Oe(new ye(.5*(m[0]+p[0]),.5*(m[1]+p[1]),.5*(m[2]+p[2])),new ye(.5*(m[0]-p[0]),.5*(m[1]-p[1]),.5*(m[2]-p[2]))),g=a[s].indices,v=a[s].deltaPositions,y=a[s].deltaNormals;g&&(v=d(v,g,r),y=d(y,g,r)),o=new lc({deltaPositions:v,deltaNormals:y,name:a[s].name,aabb:_}),h.push(o)}var x=new rc(h,this._device);c.push(x);var b=new oc(x);u.push(b)}}return{morphs:c,instances:u}},t._parseVertexBuffers=function(e){for(var t=e.model,i=[],n={position:vt,normal:yt,tangent:xt,blendWeight:bt,blendIndices:St,color:wt,texCoord0:At,texCoord1:Mt,texCoord2:Ct,texCoord3:Et,texCoord4:Pt,texCoord5:Rt,texCoord6:It,texCoord7:Lt},s=0;s<t.vertices.length;s++){var r=t.vertices[s],a=[];for(var o in r){var h=r[o];a.push({semantic:n[o],components:h.components,type:_p[h.type],normalize:n[o]===wt})}for(var l=new Ti(this._device,a),c=r.position.data.length/r.position.components,u=new Si(this._device,l,c),d=new Pr(u),f=0;f<c;f++){for(var p in r){var m=r[p];switch(m.components){case 1:d.element[n[p]].set(m.data[f]);break;case 2:d.element[n[p]].set(m.data[2*f],1-m.data[2*f+1]);break;case 3:d.element[n[p]].set(m.data[3*f],m.data[3*f+1],m.data[3*f+2]);break;case 4:d.element[n[p]].set(m.data[4*f],m.data[4*f+1],m.data[4*f+2],m.data[4*f+3])}}d.next()}d.end(),i.push(u)}return i},t._parseIndexBuffers=function(e,t){var i,n=e.model,s=null,r=null,a=0;for(i=0;i<n.meshes.length;i++){var o=n.meshes[i];void 0!==o.indices&&(a+=o.indices.length)}var h=0;for(i=0;i<t.length;i++)h=Math.max(h,t[i].numVertices);return a>0&&(h>65535&&this._device.extUintElement?(s=new mr(this._device,2,a),r=new Uint32Array(s.lock())):(s=new mr(this._device,1,a),r=new Uint16Array(s.lock()))),{buffer:s,data:r}},t._parseMeshes=function(e,t,i,n,s,r){for(var a=e.model,o=[],h=0,l=0;l<a.meshes.length;l++){var c=a.meshes[l],u=c.aabb,d=u.min,f=u.max,p=new Oe(new ye(.5*(f[0]+d[0]),.5*(f[1]+d[1]),.5*(f[2]+d[2])),new ye(.5*(f[0]-d[0]),.5*(f[1]-d[1]),.5*(f[2]-d[2]))),m=void 0!==c.indices,_=new ea(this._device);_.vertexBuffer=n[c.vertices],_.indexBuffer[0]=m?s:null,_.primitive[0].type=mp[c.type],_.primitive[0].base=m?c.base+h:c.base,_.primitive[0].count=c.count,_.primitive[0].indexed=m,_.skin=void 0!==c.skin?t[c.skin]:null,_.morph=void 0!==c.morph?i[c.morph]:null,_.aabb=p,m&&(r.set(c.indices,h),h+=c.indices.length),o.push(_)}return null!==s&&s.unlock(),o},t._parseMeshInstances=function(e,t,i,n,s,r,a){var o,h=e.model,l=[];for(o=0;o<h.meshInstances.length;o++){var c=h.meshInstances[o],u=t[c.node],d=i[c.mesh],f=new ka(d,this._defaultMaterial,u);if(d.skin){var p=n.indexOf(d.skin);f.skinInstance=s[p]}if(d.morph){var m=r.indexOf(d.morph);f.morphInstance=a[m]}l.push(f)}return l},e}(),vp=function(){function e(e){this.handlerType="model",this._device=e.graphicsDevice,this._parsers=[],this._defaultMaterial=ks(this._device),this.maxRetries=0,this.addParser(new gp(this._device,this._defaultMaterial),(function(e,t){return".json"===v.getExtension(e)})),this.addParser(new up(this._device,this._defaultMaterial),(function(e,t){return".glb"===v.getExtension(e)}))}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};(e.load.startsWith("blob:")||e.load.startsWith("data:"))&&(".glb"===v.getExtension(e.original).toLowerCase()?i.responseType=fe.ResponseType.ARRAY_BUFFER:i.responseType=fe.ResponseType.JSON),pe.get(e.load,i,(function(i,n){t&&(i?t("Error loading model: "+e.original+" ["+i+"]"):t(null,n))}))},t.open=function(e,t){for(var i=0;i<this._parsers.length;i++){var n=this._parsers[i];if(n.decider(e,t))return n.parser.parse(t)}return null},t.patch=function(e,t){if(e.resource){var i=e.data,n=this;e.resource.meshInstances.forEach((function(s,r){if(i.mapping){var a=function e(i){i.resource?s.material=i.resource:(i.once("load",e),t.load(i)),i.once("remove",(function(e){s.material===e.resource&&(s.material=n._defaultMaterial)}))};if(!i.mapping[r])return void(s.material=n._defaultMaterial);var o,h=i.mapping[r].material,l=i.mapping[r].path;if(void 0!==h)h?(o=t.get(h))?a(o):t.once("add:"+h,a):s.material=n._defaultMaterial;else if(l){var c=e.getAbsoluteUrl(i.mapping[r].path);(o=t.getByUrl(c))?a(o):t.once("add:url:"+c,a)}}}))}},t.addParser=function(e,t){this._parsers.push({parser:e,decider:t})},e}();function yp(e){var t=this;if(t.resource){var i=e.resource,n=i.renders&&i.renders[t.data.renderIndex];n&&(t.resource.meshes=n.resource.meshes)}}function xp(e){var t=this;t.registry.off("load:"+e.id,yp,t),t.registry.on("load:"+e.id,yp,t),t.registry.off("remove:"+e.id,bp,t),t.registry.once("remove:"+e.id,bp,t),e.resource?yp.call(t,e):t.registry.load(e)}function bp(e){var t=this;t.registry.off("load:"+e.id,yp,t),t.resource&&t.resource.destroy()}var Sp=function(){function e(e){this.handlerType="render",this._registry=e.assets}var t=e.prototype;return t.load=function(e,t,i){},t.open=function(e,t){return new qd},t.patch=function(e,t){if(e.data.containerAsset){var i=t.get(e.data.containerAsset);i?xp.call(e,i):t.once("add:"+e.data.containerAsset,xp,e)}},e}(),wp=function(){function e(){}var t=e.prototype;return t.load=function(e,t,i){throw new Error("not implemented")},t.open=function(e,t,i){throw new Error("not implemented")},t.patch=function(e,t){},e}(),Tp=function(){function e(e){this.handlerType="scene",this._app=e,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){ip(e,this.maxRetries,t)},t.open=function(e,t){this._app.systems.script.preloading=!0;var i=new tp(this._app,!1).parse(t),n=this._app.scene;return n.root=i,this._app.applySceneSettings(t.settings),this._app.systems.script.preloading=!1,n},t.patch=function(e,t){},e}(),Ap=function(){function e(e){this._app=e,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){ip(e,this.maxRetries,t)},t.open=function(e,t){return t.settings},e}(),Mp=function(){function e(e){this.handlerType="shader",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),pe.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?t("Error loading shader resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}();function Cp(e){this.resource&&(this.resource.atlas=e.resource)}function Ep(e){this.registry.load(e)}var Pp=function(){function e(e){this.handlerType="sprite",this._assets=e.assets,this._device=e.graphicsDevice,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),".json"===v.getExtension(e.original)&&pe.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(e,i){e?t(e):t(null,i)}))},t.open=function(e,t){var i=new uu(this._device);return e&&(i.__data=t),i},t.patch=function(e,t){var i=e.resource;if(i.__data&&(e.data.pixelsPerUnit=i.__data.pixelsPerUnit,e.data.renderMode=i.__data.renderMode,e.data.frameKeys=i.__data.frameKeys,i.__data.textureAtlasAsset)){var n=t.getByUrl(i.__data.textureAtlasAsset);n?e.data.textureAtlasAsset=n.id:console.warn("Could not find textureatlas with url: "+i.__data.textureAtlasAsset)}i.startUpdate(),i.renderMode=e.data.renderMode,i.pixelsPerUnit=e.data.pixelsPerUnit,i.frameKeys=e.data.frameKeys,this._updateAtlas(e),i.endUpdate(),e.off("change",this._onAssetChange,this),e.on("change",this._onAssetChange,this)},t._updateAtlas=function(e){var t=e.resource;if(e.data.textureAtlasAsset){this._assets.off("load:"+e.data.textureAtlasAsset,Cp,e),this._assets.on("load:"+e.data.textureAtlasAsset,Cp,e);var i=this._assets.get(e.data.textureAtlasAsset);i&&i.resource?t.atlas=i.resource:i?this._assets.load(i):(this._assets.off("add:"+e.data.textureAtlasAsset,Ep,e),this._assets.on("add:"+e.data.textureAtlasAsset,Ep,e))}else t.atlas=null},t._onAssetChange=function(e,t,i,n){"data"===t&&i&&i.textureAtlasAsset&&n&&i.textureAtlasAsset!==n.textureAtlasAsset&&(this._assets.off("load:"+n.textureAtlasAsset,Cp,e),this._assets.off("add:"+n.textureAtlasAsset,Ep,e))},e}(),Rp=function(){function e(e,t){this._app=e,this._data=t,this._templateRoot=null}var t=e.prototype;return t.instantiate=function(){return this._templateRoot||this._parseTemplate(),this._templateRoot.clone()},t._parseTemplate=function(){var e=new tp(this._app,!0);this._templateRoot=e.parse(this._data)},e}(),Ip=function(){function e(e){this.handlerType="template",this._app=e,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};pe.get(e.load,i,(function(i,n){i?t("Error requesting template: "+e.original):t(i,n)}))},t.open=function(e,t){return new Rp(this._app,t)},e}(),Lp=function(){function e(e){this.handlerType="text",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),pe.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?t("Error loading text resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}(),Dp=function(){function e(e,t){this.device=t,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t,i){var n=this.device;ml.fetchArrayBuffer(e.load,(function(s,r){s?t(s):function(s){var r,a,o;Wd(n,e.load,s,t,{isGGGR:0!=(8&(null==i||null==(r=i.file)||null==(a=r.variants)||null==(o=a.basis)?void 0:o.opt))})||t("Basis module not found. Asset '"+i.name+"' basis texture variant will not be loaded.")}(r)}),i,this.maxRetries)},t.open=function(e,t,i){var n=new wn(i,{name:e,addressU:t.cubemap?1:0,addressV:t.cubemap?1:0,width:t.width,height:t.height,format:t.format,cubemap:t.cubemap,levels:t.levels});return n.upload(),n},e}(),kp=function(){function e(e,t){this.crossOrigin=e.prefix?"anonymous":null,this.maxRetries=0,this.device=t}var t=e.prototype;return t.load=function(e,t,i){var n,s=!(null==i||null==(n=i.file)||!n.contents);if(s){if(this.device.supportsImageBitmap)return void this._loadImageBitmapFromData(i.file.contents,t);e={load:URL.createObjectURL(new Blob([i.file.contents])),original:e.original}}var r,a=function(i,n){s&&URL.revokeObjectURL(e.load),t(i,n)};i&&i.options&&i.options.hasOwnProperty("crossOrigin")?r=i.options.crossOrigin:cl.test(e.load)&&(r=this.crossOrigin),this.device.supportsImageBitmap?this._loadImageBitmap(e.load,e.original,r,a):this._loadImage(e.load,e.original,r,a)},t.open=function(e,t,i){var n=v.getExtension(e).toLowerCase(),s=".jpg"===n||".jpeg"===n?6:7,r=new wn(i,{name:e,width:t.width,height:t.height,format:s});return r.setSource(t),r},t._loadImage=function(e,t,i,n){var s=new Image;i&&(s.crossOrigin=i);var r,a=0,o=this.maxRetries;s.onload=function(){n(null,s)},s.onerror=function(){if(!r)if(o>0&&++a<=o){var i=100*Math.pow(2,a);console.log("Error loading Texture from: '"+t+"' - Retrying in "+i+"ms...");var h=e.indexOf("?")>=0?"&":"?";r=setTimeout((function(){s.src=e+h+"retry="+Date.now(),r=null}),i)}else n("Error loading Texture from: '"+t+"'")},s.src=e},t._loadImageBitmap=function(e,t,i,n){var s={cache:!0,responseType:"blob",retry:this.maxRetries>0,maxRetries:this.maxRetries};pe.get(e,s,(function(e,t){e?n(e):createImageBitmap(t,{premultiplyAlpha:"none"}).then((function(e){return n(null,e)})).catch((function(e){return n(e)}))}))},t._loadImageBitmapFromData=function(e,t){createImageBitmap(new Blob([e]),{premultiplyAlpha:"none"}).then((function(e){return t(null,e)})).catch((function(e){return t(e)}))},e}(),Op=[1481919403,3140563232,169478669],Fp={33776:8,33778:9,33779:ht,36196:mt,37492:22,37496:23,35840:26,35841:_t,35842:27,35843:gt,32849:6,32856:7,35905:19,35907:20,35898:18,34843:lt,34842:ct};var Bp=function(){function e(e){this.maxRetries=0}var t=e.prototype;return t.load=function(e,t,i){ml.fetchArrayBuffer(e.load,t,i,this.maxRetries)},t.open=function(e,t,i){var n=this.parse(t);if(!n)return null;var s=new wn(i,{name:e,addressU:n.cubemap?1:0,addressV:n.cubemap?1:0,width:n.width,height:n.height,format:n.format,cubemap:n.cubemap,levels:n.levels});return s.upload(),s},t.parse=function(e){var t=new Uint32Array(e);if(Op[0]!==t[0]||Op[1]!==t[1]||Op[2]!==t[2])return null;var i={endianness:t[3],glType:t[4],glTypeSize:t[5],glFormat:t[6],glInternalFormat:t[7],glBaseInternalFormat:t[8],pixelWidth:t[9],pixelHeight:t[10],pixelDepth:t[11],numberOfArrayElements:t[12],numberOfFaces:t[13],numberOfMipmapLevels:t[14],bytesOfKeyValueData:t[15]};if(i.pixelDepth>1)return null;if(0!==i.numberOfArrayElements)return null;var n=Fp[i.glInternalFormat];if(void 0===n)return null;for(var s,r,a,o=16+i.bytesOfKeyValueData/4,h=i.numberOfFaces>1,l=[],c=0;c<(i.numberOfMipmapLevels||1);c++){var u=t[o++];h&&l.push([]);for(var d=h?l[c]:l,f=0;f<(h?6:1);++f)d.push((s=e,r=4*o,a=u,18===n?new Uint32Array(s,r,a/4):new Uint8Array(s,r,a))),o+=u+3>>2}return{format:n,width:i.pixelWidth,height:i.pixelHeight,levels:l,cubemap:h}},e}(),Np=166,Up=function(){function e(e,t){this.maxRetries=0,this.device=t}var t=e.prototype;return t.load=function(e,t,i){var n=this;ml.fetchArrayBuffer(e.load,(function(s,r){s?t(s,r):n.parse(r,e,t,i)}),i,this.maxRetries)},t.open=function(e,t,i){var n=new wn(i,{name:e,addressU:t.cubemap?1:0,addressV:t.cubemap?1:0,width:t.width,height:t.height,format:t.format,cubemap:t.cubemap,levels:t.levels});return n.upload(),n},t.parse=function(e,t,i,n){var s=new se(e),r=[s.readU32be(),s.readU32be(),s.readU32be()];if(2873840728!==r[0]||540160187!==r[1]||218765834!==r[2])return null;for(var a={vkFormat:s.readU32(),typeSize:s.readU32(),pixelWidth:s.readU32(),pixelHeight:s.readU32(),pixelDepth:s.readU32(),layerCount:s.readU32(),faceCount:s.readU32(),levelCount:s.readU32(),supercompressionScheme:s.readU32()},o={dfdByteOffset:s.readU32(),dfdByteLength:s.readU32(),kvdByteOffset:s.readU32(),kvdByteLength:s.readU32(),sgdByteOffset:s.readU64(),sgdByteLength:s.readU64()},h=[],l=0;l<Math.max(1,a.levelCount);++l)h.push({byteOffset:s.readU64(),byteLength:s.readU64(),uncompressedByteLength:s.readU64()});if(s.readU32()!==o.kvdByteOffset-o.dfdByteOffset)return null;s.skip(8);var c,u,d,f=s.readU8();(s.skip(o.dfdByteLength-9),s.skip(o.kvdByteLength),1===a.supercompressionScheme||f===Np)?Wd(this.device,t.load,e,i,{isGGGR:0!=(8&(null==n||null==(c=n.file)||null==(u=c.variants)||null==(d=u.basis)?void 0:d.opt)),isKTX2:!0})||i('Basis module not found. Asset "'+n.name+'" basis texture variant will not be loaded.'):i("unsupported KTX2 pixel format")},e}(),zp=function(){function e(e){this.maxRetries=0}var t=e.prototype;return t.load=function(e,t,i){ml.fetchArrayBuffer(e.load,t,i,this.maxRetries)},t.open=function(e,t,i){var n,s=new Uint32Array(t,0,32),r=s[4],a=s[3],o=Math.max(s[7],1),h=4===s[20],l=s[21],c=s[22],u=65024===s[28],d=827611204,f=825438800,p=825439312,m=!1,_=!1,g=!1,v=!1,y=null,x=1;if(h?l===d?(y=8,m=!0):894720068===l?(y=ht,m=!0):113===l?(y=ct,x=2):116===l?(y=dt,x=4):826496069===l?(y=mt,m=!0,_=!0):l===f||825504336===l?(y=l===f?_t:gt,m=!0,g=!0):l!==p&&825504848!==l||(y=l===p?26:27,m=!0,v=!0):32===c&&(y=7),!y)return n=new wn(i,{width:4,height:4,format:6,name:"dds-legacy-empty"});n=new wn(i,{name:e,addressU:u?1:0,addressV:u?1:0,width:r,height:a,format:y,cubemap:u,mipmaps:o>1});for(var b,S=128,w=u?6:1,T=l===d?8:16,A=0;A<w;A++)for(var M=r,C=a,E=0;E<o;E++){b=m?_?Math.floor((M+3)/4)*Math.floor((C+3)/4)*8:g?Math.max(M,16)*Math.max(C,8)/4:v?Math.max(M,8)*Math.max(C,8)/2:Math.floor((M+4-1)/4)*Math.floor((C+4-1)/4)*T:M*C*4;var P=y===dt?new Float32Array(t,S,b):y===ct?new Uint16Array(t,S,b):new Uint8Array(t,S,b);u?(n._levels[E]||(n._levels[E]=[]),n._levels[E][A]=P):n._levels[E]=P,S+=b*x,M=Math.max(.5*M,1),C=Math.max(.5*C,1)}return n.upload(),n},e}(),Vp=function(){function e(e){this.maxRetries=0}var t=e.prototype;return t.load=function(e,t,i){ml.fetchArrayBuffer(e.load,t,i,this.maxRetries)},t.open=function(e,t,i){var n=this.parse(t);if(!n)return null;var s=new wn(i,{name:e,addressU:0,addressV:1,minFilter:0,magFilter:0,width:n.width,height:n.height,levels:n.levels,format:7,type:Qt,mipmaps:!1});return s.upload(),s},t.parse=function(e){var t=new se(e);if(!t.readLine().startsWith("#?RADIANCE"))return null;for(var i={};;){var n=t.readLine();if(0===n.length)break;var s=n.split("=");2===s.length&&(i[s[0]]=s[1])}if(!i.hasOwnProperty("FORMAT"))return null;var r=t.readLine().split(" ");if(4!==r.length)return null;var a=parseInt(r[1],10),o=parseInt(r[3],10),h=this._readPixels(t,o,a,"-Y"===r[0]);return h?{width:o,height:a,levels:[h]}:null},t._readPixels=function(e,t,i,n){if(t<8||t>32767)return this._readPixelsFlat(e,t,i);var s=[0,0,0,0];if(e.readArray(s),2!==s[0]||2!==s[1]||0!=(128&s[2]))return e.skip(-4),this._readPixelsFlat(e,t,i);var r,a,o,h,l,c,u=new ArrayBuffer(t*i*4),d=new Uint8Array(u),f=n?0:4*t*(i-1);for(a=0;a<i;++a){if(a&&e.readArray(s),(s[2]<<8)+s[3]!==t)return null;for(h=0;h<4;++h)for(r=0;r<t;)if((l=e.readU8())>128){if(r+(l-=128)>t)return null;for(c=e.readU8(),o=0;o<l;++o)d[f+h+4*r++]=c}else{if(0===l||r+l>t)return null;for(o=0;o<l;++o)d[f+h+4*r++]=e.readU8()}f+=4*t*(n?1:-1)}return d},t._readPixelsFlat=function(e,t,i){return e.remainingBytes===t*i*4?new Uint8Array(e.arraybuffer,e.offset):null},e}(),Gp={repeat:0,clamp:1,mirror:2},Wp={nearest:0,linear:1,nearest_mip_nearest:2,linear_mip_nearest:4,nearest_mip_linear:3,linear_mip_linear:5},Hp={default:Zt,rgbm:$t,rgbe:Qt,rgbp:Jt,swizzleGGGR:ei},Xp=function(){function e(){}var t=e.prototype;return t.load=function(e,t,i){throw new Error("not implemented")},t.open=function(e,t,i){throw new Error("not implemented")},e}(),qp=function(){function e(e){this.handlerType="texture";var t=e.assets,i=e.graphicsDevice;this._device=i,this._assets=t,this._loader=e.loader,this.imgParser=new kp(t,i),this.parsers={dds:new zp(t),ktx:new Bp(t),ktx2:new Up(t,i),basis:new Dp(t,i),hdr:new Vp(t)}}var t=e.prototype;return t._getUrlWithoutParams=function(e){return e.indexOf("?")>=0?e.split("?")[0]:e},t._getParser=function(e){var t=v.getExtension(this._getUrlWithoutParams(e)).toLowerCase().replace(".","");return this.parsers[t]||this.imgParser},t.load=function(e,t,i){"string"==typeof e&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,i)},t.open=function(e,t,i){if(e){var n=this._getParser(e).open(e,t,this._device);return null===n?n=new wn(this._device,{width:4,height:4,format:6}):(!function(e){var t=Math.log2(Math.max(e._width,e._height))+1;if(!(7!==e._format&&e._format!==dt||e._volume||e._compressed||1===e._levels.length||e._levels.length===t||(i=e._cubemap?e._levels[0][0]:e._levels[0],i instanceof HTMLCanvasElement||i instanceof HTMLImageElement||i instanceof HTMLVideoElement))){for(var i,n=function(e,t,i){for(var n=Math.max(1,e>>1),s=Math.max(1,t>>1),r=new i.constructor(n*s*4),a=Math.floor(e/n),o=Math.floor(t/s),h=a*o,l=0;l<s;++l)for(var c=0;c<n;++c)for(var u=0;u<4;++u){for(var d=0,f=0;f<o;++f)for(var p=0;p<a;++p)d+=i[4*(c*a+p+(l*o+f)*e)+u];r[4*(c+l*n)+u]=d/h}return r},s=e._levels.length;s<t;++s){var r=Math.max(1,e._width>>s-1),a=Math.max(1,e._height>>s-1);if(e._cubemap){for(var o=[],h=0;h<6;++h)o.push(n(r,a,e._levels[s-1][h]));e._levels.push(o)}else e._levels.push(n(r,a,e._levels[s-1]))}e._levelsUpdated=e._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0]}}(n),t.unswizzledGGGR&&(i.file.variants.basis.opt&=-9)),n}},t.patch=function(e,t){var i=e.resource;if(i){e.name&&e.name.length>0&&(i.name=e.name);var n=e.data;n.hasOwnProperty("minfilter")&&(i.minFilter=Wp[n.minfilter]),n.hasOwnProperty("magfilter")&&(i.magFilter=Wp[n.magfilter]),i.cubemap||(n.hasOwnProperty("addressu")&&(i.addressU=Gp[n.addressu]),n.hasOwnProperty("addressv")&&(i.addressV=Gp[n.addressv])),n.hasOwnProperty("mipmaps")&&(i.mipmaps=n.mipmaps),n.hasOwnProperty("anisotropy")&&(i.anisotropy=n.anisotropy),n.hasOwnProperty("flipY")&&(i.flipY=!!n.flipY),n.hasOwnProperty("type")?i.type=Hp[n.type]:n.hasOwnProperty("rgbm")&&n.rgbm?i.type=$t:e.file&&0!=(8&e.file.opt)&&(i.type=ei)}},$(e,[{key:"crossOrigin",get:function(){return this.imgParser.crossOrigin},set:function(e){this.imgParser.crossOrigin=e}},{key:"maxRetries",get:function(){return this.imgParser.maxRetries},set:function(e){for(var t in this.imgParser.maxRetries=e,this.parsers)this.parsers.hasOwnProperty(t)&&(this.parsers[t].maxRetries=e)}}]),e}(),jp={repeat:0,clamp:1,mirror:2},Yp={nearest:0,linear:1,nearest_mip_nearest:2,linear_mip_nearest:4,nearest_mip_linear:3,linear_mip_linear:5},Kp=/^data\.frames\.(\d+)$/,Zp=function(){function e(e){this.handlerType="textureatlas",this._loader=e.loader,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i=this,n=this._loader.getHandler("texture");if(".json"!==v.getExtension(e.original))return n.load(e,t);pe.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(n,s){if(n)t(n);else{var r=e.original.replace(".json",".png");i._loader.load(r,"texture",(function(e,i){e?t(e):t(null,{data:s,texture:i})}))}}))},t.open=function(e,t){var i=new fu;if(t.texture&&t.data)i.texture=t.texture,i.__data=t.data;else{var n=this._loader.getHandler("texture").open(e,t);if(!n)return null;i.texture=n}return i},t.patch=function(e,t){if(e.resource){e.resource.__data&&(void 0!==e.resource.__data.minfilter&&(e.data.minfilter=e.resource.__data.minfilter),void 0!==e.resource.__data.magfilter&&(e.data.magfilter=e.resource.__data.magfilter),void 0!==e.resource.__data.addressu&&(e.data.addressu=e.resource.__data.addressu),void 0!==e.resource.__data.addressv&&(e.data.addressv=e.resource.__data.addressv),void 0!==e.resource.__data.mipmaps&&(e.data.mipmaps=e.resource.__data.mipmaps),void 0!==e.resource.__data.anisotropy&&(e.data.anisotropy=e.resource.__data.anisotropy),void 0!==e.resource.__data.rgbm&&(e.data.rgbm=!!e.resource.__data.rgbm),e.data.frames=e.resource.__data.frames,delete e.resource.__data);var i=e.resource.texture;if(i&&(i.name=e.name,e.data.hasOwnProperty("minfilter")&&i.minFilter!==Yp[e.data.minfilter]&&(i.minFilter=Yp[e.data.minfilter]),e.data.hasOwnProperty("magfilter")&&i.magFilter!==Yp[e.data.magfilter]&&(i.magFilter=Yp[e.data.magfilter]),e.data.hasOwnProperty("addressu")&&i.addressU!==jp[e.data.addressu]&&(i.addressU=jp[e.data.addressu]),e.data.hasOwnProperty("addressv")&&i.addressV!==jp[e.data.addressv]&&(i.addressV=jp[e.data.addressv]),e.data.hasOwnProperty("mipmaps")&&i.mipmaps!==e.data.mipmaps&&(i.mipmaps=e.data.mipmaps),e.data.hasOwnProperty("anisotropy")&&i.anisotropy!==e.data.anisotropy&&(i.anisotropy=e.data.anisotropy),e.data.hasOwnProperty("rgbm"))){var n=e.data.rgbm?$t:Zt;i.type!==n&&(i.type=n)}e.resource.texture=i;var s={};for(var r in e.data.frames){var a=e.data.frames[r];s[r]={rect:new Se(a.rect),pivot:new be(a.pivot),border:new Se(a.border)}}e.resource.frames=s,e.off("change",this._onAssetChange,this),e.on("change",this._onAssetChange,this)}},t._onAssetChange=function(e,t,i){var n;if("data"===t||"data.frames"===t){var s={};for(var r in i.frames)n=i.frames[r],s[r]={rect:new Se(n.rect),pivot:new be(n.pivot),border:new Se(n.border)};e.resource.frames=s}else{var a=t.match(Kp);if(a){var o=a[1];i?(e.resource.frames[o]?((n=e.resource.frames[o]).rect.set(i.rect[0],i.rect[1],i.rect[2],i.rect[3]),n.pivot.set(i.pivot[0],i.pivot[1]),n.border.set(i.border[0],i.border[1],i.border[2],i.border[3])):e.resource.frames[o]={rect:new Se(i.rect),pivot:new be(i.pivot),border:new Se(i.border)},e.resource.fire("set:frame",o,e.resource.frames[o])):e.resource.frames[o]&&(delete e.resource.frames[o],e.resource.fire("remove:frame",o))}}},e}(),$p=function(e){function t(t,i){var n;return(n=e.call(this)||this)._assets=new Set,n._loadingAssets=new Set,n._waitingAssets=new Set,n._registry=i,n._loading=!1,n._loaded=!1,n._failed=[],t.forEach((function(e){if(e instanceof ml)e.registry||(e.registry=i),n._assets.add(e);else{var t=i.get(e);t?n._assets.add(t):n._waitForAsset(e)}})),n}J(t,e);var i=t.prototype;return i.destroy=function(){var e=this;this._registry.off("load",this._onLoad),this._registry.off("error",this._onError),this._waitingAssets.forEach((function(t){e._registry.off("add:"+t,this._onAddAsset)})),this.off("progress"),this.off("load")},i._assetHasDependencies=function(e){var t;return"model"===e.type&&(null==(t=e.file)?void 0:t.url)&&e.file.url&&e.file.url.match(/.json$/g)},i.load=function(e,t){var i=this;if(!this._loading){this._loading=!0,this._callback=e,this._scope=t,this._registry.on("load",this._onLoad,this),this._registry.on("error",this._onError,this);var n=!1;this._assets.forEach((function(e){e.loaded||(n=!0,i._assetHasDependencies(e)&&i._registry.loadFromUrl(e.file.url,e.type,(function(t,n){t?i._onError(t,e):i._onLoad(e)})),i._loadingAssets.add(e),i._registry.add(e))})),this._loadingAssets.forEach((function(e){i._assetHasDependencies(e)||i._registry.load(e)})),n||0!==this._waitingAssets.size||this._loadingComplete()}},i.ready=function(e,t){void 0===t&&(t=this),this._loaded?e.call(t,Array.from(this._assets)):this.once("load",(function(i){e.call(t,i)}))},i._loadingComplete=function(){this._loaded||(this._loaded=!0,this._registry.off("load",this._onLoad,this),this._registry.off("error",this._onError,this),this._failed.length?(this._callback&&this._callback.call(this._scope,"Failed to load some assets",this._failed),this.fire("error",this._failed)):(this._callback&&this._callback.call(this._scope),this.fire("load",Array.from(this._assets))))},i._onLoad=function(e){var t=this;this._loadingAssets.has(e)&&(this.fire("progress",e),this._loadingAssets.delete(e)),0===this._loadingAssets.size&&setTimeout((function(){t._loadingComplete(t._failed)}),0)},i._onError=function(e,t){var i=this;this._loadingAssets.has(t)&&(this._failed.push(t),this._loadingAssets.delete(t)),0===this._loadingAssets.size&&setTimeout((function(){i._loadingComplete(i._failed)}),0)},i._onAddAsset=function(e){this._waitingAssets.delete(e),this._assets.add(e),e.loaded||(this._loadingAssets.add(e),this._registry.load(e))},i._waitForAsset=function(e){this._waitingAssets.add(e),this._registry.once("add:"+e,this._onAddAsset,this)},t}(m),Qp=function(e){function t(t){var i;return(i=e.call(this)||this)._app=t,t.i18n.on("set:locale",i._onSetLocale,te(i)),i._autoLoad=!1,i._disableLocalization=!1,i._defaultAsset=null,i._localizedAsset=null,i}J(t,e);var i=t.prototype;return i._bindDefaultAsset=function(){var e=this._app.assets.get(this._defaultAsset);e?this._onDefaultAssetAdd(e):this._app.assets.once("add:"+this._defaultAsset,this._onDefaultAssetAdd,this)},i._unbindDefaultAsset=function(){if(this._defaultAsset){this._app.assets.off("add:"+this._defaultAsset,this._onDefaultAssetAdd,this);var e=this._app.assets.get(this._defaultAsset);e&&(e.off("add:localized",this._onLocaleAdd,this),e.off("remove:localized",this._onLocaleRemove,this),e.off("remove",this._onDefaultAssetRemove,this))}},i._onDefaultAssetAdd=function(e){this._defaultAsset===e.id&&(e.on("add:localized",this._onLocaleAdd,this),e.on("remove:localized",this._onLocaleRemove,this),e.once("remove",this._onDefaultAssetRemove,this))},i._onDefaultAssetRemove=function(e){this._defaultAsset===e.id&&(e.off("add:localized",this._onLocaleAdd,this),e.off("remove:localized",this._onLocaleAdd,this),this._app.assets.once("add:"+this._defaultAsset,this._onDefaultAssetAdd,this))},i._bindLocalizedAsset=function(){if(this._autoLoad){var e=this._app.assets.get(this._localizedAsset);e&&(e.on("load",this._onLocalizedAssetLoad,this),e.on("change",this._onLocalizedAssetChange,this),e.on("remove",this._onLocalizedAssetRemove,this),e.resource?this._onLocalizedAssetLoad(e):this._app.assets.load(e))}},i._unbindLocalizedAsset=function(){var e=this._app.assets.get(this._localizedAsset);e&&(e.off("load",this._onLocalizedAssetLoad,this),e.off("change",this._onLocalizedAssetChange,this),e.off("remove",this._onLocalizedAssetRemove,this))},i._onLocalizedAssetAdd=function(e){this._localizedAsset===e.id&&this._bindLocalizedAsset()},i._onLocalizedAssetLoad=function(e){this.fire("load",e)},i._onLocalizedAssetChange=function(e,t,i,n){this.fire("change",e,t,i,n)},i._onLocalizedAssetRemove=function(e){this._localizedAsset===e.id&&(this.localizedAsset=this._defaultAsset),this.fire("remove",e)},i._onLocaleAdd=function(e,t){this._app.i18n.locale===e&&this._onSetLocale(e)},i._onLocaleRemove=function(e,t){this._app.i18n.locale===e&&this._onSetLocale(e)},i._onSetLocale=function(e){if(this._defaultAsset){var t=this._app.assets.get(this._defaultAsset);if(t&&!this._disableLocalization){var i=t.getLocalizedAssetId(e);this.localizedAsset=i||this._defaultAsset}else this.localizedAsset=this._defaultAsset}else this.localizedAsset=null},i.destroy=function(){this.defaultAsset=null,this._app.i18n.off("set:locale",this._onSetLocale,this),this.off()},$(t,[{key:"defaultAsset",get:function(){return this._defaultAsset},set:function(e){var t=e instanceof ml?e.id:e;this._defaultAsset!==t&&(this._defaultAsset&&this._unbindDefaultAsset(),this._defaultAsset=t,this._defaultAsset&&this._bindDefaultAsset(),this._onSetLocale(this._app.i18n.locale))}},{key:"localizedAsset",get:function(){return this._localizedAsset},set:function(e){var t=e instanceof ml?e.id:e;this._localizedAsset!==t&&(this._localizedAsset&&(this._app.assets.off("add:"+this._localizedAsset,this._onLocalizedAssetAdd,this),this._unbindLocalizedAsset(),this._localizedAsset=null),this._localizedAsset=t,this._localizedAsset&&(this._app.assets.get(this._localizedAsset)?this._bindLocalizedAsset():this._app.assets.once("add:"+this._localizedAsset,this._onLocalizedAssetAdd,this)))}},{key:"autoLoad",get:function(){return this._autoLoad},set:function(e){this._autoLoad!==e&&(this._autoLoad=e,this._autoLoad&&this._localizedAsset&&(this._unbindLocalizedAsset(),this._bindLocalizedAsset()))}},{key:"disableLocalization",get:function(){return this._disableLocalization},set:function(e){this._disableLocalization!==e&&(this._disableLocalization=e,this._onSetLocale(this._app.i18n.locale))}}]),t}(m),Jp=new Set(["system","entity","create","destroy","swap","move","scripts","_scripts","_scriptsIndex","_scriptsData","enabled","_oldState","onEnable","onDisable","onPostStateChange","_onSetEnabled","_checkState","_onBeforeRemove","_onInitializeAttributes","_onInitialize","_onPostInitialize","_onUpdate","_onPostUpdate","_callbacks","has","get","on","off","fire","once","hasEvent"]);function em(e,t){if(xl.legacy)return null;if(Jp.has(e))throw new Error("script name: '"+e+"' is reserved, please change script name");var i=function(e){m.prototype.initEventHandler.call(this),Rl.prototype.initScriptType.call(this,e)};return(i.prototype=Object.create(Rl.prototype)).constructor=i,i.extend=Rl.extend,i.attributes=new Ml(i),im(i,e,t),i}var tm={};function im(e,t,i){if(!e.legacy){if("function"!=typeof e)throw new Error("script class: '"+e+"' must be a constructor function (i.e. class).");if(!(e.prototype instanceof Rl))throw new Error("script class: '"+Rl.__getScriptName(e)+"' does not extend pc.ScriptType.");if(t=t||e.__name||Rl.__getScriptName(e),Jp.has(t))throw new Error("script name: '"+t+"' is reserved, please change script name");e.__name=t,(i?i.scripts:jl.getApplication().scripts).add(e),gl._push(e)}}Ml.reservedNames.forEach((function(e,t,i){tm[e]=1})),em.reservedAttributes=tm;var nm="mouse",sm="keyboard",rm="gamepad",am="mousedown",om="mousemove",hm="mouseup",lm="mousewheel",cm=function(e,t){t?(this.key=t.keyCode,this.element=t.target,this.event=t):(this.key=null,this.element=null,this.event=null)},um=new cm;function dm(e){return um.key=e.keyCode,um.element=e.target,um.event=e,um}function fm(e){return"string"==typeof e?e.toUpperCase().charCodeAt(0):e}var pm={9:"Tab",13:"Enter",16:"Shift",17:"Control",18:"Alt",27:"Escape",37:"Left",38:"Up",39:"Right",40:"Down",46:"Delete",91:"Win"},mm=function(e){function t(t,i){var n;return void 0===i&&(i={}),(n=e.call(this)||this)._element=null,n._keyDownHandler=n._handleKeyDown.bind(te(n)),n._keyUpHandler=n._handleKeyUp.bind(te(n)),n._keyPressHandler=n._handleKeyPress.bind(te(n)),n._visibilityChangeHandler=n._handleVisibilityChange.bind(te(n)),n._windowBlurHandler=n._handleWindowBlur.bind(te(n)),n._keymap={},n._lastmap={},t&&n.attach(t),n.preventDefault=i.preventDefault||!1,n.stopPropagation=i.stopPropagation||!1,n}J(t,e);var i=t.prototype;return i.attach=function(e){this._element&&this.detach(),this._element=e,this._element.addEventListener("keydown",this._keyDownHandler,!1),this._element.addEventListener("keypress",this._keyPressHandler,!1),this._element.addEventListener("keyup",this._keyUpHandler,!1),document.addEventListener("visibilitychange",this._visibilityChangeHandler,!1),window.addEventListener("blur",this._windowBlurHandler,!1)},i.detach=function(){this._element&&(this._element.removeEventListener("keydown",this._keyDownHandler),this._element.removeEventListener("keypress",this._keyPressHandler),this._element.removeEventListener("keyup",this._keyUpHandler),this._element=null,document.removeEventListener("visibilitychange",this._visibilityChangeHandler,!1),window.removeEventListener("blur",this._windowBlurHandler,!1))},i.toKeyIdentifier=function(e){e=fm(e);var t=pm[e.toString()];if(t)return t;for(var i=e.toString(16).toUpperCase(),n=i.length,s=0;s<4-n;s++)i="0"+i;return"U+"+i},i._handleKeyDown=function(e){var t=e.keyCode||e.charCode;if(void 0!==t){var i=this.toKeyIdentifier(t);this._keymap[i]=!0,this.fire("keydown",dm(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation()}},i._handleKeyUp=function(e){var t=e.keyCode||e.charCode;if(void 0!==t){var i=this.toKeyIdentifier(t);delete this._keymap[i],this.fire("keyup",dm(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation()}},i._handleKeyPress=function(e){this.fire("keypress",dm(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation()},i._handleVisibilityChange=function(){"hidden"===document.visibilityState&&this._handleWindowBlur()},i._handleWindowBlur=function(){this._keymap={},this._lastmap={}},i.update=function(){for(var e in this._lastmap)delete this._lastmap[e];for(var t in this._keymap)this._keymap.hasOwnProperty(t)&&(this._lastmap[t]=this._keymap[t])},i.isPressed=function(e){var t=fm(e),i=this.toKeyIdentifier(t);return!!this._keymap[i]},i.wasPressed=function(e){var t=fm(e),i=this.toKeyIdentifier(t);return!!this._keymap[i]&&!this._lastmap[i]},i.wasReleased=function(e){var t=fm(e),i=this.toKeyIdentifier(t);return!this._keymap[i]&&!!this._lastmap[i]},t}(m);function _m(){return!!(document.pointerLockElement||document.mozPointerLockElement||document.webkitPointerLockElement)}var gm,vm,ym=function e(t,i){var n={x:0,y:0};if(i){if(i instanceof e)throw Error("Expected MouseEvent");n=t._getTargetCoords(i)}else i={};if(n)this.x=n.x,this.y=n.y;else{if(!_m())return;this.x=0,this.y=0}this.wheelDelta=0,"wheel"===i.type&&(i.deltaY>0?this.wheelDelta=1:i.deltaY<0&&(this.wheelDelta=-1)),_m()?(this.dx=i.movementX||i.webkitMovementX||i.mozMovementX||0,this.dy=i.movementY||i.webkitMovementY||i.mozMovementY||0):(this.dx=this.x-t._lastX,this.dy=this.y-t._lastY),"mousedown"===i.type||"mouseup"===i.type?this.button=i.button:this.button=-1,this.buttons=t._buttons.slice(0),this.element=i.target,this.ctrlKey=i.ctrlKey||!1,this.altKey=i.altKey||!1,this.shiftKey=i.shiftKey||!1,this.metaKey=i.metaKey||!1,this.event=i},xm=function(e){function t(t){var i;return(i=e.call(this)||this)._lastX=0,i._lastY=0,i._buttons=[!1,!1,!1],i._lastbuttons=[!1,!1,!1],i._upHandler=i._handleUp.bind(te(i)),i._downHandler=i._handleDown.bind(te(i)),i._moveHandler=i._handleMove.bind(te(i)),i._wheelHandler=i._handleWheel.bind(te(i)),i._contextMenuHandler=function(e){e.preventDefault()},i._target=null,i._attached=!1,i.attach(t),i}J(t,e),t.isPointerLocked=function(){return _m()};var i=t.prototype;return i.attach=function(e){if(this._target=e,!this._attached){this._attached=!0;var t=!!L.passiveEvents&&{passive:!1};window.addEventListener("mouseup",this._upHandler,t),window.addEventListener("mousedown",this._downHandler,t),window.addEventListener("mousemove",this._moveHandler,t),window.addEventListener("wheel",this._wheelHandler,t)}},i.detach=function(){if(this._attached){this._attached=!1,this._target=null;var e=!!L.passiveEvents&&{passive:!1};window.removeEventListener("mouseup",this._upHandler,e),window.removeEventListener("mousedown",this._downHandler,e),window.removeEventListener("mousemove",this._moveHandler,e),window.removeEventListener("wheel",this._wheelHandler,e)}},i.disableContextMenu=function(){this._target&&this._target.addEventListener("contextmenu",this._contextMenuHandler)},i.enableContextMenu=function(){this._target&&this._target.removeEventListener("contextmenu",this._contextMenuHandler)},i.enablePointerLock=function(e,t){if(document.body.requestPointerLock){e&&document.addEventListener("pointerlockchange",(function t(){e(),document.removeEventListener("pointerlockchange",t)}),!1),t&&document.addEventListener("pointerlockerror",(function e(){t(),document.removeEventListener("pointerlockerror",e)}),!1),document.body.requestPointerLock()}else t&&t()},i.disablePointerLock=function(e){if(document.exitPointerLock){e&&document.addEventListener("pointerlockchange",(function t(){e(),document.removeEventListener("pointerlockchange",t)}),!1),document.exitPointerLock()}},i.update=function(){this._lastbuttons[0]=this._buttons[0],this._lastbuttons[1]=this._buttons[1],this._lastbuttons[2]=this._buttons[2]},i.isPressed=function(e){return this._buttons[e]},i.wasPressed=function(e){return this._buttons[e]&&!this._lastbuttons[e]},i.wasReleased=function(e){return!this._buttons[e]&&this._lastbuttons[e]},i._handleUp=function(e){this._buttons[e.button]=!1;var t=new ym(this,e);t.event&&this.fire(hm,t)},i._handleDown=function(e){this._buttons[e.button]=!0;var t=new ym(this,e);t.event&&this.fire(am,t)},i._handleMove=function(e){var t=new ym(this,e);t.event&&(this.fire(om,t),this._lastX=t.x,this._lastY=t.y)},i._handleWheel=function(e){var t=new ym(this,e);t.event&&this.fire(lm,t)},i._getTargetCoords=function(e){var t=this._target.getBoundingClientRect(),i=Math.floor(t.left),n=Math.floor(t.top);return e.clientX<i||e.clientX>=i+this._target.clientWidth||e.clientY<n||e.clientY>=n+this._target.clientHeight?null:{x:e.clientX-i,y:e.clientY-n}},t}(m),bm=function(){function e(e,t){void 0===t&&(t={}),this._keyboard=t.keyboard||null,this._mouse=t.mouse||null,this._gamepads=t.gamepads||null,this._element=null,this._actions={},this._axes={},this._axesValues={},e&&this.attach(e)}var t=e.prototype;return t.attach=function(e){this._element=e,this._keyboard&&this._keyboard.attach(e),this._mouse&&this._mouse.attach(e)},t.detach=function(){this._keyboard&&this._keyboard.detach(),this._mouse&&this._mouse.detach(),this._element=null},t.disableContextMenu=function(){this._mouse||this._enableMouse(),this._mouse.disableContextMenu()},t.enableContextMenu=function(){this._mouse||this._enableMouse(),this._mouse.enableContextMenu()},t.update=function(e){for(var t in this._keyboard&&this._keyboard.update(),this._mouse&&this._mouse.update(),this._gamepads&&this._gamepads.update(),this._axesValues={},this._axes)this._axesValues[t]=[]},t.appendAction=function(e,t){this._actions[e]=this._actions[e]||[],this._actions[e].push(t)},t.registerKeys=function(e,t){if(this._keyboard||this._enableKeyboard(),this._actions[e])throw new Error("Action: "+e+" already registered");if(void 0===t)throw new Error("Invalid button");t.length||(t=[t]),this.appendAction(e,{type:sm,keys:t})},t.registerMouse=function(e,t){if(this._mouse||this._enableMouse(),void 0===t)throw new Error("Invalid button");this.appendAction(e,{type:nm,button:t})},t.registerPadButton=function(e,t,i){if(void 0===i)throw new Error("Invalid button");this.appendAction(e,{type:rm,button:i,pad:t})},t.registerAxis=function(e){var t=e.name;this._axes[t]||(this._axes[t]=[]);var i=this._axes[t].push(t);(e=e||{}).pad=e.pad||0;var n=function(n,s,r,a){switch(s){case"mousex":n._mouse.on(om,(function(e){n._axesValues[t][i]=e.dx/10}));break;case"mousey":n._mouse.on(om,(function(e){n._axesValues[t][i]=e.dy/10}));break;case"key":n._axes[t].push((function(){return n._keyboard.isPressed(a)?r:0}));break;case"padrx":n._axes[t].push((function(){return n._gamepads.getAxis(e.pad,2)}));break;case"padry":n._axes[t].push((function(){return n._gamepads.getAxis(e.pad,3)}));break;case"padlx":n._axes[t].push((function(){return n._gamepads.getAxis(e.pad,0)}));break;case"padly":n._axes[t].push((function(){return n._gamepads.getAxis(e.pad,1)}));break;default:throw new Error("Unknown axis")}};n(this,e.positive,1,e.positiveKey),(e.negativeKey||e.negative!==e.positive)&&n(this,e.negative,-1,e.negativeKey)},t.isPressed=function(e){if(!this._actions[e])return!1;for(var t=this._actions[e].length,i=0;i<t;++i){var n=this._actions[e][i];switch(n.type){case sm:if(this._keyboard)for(var s=n.keys.length,r=0;r<s;r++)if(this._keyboard.isPressed(n.keys[r]))return!0;break;case nm:if(this._mouse&&this._mouse.isPressed(n.button))return!0;break;case rm:if(this._gamepads&&this._gamepads.isPressed(n.pad,n.button))return!0}}return!1},t.wasPressed=function(e){if(!this._actions[e])return!1;for(var t=this._actions[e].length,i=0;i<t;++i){var n=this._actions[e][i];switch(n.type){case sm:if(this._keyboard)for(var s=n.keys.length,r=0;r<s;r++)if(this._keyboard.wasPressed(n.keys[r]))return!0;break;case nm:if(this._mouse&&this._mouse.wasPressed(n.button))return!0;break;case rm:if(this._gamepads&&this._gamepads.wasPressed(n.pad,n.button))return!0}}return!1},t.getAxis=function(e){var t=0;if(this._axes[e])for(var i=this._axes[e].length,n=0;n<i;n++)if("function"===d(this._axes[e][n])){var s=this._axes[e][n]();Math.abs(s)>Math.abs(t)&&(t=s)}else this._axesValues[e]&&Math.abs(this._axesValues[e][n])>Math.abs(t)&&(t=this._axesValues[e][n]);return t},t._enableMouse=function(){if(this._mouse=new xm,!this._element)throw new Error("Controller must be attached to an Element");this._mouse.attach(this._element)},t._enableKeyboard=function(){if(this._keyboard=new mm,!this._element)throw new Error("Controller must be attached to an Element");this._keyboard.attach(this._element)},e}(),Sm=new ye,wm=new ye,Tm=new et,Am=new et,Mm=new et;Tm.end=new ye,Am.end=new ye,Mm.end=new ye;var Cm=new ye,Em=new ye,Pm=new ye,Rm=new ye,Im=new ye,Lm=new ye,Dm=new ye,km=new ye,Om=new ye,Fm=new ye,Bm=new ye,Nm=new ye,Um=new ye,zm=new ye,Vm=new ye,Gm=new ye,Wm=new ye,Hm=new ye,Xm=new ye,qm=new ye,jm=new Se;function Ym(e,t,i){return Bm.cross(e,t).dot(i)}var Km=function(){function e(e,t,i){this.event=e,this.element=t,this.camera=i,this._stopPropagation=!1}return e.prototype.stopPropagation=function(){this._stopPropagation=!0,this.event&&(this.event.stopImmediatePropagation(),this.event.stopPropagation())},e}(),Zm=function(e){function t(t,i,n,s,r,a,o){var h;return(h=e.call(this,t,i,n)||this).x=s,h.y=r,h.ctrlKey=t.ctrlKey||!1,h.altKey=t.altKey||!1,h.shiftKey=t.shiftKey||!1,h.metaKey=t.metaKey||!1,h.button=t.button,xm.isPointerLocked()?(h.dx=t.movementX||t.webkitMovementX||t.mozMovementX||0,h.dy=t.movementY||t.webkitMovementY||t.mozMovementY||0):(h.dx=s-a,h.dy=r-o),h.wheelDelta=0,"wheel"===t.type&&(t.deltaY>0?h.wheelDelta=1:t.deltaY<0&&(h.wheelDelta=-1)),h}return J(t,e),t}(Km),$m=function(e){function t(t,i,n,s,r,a){var o;return(o=e.call(this,t,i,n)||this).touches=t.touches,o.changedTouches=t.changedTouches,o.x=s,o.y=r,o.touch=a,o}return J(t,e),t}(Km),Qm=function(e){function t(t,i,n,s){var r;return(r=e.call(this,t,i,n)||this).inputSource=s,r}return J(t,e),t}(Km),Jm=function(){function e(e,t){this._app=null,this._attached=!1,this._target=null,this._enabled=!0,this._lastX=0,this._lastY=0,this._upHandler=this._handleUp.bind(this),this._downHandler=this._handleDown.bind(this),this._moveHandler=this._handleMove.bind(this),this._wheelHandler=this._handleWheel.bind(this),this._touchstartHandler=this._handleTouchStart.bind(this),this._touchendHandler=this._handleTouchEnd.bind(this),this._touchcancelHandler=this._touchendHandler,this._touchmoveHandler=this._handleTouchMove.bind(this),this._sortHandler=this._sortElements.bind(this),this._elements=[],this._hoveredElement=null,this._pressedElement=null,this._touchedElements={},this._touchesForWhichTouchLeaveHasFired={},this._selectedElements={},this._selectedPressedElements={},this._useMouse=!t||!1!==t.useMouse,this._useTouch=!t||!1!==t.useTouch,this._useXr=!t||!1!==t.useXr,this._selectEventsAttached=!1,L.touch&&(this._clickedEntities={}),this.attach(e)}var t=e.prototype;return t.attach=function(e){this._attached&&(this._attached=!1,this.detach()),this._target=e,this._attached=!0;var t=!!L.passiveEvents&&{passive:!0};this._useMouse&&(window.addEventListener("mouseup",this._upHandler,t),window.addEventListener("mousedown",this._downHandler,t),window.addEventListener("mousemove",this._moveHandler,t),window.addEventListener("wheel",this._wheelHandler,t)),this._useTouch&&L.touch&&(this._target.addEventListener("touchstart",this._touchstartHandler,t),this._target.addEventListener("touchend",this._touchendHandler,!1),this._target.addEventListener("touchmove",this._touchmoveHandler,!1),this._target.addEventListener("touchcancel",this._touchcancelHandler,!1)),this.attachSelectEvents()},t.attachSelectEvents=function(){!this._selectEventsAttached&&this._useXr&&this.app&&this.app.xr&&this.app.xr.supported&&(this._clickedEntities||(this._clickedEntities={}),this._selectEventsAttached=!0,this.app.xr.on("start",this._onXrStart,this))},t.detach=function(){if(this._attached){this._attached=!1;var e=!!L.passiveEvents&&{passive:!0};this._useMouse&&(window.removeEventListener("mouseup",this._upHandler,e),window.removeEventListener("mousedown",this._downHandler,e),window.removeEventListener("mousemove",this._moveHandler,e),window.removeEventListener("wheel",this._wheelHandler,e)),this._useTouch&&(this._target.removeEventListener("touchstart",this._touchstartHandler,e),this._target.removeEventListener("touchend",this._touchendHandler,!1),this._target.removeEventListener("touchmove",this._touchmoveHandler,!1),this._target.removeEventListener("touchcancel",this._touchcancelHandler,!1)),this._selectEventsAttached&&(this._selectEventsAttached=!1,this.app.xr.off("start",this._onXrStart,this),this.app.xr.off("end",this._onXrEnd,this),this.app.xr.off("update",this._onXrUpdate,this),this.app.xr.input.off("selectstart",this._onSelectStart,this),this.app.xr.input.off("selectend",this._onSelectEnd,this),this.app.xr.input.off("remove",this._onXrInputRemove,this)),this._target=null}},t.addElement=function(e){-1===this._elements.indexOf(e)&&this._elements.push(e)},t.removeElement=function(e){var t=this._elements.indexOf(e);-1!==t&&this._elements.splice(t,1)},t._handleUp=function(e){this._enabled&&(xm.isPointerLocked()||(this._calcMouseCoords(e),this._onElementMouseEvent("mouseup",e)))},t._handleDown=function(e){this._enabled&&(xm.isPointerLocked()||(this._calcMouseCoords(e),this._onElementMouseEvent("mousedown",e)))},t._handleMove=function(e){this._enabled&&(this._calcMouseCoords(e),this._onElementMouseEvent("mousemove",e),this._lastX=gm,this._lastY=vm)},t._handleWheel=function(e){this._enabled&&(this._calcMouseCoords(e),this._onElementMouseEvent("mousewheel",e))},t._determineTouchedElements=function(e){for(var t={},i=this.app.systems.camera.cameras,n=i.length-1;n>=0;n--){for(var s=i[n],r=0,a=e.changedTouches.length,o=0;o<a;o++)if(t[e.changedTouches[o].identifier])r++;else{var h=this._calcTouchCoords(e.changedTouches[o]),l=this._getTargetElementByCoords(s,h.x,h.y);l&&(r++,t[e.changedTouches[o].identifier]={element:l,camera:s,x:h.x,y:h.y})}if(r===a)break}return t},t._handleTouchStart=function(e){if(this._enabled){for(var t=this._determineTouchedElements(e),i=0,n=e.changedTouches.length;i<n;i++){var s=e.changedTouches[i],r=t[s.identifier],a=this._touchedElements[s.identifier];!r||a&&r.element===a.element||(this._fireEvent(e.type,new $m(e,r.element,r.camera,r.x,r.y,s)),this._touchesForWhichTouchLeaveHasFired[s.identifier]=!1)}for(var o in t)this._touchedElements[o]=t[o]}},t._handleTouchEnd=function(e){if(this._enabled){var t=this.app.systems.camera.cameras;for(var i in this._clickedEntities)delete this._clickedEntities[i];for(var n=0,s=e.changedTouches.length;n<s;n++){var r=e.changedTouches[n],a=this._touchedElements[r.identifier];if(a){var o=a.element,h=a.camera,l=a.x,c=a.y;delete this._touchedElements[r.identifier],delete this._touchesForWhichTouchLeaveHasFired[r.identifier],this._fireEvent(e.type,new $m(e,o,h,l,c,r));for(var u=this._calcTouchCoords(r),d=t.length-1;d>=0;d--){this._getTargetElementByCoords(t[d],u.x,u.y)===o&&(this._clickedEntities[o.entity.getGuid()]||(this._fireEvent("click",new $m(e,o,h,l,c,r)),this._clickedEntities[o.entity.getGuid()]=!0))}}}}},t._handleTouchMove=function(e){if(e.preventDefault(),this._enabled)for(var t=this._determineTouchedElements(e),i=0,n=e.changedTouches.length;i<n;i++){var s=e.changedTouches[i],r=t[s.identifier],a=this._touchedElements[s.identifier];if(a){var o=this._calcTouchCoords(s);r&&r.element===a.element||this._touchesForWhichTouchLeaveHasFired[s.identifier]||(this._fireEvent("touchleave",new $m(e,a.element,a.camera,o.x,o.y,s)),this._touchesForWhichTouchLeaveHasFired[s.identifier]=!0),this._fireEvent("touchmove",new $m(e,a.element,a.camera,o.x,o.y,s))}}},t._onElementMouseEvent=function(e,t){var i=null,n=this._hoveredElement;this._hoveredElement=null;for(var s,r=this.app.systems.camera.cameras,a=r.length-1;a>=0&&(s=r[a],!(i=this._getTargetElementByCoords(s,gm,vm)));a--);this._hoveredElement=i,"mousemove"!==e&&"mouseup"!==e||!this._pressedElement?i&&(this._fireEvent(e,new Zm(t,i,s,gm,vm,this._lastX,this._lastY)),"mousedown"===e&&(this._pressedElement=i)):this._fireEvent(e,new Zm(t,this._pressedElement,s,gm,vm,this._lastX,this._lastY)),n!==this._hoveredElement&&(n&&this._fireEvent("mouseleave",new Zm(t,n,s,gm,vm,this._lastX,this._lastY)),this._hoveredElement&&this._fireEvent("mouseenter",new Zm(t,this._hoveredElement,s,gm,vm,this._lastX,this._lastY))),"mouseup"===e&&this._pressedElement&&(this._pressedElement===this._hoveredElement?(this._pressedElement=null,this._clickedEntities&&this._clickedEntities[this._hoveredElement.entity.getGuid()]||this._fireEvent("click",new Zm(t,this._hoveredElement,s,gm,vm,this._lastX,this._lastY))):this._pressedElement=null)},t._onXrStart=function(){this.app.xr.on("end",this._onXrEnd,this),this.app.xr.on("update",this._onXrUpdate,this),this.app.xr.input.on("selectstart",this._onSelectStart,this),this.app.xr.input.on("selectend",this._onSelectEnd,this),this.app.xr.input.on("remove",this._onXrInputRemove,this)},t._onXrEnd=function(){this.app.xr.off("update",this._onXrUpdate,this),this.app.xr.input.off("selectstart",this._onSelectStart,this),this.app.xr.input.off("selectend",this._onSelectEnd,this),this.app.xr.input.off("remove",this._onXrInputRemove,this)},t._onXrUpdate=function(){if(this._enabled)for(var e=this.app.xr.input.inputSources,t=0;t<e.length;t++)this._onElementSelectEvent("selectmove",e[t],null)},t._onXrInputRemove=function(e){var t=this._selectedElements[e.id];t&&(e._elementEntity=null,this._fireEvent("selectleave",new Qm(null,t,null,e))),delete this._selectedElements[e.id],delete this._selectedPressedElements[e.id]},t._onSelectStart=function(e,t){this._enabled&&this._onElementSelectEvent("selectstart",e,t)},t._onSelectEnd=function(e,t){this._enabled&&this._onElementSelectEvent("selectend",e,t)},t._onElementSelectEvent=function(e,t,i){var n,s,r,a=this._selectedElements[t.id],o=this.app.systems.camera.cameras;if(t.elementInput){Mm.set(t.getOrigin(),t.getDirection());for(var h=o.length-1;h>=0&&(r=o[h],!(n=this._getTargetElementByRay(Mm,r)));h--);}t._elementEntity=n||null,n?(this._selectedElements[t.id]=n,s=n):delete this._selectedElements[t.id],a!==s&&(a&&this._fireEvent("selectleave",new Qm(i,a,r,t)),s&&this._fireEvent("selectenter",new Qm(i,s,r,t))),"selectstart"===e&&(this._selectedPressedElements[t.id]=s,s&&this._fireEvent("selectstart",new Qm(i,s,r,t)));var l=this._selectedPressedElements[t.id];!t.elementInput&&l&&(delete this._selectedPressedElements[t.id],a&&this._fireEvent("selectend",new Qm(i,a,r,t))),"selectend"===e&&t.elementInput&&(delete this._selectedPressedElements[t.id],a&&this._fireEvent("selectend",new Qm(i,a,r,t)),l&&l===a&&this._fireEvent("click",new Qm(i,l,r,t)))},t._fireEvent=function(e,t){for(var i=t.element;i.fire(e,t),!t._stopPropagation&&i.entity.parent&&(i=i.entity.parent.element););},t._calcMouseCoords=function(e){var t=this._target.getBoundingClientRect(),i=Math.floor(t.left),n=Math.floor(t.top);gm=e.clientX-i,vm=e.clientY-n},t._calcTouchCoords=function(e){for(var t=0,i=0,n=e.target;!(n instanceof HTMLElement);)n=n.parentNode;var s=n;do{t+=s.offsetLeft-s.scrollLeft,i+=s.offsetTop-s.scrollTop,s=s.offsetParent}while(s);return{x:e.pageX-t,y:e.pageY-i}},t._sortElements=function(e,t){var i=this.app.scene.layers.sortTransparentLayers(e.layers,t.layers);return 0!==i?i:e.screen&&!t.screen?-1:!e.screen&&t.screen?1:e.screen||t.screen?e.screen.screen.screenSpace&&!t.screen.screen.screenSpace?-1:t.screen.screen.screenSpace&&!e.screen.screen.screenSpace?1:t.drawOrder-e.drawOrder:0},t._getTargetElementByCoords=function(e,t,i){var n=this._calculateRayScreen(t,i,e,Tm)?Tm:null,s=this._calculateRay3d(t,i,e,Am)?Am:null;return this._getTargetElement(e,n,s)},t._getTargetElementByRay=function(e,t){Tm.origin.copy(e.origin),Tm.direction.copy(e.direction),Tm.end.copy(Tm.direction).mulScalar(2*t.farClip).add(Tm.origin);var i=Tm,n=t.worldToScreen(i.origin,Sm),s=this._calculateRayScreen(n.x,n.y,t,Am)?Am:null;return this._getTargetElement(t,s,i)},t._getTargetElement=function(e,t,i){var n=null,s=1/0;this._elements.sort(this._sortHandler);for(var r=0,a=this._elements.length;r<a;r++){var o=this._elements[r];if(o.layers.some((function(t){return e.layersSet.has(t)})))if(o.screen&&o.screen.screen.screenSpace){if(!t)continue;if(this._checkElement(t,o,!0)>=0){n=o;break}}else{if(!i)continue;var h=this._checkElement(i,o,!1);if(h>=0&&(h<s&&(n=o,s=h),o.screen)){n=o;break}}}return n},t._buildHitCorners=function(e,t,i,n,s){var r=t;if(e.entity&&e.entity.button){var a=e.entity.button.hitPadding||jm;Um.copy(e.entity.up),zm.copy(Um).mulScalar(-1),Gm.copy(e.entity.right),Vm.copy(Gm).mulScalar(-1),Um.mulScalar(a.w*n),zm.mulScalar(a.y*n),Gm.mulScalar(a.z*i),Vm.mulScalar(a.x*i),Wm.copy(r[0]).add(zm).add(Vm),Hm.copy(r[1]).add(zm).add(Gm),Xm.copy(r[2]).add(Um).add(Gm),qm.copy(r[3]).add(Um).add(Vm),r=[Wm,Hm,Xm,qm]}if(i<0){var o=r[2].x,h=r[0].x;r[0].x=o,r[1].x=h,r[2].x=h,r[3].x=o}if(n<0){var l=r[2].y,c=r[0].y;r[0].y=l,r[1].y=l,r[2].y=c,r[3].y=c}if(s<0){var u=r[2].x,d=r[2].y,f=r[2].z;r[2].x=r[0].x,r[2].y=r[0].y,r[2].z=r[0].z,r[0].x=u,r[0].y=d,r[0].z=f}return r},t._calculateScaleToScreen=function(e){var t=e.entity,i=e.screen.screen.scale;for(Nm.set(i,i,i);t&&!t.screen;)Nm.mul(t.getLocalScale()),t=t.parent;return Nm},t._calculateScaleToWorld=function(e){var t=e.entity;for(Nm.set(1,1,1);t;)Nm.mul(t.getLocalScale()),t=t.parent;return Nm},t._calculateRayScreen=function(e,t,i,n){var s=this.app.graphicsDevice.width,r=this.app.graphicsDevice.height,a=i.rect.z*s,o=i.rect.w*r,h=i.rect.x*s,l=h+a,c=(1-i.rect.y)*r,u=c-o,d=e*s/this._target.clientWidth,f=t*r/this._target.clientHeight;return d>=h&&d<=l&&f<=c&&f>=u&&(d=s*(d-h)/a,f=r-(f=r*(f-u)/o),n.origin.set(d,f,1),n.direction.set(0,0,-1),n.end.copy(n.direction).mulScalar(2).add(n.origin),!0)},t._calculateRay3d=function(e,t,i,n){var s=this._target.clientWidth,r=this._target.clientHeight,a=i.rect.z*s,o=i.rect.w*r,h=i.rect.x*s,l=h+a,c=(1-i.rect.y)*r,u=c-o,d=e,f=t;return e>=h&&e<=l&&t<=c&&f>=u&&(d=s*(d-h)/a,f=r*(f-u)/o,i.screenToWorld(d,f,i.nearClip,Sm),i.screenToWorld(d,f,i.farClip,wm),n.origin.copy(Sm),n.direction.set(0,0,-1),n.end.copy(wm),!0)},t._checkElement=function(e,t,i){if(t.maskedBy&&this._checkElement(e,t.maskedBy.element,i)<0)return-1;var n;n=i?this._calculateScaleToScreen(t):this._calculateScaleToWorld(t);var s=this._buildHitCorners(t,i?t.screenCorners:t.worldCorners,n.x,n.y,n.z);return function(e,t,i){Cm.sub2(t,e),Em.sub2(i[0],e),Pm.sub2(i[1],e),Rm.sub2(i[2],e),Lm.cross(Rm,Cm);var n,s,r=Em.dot(Lm);if(r>=0){if((n=-Pm.dot(Lm))<0)return-1;if((s=Ym(Cm,Pm,Em))<0)return-1;var a=1/(n+r+s);Dm.copy(i[0]).mulScalar(n*a),km.copy(i[1]).mulScalar(r*a),Om.copy(i[2]).mulScalar(s*a),Fm.copy(Dm).add(km).add(Om)}else{if(Im.sub2(i[3],e),(n=Im.dot(Lm))<0)return-1;if((s=Ym(Cm,Em,Im))<0)return-1;var o=1/(n+(r=-r)+s);Dm.copy(i[0]).mulScalar(n*o),km.copy(i[3]).mulScalar(r*o),Om.copy(i[2]).mulScalar(s*o),Fm.copy(Dm).add(km).add(Om)}return Cm.sub2(i[0],i[2]).lengthSq()<1e-8||Cm.sub2(i[1],i[3]).lengthSq()<1e-8?-1:Fm.sub(e).lengthSq()}(e.origin,e.end,s)},$(e,[{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"app",get:function(){return this._app||Kr()},set:function(e){this._app=e}}]),e}(),e_={DEFAULT:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_3","PAD_FACE_4","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_UP","PAD_DOWN","PAD_LEFT","PAD_RIGHT","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"]},PS3:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_4","PAD_FACE_3","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_UP","PAD_DOWN","PAD_LEFT","PAD_RIGHT","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"]}},t_={"Product: 0268":"PS3"},i_=function(){function e(){this.gamepadsSupported=!!navigator.getGamepads||!!navigator.webkitGetGamepads,this.current=[],this.previous=[],this.deadZone=.25}var t=e.prototype;return t.update=function(){for(var e=0,t=this.current.length;e<t;e++)for(var i=this.current[e].pad.buttons,n=i.length,s=0;s<n;s++)void 0===this.previous[e]&&(this.previous[e]=[]),this.previous[e][s]=i[s].pressed;this.poll(this.current)},t.poll=function(e){if(void 0===e&&(e=[]),e.length>0&&(e.length=0),this.gamepadsSupported)for(var t=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads(),i=0,n=t.length;i<n;i++)t[i]&&e.push({map:this.getMap(t[i]),pad:t[i]});return e},t.getMap=function(e){for(var t in t_)if(e.id.indexOf(t)>=0)return e_[t_[t]];return e_.DEFAULT},t.isPressed=function(e,t){if(!this.current[e])return!1;var i=this.current[e].map.buttons[t];return this.current[e].pad.buttons[pc[i]].pressed},t.wasPressed=function(e,t){if(!this.current[e])return!1;var i=this.current[e].map.buttons[t],n=pc[i];return this.current[e].pad.buttons[n].pressed&&!(this.previous[e]&&this.previous[e][n])},t.wasReleased=function(e,t){if(!this.current[e])return!1;var i=this.current[e].map.buttons[t],n=pc[i];return!this.current[e].pad.buttons[n].pressed&&this.previous[e]&&this.previous[e][n]},t.getAxis=function(e,t){if(!this.current[e])return 0;var i=this.current[e].map.axes[t],n=this.current[e].pad.axes[pc[i]];return Math.abs(n)<this.deadZone&&(n=0),n},e}();function n_(e){for(var t=0,i=0,n=e.target;!(n instanceof HTMLElement);)n=n.parentNode;var s=n;do{t+=s.offsetLeft-s.scrollLeft,i+=s.offsetTop-s.scrollTop,s=s.offsetParent}while(s);return{x:e.pageX-t,y:e.pageY-i}}var s_=function(e){var t=n_(e);this.id=e.identifier,this.x=t.x,this.y=t.y,this.target=e.target,this.touch=e},r_=function(){function e(e,t){if(this.element=t.target,this.event=t,this.touches=[],this.changedTouches=[],t){for(var i=0,n=t.touches.length;i<n;i++)this.touches.push(new s_(t.touches[i]));for(var s=0,r=t.changedTouches.length;s<r;s++)this.changedTouches.push(new s_(t.changedTouches[s]))}}return e.prototype.getTouchById=function(e,t){for(var i=0,n=t.length;i<n;i++)if(t[i].id===e)return t[i];return null},e}(),a_=function(e){function t(t){var i;return(i=e.call(this)||this)._element=null,i._startHandler=i._handleTouchStart.bind(te(i)),i._endHandler=i._handleTouchEnd.bind(te(i)),i._moveHandler=i._handleTouchMove.bind(te(i)),i._cancelHandler=i._handleTouchCancel.bind(te(i)),i.attach(t),i}J(t,e);var i=t.prototype;return i.attach=function(e){this._element&&this.detach(),this._element=e,this._element.addEventListener("touchstart",this._startHandler,!1),this._element.addEventListener("touchend",this._endHandler,!1),this._element.addEventListener("touchmove",this._moveHandler,!1),this._element.addEventListener("touchcancel",this._cancelHandler,!1)},i.detach=function(){this._element&&(this._element.removeEventListener("touchstart",this._startHandler,!1),this._element.removeEventListener("touchend",this._endHandler,!1),this._element.removeEventListener("touchmove",this._moveHandler,!1),this._element.removeEventListener("touchcancel",this._cancelHandler,!1)),this._element=null},i._handleTouchStart=function(e){this.fire("touchstart",new r_(this,e))},i._handleTouchEnd=function(e){this.fire("touchend",new r_(this,e))},i._handleTouchMove=function(e){e.preventDefault(),this.fire("touchmove",new r_(this,e))},i._handleTouchCancel=function(e){this.fire("touchcancel",new r_(this,e))},t}(m),o_=function(){this.elementInput=void 0,this.keyboard=void 0,this.mouse=void 0,this.touch=void 0,this.gamepads=void 0,this.scriptPrefix=void 0,this.assetPrefix=void 0,this.scriptsOrder=void 0,this.soundManager=void 0,this.graphicsDevice=void 0,this.lightmapper=void 0,this.batchManager=void 0,this.xr=void 0,this.componentSystems=[],this.resourceHandlers=[]},h_=function(e){function t(t){var i;return(i=e.call(this)||this).app=t,i.store={},i.schema=[],i}J(t,e);var i=t.prototype;return i.addComponent=function(e,t){void 0===t&&(t={});var i=new this.ComponentType(this,e),n=new this.DataType;return this.store[e.getGuid()]={entity:e,data:n},e[this.id]=i,e.c[this.id]=i,this.initializeComponentData(i,t,[]),this.fire("add",e,i),i},i.removeComponent=function(e){var t=this.store[e.getGuid()],i=e.c[this.id];this.fire("beforeremove",e,i),delete this.store[e.getGuid()],e[this.id]=void 0,delete e.c[this.id],this.fire("remove",e,t.data)},i.cloneComponent=function(e,t){var i=this.store[e.getGuid()];return this.addComponent(t,i.data)},i.initializeComponentData=function(e,t,i){void 0===t&&(t={});for(var n=0,s=i.length;n<s;n++){var r=i[n],a=void 0,o=void 0;"object"==typeof r?(a=r.name,o=r.type):(a=r,o=void 0);var h=t[a];void 0!==h?(void 0!==o&&(h=l_(h,o)),e[a]=h):e[a]=e.data[a]}e.enabled&&e.entity.enabled&&e.onEnable()},i.getPropertiesOfType=function(e){var t=[];return(this.schema||[]).forEach((function(i){i&&"object"==typeof i&&i.type===e&&t.push(i)})),t},i.destroy=function(){this.off()},t}(m);function l_(e,t){if(!e)return e;switch(t){case"rgb":return e instanceof me?e.clone():new me(e[0],e[1],e[2]);case"rgba":return e instanceof me?e.clone():new me(e[0],e[1],e[2],e[3]);case"vec2":return e instanceof be?e.clone():new be(e[0],e[1]);case"vec3":return e instanceof ye?e.clone():new ye(e[0],e[1],e[2]);case"vec4":return e instanceof Se?e.clone():new Se(e[0],e[1],e[2],e[3]);case"boolean":case"number":case"string":case"entity":return e;default:throw new Error("Could not convert unhandled type: "+t)}}var c_=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._animations={},n._assets=[],n._loop=!0,n.animEvaluator=null,n.model=null,n.skeleton=null,n.fromSkel=null,n.toSkel=null,n.animationsIndex={},n.prevAnim=null,n.currAnim=null,n.blend=0,n.blending=!1,n.blendSpeed=0,n.activate=!0,n.speed=1,n}J(t,e);var i=t.prototype;return i.play=function(e,t){if(void 0===t&&(t=0),this.enabled&&this.entity.enabled&&this.animations[e]){if(this.prevAnim=this.currAnim,this.currAnim=e,this.model){this.skeleton||this.animEvaluator||this._createAnimationController();var i=this.animations[this.prevAnim],n=this.animations[this.currAnim];if(this.blending=t>0&&!!this.prevAnim,this.blending&&(this.blend=0,this.blendSpeed=1/t),this.skeleton&&(this.blending?(this.fromSkel.animation=i,this.fromSkel.addTime(this.skeleton._time),this.toSkel.animation=n):this.skeleton.animation=n),this.animEvaluator){var s=this.animEvaluator;if(this.blending)for(;s.clips.length>1;)s.removeClip(0);else this.animEvaluator.removeClips();var r=new Su(this.animations[this.currAnim],0,1,!0,this.loop);r.name=this.currAnim,r.blendWeight=this.blending?0:1,r.reset(),this.animEvaluator.addClip(r)}}this.playing=!0}},i.getAnimation=function(e){return this.animations[e]},i.setModel=function(e){e!==this.model&&(this._resetAnimationController(),this.model=e,this.animations&&this.currAnim&&this.animations[this.currAnim]&&this.play(this.currAnim))},i.onSetAnimations=function(){var e=this.entity.model;if(e){var t=e.model;t&&t!==this.model&&this.setModel(t)}if(!this.currAnim&&this.activate&&this.enabled&&this.entity.enabled){var i=Object.keys(this._animations);i.length>0&&this.play(i[0])}},i._resetAnimationController=function(){this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animEvaluator=null},i._createAnimationController=function(){var e=this.model,t=this.animations,i=!1,n=!1;for(var s in t){if(t.hasOwnProperty(s))t[s].constructor===Ju?n=!0:i=!0}var r=e.getGraph();i?(this.fromSkel=new vu(r),this.toSkel=new vu(r),this.skeleton=new vu(r),this.skeleton.looping=this.loop,this.skeleton.setGraph(r)):n&&(this.animEvaluator=new Zu(new ed(this.entity)))},i.loadAnimationAssets=function(e){var t=this;if(e&&e.length)for(var i=this.system.app.assets,n=function(e){if(e.resources.length>1)for(var i=0;i<e.resources.length;i++)t.animations[e.resources[i].name]=e.resources[i],t.animationsIndex[e.id]=e.resources[i].name;else t.animations[e.name]=e.resource,t.animationsIndex[e.id]=e.name;t.animations=t.animations},s=function(e){e.off("change",t.onAssetChanged,t),e.on("change",t.onAssetChanged,t),e.off("remove",t.onAssetRemoved,t),e.on("remove",t.onAssetRemoved,t),e.resource?n(e):(e.once("load",n,t),t.enabled&&t.entity.enabled&&i.load(e))},r=0,a=e.length;r<a;r++){var o=i.get(e[r]);o?s(o):i.on("add:"+e[r],s)}},i.onAssetChanged=function(e,t,i,n){if("resource"===t||"resources"===t)if("resources"===t&&i&&0===i.length&&(i=null),i){var s=!1;if(i.length>1){if(n&&n.length>1)for(var r=0;r<n.length;r++)delete this.animations[n[r].name];else delete this.animations[e.name];s=!1;for(var a=0;a<i.length;a++)this.animations[i[a].name]=i[a],s||this.currAnim!==i[a].name||this.playing&&this.enabled&&this.entity.enabled&&(s=!0,this.play(i[a].name));s||(this._stopCurrentAnimation(),this.onSetAnimations())}else{if(n&&n.length>1)for(var o=0;o<n.length;o++)delete this.animations[n[o].name];this.animations[e.name]=i[0]||i,s=!1,this.currAnim===e.name&&this.playing&&this.enabled&&this.entity.enabled&&(s=!0,this.play(e.name)),s||(this._stopCurrentAnimation(),this.onSetAnimations())}this.animationsIndex[e.id]=e.name}else{if(n.length>1)for(var h=0;h<n.length;h++)delete this.animations[n[h].name],this.currAnim===n[h].name&&this._stopCurrentAnimation();else delete this.animations[e.name],this.currAnim===e.name&&this._stopCurrentAnimation();delete this.animationsIndex[e.id]}},i.onAssetRemoved=function(e){if(e.off("remove",this.onAssetRemoved,this),this.animations){if(e.resources.length>1)for(var t=0;t<e.resources.length;t++)delete this.animations[e.resources[t].name],this.currAnim===e.resources[t].name&&this._stopCurrentAnimation();else delete this.animations[e.name],this.currAnim===e.name&&this._stopCurrentAnimation();delete this.animationsIndex[e.id]}},i._stopCurrentAnimation=function(){if(this.currAnim=null,this.playing=!1,this.skeleton&&(this.skeleton.currentTime=0,this.skeleton.animation=null),this.animEvaluator){for(var e=0;e<this.animEvaluator.clips.length;++e)this.animEvaluator.clips[e].stop();this.animEvaluator.update(0),this.animEvaluator.removeClips()}},i.onEnable=function(){e.prototype.onEnable.call(this);var t=this.assets,i=this.system.app.assets;if(t)for(var n=0,s=t.length;n<s;n++){var r=t[n];r instanceof ml||(r=i.get(r)),r&&!r.resource&&i.load(r)}if(this.activate&&!this.currAnim){var a=Object.keys(this.animations);a.length>0&&this.play(a[0])}},i.onBeforeRemove=function(){for(var e=0;e<this.assets.length;e++){var t=this.assets[e];"number"==typeof t&&(t=this.system.app.assets.get(t)),t&&(t.off("change",this.onAssetChanged,this),t.off("remove",this.onAssetRemoved,this))}this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animEvaluator=null},i.update=function(e){if(this.blending&&(this.blend+=e*this.blendSpeed,this.blend>=1&&(this.blend=1)),this.playing){var t=this.skeleton;if(null!==t&&null!==this.model){if(this.blending)t.blend(this.fromSkel,this.toSkel,this.blend);else{var i=e*this.speed;t.addTime(i),(this.speed>0&&t._time===t.animation.duration&&!this.loop||this.speed<0&&0===t._time&&!this.loop)&&(this.playing=!1)}this.blending&&1===this.blend&&(t.animation=this.toSkel.animation),t.updateGraph()}}var n=this.animEvaluator;if(n){for(var s=0;s<n.clips.length;++s){var r=n.clips[s];r.speed=this.speed,this.playing?r.resume():r.pause()}this.blending&&n.clips.length>1&&(n.clips[1].blendWeight=this.blend),n.update(e)}this.blending&&1===this.blend&&(this.blending=!1)},$(t,[{key:"animations",get:function(){return this._animations},set:function(e){this._animations=e,this.onSetAnimations()}},{key:"assets",get:function(){return this._assets},set:function(e){var t=this._assets;if(t&&t.length)for(var i=0;i<t.length;i++)if(t[i]){var n=this.system.app.assets.get(t[i]);if(n){n.off("change",this.onAssetChanged,this),n.off("remove",this.onAssetRemoved,this);var s=this.animationsIndex[n.id];this.currAnim===s&&this._stopCurrentAnimation(),delete this.animations[s],delete this.animationsIndex[n.id]}}this._assets=e;var r=e.map((function(e){return e instanceof ml?e.id:e}));this.loadAnimationAssets(r)}},{key:"currentTime",get:function(){if(this.skeleton)return this.skeleton._time;if(this.animEvaluator){var e=this.animEvaluator.clips;if(e.length>0)return e[e.length-1].time}return 0},set:function(e){if(this.skeleton&&(this.skeleton.currentTime=e,this.skeleton.addTime(0),this.skeleton.updateGraph()),this.animEvaluator)for(var t=this.animEvaluator.clips,i=0;i<t.length;++i)t[i].time=e}},{key:"duration",get:function(){return this.animations[this.currAnim].duration}},{key:"loop",get:function(){return this._loop},set:function(e){if(this._loop=e,this.skeleton&&(this.skeleton.looping=e),this.animEvaluator)for(var t=0;t<this.animEvaluator.clips.length;++t)this.animEvaluator.clips[t].loop=e}}]),t}(Cl),u_=function(){this.enabled=!0},d_=["enabled"],f_=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="animation",i.ComponentType=c_,i.DataType=u_,i.schema=d_,i.on("beforeremove",i.onBeforeRemove,te(i)),i.app.systems.on("update",i.onUpdate,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){for(var s,r=ne(["activate","enabled","loop","speed","assets"]);!(s=r()).done;){var a=s.value;i.hasOwnProperty(a)&&(t[a]=i[a])}e.prototype.initializeComponentData.call(this,t,i,d_)},i.cloneComponent=function(e,t){this.addComponent(t,{}),t.animation.assets=e.animation.assets.slice(),t.animation.speed=e.animation.speed,t.animation.loop=e.animation.loop,t.animation.activate=e.animation.activate,t.animation.enabled=e.animation.enabled;var i={},n=e.animation.animations;for(var s in n)n.hasOwnProperty(s)&&(i[s]=n[s]);t.animation.animations=i;var r={},a=e.animation.animationsIndex;for(var o in a)a.hasOwnProperty(o)&&(r[o]=a[o]);return t.animation.animationsIndex=r,t.animation},i.onBeforeRemove=function(e,t){t.onBeforeRemove()},i.onUpdate=function(e){var t=this.store;for(var i in t)if(t.hasOwnProperty(i)){var n=t[i];n.data.enabled&&n.entity.enabled&&n.entity.animation.update(e)}},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},t}(h_);Cl._buildAccessors(c_.prototype,d_);var p_=new be,m_=new ye,__=new Se,g_=new me,v_=new Pe,y_=function(e){function t(t,i,n,s,r){var a;return(a=e.call(this,i)||this).animComponent=t,a._mask=s,a.layerName=n,a.layerIndex=r,a}J(t,e),t._packFloat=function(e){return e[0]},t._packBoolean=function(e){return!!e[0]},t._packVec2=function(e){return p_.x=e[0],p_.y=e[1],p_},t._packVec3=function(e){return m_.x=e[0],m_.y=e[1],m_.z=e[2],m_},t._packVec4=function(e){return __.x=e[0],__.y=e[1],__.z=e[2],__.w=e[3],__},t._packColor=function(e){return g_.r=e[0],g_.g=e[1],g_.b=e[2],g_.a=e[3],g_},t._packQuat=function(e){return v_.x=e[0],v_.y=e[1],v_.z=e[2],v_.w=e[3],v_};var i=t.prototype;return i.resolve=function(e){var t,i,n,s=yu.encode(e.entityPath,e.component,e.propertyPath),r=this.targetCache[s];if(r)return r;switch(e.component){case"entity":t=this._getEntityFromHierarchy(e.entityPath),n=yu.encode(t.path,"entity",e.propertyPath),i=t;break;case"graph":if(!(i=this.findNode(e)))return null;n=yu.encode(i.path,"graph",e.propertyPath);break;default:if(!(i=(t=this._getEntityFromHierarchy(e.entityPath)).findComponent(e.component)))return null;n=yu.encode(t.path,e.component,e.propertyPath)}return r=this._createAnimTargetForProperty(i,e.propertyPath,n),this.targetCache[s]=r,r},i.update=function(e){var t=this.activeNodes;if(t)for(var i=0;i<t.length;i++)t[i]._dirtifyLocal()},i._getEntityFromHierarchy=function(e){if(!this.animComponent.entity.name===e[0])return null;var t=this.animComponent.entity;return 1===e.length?t:t._parent.findByPath(e)},i._resolvePath=function(e,t,i){for(var n=t.length-(i?0:1),s=0;s<n;s++)e=e[t[s]];return e},i._setter=function(e,t,i){var n=this._resolvePath(e,t),s=t[t.length-1],r="set"+s.substring(0,1).toUpperCase()+s.substring(1);if(n[r]){var a=n["get"+s.substring(0,1).toUpperCase()+s.substring(1)].bind(n)();a=[a.x,a.y,a.z,a.w];var o=n[r].bind(n);return{set:function(e){o(i(e))},get:function(){return a}}}var h=n[s];if("object"==typeof h&&h.hasOwnProperty("copy"))return function(e){h.copy(i(e))};if(-1!==[be,ye,Se,me,Pe].indexOf(n.constructor)&&t.length>1){var l=t.length>2?this._resolvePath(e,t.slice(0,-1)):e,c=t[t.length-2];return function(e){n[s]=i(e),l[c]=n}}return function(e){n[s]=i(e)}},i._createAnimTargetForProperty=function(e,i,n){if(this.handlers&&i[0].startsWith("weight."))return this.handlers.weight(e,i[0].replace("weight.",""));if(this.handlers&&"material"===i[0]&&2===i.length){var s=i[1];if(s.endsWith("Map"))return this.handlers.materialTexture(e,s)}var r,a,o,h=this._resolvePath(e,i,!0);if(void 0===h)return null;if("number"==typeof h)r=this._setter(e,i,t._packFloat),a="vector",o=1;else if("boolean"==typeof h)r=this._setter(e,i,t._packBoolean),a="vector",o=1;else if("object"==typeof h)switch(h.constructor){case be:r=this._setter(e,i,t._packVec2),a="vector",o=2;break;case ye:r=this._setter(e,i,t._packVec3),a="vector",o=3;break;case Se:r=this._setter(e,i,t._packVec4),a="vector",o=4;break;case me:r=this._setter(e,i,t._packColor),a="vector",o=4;break;case Pe:r=this._setter(e,i,t._packQuat),a="quaternion",o=4;break;default:return null}return-1!==i.indexOf("material")?new $u((function(t){r(t),e.material.update()}),a,o,n):new $u(r,a,o,n)},i.rebind=function(){this.targetCache={},this.animComponent.rootBone?this.graph=this.animComponent.rootBone:this.graph=this.animComponent.entity;var e={};!function t(i){e[i.name]=i;for(var n=0;n<i.children.length;++n)t(i.children[n])}(this.graph),this.nodes=e},t}(ed),x_=function(){function e(e,t,i,n,s,r){void 0===n&&(n=1),void 0===s&&(s=ju),void 0===r&&(r=!0),this._name=e,this._controller=t,this._component=i,this._weight=n,this._blendType=s,this._normalizedWeight=r,this._mask=null,this._blendTime=0,this._blendTimeElapsed=0,this._startingWeight=0,this._targetWeight=0}var t=e.prototype;return t.play=function(e){this._controller.play(e)},t.pause=function(){this._controller.pause()},t.reset=function(){this._controller.reset()},t.rebind=function(){this._controller.rebind()},t.update=function(e){this._blendTime&&(this._blendTimeElapsed<this._blendTime?(this.weight=de.lerp(this._startingWeight,this._targetWeight,this._blendTimeElapsed/this._blendTime),this._blendTimeElapsed+=e):(this.weight=this._targetWeight,this._blendTime=0,this._blendTimeElapsed=0,this._startingWeight=0,this._targetWeight=0)),this._controller.update(e)},t.blendToWeight=function(e,t){this._startingWeight=this.weight,this._targetWeight=e,this._blendTime=Math.max(0,t),this._blendTimeElapsed=0},t.assignMask=function(e){this._controller.assignMask(e)&&this._component.rebind(),this._mask=e},t.assignAnimation=function(e,t,i,n){t.constructor===Ju&&(this._controller.assignAnimation(e,t,i,n),0===this._controller._transitions.length&&this._controller._transitions.push(new hd({from:"START",to:e})),this._component.activate&&this._component.playable&&(this._component.playing=!0))},t.removeNodeAnimations=function(e){this._controller.removeNodeAnimations(e)&&(this._component.playing=!1)},t.getAnimationAsset=function(e){return this._component.animationAssets[this.name+":"+e]},t.transition=function(e,t,i){void 0===t&&(t=0),void 0===i&&(i=null),this._controller.updateStateFromTransition(new hd({from:this._controller.activeStateName,to:e,time:t,transitionOffset:i}))},$(e,[{key:"name",get:function(){return this._name}},{key:"playing",get:function(){return this._controller.playing},set:function(e){this._controller.playing=e}},{key:"playable",get:function(){return this._controller.playable}},{key:"activeState",get:function(){return this._controller.activeStateName}},{key:"previousState",get:function(){return this._controller.previousStateName}},{key:"activeStateProgress",get:function(){return this._controller.activeStateProgress}},{key:"activeStateDuration",get:function(){return this._controller.activeStateDuration}},{key:"activeStateCurrentTime",get:function(){return this._controller.activeStateCurrentTime},set:function(e){var t=this._controller,i=t.playing;t.playing=!0,t.activeStateCurrentTime=e,i||t.update(0),t.playing=i}},{key:"transitioning",get:function(){return this._controller.transitioning}},{key:"transitionProgress",get:function(){return this.transitioning?this._controller.transitionProgress:null}},{key:"states",get:function(){return this._controller.states}},{key:"weight",get:function(){return this._weight},set:function(e){this._weight=e,this._component.dirtifyTargets()}},{key:"blendType",get:function(){return this._blendType},set:function(e){e!==this._blendType&&(this._blendType=e,this._controller.normalizeWeights&&this._component.rebind())}},{key:"mask",get:function(){return this._mask},set:function(e){this._controller.assignMask(e)&&this._component.rebind(),this._mask=e}}]),e}(),b_=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._stateGraphAsset=null,n._animationAssets={},n._speed=1,n._activate=!0,n._playing=!1,n._rootBone=null,n._stateGraph=null,n._layers=[],n._layerIndices={},n._parameters={},n._targets={},n._consumedTriggers=new Set,n._normalizeWeights=!1,n}J(t,e);var i=t.prototype;return i._onStateGraphAssetChangeEvent=function(e){var t=this.animationAssets,i=this.layers.map((function(e){return e.mask}));this.removeStateGraph(),this._stateGraph=new cd(e._data),this.loadStateGraph(this._stateGraph),this.animationAssets=t,this.loadAnimationAssets(),this.layers.forEach((function(e,t){e.mask=i[t]})),this.rebind()},i.dirtifyTargets=function(){for(var e=Object.values(this._targets),t=0;t<e.length;t++)e[t].dirty=!0},i._addLayer=function(e){var t,i=e.name,n=e.states,s=e.transitions,r=e.weight,a=e.mask,o=e.blendType;t=this.rootBone?this.rootBone:this.entity;var h=this._layers.length,l=new y_(this,t,i,a,h),c=new Zu(l),u=new ld(c,n,s,this._parameters,this._activate,this,this._consumedTriggers);return this._layers.push(new x_(i,u,this,r,o)),this._layerIndices[i]=h,this._layers[h]},i.addLayer=function(e,t,i,n){var s=this.findAnimationLayer(e);if(s)return s;return this._addLayer({name:e,states:[{name:"START",speed:1}],transitions:[],weight:t,mask:i,blendType:n})},i.loadStateGraph=function(e){this._stateGraph=e,this._parameters={};for(var t=Object.keys(e.parameters),i=0;i<t.length;i++){var n=t[i];this._parameters[n]={type:e.parameters[n].type,value:e.parameters[n].value}}this._layers=[];for(var s=0;s<e.layers.length;s++){var r=e.layers[s];this._addLayer.bind(this)(Q({},r))}this.setupAnimationAssets()},i.setupAnimationAssets=function(){for(var e=0;e<this._layers.length;e++)for(var t=this._layers[e],i=t.name,n=0;n<t.states.length;n++){var s=t.states[n];if(-1===qu.indexOf(s)){var r=i+":"+s;this._animationAssets[r]||(this._animationAssets[r]={asset:null})}}this.loadAnimationAssets()},i.loadAnimationAssets=function(){for(var e=0;e<this._layers.length;e++)for(var t=this._layers[e],i=0;i<t.states.length;i++){var n=t.states[i];if(-1===qu.indexOf(n)){var s=this._animationAssets[t.name+":"+n];if(s&&s.asset){var r=s.asset,a=this.system.app.assets.get(r);a&&(a.resource?this.onAnimationAssetLoaded(t.name,n,a):(a.once("load",function(e,t){return function(i){this.onAnimationAssetLoaded(e,t,i)}.bind(this)}.bind(this)(t.name,n)),this.system.app.assets.load(a)))}else this.removeNodeAnimations(n,t.name)}}},i.onAnimationAssetLoaded=function(e,t,i){this.findAnimationLayer(e).assignAnimation(t,i.resource)},i.removeStateGraph=function(){this._stateGraph=null,this._stateGraphAsset=null,this._animationAssets={},this._layers=[],this._layerIndices={},this._parameters={},this._playing=!1,this.unbind(),this._targets={}},i.reset=function(){this._parameters=Object.assign({},this._stateGraph.parameters);for(var e=0;e<this._layers.length;e++){var t=this._layers[e].playing;this._layers[e].reset(),this._layers[e].playing=t}},i.unbind=function(){var e=this;this._normalizeWeights||Object.keys(this._targets).forEach((function(t){e._targets[t].unbind()}))},i.rebind=function(){this._targets={};for(var e=0;e<this._layers.length;e++)this._layers[e].rebind()},i.findAnimationLayer=function(e){var t=this._layerIndices[e];return this._layers[t]||null},i.addAnimationState=function(e,t,i,n,s){void 0===i&&(i=1),void 0===n&&(n=!0),void 0===s&&(s="Base"),this._stateGraph||this.loadStateGraph(new cd({layers:[{name:s,states:[{name:"START",speed:1},{name:e,speed:i,loop:n,defaultState:!0}],transitions:[{from:"START",to:e}]}],parameters:{}}));var r,a=this.findAnimationLayer(s);a?a.assignAnimation(e,t,i,n):null==(r=this.addLayer(s))||r.assignAnimation(e,t,i,n)},i.assignAnimation=function(e,t,i,n,s){if(void 0===n&&(n=1),void 0===s&&(s=!0),!this._stateGraph&&-1===e.indexOf("."))return this.loadStateGraph(new cd({layers:[{name:"Base",states:[{name:"START",speed:1},{name:e,speed:n,loop:s,defaultState:!0}],transitions:[{from:"START",to:e}]}],parameters:{}})),void this.baseLayer.assignAnimation(e,t);var r=i?this.findAnimationLayer(i):this.baseLayer;r&&r.assignAnimation(e,t,n,s)},i.removeNodeAnimations=function(e,t){var i=t?this.findAnimationLayer(t):this.baseLayer;i&&i.removeNodeAnimations(e)},i.getParameterValue=function(e,t){var i=this._parameters[e];if(i&&i.type===t)return i.value},i.setParameterValue=function(e,t,i){var n=this._parameters[e];n&&n.type===t&&(n.value=i)},i.getFloat=function(e){return this.getParameterValue(e,Bu)},i.setFloat=function(e,t){this.setParameterValue(e,Bu,t)},i.getInteger=function(e){return this.getParameterValue(e,Fu)},i.setInteger=function(e,t){"number"==typeof t&&t%1==0&&this.setParameterValue(e,Fu,t)},i.getBoolean=function(e){return this.getParameterValue(e,Nu)},i.setBoolean=function(e,t){this.setParameterValue(e,Nu,!!t)},i.getTrigger=function(e){return this.getParameterValue(e,Uu)},i.setTrigger=function(e,t){void 0===t&&(t=!1),this.setParameterValue(e,Uu,!0),t&&this._consumedTriggers.add(e)},i.resetTrigger=function(e){this.setParameterValue(e,Uu,!1)},i.onBeforeRemove=function(){Number.isFinite(this._stateGraphAsset)&&this.system.app.assets.get(this._stateGraphAsset).off("change",this._onStateGraphAssetChangeEvent,this)},i.update=function(e){for(var t=this,i=0;i<this.layers.length;i++)this.layers[i].update(e*this.speed);this._consumedTriggers.forEach((function(e){t.parameters[e].value=!1})),this._consumedTriggers.clear()},i.resolveDuplicatedEntityReferenceProperties=function(e,t){e.rootBone&&t[e.rootBone.getGuid()]?this.rootBone=t[e.rootBone.getGuid()]:this.rebind()},$(t,[{key:"stateGraphAsset",get:function(){return this._stateGraphAsset},set:function(e){var t=this;if(null!==e){var i,n;if(this._stateGraphAsset)this.system.app.assets.get(this._stateGraphAsset).off("change",this._onStateGraphAssetChangeEvent,this);e instanceof ml?(i=e.id,(n=this.system.app.assets.get(i))||(this.system.app.assets.add(e),n=this.system.app.assets.get(i))):(i=e,n=this.system.app.assets.get(i)),n&&this._stateGraphAsset!==i&&(n.resource?(this._stateGraph=n.resource,this.loadStateGraph(this._stateGraph),n.on("change",this._onStateGraphAssetChangeEvent,this)):(n.once("load",(function(e){t._stateGraph=e.resource,t.loadStateGraph(t._stateGraph)})),n.on("change",this._onStateGraphAssetChangeEvent,this),this.system.app.assets.load(n)),this._stateGraphAsset=i)}else this.removeStateGraph()}},{key:"normalizeWeights",get:function(){return this._normalizeWeights},set:function(e){this._normalizeWeights=e,this.unbind()}},{key:"animationAssets",get:function(){return this._animationAssets},set:function(e){this._animationAssets=e,this.loadAnimationAssets()}},{key:"speed",get:function(){return this._speed},set:function(e){this._speed=e}},{key:"activate",get:function(){return this._activate},set:function(e){this._activate=e}},{key:"playing",get:function(){return this._playing},set:function(e){this._playing=e}},{key:"rootBone",get:function(){return this._rootBone},set:function(e){if("string"==typeof e){var t=this.entity.root.findByGuid(e);this._rootBone=t}else this._rootBone=e instanceof $l?e:null;this.rebind()}},{key:"stateGraph",get:function(){return this._stateGraph},set:function(e){this._stateGraph=e}},{key:"layers",get:function(){return this._layers}},{key:"layerIndices",get:function(){return this._layerIndices},set:function(e){this._layerIndices=e}},{key:"parameters",get:function(){return this._parameters},set:function(e){this._parameters=e}},{key:"targets",get:function(){return this._targets},set:function(e){this._targets=e}},{key:"playable",get:function(){for(var e=0;e<this._layers.length;e++)if(!this._layers[e].playable)return!1;return!0}},{key:"baseLayer",get:function(){return this._layers.length>0?this._layers[0]:null}}]),t}(Cl),S_=function(){this.enabled=!0},w_=["enabled"],T_=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="anim",i.ComponentType=b_,i.DataType=S_,i.schema=w_,i.on("beforeremove",i.onBeforeRemove,te(i)),i.app.systems.on("animationUpdate",i.onAnimationUpdate,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){e.prototype.initializeComponentData.call(this,t,i,w_);var s=["animationAssets","stateGraph","layers","masks"];Object.keys(i).forEach((function(e){s.includes(e)||(t[e]=i[e])})),i.stateGraph&&(t.stateGraph=i.stateGraph,t.loadStateGraph(t.stateGraph)),i.layers?i.layers.forEach((function(e,i){e._controller.states.forEach((function(n){e._controller._states[n]._animationList.forEach((function(e){t.layers[i].assignAnimation(e.name,e.animTrack)}))}))})):i.animationAssets&&(t.animationAssets=Object.assign(t.animationAssets,i.animationAssets)),i.masks&&Object.keys(i.masks).forEach((function(e){if(t.layers[e]){var n=i.masks[e].mask,s={};Object.keys(n).forEach((function(e){s[decodeURI(e)]=n[e]})),t.layers[e].mask=s}}))},i.onAnimationUpdate=function(e){var t=this.store;for(var i in t)if(t.hasOwnProperty(i)){var n=t[i].entity.anim;n.data.enabled&&n.entity.enabled&&n.playing&&n.update(e)}},i.cloneComponent=function(e,t){var i;e.anim.rootBone&&e.anim.rootBone!==e||(i={},e.anim.layers.forEach((function(e,n){if(e.mask){var s={};Object.keys(e.mask).forEach((function(i){var n=i.split("/");n.shift();var r=[t.name].concat(n).join("/");s[r]=e.mask[i]})),i[n]={mask:s}}})));var n={stateGraphAsset:e.anim.stateGraphAsset,animationAssets:e.anim.animationAssets,speed:e.anim.speed,activate:e.anim.activate,playing:e.anim.playing,rootBone:e.anim.rootBone,stateGraph:e.anim.stateGraph,layers:e.anim.layers,layerIndices:e.anim.layerIndices,parameters:e.anim.parameters,normalizeWeights:e.anim.normalizeWeights,masks:i};return this.addComponent(t,n)},i.onBeforeRemove=function(e,t){t.onBeforeRemove()},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("animationUpdate",this.onAnimationUpdate,this)},t}(h_);Cl._buildAccessors(b_.prototype,w_);var A_=function(e){function t(t,i){return e.call(this,t,i)||this}J(t,e);var i=t.prototype;return i.setCurrentListener=function(){if(this.enabled&&this.entity.audiolistener&&this.entity.enabled){this.system.current=this.entity;var e=this.system.current.getPosition();this.system.manager.listener.setPosition(e)}},i.onEnable=function(){this.setCurrentListener()},i.onDisable=function(){this.system.current===this.entity&&(this.system.current=null)},t}(Cl),M_=function(){this.enabled=!0},C_=["enabled"],E_=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="audiolistener",i.ComponentType=A_,i.DataType=M_,i.schema=C_,i.manager=t.soundManager,i.current=null,i.app.systems.on("update",i.onUpdate,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){n=["enabled"],e.prototype.initializeComponentData.call(this,t,i,n)},i.onUpdate=function(e){if(this.current){var t=this.current.getPosition();this.manager.listener.setPosition(t);var i=this.current.getWorldTransform();this.manager.listener.setOrientation(i)}},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},t}(h_);Cl._buildAccessors(A_.prototype,C_);var P_=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this).on("set_assets",n.onSetAssets,te(n)),n.on("set_loop",n.onSetLoop,te(n)),n.on("set_volume",n.onSetVolume,te(n)),n.on("set_pitch",n.onSetPitch,te(n)),n.on("set_minDistance",n.onSetMinDistance,te(n)),n.on("set_maxDistance",n.onSetMaxDistance,te(n)),n.on("set_rollOffFactor",n.onSetRollOffFactor,te(n)),n.on("set_distanceModel",n.onSetDistanceModel,te(n)),n.on("set_3d",n.onSet3d,te(n)),n}J(t,e);var i=t.prototype;return i.play=function(e){if(this.enabled&&this.entity.enabled){var t;this.channel&&this.stop();var i=this.data;if(i.sources[e])if(i["3d"]){var n=this.entity.getPosition();t=this.system.manager.playSound3d(i.sources[e],n,i),i.currentSource=e,i.channel=t}else t=this.system.manager.playSound(i.sources[e],i),i.currentSource=e,i.channel=t}},i.pause=function(){this.channel&&this.channel.pause()},i.unpause=function(){this.channel&&this.channel.paused&&this.channel.unpause()},i.stop=function(){this.channel&&(this.channel.stop(),this.channel=null)},i.onSetAssets=function(e,t,i){var n=[],s=i.length;if(t&&t.length)for(var r=0;r<t.length;r++)if(t[r]){var a=this.system.app.assets.get(t[r]);a&&(a.off("change",this.onAssetChanged,this),a.off("remove",this.onAssetRemoved,this),this.currentSource===a.name&&this.stop())}if(s)for(var o=0;o<s;o++)t.indexOf(i[o])<0&&(i[o]instanceof ml?n.push(i[o].id):n.push(i[o]));!this.system._inTools&&n.length&&this.loadAudioSourceAssets(n)},i.onAssetChanged=function(e,t,i,n){"resource"===t&&(this.data.sources&&(this.data.sources[e.name]=i,this.data.currentSource===e.name&&this.channel&&(this.channel.paused?(this.play(e.name),this.pause()):this.play(e.name))))},i.onAssetRemoved=function(e){e.off("remove",this.onAssetRemoved,this),this.data.sources[e.name]&&(delete this.data.sources[e.name],this.data.currentSource===e.name&&(this.stop(),this.data.currentSource=null))},i.onSetLoop=function(e,t,i){t!==i&&this.channel&&this.channel.setLoop(i)},i.onSetVolume=function(e,t,i){t!==i&&this.channel&&this.channel.setVolume(i)},i.onSetPitch=function(e,t,i){t!==i&&this.channel&&this.channel.setPitch(i)},i.onSetMaxDistance=function(e,t,i){t!==i&&this.channel instanceof bd&&this.channel.setMaxDistance(i)},i.onSetMinDistance=function(e,t,i){t!==i&&this.channel instanceof bd&&this.channel.setMinDistance(i)},i.onSetRollOffFactor=function(e,t,i){t!==i&&this.channel instanceof bd&&this.channel.setRollOffFactor(i)},i.onSetDistanceModel=function(e,t,i){t!==i&&this.channel instanceof bd&&this.channel.setDistanceModel(i)},i.onSet3d=function(e,t,i){if(t!==i&&this.system.initialized&&this.currentSource){var n=!1,s=!1;this.channel&&(n=this.channel.paused,s=this.channel.suspended),this.play(this.currentSource),this.channel&&(this.channel.paused=n,this.channel.suspended=s)}},i.onEnable=function(){var e=this.data.assets;if(e)for(var t=this.system.app.assets,i=0,n=e.length;i<n;i++){var s=e[i];s instanceof ml||(s=t.get(s)),s&&!s.resource&&t.load(s)}this.system.initialized&&(this.data.activate&&!this.channel?this.play(this.currentSource):this.unpause())},i.onDisable=function(){this.pause()},i.loadAudioSourceAssets=function(e){var t=this,i=e.map((function(e){return t.system.app.assets.get(e)})),n={},s=null,r=i.length,a=function(e){r--},o=function(){t.data.sources=n,t.data.currentSource=s,t.enabled&&t.activate&&s&&t.onEnable()};i.forEach((function(i,h){i?(s=s||i.name,i.off("change",t.onAssetChanged,t),i.on("change",t.onAssetChanged,t),i.off("remove",t.onAssetRemoved,t),i.on("remove",t.onAssetRemoved,t),i.off("error",a,t),i.on("error",a,t),i.ready((function(e){n[e.name]=e.resource,0===--r&&o()})),!i.resource&&t.enabled&&t.entity.enabled&&t.system.app.assets.load(i)):(0===--r&&o(),t.system.app.assets.on("add:"+e[h],(function(e){e.ready((function(e){t.data.sources[e.name]=e.resource})),e.resource||t.system.app.assets.load(e)})))}))},t}(Cl),R_=function(){this.enabled=!0,this.assets=[],this.activate=!0,this.volume=1,this.pitch=1,this.loop=!1,this["3d"]=!0,this.minDistance=1,this.maxDistance=1e4,this.rollOffFactor=1,this.distanceModel=gd,this.paused=!0,this.sources={},this.currentSource=null,this.channel=null},I_=["enabled","assets","volume","pitch","loop","activate","3d","minDistance","maxDistance","rollOffFactor","distanceModel","sources","currentSource","channel"],L_=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="audiosource",i.ComponentType=P_,i.DataType=R_,i.schema=I_,i.manager=t.soundManager,i.initialized=!1,i.app.systems.on("initialize",i.onInitialize,te(i)),i.app.systems.on("update",i.onUpdate,te(i)),i.on("remove",i.onRemove,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){n=["activate","volume","pitch","loop","3d","minDistance","maxDistance","rollOffFactor","distanceModel","enabled","assets"],e.prototype.initializeComponentData.call(this,t,i,n),t.paused=!(t.enabled&&t.activate)},i.onInitialize=function(e){e.audiosource&&e.enabled&&e.audiosource.enabled&&e.audiosource.activate&&e.audiosource.play(e.audiosource.currentSource);for(var t=e._children,i=0,n=t.length;i<n;i++)t[i]instanceof $l&&this.onInitialize(t[i]);this.initialized=!0},i.onUpdate=function(e){var t=this.store;for(var i in t)if(t.hasOwnProperty(i)){var n=t[i],s=n.entity,r=n.data;if(r.enabled&&s.enabled&&r.channel instanceof bd){var a=s.getPosition();r.channel.setPosition(a)}}},i.onRemove=function(e,t){t.channel&&(t.channel.stop(),t.channel=null)},i.setVolume=function(e){this.manager.setVolume(e)},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("initialize",this.onInitialize,this),this.app.systems.off("update",this.onUpdate,this)},t}(h_);Cl._buildAccessors(P_.prototype,I_);var D_=function(e){function t(t,i,n){var s;if(s=e.call(this)||this,!(t&&t instanceof Cl))throw new Error("The parentComponent argument is required and must be a Component");if(!i||"string"!=typeof i)throw new Error("The propertyName argument is required and must be a string");if(n&&"object"!=typeof n)throw new Error("If provided, the eventConfig argument must be an object");return s._parentComponent=t,s._entityPropertyName=i,s._entity=null,s._app=t.system.app,s._configureEventListeners(n||{},{"entity#destroy":s._onEntityDestroy}),s._toggleLifecycleListeners("on"),s}J(t,e);var i=t.prototype;return i._configureEventListeners=function(e,t){var i=this._parseEventListenerConfig(e,"external",this._parentComponent),n=this._parseEventListenerConfig(t,"internal",this);this._eventListenerConfigs=i.concat(n),this._listenerStatusFlags={},this._gainListeners={},this._loseListeners={}},i._parseEventListenerConfig=function(e,t,i){return Object.keys(e).map((function(n,s){var r=n.split("#"),a=r[0],o=r[1],h=e[n];if(2!==r.length||"string"!=typeof a||0===a.length||"string"!=typeof o||0===o.length)throw new Error("Invalid event listener description: `"+n+"`");if("function"!=typeof h)throw new Error("Invalid or missing callback for event listener `"+n+"`");return{id:t+"_"+s+"_"+n,sourceName:a,eventName:o,callback:h,scope:i}}),this)},i._toggleLifecycleListeners=function(e){this._parentComponent[e]("set_"+this._entityPropertyName,this._onSetEntity,this),this._parentComponent.system[e]("beforeremove",this._onParentComponentRemove,this),this._app.systems[e]("postPostInitialize",this._updateEntityReference,this),this._app[e]("tools:sceneloaded",this._onSceneLoaded,this);for(var t=[],i=0;i<this._eventListenerConfigs.length;++i){var n=this._eventListenerConfigs[i],s=this._app.systems[n.sourceName];s&&(-1===t.indexOf(s)&&t.push(s),s&&"gain"===n.eventName&&(this._gainListeners[n.sourceName]=n),s&&"lose"===n.eventName&&(this._loseListeners[n.sourceName]=n))}for(var r=0;r<t.length;++r)t[r][e]("add",this._onComponentAdd,this),t[r][e]("beforeremove",this._onComponentRemove,this)},i._onSetEntity=function(e,t,i){if(i instanceof $l)this._updateEntityReference();else{if(null!=i&&"string"!=typeof i)return void console.warn("Entity field `"+this._entityPropertyName+"` was set to unexpected type '"+typeof i+"'");t!==i&&this._updateEntityReference()}},i.onParentComponentEnable=function(){this._entity||this._updateEntityReference()},i._onSceneLoaded=function(){this._updateEntityReference()},i._updateEntityReference=function(){var e,t=this._parentComponent.data[this._entityPropertyName];if(t instanceof $l)t=(e=t).getGuid(),this._parentComponent.data[this._entityPropertyName]=t;else{var i=this._parentComponent.system.app.root;e=this._parentComponent.entity.isDescendantOf(i)&&t?i.findByGuid(t):null}this._entity!==e&&(this._entity&&this._onBeforeEntityChange(),this._entity=e,this._entity&&this._onAfterEntityChange(),this.fire("set:entity",this._entity))},i._onBeforeEntityChange=function(){this._toggleEntityListeners("off"),this._callAllGainOrLoseListeners(this._loseListeners)},i._onAfterEntityChange=function(){this._toggleEntityListeners("on"),this._callAllGainOrLoseListeners(this._gainListeners)},i._onComponentAdd=function(e,t){var i=t.system.id;e===this._entity&&(this._callGainOrLoseListener(i,this._gainListeners),this._toggleComponentListeners("on",i))},i._onComponentRemove=function(e,t){var i=t.system.id;e===this._entity&&(this._callGainOrLoseListener(i,this._loseListeners),this._toggleComponentListeners("off",i,!0))},i._callAllGainOrLoseListeners=function(e){for(var t in this._entity.c)this._callGainOrLoseListener(t,e)},i._callGainOrLoseListener=function(e,t){if(this._entity.c.hasOwnProperty(e)&&t[e]){var i=t[e];i.callback.call(i.scope)}},i._toggleEntityListeners=function(e,t){if(this._entity)for(var i=0;i<this._eventListenerConfigs.length;++i)this._safeToggleListener(e,this._eventListenerConfigs[i],t)},i._toggleComponentListeners=function(e,t,i){for(var n=0;n<this._eventListenerConfigs.length;++n){var s=this._eventListenerConfigs[n];s.sourceName===t&&this._safeToggleListener(e,s,i)}},i._safeToggleListener=function(e,t,i){var n="on"===e;if(!n||!this._listenerStatusFlags[t.id]){var s=this._getEventSource(t.sourceName,i);s&&(s[e](t.eventName,t.callback,t.scope),this._listenerStatusFlags[t.id]=n)}},i._getEventSource=function(e,t){if("entity"===e)return this._entity;var i=this._entity[e];return i||(t||console.warn("Entity has no component with name "+e),null)},i._onEntityDestroy=function(e){this._entity===e&&(this._toggleEntityListeners("off",!0),this._entity=null)},i._onParentComponentRemove=function(e,t){t===this._parentComponent&&(this._toggleLifecycleListeners("off"),this._toggleEntityListeners("off",!0))},i.hasComponent=function(e){return!(!this._entity||!this._entity.c)&&!!this._entity.c[e]},$(t,[{key:"entity",get:function(){return this._entity}}]),t}(m),k_="group",O_="image",F_="text",B_="stretch",N_="contain",U_="cover",z_="DEFAULT",V_="HOVER",G_="PRESSED",W_="INACTIVE",H_={};H_[z_]="_defaultTint",H_[V_]="hoverTint",H_[G_]="pressedTint",H_[W_]="inactiveTint";var X_={};X_[z_]="_defaultSpriteAsset",X_[V_]="hoverSpriteAsset",X_[G_]="pressedSpriteAsset",X_[W_]="inactiveSpriteAsset";var q_={};q_[z_]="_defaultSpriteFrame",q_[V_]="hoverSpriteFrame",q_[G_]="pressedSpriteFrame",q_[W_]="inactiveSpriteFrame";var j_=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._visualState=z_,n._isHovering=!1,n._hoveringCounter=0,n._isPressed=!1,n._defaultTint=new me(1,1,1,1),n._defaultSpriteAsset=null,n._defaultSpriteFrame=0,n._imageReference=new D_(te(n),"imageEntity",{"element#gain":n._onImageElementGain,"element#lose":n._onImageElementLose,"element#set:color":n._onSetColor,"element#set:opacity":n._onSetOpacity,"element#set:spriteAsset":n._onSetSpriteAsset,"element#set:spriteFrame":n._onSetSpriteFrame}),n._toggleLifecycleListeners("on",t),n}J(t,e);var i=t.prototype;return i._toggleLifecycleListeners=function(e,t){this[e]("set_active",this._onSetActive,this),this[e]("set_transitionMode",this._onSetTransitionMode,this),this[e]("set_hoverTint",this._onSetTransitionValue,this),this[e]("set_pressedTint",this._onSetTransitionValue,this),this[e]("set_inactiveTint",this._onSetTransitionValue,this),this[e]("set_hoverSpriteAsset",this._onSetTransitionValue,this),this[e]("set_hoverSpriteFrame",this._onSetTransitionValue,this),this[e]("set_pressedSpriteAsset",this._onSetTransitionValue,this),this[e]("set_pressedSpriteFrame",this._onSetTransitionValue,this),this[e]("set_inactiveSpriteAsset",this._onSetTransitionValue,this),this[e]("set_inactiveSpriteFrame",this._onSetTransitionValue,this),t.app.systems.element[e]("add",this._onElementComponentAdd,this),t.app.systems.element[e]("beforeremove",this._onElementComponentRemove,this)},i._onSetActive=function(e,t,i){t!==i&&this._updateVisualState()},i._onSetTransitionMode=function(e,t,i){t!==i&&(this._cancelTween(),this._resetToDefaultVisualState(t),this._forceReapplyVisualState())},i._onSetTransitionValue=function(e,t,i){t!==i&&this._forceReapplyVisualState()},i._onElementComponentRemove=function(e){this.entity===e&&this._toggleHitElementListeners("off")},i._onElementComponentAdd=function(e){this.entity===e&&this._toggleHitElementListeners("on")},i._onImageElementLose=function(){this._cancelTween(),this._resetToDefaultVisualState(this.transitionMode)},i._onImageElementGain=function(){this._storeDefaultVisualState(),this._forceReapplyVisualState()},i._toggleHitElementListeners=function(e){if(this.entity.element){var t="on"===e;if(t&&this._hasHitElementListeners)return;this.entity.element[e]("mouseenter",this._onMouseEnter,this),this.entity.element[e]("mouseleave",this._onMouseLeave,this),this.entity.element[e]("mousedown",this._onMouseDown,this),this.entity.element[e]("mouseup",this._onMouseUp,this),this.entity.element[e]("touchstart",this._onTouchStart,this),this.entity.element[e]("touchend",this._onTouchEnd,this),this.entity.element[e]("touchleave",this._onTouchLeave,this),this.entity.element[e]("touchcancel",this._onTouchCancel,this),this.entity.element[e]("selectstart",this._onSelectStart,this),this.entity.element[e]("selectend",this._onSelectEnd,this),this.entity.element[e]("selectenter",this._onSelectEnter,this),this.entity.element[e]("selectleave",this._onSelectLeave,this),this.entity.element[e]("click",this._onClick,this),this._hasHitElementListeners=t}},i._storeDefaultVisualState=function(){if(this._imageReference.hasComponent("element")){var e=this._imageReference.entity.element;e.type!==k_&&(this._storeDefaultColor(e.color),this._storeDefaultOpacity(e.opacity),this._storeDefaultSpriteAsset(e.spriteAsset),this._storeDefaultSpriteFrame(e.spriteFrame))}},i._storeDefaultColor=function(e){this._defaultTint.r=e.r,this._defaultTint.g=e.g,this._defaultTint.b=e.b},i._storeDefaultOpacity=function(e){this._defaultTint.a=e},i._storeDefaultSpriteAsset=function(e){this._defaultSpriteAsset=e},i._storeDefaultSpriteFrame=function(e){this._defaultSpriteFrame=e},i._onSetColor=function(e){this._isApplyingTint||(this._storeDefaultColor(e),this._forceReapplyVisualState())},i._onSetOpacity=function(e){this._isApplyingTint||(this._storeDefaultOpacity(e),this._forceReapplyVisualState())},i._onSetSpriteAsset=function(e){this._isApplyingSprite||(this._storeDefaultSpriteAsset(e),this._forceReapplyVisualState())},i._onSetSpriteFrame=function(e){this._isApplyingSprite||(this._storeDefaultSpriteFrame(e),this._forceReapplyVisualState())},i._onMouseEnter=function(e){this._isHovering=!0,this._updateVisualState(),this._fireIfActive("mouseenter",e)},i._onMouseLeave=function(e){this._isHovering=!1,this._isPressed=!1,this._updateVisualState(),this._fireIfActive("mouseleave",e)},i._onMouseDown=function(e){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("mousedown",e)},i._onMouseUp=function(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("mouseup",e)},i._onTouchStart=function(e){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("touchstart",e)},i._onTouchEnd=function(e){e.event.preventDefault(),this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchend",e)},i._onTouchLeave=function(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchleave",e)},i._onTouchCancel=function(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchcancel",e)},i._onSelectStart=function(e){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("selectstart",e)},i._onSelectEnd=function(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("selectend",e)},i._onSelectEnter=function(e){this._hoveringCounter++,1===this._hoveringCounter&&(this._isHovering=!0,this._updateVisualState()),this._fireIfActive("selectenter",e)},i._onSelectLeave=function(e){this._hoveringCounter--,0===this._hoveringCounter&&(this._isHovering=!1,this._isPressed=!1,this._updateVisualState()),this._fireIfActive("selectleave",e)},i._onClick=function(e){this._fireIfActive("click",e)},i._fireIfActive=function(e,t){this.data.active&&this.fire(e,t)},i._updateVisualState=function(e){var t=this._visualState,i=this._determineVisualState();if((t!==i||e)&&this.enabled)switch(this._visualState=i,t===V_&&this._fireIfActive("hoverend"),t===G_&&this._fireIfActive("pressedend"),i===V_&&this._fireIfActive("hoverstart"),i===G_&&this._fireIfActive("pressedstart"),this.transitionMode){case 0:var n=this[H_[this._visualState]];this._applyTint(n);break;case 1:var s=X_[this._visualState],r=q_[this._visualState],a=this[s],o=this[r];this._applySprite(a,o)}},i._forceReapplyVisualState=function(){this._updateVisualState(!0)},i._resetToDefaultVisualState=function(e){if(this._imageReference.hasComponent("element"))switch(e){case 0:this._cancelTween(),this._applyTintImmediately(this._defaultTint);break;case 1:this._applySprite(this._defaultSpriteAsset,this._defaultSpriteFrame)}},i._determineVisualState=function(){return this.active?this._isPressed?G_:this._isHovering?V_:z_:W_},i._applySprite=function(e,t){t=t||0,this._imageReference.hasComponent("element")&&(this._isApplyingSprite=!0,this._imageReference.entity.element.spriteAsset!==e&&(this._imageReference.entity.element.spriteAsset=e),this._imageReference.entity.element.spriteFrame!==t&&(this._imageReference.entity.element.spriteFrame=t),this._isApplyingSprite=!1)},i._applyTint=function(e){this._cancelTween(),0===this.fadeDuration?this._applyTintImmediately(e):this._applyTintWithTween(e)},i._applyTintImmediately=function(e){if(e&&this._imageReference.hasComponent("element")&&this._imageReference.entity.element.type!==k_){var t=Y_(e);this._isApplyingTint=!0,t.equals(this._imageReference.entity.element.color)||(this._imageReference.entity.element.color=t),this._imageReference.entity.element.opacity!==e.a&&(this._imageReference.entity.element.opacity=e.a),this._isApplyingTint=!1}},i._applyTintWithTween=function(e){if(e&&this._imageReference.hasComponent("element")&&this._imageReference.entity.element.type!==k_){var t=Y_(e),i=this._imageReference.entity.element.color,n=this._imageReference.entity.element.opacity;t.equals(i)&&e.a===n||(this._tweenInfo={startTime:oe(),from:new me(i.r,i.g,i.b,n),to:e.clone(),lerpColor:new me})}},i._updateTintTween=function(){var e=oe()-this._tweenInfo.startTime,t=0===this.fadeDuration?1:e/this.fadeDuration;if(t=de.clamp(t,0,1),Math.abs(t-1)>1e-5){var i=this._tweenInfo.lerpColor;i.lerp(this._tweenInfo.from,this._tweenInfo.to,t),this._applyTintImmediately(new me(i.r,i.g,i.b,i.a))}else this._applyTintImmediately(this._tweenInfo.to),this._cancelTween()},i._cancelTween=function(){delete this._tweenInfo},i.onUpdate=function(){this._tweenInfo&&this._updateTintTween()},i.onEnable=function(){this._isHovering=!1,this._hoveringCounter=0,this._isPressed=!1,this._imageReference.onParentComponentEnable(),this._toggleHitElementListeners("on"),this._forceReapplyVisualState()},i.onDisable=function(){this._toggleHitElementListeners("off"),this._resetToDefaultVisualState(this.transitionMode)},i.onRemove=function(){this._toggleLifecycleListeners("off",this.system),this.onDisable()},t}(Cl);function Y_(e){return new me(e.r,e.g,e.b)}var K_=function(){this.enabled=!0,this.active=!0,this.imageEntity=null,this.hitPadding=new Se,this.transitionMode=0,this.hoverTint=new me(.75,.75,.75),this.pressedTint=new me(.5,.5,.5),this.inactiveTint=new me(.25,.25,.25),this.fadeDuration=0,this.hoverSpriteAsset=null,this.hoverSpriteFrame=0,this.pressedSpriteAsset=null,this.pressedSpriteFrame=0,this.inactiveSpriteAsset=null,this.inactiveSpriteFrame=0},Z_=["enabled","active",{name:"imageEntity",type:"entity"},{name:"hitPadding",type:"vec4"},"transitionMode",{name:"hoverTint",type:"rgba"},{name:"pressedTint",type:"rgba"},{name:"inactiveTint",type:"rgba"},"fadeDuration","hoverSpriteAsset","hoverSpriteFrame","pressedSpriteAsset","pressedSpriteFrame","inactiveSpriteAsset","inactiveSpriteFrame"],$_=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="button",i.ComponentType=j_,i.DataType=K_,i.schema=Z_,i.on("beforeremove",i._onRemoveComponent,te(i)),i.app.systems.on("update",i.onUpdate,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){e.prototype.initializeComponentData.call(this,t,i,Z_)},i.onUpdate=function(e){var t=this.store;for(var i in t){var n=t[i].entity,s=n.button;s.enabled&&n.enabled&&s.onUpdate()}},i._onRemoveComponent=function(e,t){t.onRemove()},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},t}(h_);Cl._buildAccessors(j_.prototype,Z_);var Q_,J_,eg,tg=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._compoundParent=null,n.entity.on("insert",n._onInsert,te(n)),n.on("set_type",n.onSetType,te(n)),n.on("set_halfExtents",n.onSetHalfExtents,te(n)),n.on("set_radius",n.onSetRadius,te(n)),n.on("set_height",n.onSetHeight,te(n)),n.on("set_axis",n.onSetAxis,te(n)),n.on("set_asset",n.onSetAsset,te(n)),n.on("set_renderAsset",n.onSetRenderAsset,te(n)),n.on("set_model",n.onSetModel,te(n)),n.on("set_render",n.onSetRender,te(n)),n}J(t,e);var i=t.prototype;return i.onSetType=function(e,t,i){t!==i&&this.system.changeType(this,t,i)},i.onSetHalfExtents=function(e,t,i){var n=this.data.type;this.data.initialized&&"box"===n&&this.system.recreatePhysicalShapes(this)},i.onSetRadius=function(e,t,i){var n=this.data.type;!this.data.initialized||"sphere"!==n&&"capsule"!==n&&"cylinder"!==n&&"cone"!==n||this.system.recreatePhysicalShapes(this)},i.onSetHeight=function(e,t,i){var n=this.data.type;!this.data.initialized||"capsule"!==n&&"cylinder"!==n&&"cone"!==n||this.system.recreatePhysicalShapes(this)},i.onSetAxis=function(e,t,i){var n=this.data.type;!this.data.initialized||"capsule"!==n&&"cylinder"!==n&&"cone"!==n||this.system.recreatePhysicalShapes(this)},i.onSetAsset=function(e,t,i){var n=this.system.app.assets;if(t){var s=n.get(t);s&&s.off("remove",this.onAssetRemoved,this)}if(i){i instanceof ml&&(this.data.asset=i.id);var r=n.get(this.data.asset);r&&(r.off("remove",this.onAssetRemoved,this),r.on("remove",this.onAssetRemoved,this))}this.data.initialized&&"mesh"===this.data.type&&(i||(this.data.model=null),this.system.recreatePhysicalShapes(this))},i.onSetRenderAsset=function(e,t,i){var n=this.system.app.assets;if(t){var s=n.get(t);s&&s.off("remove",this.onRenderAssetRemoved,this)}if(i){i instanceof ml&&(this.data.renderAsset=i.id);var r=n.get(this.data.renderAsset);r&&(r.off("remove",this.onRenderAssetRemoved,this),r.on("remove",this.onRenderAssetRemoved,this))}this.data.initialized&&"mesh"===this.data.type&&(i||(this.data.render=null),this.system.recreatePhysicalShapes(this))},i.onSetModel=function(e,t,i){this.data.initialized&&"mesh"===this.data.type&&this.system.implementations.mesh.doRecreatePhysicalShape(this)},i.onSetRender=function(e,t,i){this.onSetModel(e,t,i)},i.onAssetRemoved=function(e){e.off("remove",this.onAssetRemoved,this),this.data.asset===e.id&&(this.asset=null)},i.onRenderAssetRemoved=function(e){e.off("remove",this.onRenderAssetRemoved,this),this.data.renderAsset===e.id&&(this.renderAsset=null)},i._getCompoundChildShapeIndex=function(e){for(var t=this.data.shape,i=t.getNumChildShapes(),n=0;n<i;n++){if(t.getChildShape(n).ptr===e.ptr)return n}return null},i._onInsert=function(e){if("undefined"!=typeof Ammo)if(this._compoundParent)this.system.recreatePhysicalShapes(this);else if(!this.entity.rigidbody)for(var t=this.entity.parent;t;){if(t.collision&&"compound"===t.collision.type){0===t.collision.shape.getNumChildShapes()?this.system.recreatePhysicalShapes(t.collision):this.system.recreatePhysicalShapes(this);break}t=t.parent}},i._updateCompound=function(){var e=this.entity;if(e._dirtyWorld){for(var t=e._dirtyLocal,i=e;i&&!t&&(!i.collision||i.collision!==this._compoundParent);)i._dirtyLocal&&(t=!0),i=i.parent;if(t){e.forEach(this.system.implementations.compound._updateEachDescendantTransform,e);var n=this._compoundParent.entity.rigidbody;n&&n.activate()}}},i.onEnable=function(){if("mesh"===this.data.type&&(this.data.asset||this.data.renderAsset)&&this.data.initialized){var e=this.system.app.assets.get(this.data.asset||this.data.renderAsset);if(e&&(!e.resource||!this.data.shape))return void this.system.recreatePhysicalShapes(this)}if(this.entity.rigidbody)this.entity.rigidbody.enabled&&this.entity.rigidbody.enableSimulation();else if(this._compoundParent&&this!==this._compoundParent)if(0===this._compoundParent.shape.getNumChildShapes())this.system.recreatePhysicalShapes(this._compoundParent);else{var t=this.system._getNodeTransform(this.entity,this._compoundParent.entity);this._compoundParent.shape.addChildShape(t,this.data.shape),Ammo.destroy(t),this._compoundParent.entity.rigidbody&&this._compoundParent.entity.rigidbody.activate()}else this.entity.trigger&&this.entity.trigger.enable()},i.onDisable=function(){this.entity.rigidbody?this.entity.rigidbody.disableSimulation():this._compoundParent&&this!==this._compoundParent?this._compoundParent.entity._destroying||(this.system._removeCompoundChild(this._compoundParent,this.data.shape),this._compoundParent.entity.rigidbody&&this._compoundParent.entity.rigidbody.activate()):this.entity.trigger&&this.entity.trigger.disable()},i.onBeforeRemove=function(){this.asset&&(this.asset=null),this.renderAsset&&(this.renderAsset=null),this.entity.off("insert",this._onInsert,this),this.off()},t}(Cl),ig=function(){this.enabled=!0,this.type="box",this.halfExtents=new ye(.5,.5,.5),this.radius=.5,this.axis=1,this.height=2,this.asset=null,this.renderAsset=null,this.shape=null,this.model=null,this.render=null,this.initialized=!1},ng="static",sg="dynamic",rg="kinematic",ag=65535,og=65533,hg=function(){function e(e,t,i){this.entity=t.entity,this.component=t,this.app=e,"undefined"==typeof Ammo||Q_||(Q_=new Ammo.btVector3,J_=new Ammo.btQuaternion,eg=new Ammo.btTransform),this.initialize(i)}var t=e.prototype;return t.initialize=function(e){var t=this.entity,i=e.shape;if(i&&"undefined"!=typeof Ammo){t.trigger&&t.trigger.destroy();var n=t.getPosition(),s=t.getRotation();Q_.setValue(n.x,n.y,n.z),J_.setValue(s.x,s.y,s.z,s.w),eg.setOrigin(Q_),eg.setRotation(J_);var r=this.app.systems.rigidbody.createBody(1,i,eg);r.setRestitution(0),r.setFriction(0),r.setDamping(0,0),Q_.setValue(0,0,0),r.setLinearFactor(Q_),r.setAngularFactor(Q_),r.setCollisionFlags(4|r.getCollisionFlags()),r.entity=t,this.body=r,this.component.enabled&&t.enabled&&this.enable()}},t.destroy=function(){var e=this.body;e&&(this.disable(),this.app.systems.rigidbody.destroyBody(e))},t._getEntityTransform=function(e){var t=this.entity.getPosition(),i=this.entity.getRotation();Q_.setValue(t.x,t.y,t.z),J_.setValue(i.x,i.y,i.z,i.w),e.setOrigin(Q_),e.setRotation(J_)},t.updateTransform=function(){this._getEntityTransform(eg);var e=this.body;e.setWorldTransform(eg),e.activate()},t.enable=function(){var e=this.body;if(e){var t=this.app.systems;t.rigidbody.addBody(e,16,65517),t.rigidbody._triggers.push(this),e.forceActivationState(1),this.updateTransform()}},t.disable=function(){var e=this.body;if(e){var t=this.app.systems,i=t.rigidbody._triggers.indexOf(this);i>-1&&t.rigidbody._triggers.splice(i,1),t.rigidbody.removeBody(e),e.forceActivationState(5)}},e}(),lg=new Ee,cg=new ye,ug=new Pe,dg=new Hn,fg=["enabled","type","halfExtents","radius","axis","height","asset","renderAsset","shape","model","render"],pg=function(){function e(e){this.system=e}var t=e.prototype;return t.beforeInitialize=function(e,t){t.shape=null,t.model=new hc,t.model.graph=new Hn},t.afterInitialize=function(e,t){this.recreatePhysicalShapes(e),e.data.initialized=!0},t.reset=function(e,t){this.beforeInitialize(e,t),this.afterInitialize(e,t)},t.recreatePhysicalShapes=function(e){var t=e.entity,i=e.data;if("undefined"!=typeof Ammo){t.trigger&&(t.trigger.destroy(),delete t.trigger),i.shape&&(e._compoundParent&&(this.system._removeCompoundChild(e._compoundParent,i.shape),e._compoundParent.entity.rigidbody&&e._compoundParent.entity.rigidbody.activate()),Ammo.destroy(i.shape),i.shape=null),i.shape=this.createPhysicalShape(e.entity,i);var n=!e._compoundParent;if("compound"!==i.type||e._compoundParent&&e!==e._compoundParent){if("compound"!==i.type&&(e._compoundParent&&e===e._compoundParent&&t.forEach(this.system.implementations.compound._updateEachDescendant,e),!e.rigidbody)){e._compoundParent=null;for(var s=t.parent;s;){if(s.collision&&"compound"===s.collision.type){e._compoundParent=s.collision;break}s=s.parent}}}else e._compoundParent=e,t.forEach(this._addEachDescendant,e);e._compoundParent&&e!==e._compoundParent&&(n&&0===e._compoundParent.shape.getNumChildShapes()?this.system.recreatePhysicalShapes(e._compoundParent):(this.system.updateCompoundChildTransform(t),e._compoundParent.entity.rigidbody&&e._compoundParent.entity.rigidbody.activate())),t.rigidbody?(t.rigidbody.disableSimulation(),t.rigidbody.createBody(),t.enabled&&t.rigidbody.enabled&&t.rigidbody.enableSimulation()):e._compoundParent||(t.trigger?t.trigger.initialize(i):t.trigger=new hg(this.system.app,e,i))}},t.createPhysicalShape=function(e,t){},t.updateTransform=function(e,t,i,n){e.entity.trigger&&e.entity.trigger.updateTransform()},t.beforeRemove=function(e,t){t.data.shape&&(t._compoundParent&&!t._compoundParent.entity._destroying&&(this.system._removeCompoundChild(t._compoundParent,t.data.shape),t._compoundParent.entity.rigidbody&&t._compoundParent.entity.rigidbody.activate()),t._compoundParent=null,Ammo.destroy(t.data.shape),t.data.shape=null)},t.remove=function(e,t){e.rigidbody&&e.rigidbody.body&&e.rigidbody.disableSimulation(),e.trigger&&(e.trigger.destroy(),delete e.trigger)},t.clone=function(e,t){var i=this.system.store[e.getGuid()],n={enabled:i.data.enabled,type:i.data.type,halfExtents:[i.data.halfExtents.x,i.data.halfExtents.y,i.data.halfExtents.z],radius:i.data.radius,axis:i.data.axis,height:i.data.height,asset:i.data.asset,renderAsset:i.data.renderAsset,model:i.data.model,render:i.data.render};return this.system.addComponent(t,n)},e}(),mg=function(e){function t(){return e.apply(this,arguments)||this}return J(t,e),t.prototype.createPhysicalShape=function(e,t){if("undefined"!=typeof Ammo){var i=t.halfExtents,n=new Ammo.btVector3(i?i.x:.5,i?i.y:.5,i?i.z:.5),s=new Ammo.btBoxShape(n);return Ammo.destroy(n),s}},t}(pg),_g=function(e){function t(){return e.apply(this,arguments)||this}return J(t,e),t.prototype.createPhysicalShape=function(e,t){if("undefined"!=typeof Ammo)return new Ammo.btSphereShape(t.radius)},t}(pg),gg=function(e){function t(){return e.apply(this,arguments)||this}return J(t,e),t.prototype.createPhysicalShape=function(e,t){var i=void 0!==t.axis?t.axis:1,n=t.radius||.5,s=Math.max((t.height||2)-2*n,0),r=null;if("undefined"!=typeof Ammo)switch(i){case 0:r=new Ammo.btCapsuleShapeX(n,s);break;case 1:r=new Ammo.btCapsuleShape(n,s);break;case 2:r=new Ammo.btCapsuleShapeZ(n,s)}return r},t}(pg),vg=function(e){function t(){return e.apply(this,arguments)||this}return J(t,e),t.prototype.createPhysicalShape=function(e,t){var i=void 0!==t.axis?t.axis:1,n=void 0!==t.radius?t.radius:.5,s=void 0!==t.height?t.height:1,r=null,a=null;if("undefined"!=typeof Ammo)switch(i){case 0:r=new Ammo.btVector3(.5*s,n,n),a=new Ammo.btCylinderShapeX(r);break;case 1:r=new Ammo.btVector3(n,.5*s,n),a=new Ammo.btCylinderShape(r);break;case 2:r=new Ammo.btVector3(n,n,.5*s),a=new Ammo.btCylinderShapeZ(r)}return r&&Ammo.destroy(r),a},t}(pg),yg=function(e){function t(){return e.apply(this,arguments)||this}return J(t,e),t.prototype.createPhysicalShape=function(e,t){var i=void 0!==t.axis?t.axis:1,n=void 0!==t.radius?t.radius:.5,s=void 0!==t.height?t.height:1,r=null;if("undefined"!=typeof Ammo)switch(i){case 0:r=new Ammo.btConeShapeX(n,s);break;case 1:r=new Ammo.btConeShape(n,s);break;case 2:r=new Ammo.btConeShapeZ(n,s)}return r},t}(pg),xg=function(e){function t(){return e.apply(this,arguments)||this}J(t,e);var i=t.prototype;return i.beforeInitialize=function(e,t){},i.createAmmoMesh=function(e,t,i){var n;if(this.system._triMeshCache[e.id])n=this.system._triMeshCache[e.id];else{for(var s,r,a=e.vertexBuffer,o=a.getFormat(),h=0;h<o.elements.length;h++){var l=o.elements[h];if(l.name===vt){r=new Float32Array(a.lock(),l.offset),s=l.stride/4;break}}var c=[];e.getIndices(c);var u,d,f,p=e.primitive[0].count/3,m=new Ammo.btVector3,_=new Ammo.btVector3,g=new Ammo.btVector3,v=e.primitive[0].base;n=new Ammo.btTriangleMesh,this.system._triMeshCache[e.id]=n;for(var y=0;y<p;y++)u=c[v+3*y]*s,d=c[v+3*y+1]*s,f=c[v+3*y+2]*s,m.setValue(r[u],r[u+1],r[u+2]),_.setValue(r[d],r[d+1],r[d+2]),g.setValue(r[f],r[f+1],r[f+2]),n.addTriangle(m,_,g,!0);Ammo.destroy(m),Ammo.destroy(_),Ammo.destroy(g)}var x=new Ammo.btBvhTriangleMeshShape(n,!0),b=this.system._getNodeScaling(t);x.setLocalScaling(b),Ammo.destroy(b);var S=this.system._getNodeTransform(t);i.addChildShape(S,x),Ammo.destroy(S)},i.createPhysicalShape=function(e,t){if("undefined"!=typeof Ammo&&(t.model||t.render)){var i=new Ammo.btCompoundShape;if(t.model)for(var n=t.model.meshInstances,s=0;s<n.length;s++)this.createAmmoMesh(n[s].mesh,n[s].node,i);else if(t.render)for(var r=t.render.meshes,a=0;a<r.length;a++)this.createAmmoMesh(r[a],dg,i);var o=e.getWorldTransform().getScale(),h=new Ammo.btVector3(o.x,o.y,o.z);return i.setLocalScaling(h),Ammo.destroy(h),i}},i.recreatePhysicalShapes=function(e){var t=e.data;(t.renderAsset||t.asset)&&e.enabled&&e.entity.enabled?this.loadAsset(e,t.renderAsset||t.asset,t.renderAsset?"render":"model"):this.doRecreatePhysicalShape(e)},i.loadAsset=function(e,t,i){var n=this,s=e.data,r=this.system.app.assets,a=r.get(t);a?(a.ready((function(t){s[i]=t.resource,n.doRecreatePhysicalShape(e)})),r.load(a)):r.once("add:"+t,(function(t){t.ready((function(t){s[i]=t.resource,n.doRecreatePhysicalShape(e)})),r.load(t)}))},i.doRecreatePhysicalShape=function(e){var t=e.entity,i=e.data;i.model||i.render?(this.destroyShape(i),i.shape=this.createPhysicalShape(t,i),t.rigidbody?(t.rigidbody.disableSimulation(),t.rigidbody.createBody(),t.enabled&&t.rigidbody.enabled&&t.rigidbody.enableSimulation()):t.trigger?t.trigger.initialize(i):t.trigger=new hg(this.system.app,e,i)):(this.beforeRemove(t,e),this.remove(t,i))},i.updateTransform=function(t,i,n,s){if(t.shape){var r=t.entity.getWorldTransform().getScale(),a=t.shape.getLocalScaling();r.x===a.x()&&r.y===a.y()&&r.z===a.z()||this.doRecreatePhysicalShape(t)}e.prototype.updateTransform.call(this,t,i,n,s)},i.destroyShape=function(e){if(e.shape){for(var t=e.shape.getNumChildShapes(),i=0;i<t;i++){var n=e.shape.getChildShape(i);Ammo.destroy(n)}Ammo.destroy(e.shape),e.shape=null}},i.remove=function(t,i){this.destroyShape(i),e.prototype.remove.call(this,t,i)},t}(pg),bg=function(e){function t(){return e.apply(this,arguments)||this}J(t,e);var i=t.prototype;return i.createPhysicalShape=function(e,t){if("undefined"!=typeof Ammo)return new Ammo.btCompoundShape},i._addEachDescendant=function(e){e.collision&&!e.rigidbody&&(e.collision._compoundParent=this,e!==this.entity&&e.collision.system.recreatePhysicalShapes(e.collision))},i._updateEachDescendant=function(e){e.collision&&e.collision._compoundParent===this&&(e.collision._compoundParent=null,e===this.entity||e.rigidbody||e.collision.system.recreatePhysicalShapes(e.collision))},i._updateEachDescendantTransform=function(e){e.collision&&e.collision._compoundParent===this.collision._compoundParent&&this.collision.system.updateCompoundChildTransform(e)},t}(pg),Sg=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="collision",i.ComponentType=tg,i.DataType=ig,i.schema=fg,i.implementations={},i._triMeshCache={},i.on("beforeremove",i.onBeforeRemove,te(i)),i.on("remove",i.onRemove,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){for(var s,r={},a=0,o=(n=["type","halfExtents","radius","axis","height","shape","model","asset","render","renderAsset","enabled"]).length;a<o;a++){var h=n[a];r[h]=i[h]}i.hasOwnProperty("asset")?(-1!==(s=n.indexOf("model"))&&n.splice(s,1),-1!==(s=n.indexOf("render"))&&n.splice(s,1)):i.hasOwnProperty("model")&&-1!==(s=n.indexOf("asset"))&&n.splice(s,1),r.type||(r.type=t.data.type),t.data.type=r.type,r.halfExtents&&Array.isArray(r.halfExtents)&&(r.halfExtents=new ye(r.halfExtents[0],r.halfExtents[1],r.halfExtents[2]));var l=this._createImplementation(r.type);l.beforeInitialize(t,r),e.prototype.initializeComponentData.call(this,t,r,n),l.afterInitialize(t,r)},i._createImplementation=function(e){if(void 0===this.implementations[e]){var t;switch(e){case"box":t=new mg(this);break;case"sphere":t=new _g(this);break;case"capsule":t=new gg(this);break;case"cylinder":t=new vg(this);break;case"cone":t=new yg(this);break;case"mesh":t=new xg(this);break;case"compound":t=new bg(this)}this.implementations[e]=t}return this.implementations[e]},i._getImplementation=function(e){return this.implementations[e.collision.data.type]},i.cloneComponent=function(e,t){return this._getImplementation(e).clone(e,t)},i.onBeforeRemove=function(e,t){this.implementations[t.data.type].beforeRemove(e,t),t.onBeforeRemove()},i.onRemove=function(e,t){this.implementations[t.type].remove(e,t)},i.updateCompoundChildTransform=function(e){if(this._removeCompoundChild(e.collision._compoundParent,e.collision.data.shape),e.enabled&&e.collision.enabled){var t=this._getNodeTransform(e,e.collision._compoundParent.entity);e.collision._compoundParent.shape.addChildShape(t,e.collision.data.shape),Ammo.destroy(t)}},i._removeCompoundChild=function(e,t){if(e.shape.removeChildShape)e.shape.removeChildShape(t);else{var i=e._getCompoundChildShapeIndex(t);null!==i&&e.shape.removeChildShapeByIndex(i)}},i.onTransformChanged=function(e,t,i,n){this.implementations[e.data.type].updateTransform(e,t,i,n)},i.changeType=function(e,t,i){this.implementations[t].beforeRemove(e.entity,e),this.implementations[t].remove(e.entity,e.data),this._createImplementation(i).reset(e,e.data)},i.recreatePhysicalShapes=function(e){this.implementations[e.data.type].recreatePhysicalShapes(e)},i._calculateNodeRelativeTransform=function(e,t){if(e===t){var i=e.getWorldTransform().getScale();lg.setScale(i.x,i.y,i.z)}else this._calculateNodeRelativeTransform(e.parent,t),lg.mul(e.getLocalTransform())},i._getNodeScaling=function(e){var t=e.getWorldTransform().getScale();return new Ammo.btVector3(t.x,t.y,t.z)},i._getNodeTransform=function(e,t){var i,n;t?(this._calculateNodeRelativeTransform(e,t),i=cg,n=ug,lg.getTranslation(i),n.setFromMat4(lg)):(i=e.getPosition(),n=e.getRotation());var s=new Ammo.btTransform;s.setIdentity();var r=s.getOrigin();r.setValue(i.x,i.y,i.z);var a=new Ammo.btQuaternion;return a.setValue(n.x,n.y,n.z,n.w),s.setRotation(a),Ammo.destroy(a),Ammo.destroy(r),s},i.destroy=function(){for(var t in this._triMeshCache)Ammo.destroy(this._triMeshCache[t]);this._triMeshCache=null,e.prototype.destroy.call(this)},t}(h_);Cl._buildAccessors(tg.prototype,fg);var wg=function(){function e(e,t,i){this._entity=e,this._element=e.element,this.model=new hc,this.node=new Hn,this.model.graph=this.node,this.mesh=t,this.meshInstance=new ka(this.mesh,i,this.node),this.meshInstance.name="ImageElement: "+e.name,this.meshInstance.castShadow=!1,this.meshInstance.receiveShadow=!1,this._meshDirty=!1,this.model.meshInstances.push(this.meshInstance),this._entity.addChild(this.model.graph),this.model._entity=this._entity,this.unmaskMeshInstance=null}var t=e.prototype;return t.destroy=function(){this.setMaterial(null),this._element.removeModelFromLayers(this.model),this.model.destroy(),this.model=null,this.node=null,this.mesh=null,this.meshInstance=null,this._entity=null,this._element=null},t.setMesh=function(e){this.meshInstance&&(this.mesh=e,this.meshInstance.mesh=e,this.meshInstance.visible=!!e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.mesh=e),this.forceUpdateAabb())},t.setMask=function(e){if(this.meshInstance){if(e)for(var t in this.unmaskMeshInstance=new ka(this.mesh,this.meshInstance.material,this.node),this.unmaskMeshInstance.name="Unmask: "+this._entity.name,this.unmaskMeshInstance.castShadow=!1,this.unmaskMeshInstance.receiveShadow=!1,this.unmaskMeshInstance.pick=!1,this.model.meshInstances.push(this.unmaskMeshInstance),this.meshInstance.parameters)this.unmaskMeshInstance.setParameter(t,this.meshInstance.parameters[t].data);else{var i=this.model.meshInstances.indexOf(this.unmaskMeshInstance);i>=0&&this.model.meshInstances.splice(i,1),this.unmaskMeshInstance=null}this._entity.enabled&&this._element.enabled&&(this._element.removeModelFromLayers(this.model),this._element.addModelToLayers(this.model))}},t.setMaterial=function(e){this.meshInstance&&(this.meshInstance.material=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.material=e))},t.setParameter=function(e,t){this.meshInstance&&(this.meshInstance.setParameter(e,t),this.unmaskMeshInstance&&this.unmaskMeshInstance.setParameter(e,t))},t.deleteParameter=function(e){this.meshInstance&&(this.meshInstance.deleteParameter(e),this.unmaskMeshInstance&&this.unmaskMeshInstance.deleteParameter(e))},t.setUnmaskDrawOrder=function(){if(this.meshInstance){if(this.unmaskMeshInstance){var e=function e(t){var i,n=t.children,s=n.length;if(s){for(var r=0;r<s;r++)n[r].element&&(i=n[r]);return i?e(i)||i:null}return null}(this._entity);e&&e.element?this.unmaskMeshInstance.drawOrder=e.element.drawOrder+e.element.getMaskOffset():this.unmaskMeshInstance.drawOrder=this.meshInstance.drawOrder+this._element.getMaskOffset()}}},t.setDrawOrder=function(e){this.meshInstance&&(this.meshInstance.drawOrder=e)},t.setCull=function(e){if(this.meshInstance){var t=this._element,i=null;e&&t._isScreenSpace()&&(i=function(e){return t.isVisibleForCamera(e)}),this.meshInstance.cull=e,this.meshInstance.isVisibleFunc=i,this.unmaskMeshInstance&&(this.unmaskMeshInstance.cull=e,this.unmaskMeshInstance.isVisibleFunc=i)}},t.setScreenSpace=function(e){this.meshInstance&&(this.meshInstance.screenSpace=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.screenSpace=e))},t.setLayer=function(e){this.meshInstance&&(this.meshInstance.layer=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.layer=e))},t.forceUpdateAabb=function(e){this.meshInstance&&(this.meshInstance._aabbVer=-1,this.unmaskMeshInstance&&(this.unmaskMeshInstance._aabbVer=-1))},t.setAabbFunc=function(e){this.meshInstance&&(this.meshInstance._updateAabbFunc=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance._updateAabbFunc=e))},e}(),Tg=function(){function e(e){this._element=e,this._entity=e.entity,this._system=e.system,this._textureAsset=null,this._texture=null,this._materialAsset=null,this._material=null,this._spriteAsset=null,this._sprite=null,this._spriteFrame=0,this._pixelsPerUnit=null,this._targetAspectRatio=-1,this._rect=new Se(0,0,1,1),this._mask=!1,this._maskRef=0,this._outerScale=new be,this._outerScaleUniform=new Float32Array(2),this._innerOffset=new Se,this._innerOffsetUniform=new Float32Array(4),this._atlasRect=new Se,this._atlasRectUniform=new Float32Array(4),this._defaultMesh=this._createMesh(),this._renderable=new wg(this._entity,this._defaultMesh,this._material),this._color=new me(1,1,1,1),this._colorUniform=new Float32Array([1,1,1]),this._renderable.setParameter("material_emissive",this._colorUniform),this._renderable.setParameter("material_opacity",1),this._updateAabbFunc=this._updateAabb.bind(this),this._onScreenChange(this._element.screen),this._element.on("resize",this._onParentResizeOrPivotChange,this),this._element.on("set:pivot",this._onParentResizeOrPivotChange,this),this._element.on("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.on("set:screen",this._onScreenChange,this),this._element.on("set:draworder",this._onDrawOrderChange,this),this._element.on("screen:set:resolution",this._onResolutionChange,this)}var t=e.prototype;return t.destroy=function(){this.textureAsset=null,this.spriteAsset=null,this.materialAsset=null,this._renderable.setMesh(this._defaultMesh),this._renderable.destroy(),this._defaultMesh=null,this._element.off("resize",this._onParentResizeOrPivotChange,this),this._element.off("set:pivot",this._onParentResizeOrPivotChange,this),this._element.off("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.off("set:screen",this._onScreenChange,this),this._element.off("set:draworder",this._onDrawOrderChange,this),this._element.off("screen:set:resolution",this._onResolutionChange,this)},t._onResolutionChange=function(e){},t._onParentResizeOrPivotChange=function(){this._renderable.mesh&&this._updateMesh(this._renderable.mesh)},t._onScreenSpaceChange=function(e){this._updateMaterial(e)},t._onScreenChange=function(e,t){e?this._updateMaterial(e.screen.screenSpace):this._updateMaterial(!1)},t._onDrawOrderChange=function(e){this._renderable.setDrawOrder(e),this.mask&&this._element.screen&&this._element.screen.screen.once("syncdraworder",(function(){this._renderable.setUnmaskDrawOrder()}),this)},t._hasUserMaterial=function(){return!!this._materialAsset||!!this._material&&-1===this._system.defaultImageMaterials.indexOf(this._material)},t._use9Slicing=function(){return this.sprite&&(1===this.sprite.renderMode||2===this.sprite.renderMode)},t._updateMaterial=function(e){var t=!!this._mask,i=!(!this.sprite||1!==this.sprite.renderMode),n=!(!this.sprite||2!==this.sprite.renderMode);this._hasUserMaterial()||(this._material=this._system.getImageElementMaterial(e,t,i,n)),this._renderable&&(this._renderable.setCull(!this._element._isScreenSpace()||this._element._isScreenCulled()),this._renderable.setMaterial(this._material),this._renderable.setScreenSpace(e),this._renderable.setLayer(e?0:15))},t._createMesh=function(){var e=this._element,t=e.calculatedWidth,i=e.calculatedHeight,n=this._rect,s=new ArrayBuffer(128),r=new Float32Array(s);r[5]=1,r[6]=n.x,r[7]=1-n.y,r[8]=t,r[13]=1,r[14]=n.x+n.z,r[15]=1-n.y,r[16]=t,r[17]=i,r[21]=1,r[22]=n.x+n.z,r[23]=1-(n.y+n.w),r[25]=i,r[29]=1,r[30]=n.x,r[31]=1-(n.y+n.w);var a=[{semantic:vt,components:3,type:6},{semantic:yt,components:3,type:6},{semantic:At,components:2,type:6}],o=this._system.app.graphicsDevice,h=new Ti(o,a),l=new Si(o,h,4,0,s),c=new ea(o);return c.vertexBuffer=l,c.primitive[0].type=6,c.primitive[0].base=0,c.primitive[0].count=4,c.primitive[0].indexed=!1,c.aabb.setMinMax(ye.ZERO,new ye(t,i,0)),this._updateMesh(c),c},t._updateMesh=function(e){var t=this._element,i=t.calculatedWidth,n=t.calculatedHeight;if(t.fitMode!==B_&&this._targetAspectRatio>0){var s=t.calculatedWidth/t.calculatedHeight;t.fitMode===N_&&s>this._targetAspectRatio||t.fitMode===U_&&s<this._targetAspectRatio?i=t.calculatedHeight*this._targetAspectRatio:n=t.calculatedWidth/this._targetAspectRatio}var r=t._isScreenSpace();if(this._updateMaterial(r),this._renderable&&this._renderable.forceUpdateAabb(),!this.sprite||1!==this.sprite.renderMode&&2!==this.sprite.renderMode){var a=e.vertexBuffer,o=new Float32Array(a.lock()),h=t.pivot.x,l=t.pivot.y;o[0]=0-h*i,o[1]=0-l*n,o[8]=i-h*i,o[9]=0-l*n,o[16]=i-h*i,o[17]=n-l*n,o[24]=0-h*i,o[25]=n-l*n;var c=1,u=1,d=this._rect;if(this._sprite&&this._sprite.frameKeys[this._spriteFrame]&&this._sprite.atlas){var f=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]];f&&(d=f.rect,c=this._sprite.atlas.texture.width,u=this._sprite.atlas.texture.height)}o[6]=d.x/c,o[7]=1-d.y/u,o[14]=(d.x+d.z)/c,o[15]=1-d.y/u,o[22]=(d.x+d.z)/c,o[23]=1-(d.y+d.w)/u,o[30]=d.x/c,o[31]=1-(d.y+d.w)/u,a.unlock();var p=new ye(0-h*i,0-l*n,0),m=new ye(i-h*i,n-l*n,0);e.aabb.setMinMax(p,m),this._renderable&&(this._renderable.node.setLocalScale(1,1,1),this._renderable.node.setLocalPosition(0,0,0),this._renderable.setAabbFunc(null))}else{var _=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]],g=2/_.rect.z,v=2/_.rect.w;this._innerOffset.set(_.border.x*g,_.border.y*v,_.border.z*g,_.border.w*v);var y=this.sprite.atlas.texture;this._atlasRect.set(_.rect.x/y.width,_.rect.y/y.height,_.rect.z/y.width,_.rect.w/y.height);var x=null!==this._pixelsPerUnit?this._pixelsPerUnit:this.sprite.pixelsPerUnit,b=_.rect.z/x,S=_.rect.w/x;this._outerScale.set(Math.max(i,this._innerOffset.x*b),Math.max(n,this._innerOffset.y*S));var w=b,T=S;this._outerScale.x/=b,this._outerScale.y/=S,w*=de.clamp(i/(this._innerOffset.x*b),1e-4,1),T*=de.clamp(n/(this._innerOffset.y*S),1e-4,1),this._renderable&&(this._innerOffsetUniform[0]=this._innerOffset.x,this._innerOffsetUniform[1]=this._innerOffset.y,this._innerOffsetUniform[2]=this._innerOffset.z,this._innerOffsetUniform[3]=this._innerOffset.w,this._renderable.setParameter("innerOffset",this._innerOffsetUniform),this._atlasRectUniform[0]=this._atlasRect.x,this._atlasRectUniform[1]=this._atlasRect.y,this._atlasRectUniform[2]=this._atlasRect.z,this._atlasRectUniform[3]=this._atlasRect.w,this._renderable.setParameter("atlasRect",this._atlasRectUniform),this._outerScaleUniform[0]=this._outerScale.x,this._outerScaleUniform[1]=this._outerScale.y,this._renderable.setParameter("outerScale",this._outerScaleUniform),this._renderable.setAabbFunc(this._updateAabbFunc),this._renderable.node.setLocalScale(w,T,1),this._renderable.node.setLocalPosition((.5-t.pivot.x)*i,(.5-t.pivot.y)*n,0))}this._meshDirty=!1},t._updateSprite=function(){var e=!1,t=null;if(this._targetAspectRatio=-1,this._sprite&&this._sprite.atlas){t=this._sprite.meshes[this.spriteFrame],e=1===this._sprite.renderMode||2===this._sprite.renderMode;var i=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]];(null==i?void 0:i.rect.w)>0&&(this._targetAspectRatio=i.rect.z/i.rect.w)}this.mesh=e?t:this._defaultMesh,this.refreshMesh()},t.refreshMesh=function(){this.mesh&&(this._element._beingInitialized?this._meshDirty=!0:this._updateMesh(this.mesh))},t._updateAabb=function(e){return e.center.set(0,0,0),e.halfExtents.set(.5*this._outerScale.x,.5*this._outerScale.y,.001),e.setFromTransformedAabb(e,this._renderable.node.getWorldTransform()),e},t._toggleMask=function(){this._element._dirtifyMask();var e=this._element._isScreenSpace();this._updateMaterial(e),this._renderable.setMask(!!this._mask)},t._onMaterialLoad=function(e){this.material=e.resource},t._onMaterialAdded=function(e){this._system.app.assets.off("add:"+e.id,this._onMaterialAdded,this),this._materialAsset===e.id&&this._bindMaterialAsset(e)},t._bindMaterialAsset=function(e){this._entity.enabled&&(e.on("load",this._onMaterialLoad,this),e.on("change",this._onMaterialChange,this),e.on("remove",this._onMaterialRemove,this),e.resource?this._onMaterialLoad(e):this._system.app.assets.load(e))},t._unbindMaterialAsset=function(e){e.off("load",this._onMaterialLoad,this),e.off("change",this._onMaterialChange,this),e.off("remove",this._onMaterialRemove,this)},t._onMaterialChange=function(){},t._onMaterialRemove=function(){},t._onTextureAdded=function(e){this._system.app.assets.off("add:"+e.id,this._onTextureAdded,this),this._textureAsset===e.id&&this._bindTextureAsset(e)},t._bindTextureAsset=function(e){this._entity.enabled&&(e.on("load",this._onTextureLoad,this),e.on("change",this._onTextureChange,this),e.on("remove",this._onTextureRemove,this),e.resource?this._onTextureLoad(e):this._system.app.assets.load(e))},t._unbindTextureAsset=function(e){e.off("load",this._onTextureLoad,this),e.off("change",this._onTextureChange,this),e.off("remove",this._onTextureRemove,this)},t._onTextureLoad=function(e){this.texture=e.resource},t._onTextureChange=function(e){},t._onTextureRemove=function(e){},t._onSpriteAssetAdded=function(e){this._system.app.assets.off("add:"+e.id,this._onSpriteAssetAdded,this),this._spriteAsset===e.id&&this._bindSpriteAsset(e)},t._bindSpriteAsset=function(e){this._entity.enabled&&(e.on("load",this._onSpriteAssetLoad,this),e.on("change",this._onSpriteAssetChange,this),e.on("remove",this._onSpriteAssetRemove,this),e.resource?this._onSpriteAssetLoad(e):this._system.app.assets.load(e))},t._unbindSpriteAsset=function(e){e.off("load",this._onSpriteAssetLoad,this),e.off("change",this._onSpriteAssetChange,this),e.off("remove",this._onSpriteAssetRemove,this),e.data.textureAtlasAsset&&this._system.app.assets.off("load:"+e.data.textureAtlasAsset,this._onTextureAtlasLoad,this)},t._onSpriteAssetLoad=function(e){if(e&&e.resource)if(e.resource.atlas)this.sprite=e.resource;else{var t=e.data.textureAtlasAsset;if(t){var i=this._system.app.assets;i.off("load:"+t,this._onTextureAtlasLoad,this),i.once("load:"+t,this._onTextureAtlasLoad,this)}}else this.sprite=null},t._onSpriteAssetChange=function(e){this._onSpriteAssetLoad(e)},t._onSpriteAssetRemove=function(e){},t._bindSprite=function(e){e.on("set:meshes",this._onSpriteMeshesChange,this),e.on("set:pixelsPerUnit",this._onSpritePpuChange,this),e.on("set:atlas",this._onAtlasTextureChange,this),e.atlas&&e.atlas.on("set:texture",this._onAtlasTextureChange,this)},t._unbindSprite=function(e){e.off("set:meshes",this._onSpriteMeshesChange,this),e.off("set:pixelsPerUnit",this._onSpritePpuChange,this),e.off("set:atlas",this._onAtlasTextureChange,this),e.atlas&&e.atlas.off("set:texture",this._onAtlasTextureChange,this)},t._onSpriteMeshesChange=function(){this._sprite&&(this._spriteFrame=de.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite()},t._onSpritePpuChange=function(){0!==this.sprite.renderMode&&null===this._pixelsPerUnit&&this._updateSprite()},t._onAtlasTextureChange=function(){this.sprite&&this.sprite.atlas&&this.sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"))},t._onTextureAtlasLoad=function(e){var t=this._spriteAsset;t instanceof ml?this._onSpriteAssetLoad(t):this._onSpriteAssetLoad(this._system.app.assets.get(t))},t.onEnable=function(){if(this._materialAsset){var e=this._system.app.assets.get(this._materialAsset);e&&e.resource!==this._material&&this._bindMaterialAsset(e)}if(this._textureAsset){var t=this._system.app.assets.get(this._textureAsset);t&&t.resource!==this._texture&&this._bindTextureAsset(t)}if(this._spriteAsset){var i=this._system.app.assets.get(this._spriteAsset);i&&i.resource!==this._sprite&&this._bindSpriteAsset(i)}this._element.addModelToLayers(this._renderable.model)},t.onDisable=function(){this._element.removeModelFromLayers(this._renderable.model)},t._setStencil=function(e){this._renderable.meshInstance.stencilFront=e,this._renderable.meshInstance.stencilBack=e;var t=0;if(this._element.maskedBy&&(t=this._element.maskedBy.element._image._maskRef),this._renderable.unmaskMeshInstance){var i=new du({ref:t+1,func:2,zpass:5});this._renderable.unmaskMeshInstance.stencilFront=i,this._renderable.unmaskMeshInstance.stencilBack=i}},$(e,[{key:"color",get:function(){return this._color},set:function(e){var t=e.r,i=e.g,n=e.b;this._color.r===t&&this._color.g===i&&this._color.b===n||(this._color.r=t,this._color.g=i,this._color.b=n,this._colorUniform[0]=t,this._colorUniform[1]=i,this._colorUniform[2]=n,this._renderable.setParameter("material_emissive",this._colorUniform)),this._element&&this._element.fire("set:color",this._color)}},{key:"opacity",get:function(){return this._color.a},set:function(e){e!==this._color.a&&(this._color.a=e,this._renderable.setParameter("material_opacity",e)),this._element&&this._element.fire("set:opacity",e)}},{key:"rect",get:function(){return this._rect},set:function(e){var t,i,n,s;e instanceof Se?(t=e.x,i=e.y,n=e.z,s=e.w):(t=e[0],i=e[1],n=e[2],s=e[3]),t===this._rect.x&&i===this._rect.y&&n===this._rect.z&&s===this._rect.w||(this._rect.set(t,i,n,s),this._renderable.mesh&&(this._element._beingInitialized?this._meshDirty=!0:this._updateMesh(this._renderable.mesh)))}},{key:"material",get:function(){return this._material},set:function(e){if(this._material!==e){if(!e){var t=this._element._isScreenSpace();e=this.mask?t?this._system.defaultScreenSpaceImageMaskMaterial:this._system.defaultImageMaskMaterial:t?this._system.defaultScreenSpaceImageMaterial:this._system.defaultImageMaterial}this._material=e,e&&(this._renderable.setMaterial(e),this._hasUserMaterial()?(this._renderable.deleteParameter("material_opacity"),this._renderable.deleteParameter("material_emissive")):(this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._renderable.setParameter("material_emissive",this._colorUniform),this._renderable.setParameter("material_opacity",this._color.a)))}}},{key:"materialAsset",get:function(){return this._materialAsset},set:function(e){var t=this._system.app.assets,i=e;if(e instanceof ml&&(i=e.id),this._materialAsset!==i){if(this._materialAsset){t.off("add:"+this._materialAsset,this._onMaterialAdded,this);var n=t.get(this._materialAsset);n&&(n.off("load",this._onMaterialLoad,this),n.off("change",this._onMaterialChange,this),n.off("remove",this._onMaterialRemove,this))}if(this._materialAsset=i,this._materialAsset){var s=t.get(this._materialAsset);s?this._bindMaterialAsset(s):(this.material=null,t.on("add:"+this._materialAsset,this._onMaterialAdded,this))}else this.material=null}}},{key:"texture",get:function(){return this._texture},set:function(e){if(this._texture!==e){if(this._textureAsset){var t=this._system.app.assets.get(this._textureAsset);t&&t.resource!==e&&(this.textureAsset=null)}if(this._texture=e,e){this._spriteAsset&&(this.spriteAsset=null),this._renderable.setParameter("texture_emissiveMap",this._texture),this._renderable.setParameter("texture_opacityMap",this._texture),this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._renderable.setParameter("material_emissive",this._colorUniform),this._renderable.setParameter("material_opacity",this._color.a);var i=this._texture.width/this._texture.height;i!==this._targetAspectRatio&&(this._targetAspectRatio=i,this._element.fitMode!==B_&&this.refreshMesh())}else this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"),this._targetAspectRatio=-1,this._element.fitMode!==B_&&this.refreshMesh()}}},{key:"textureAsset",get:function(){return this._textureAsset},set:function(e){var t=this._system.app.assets,i=e;if(e instanceof ml&&(i=e.id),this._textureAsset!==i){if(this._textureAsset){t.off("add:"+this._textureAsset,this._onTextureAdded,this);var n=t.get(this._textureAsset);n&&(n.off("load",this._onTextureLoad,this),n.off("change",this._onTextureChange,this),n.off("remove",this._onTextureRemove,this))}if(this._textureAsset=i,this._textureAsset){var s=t.get(this._textureAsset);s?this._bindTextureAsset(s):(this.texture=null,t.on("add:"+this._textureAsset,this._onTextureAdded,this))}else this.texture=null}}},{key:"spriteAsset",get:function(){return this._spriteAsset},set:function(e){var t=this._system.app.assets,i=e;if(e instanceof ml&&(i=e.id),this._spriteAsset!==i){if(this._spriteAsset){t.off("add:"+this._spriteAsset,this._onSpriteAssetAdded,this);var n=t.get(this._spriteAsset);n&&this._unbindSpriteAsset(n)}if(this._spriteAsset=i,this._spriteAsset){var s=t.get(this._spriteAsset);s?this._bindSpriteAsset(s):(this.sprite=null,t.on("add:"+this._spriteAsset,this._onSpriteAssetAdded,this))}else this.sprite=null}this._element&&this._element.fire("set:spriteAsset",i)}},{key:"sprite",get:function(){return this._sprite},set:function(e){if(this._sprite!==e){if(this._sprite&&this._unbindSprite(this._sprite),this._spriteAsset){var t=this._system.app.assets.get(this._spriteAsset);t&&t.resource!==e&&(this.spriteAsset=null)}this._sprite=e,this._sprite&&(this._bindSprite(this._sprite),this._textureAsset&&(this.textureAsset=null)),this._sprite&&this._sprite.atlas&&this._sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap")),this._sprite&&(this._spriteFrame=de.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite()}}},{key:"spriteFrame",get:function(){return this._spriteFrame},set:function(e){var t=this._spriteFrame;this._sprite?this._spriteFrame=de.clamp(e,0,this._sprite.frameKeys.length-1):this._spriteFrame=e,this._spriteFrame!==t&&this._updateSprite(),this._element&&this._element.fire("set:spriteFrame",e)}},{key:"mesh",get:function(){return this._renderable.mesh},set:function(e){this._renderable.setMesh(e),this._defaultMesh===e?this._renderable.setAabbFunc(null):this._renderable.setAabbFunc(this._updateAabbFunc)}},{key:"mask",get:function(){return this._mask},set:function(e){this._mask!==e&&(this._mask=e,this._toggleMask())}},{key:"pixelsPerUnit",get:function(){return this._pixelsPerUnit},set:function(e){this._pixelsPerUnit!==e&&(this._pixelsPerUnit=e,!this._sprite||1!==this._sprite.renderMode&&2!==this._sprite.renderMode||this._updateSprite())}},{key:"aabb",get:function(){return this._renderable.meshInstance?this._renderable.meshInstance.aabb:null}}]),e}(),Ag=/[A-Z|a-z|0-9|_|-|/]/,Mg=function(){function e(e){this._symbols=e,this._index=0,this._last=0,this._cur=this._symbols.length>0?this._symbols[0]:null,this._buf=[],this._mode="text",this._error=null}var t=e.prototype;return t.read=function(){for(var e=this._read();8===e;)e=this._read();return 0!==e&&1!==e&&(this._last=this._index),e},t.buf=function(){return this._buf},t.last=function(){return this._last},t.error=function(){return this._error},t.debugPrint=function(){for(var e=["EOF","ERROR","TEXT","OPEN_BRACKET","CLOSE_BRACKET","EQUALS","STRING","IDENTIFIER","WHITESPACE"],t=this.read(),i="";i+=(i.length>0?"\n":"")+e[t]+" '"+this.buf().join("")+"'",0!==t&&1!==t;)t=this.read();return i},t._read=function(){return this._buf=[],this._eof()?0:"text"===this._mode?this._text():this._tag()},t._text=function(){for(;;)switch(this._cur){case null:return this._buf.length>0?2:0;case"[":return this._mode="tag",this._buf.length>0?2:this._tag();case"\\":if(this._next(),"["===this._cur)this._store();else this._output("\\");break;default:this._store()}},t._tag=function(){switch(this._cur){case null:return this._error="unexpected end of input reading tag",1;case"[":return this._store(),3;case"]":return this._store(),this._mode="text",4;case"=":return this._store(),5;case" ":case"\t":case"\n":case"\r":case"\v":case"\f":return this._whitespace();case'"':return this._string();default:return this._isIdentifierSymbol(this._cur)?this._identifier():(this._error="unrecognized character",1)}},t._whitespace=function(){for(this._store();-1!==" \t\n\r\v\f".indexOf(this._cur);)this._store();return 8},t._string=function(){for(this._next();;)switch(this._cur){case null:return this._error="unexpected end of input reading string",1;case'"':return this._next(),6;default:this._store()}},t._identifier=function(){for(this._store();null!==this._cur&&this._isIdentifierSymbol(this._cur);)this._store();return 7},t._isIdentifierSymbol=function(e){return 1===e.length&&null!==e.match(Ag)},t._eof=function(){return null===this._cur},t._next=function(){return this._eof()||(this._index++,this._cur=this._index<this._symbols.length?this._symbols[this._index]:null),this._cur},t._store=function(){return this._buf.push(this._cur),this._next()},t._output=function(e){this._buf.push(e)},e}(),Cg=function(){function e(e){this._scanner=new Mg(e),this._error=null}var t=e.prototype;return t.parse=function(e,t){for(;;){switch(this._scanner.read()){case 0:return!0;case 1:default:return!1;case 2:Array.prototype.push.apply(e,this._scanner.buf());break;case 3:if(!this._parseTag(e,t))return!1}}},t.error=function(){return"Error evaluating markup at #"+this._scanner.last().toString()+" ("+(this._scanner.error()||this._error)+")"},t._parseTag=function(e,t){var i=this._scanner.read();if(7!==i)return this._error="expected identifier",!1;var n=this._scanner.buf().join("");if("/"===n[0]){for(var s=t.length-1;s>=0;--s)if(n==="/"+t[s].name&&null===t[s].end)return t[s].end=e.length,4===(i=this._scanner.read())||(this._error="expected close bracket",!1);return this._error="failed to find matching tag",!1}var r={name:n,value:null,attributes:{},start:e.length,end:null};if(5===(i=this._scanner.read())){if(6!==(i=this._scanner.read()))return this._error="expected string",!1;r.value=this._scanner.buf().join(""),i=this._scanner.read()}for(;;){switch(i){case 4:return t.push(r),!0;case 7:var a=this._scanner.buf().join("");if(5!==(i=this._scanner.read()))return this._error="expected equals",!1;if(6!==(i=this._scanner.read()))return this._error="expected string",!1;var o=this._scanner.buf().join("");r.attributes[a]=o;break;default:return this._error="expected close bracket or identifier",!1}i=this._scanner.read()}},e}();function Eg(e,t){for(var i in t)if(t.hasOwnProperty(i)){var n=t[i];n instanceof Object?(e.hasOwnProperty(i)||(e[i]={}),Eg(e[i],t[i])):e[i]=n}}function Pg(e){if(0===e.length)return null;for(var t={},i=0;i<e.length;++i){var n=e[i],s={};s[n.name]={value:n.value,attributes:n.attributes},Eg(t,s)}return t}function Rg(e){var t=new Cg(e),i=[],n=[];if(!t.parse(i,n))return console.warn(t.error()),{symbols:e,tags:null};var s=n.find((function(e){return null===e.end}));if(s)return console.warn("Markup error: found unclosed tag='"+s.name+"'"),{symbols:e,tags:null};var r=function(e,t){if(0===e.length)return null;for(var i={},n=0;n<e.length;++n){var s=e[n];i.hasOwnProperty(s.start)?null===i[s.start].open?i[s.start].open=[s]:i[s.start].open.push(s):i[s.start]={open:[s],close:null},i.hasOwnProperty(s.end)?null===i[s.end].close?i[s.end].close=[s]:i[s.end].close.push(s):i[s.end]={open:null,close:[s]}}var r=[];function a(e){r=r.filter((function(t){return void 0===e.find((function(e){return e===t}))}))}function o(e){for(var t=0;t<e.length;++t)r.push(e[t])}for(var h=Object.keys(i).sort((function(e,t){return e-t})),l=[],c=0;c<h.length;++c){var u=i[h[c]];null!==u.close&&a(u.close),null!==u.open&&o(u.open),l.push({start:h[c],tags:Pg(r)})}for(var d=[],f=null,p=0;p<l.length;++p){for(var m=l[p];d.length<m.start;)d.push(f?f.tags:null);f=m}for(;d.length<t;)d.push(null);return d}(n,i.length);return{symbols:i,tags:r}}var Ig=function(){function e(){}return e.evaluate=function(e){return Rg(e)},e}(),Lg=function(){this.count=0,this.quad=0,this.lines={},this.positions=[],this.normals=[],this.uvs=[],this.colors=[],this.indices=[],this.outlines=[],this.shadows=[],this.meshInstance=null};function Dg(e,t){var i=new ea(e);return i.setPositions(t.positions),i.setNormals(t.normals),i.setColors32(t.colors),i.setUvs(0,t.uvs),i.setIndices(t.indices),i.setVertexStream(Gt,t.outlines,3,void 0,6,!1),i.setVertexStream(Wt,t.shadows,3,void 0,6,!1),i.update(),i}var kg=/^[\r\n]$/,Og=/^[ \t]$/,Fg=/^[ \t\-]|[\u200b]$/,Bg=/^[a-z0-9]$/i,Ng=/^[\u1100-\u11ff]|[\u3000-\u9fff]|[\ua960-\ua97f]|[\uac00-\ud7ff]$/,Ug=/^[〕〉》」』】〙〗〟ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻]$/,zg=["","؜","","","","","","","","","","",""],Vg={width:0,height:0,xadvance:0,xoffset:0,yoffset:0},Gg=new me,Wg=new be,Hg=function(){function e(e){this._element=e,this._system=e.system,this._entity=e.entity,this._text="",this._symbols=[],this._colorPalette=[],this._outlinePalette=[],this._shadowPalette=[],this._symbolColors=null,this._symbolOutlineParams=null,this._symbolShadowParams=null,this._i18nKey=null,this._fontAsset=new Qp(this._system.app),this._fontAsset.disableLocalization=!0,this._fontAsset.on("load",this._onFontLoad,this),this._fontAsset.on("change",this._onFontChange,this),this._fontAsset.on("remove",this._onFontRemove,this),this._font=null,this._color=new me(1,1,1,1),this._colorUniform=new Float32Array(3),this._spacing=1,this._fontSize=32,this._fontMinY=0,this._fontMaxY=0,this._originalFontSize=32,this._maxFontSize=32,this._minFontSize=8,this._autoFitWidth=!1,this._autoFitHeight=!1,this._maxLines=-1,this._lineHeight=32,this._scaledLineHeight=32,this._wrapLines=!1,this._drawOrder=0,this._alignment=new be(.5,.5),this._autoWidth=!0,this._autoHeight=!0,this.width=0,this.height=0,this._node=new Hn,this._model=new hc,this._model.graph=this._node,this._entity.addChild(this._node),this._meshInfo=[],this._material=null,this._aabbDirty=!0,this._aabb=new Oe,this._noResize=!1,this._currentMaterialType=null,this._maskedMaterialSrc=null,this._rtlReorder=!1,this._unicodeConverter=!1,this._rtl=!1,this._outlineColor=new me(0,0,0,1),this._outlineColorUniform=new Float32Array(4),this._outlineThicknessScale=.2,this._outlineThickness=0,this._shadowColor=new me(0,0,0,1),this._shadowColorUniform=new Float32Array(4),this._shadowOffsetScale=.005,this._shadowOffset=new be(0,0),this._shadowOffsetUniform=new Float32Array(2),this._enableMarkup=!1,this._onScreenChange(this._element.screen),e.on("resize",this._onParentResize,this),e.on("set:screen",this._onScreenChange,this),e.on("screen:set:screenspace",this._onScreenSpaceChange,this),e.on("set:draworder",this._onDrawOrderChange,this),e.on("set:pivot",this._onPivotChange,this),this._system.app.i18n.on("set:locale",this._onLocaleSet,this),this._system.app.i18n.on("data:add",this._onLocalizationData,this),this._system.app.i18n.on("data:remove",this._onLocalizationData,this),this._rangeStart=0,this._rangeEnd=0}var t=e.prototype;return t.destroy=function(){this._setMaterial(null),this._model&&(this._element.removeModelFromLayers(this._model),this._model.destroy(),this._model=null),this._fontAsset.destroy(),this.font=null,this._element.off("resize",this._onParentResize,this),this._element.off("set:screen",this._onScreenChange,this),this._element.off("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.off("set:draworder",this._onDrawOrderChange,this),this._element.off("set:pivot",this._onPivotChange,this),this._system.app.i18n.off("set:locale",this._onLocaleSet,this),this._system.app.i18n.off("data:add",this._onLocalizationData,this),this._system.app.i18n.off("data:remove",this._onLocalizationData,this)},t._onParentResize=function(e,t){this._noResize||this._font&&this._updateText()},t._onScreenChange=function(e){e?this._updateMaterial(e.screen.screenSpace):this._updateMaterial(!1)},t._onScreenSpaceChange=function(e){this._updateMaterial(e)},t._onDrawOrderChange=function(e){if(this._drawOrder=e,this._model)for(var t=0,i=this._model.meshInstances.length;t<i;t++)this._model.meshInstances[t].drawOrder=e},t._onPivotChange=function(e){this._font&&this._updateText()},t._onLocaleSet=function(e){if(this._i18nKey){if(this.fontAsset){var t=this._system.app.assets.get(this.fontAsset);t&&t.resource&&t.resource===this._font||(this.font=null)}this._resetLocalizedText()}},t._onLocalizationData=function(e,t){this._i18nKey&&t[this._i18nKey]&&this._resetLocalizedText()},t._resetLocalizedText=function(){this._setText(this._system.app.i18n.getText(this._i18nKey))},t._setText=function(e){if(this.unicodeConverter){var t=this._system.getUnicodeConverter();t?e=t(e):console.warn("Element created with unicodeConverter option but no unicodeConverter function registered")}this._text!==e&&(this._font&&this._updateText(e),this._text=e)},t._updateText=function(e){var t;if(void 0===e&&(e=this._text),this._symbols=q.getSymbols(e.normalize?e.normalize("NFC"):e),0===this._symbols.length&&(this._symbols=[" "]),this._enableMarkup){var i=Ig.evaluate(this._symbols);this._symbols=i.symbols,t=i.tags||[]}if(this._rtlReorder){var n=this._system.app.systems.element.getRtlReorder();if(n){var s=n(this._symbols);this._rtl=s.rtl,this._symbols=s.mapping.map((function(e){return this._symbols[e]}),this),t&&(t=s.mapping.map((function(e){return t[e]})))}else console.warn("Element created with rtlReorder option but no rtlReorder function registered")}else this._rtl=!1;var r=function(e,t){return e.toString(!0).toLowerCase()+":"+t.toFixed(2)},a=function(e,t){return e.toString(!0).toLowerCase()+":"+t.x.toFixed(2)+":"+t.y.toFixed(2)};if(t){var o={},h={},l={};this._colorPalette=[Math.round(255*this._color.r),Math.round(255*this._color.g),Math.round(255*this._color.b)],this._outlinePalette=[Math.round(255*this._outlineColor.r),Math.round(255*this._outlineColor.g),Math.round(255*this._outlineColor.b),Math.round(255*this._outlineColor.a),Math.round(255*this._outlineThickness)],this._shadowPalette=[Math.round(255*this._shadowColor.r),Math.round(255*this._shadowColor.g),Math.round(255*this._shadowColor.b),Math.round(255*this._shadowColor.a),Math.round(127*this._shadowOffset.x),Math.round(127*this._shadowOffset.y)],this._symbolColors=[],this._symbolOutlineParams=[],this._symbolShadowParams=[],o[this._color.toString(!1).toLowerCase()]=0,h[r(this._outlineColor,this._outlineThickness)]=0,l[a(this._shadowColor,this._shadowOffset)]=0;for(var c=0,u=this._symbols.length;c<u;++c){var d=t[c],f=0;if(d&&d.color&&d.color.value){var p=d.color.value;if(7===p.length&&"#"===p[0]){var m=p.substring(1).toLowerCase();o.hasOwnProperty(m)?f=o[m]:/^([0-9a-f]{2}){3}$/.test(m)&&(f=this._colorPalette.length/3,o[m]=f,this._colorPalette.push(parseInt(m.substring(0,2),16)),this._colorPalette.push(parseInt(m.substring(2,4),16)),this._colorPalette.push(parseInt(m.substring(4,6),16)))}}this._symbolColors.push(f);var _=0;if(d&&d.outline&&(d.outline.attributes.color||d.outline.attributes.thickness)){var g=d.outline.attributes.color?Gg.fromString(d.outline.attributes.color):this._outlineColor,v=Number(d.outline.attributes.thickness);(Number.isNaN(g.r)||Number.isNaN(g.g)||Number.isNaN(g.b)||Number.isNaN(g.a))&&(g=this._outlineColor),Number.isNaN(v)&&(v=this._outlineThickness);var y=r(g,v);h.hasOwnProperty(y)?_=h[y]:(_=this._outlinePalette.length/5,h[y]=_,this._outlinePalette.push(Math.round(255*g.r),Math.round(255*g.g),Math.round(255*g.b),Math.round(255*g.a),Math.round(255*v)))}this._symbolOutlineParams.push(_);var x=0;if(d&&d.shadow&&(d.shadow.attributes.color||d.shadow.attributes.offset||d.shadow.attributes.offsetX||d.shadow.attributes.offsetY)){var b=d.shadow.attributes.color?Gg.fromString(d.shadow.attributes.color):this._shadowColor,S=Number(d.shadow.attributes.offset),w=Number(d.shadow.attributes.offsetX),T=Number(d.shadow.attributes.offsetY);(Number.isNaN(b.r)||Number.isNaN(b.g)||Number.isNaN(b.b)||Number.isNaN(b.a))&&(b=this._shadowColor);var A=Wg.set(Number.isNaN(w)?Number.isNaN(S)?this._shadowOffset.x:S:w,Number.isNaN(T)?Number.isNaN(S)?this._shadowOffset.y:S:T),M=a(b,A);l.hasOwnProperty(M)?x=l[M]:(x=this._shadowPalette.length/6,l[M]=x,this._shadowPalette.push(Math.round(255*b.r),Math.round(255*b.g),Math.round(255*b.b),Math.round(255*b.a),Math.round(127*A.x),Math.round(127*A.y)))}this._symbolShadowParams.push(x)}}else this._colorPalette=[],this._symbolColors=null,this._symbolOutlineParams=null,this._symbolShadowParams=null;this._updateMaterialEmissive(),this._updateMaterialOutline(),this._updateMaterialShadow();for(var C=this._calculateCharsPerTexture(),E=!1,P=this._element,R=P._isScreenSpace(),I=P._isScreenCulled(),L=function(e){return P.isVisibleForCamera(e)},D=0,k=this._meshInfo.length;D<k;D++){var O=C[D]||0,F=this._meshInfo[D];if(F.count!==O){if(E||(P.removeModelFromLayers(this._model),E=!0),F.count=O,F.positions.length=F.normals.length=3*O*4,F.indices.length=3*O*2,F.uvs.length=2*O*4,F.colors.length=4*O*4,F.outlines.length=4*O*3,F.shadows.length=4*O*3,F.meshInstance&&this._removeMeshInstance(F.meshInstance),0===O){F.meshInstance=null;continue}for(var B=0;B<O;B++)F.indices[3*B*2+0]=4*B,F.indices[3*B*2+1]=4*B+1,F.indices[3*B*2+2]=4*B+3,F.indices[3*B*2+3]=4*B+2,F.indices[3*B*2+4]=4*B+3,F.indices[3*B*2+5]=4*B+1,F.normals[4*B*3+0]=0,F.normals[4*B*3+1]=0,F.normals[4*B*3+2]=-1,F.normals[4*B*3+3]=0,F.normals[4*B*3+4]=0,F.normals[4*B*3+5]=-1,F.normals[4*B*3+6]=0,F.normals[4*B*3+7]=0,F.normals[4*B*3+8]=-1,F.normals[4*B*3+9]=0,F.normals[4*B*3+10]=0,F.normals[4*B*3+11]=-1;var N=Dg(this._system.app.graphicsDevice,F),U=new ka(N,this._material,this._node);if(U.name="Text Element: "+this._entity.name,U.castShadow=!1,U.receiveShadow=!1,U.cull=!R,U.screenSpace=R,U.drawOrder=this._drawOrder,I&&(U.cull=!0,U.isVisibleFunc=L),this._setTextureParams(U,this._font.textures[D]),U.setParameter("material_emissive",this._colorUniform),U.setParameter("material_opacity",this._color.a),U.setParameter("font_sdfIntensity",this._font.intensity),U.setParameter("font_pxrange",this._getPxRange(this._font)),U.setParameter("font_textureWidth",this._font.data.info.maps[D].width),U.setParameter("outline_color",this._outlineColorUniform),U.setParameter("outline_thickness",this._outlineThicknessScale*this._outlineThickness),U.setParameter("shadow_color",this._shadowColorUniform),this._symbolShadowParams)this._shadowOffsetUniform[0]=0,this._shadowOffsetUniform[1]=0;else{var z=-this._font.data.info.maps[D].width/this._font.data.info.maps[D].height;this._shadowOffsetUniform[0]=this._shadowOffsetScale*this._shadowOffset.x,this._shadowOffsetUniform[1]=z*this._shadowOffsetScale*this._shadowOffset.y}U.setParameter("shadow_offset",this._shadowOffsetUniform),F.meshInstance=U,this._model.meshInstances.push(U)}}this._element.maskedBy&&this._element._setMaskedBy(this._element.maskedBy),E&&this._element.enabled&&this._entity.enabled&&this._element.addModelToLayers(this._model),this._updateMeshes(),this._rangeStart=0,this._rangeEnd=this._symbols.length,this._updateRenderRange()},t._removeMeshInstance=function(e){e.destroy();var t=this._model.meshInstances.indexOf(e);-1!==t&&this._model.meshInstances.splice(t,1)},t._setMaterial=function(e){if(this._material=e,this._model)for(var t=0,i=this._model.meshInstances.length;t<i;t++){this._model.meshInstances[t].material=e}},t._updateMaterial=function(e){var t=this._element,i=t._isScreenCulled(),n=function(e){return t.isVisibleForCamera(e)},s=this._font&&this._font.type===ud;if(this._material=this._system.getTextElementMaterial(e,s,this._enableMarkup),this._model)for(var r=0,a=this._model.meshInstances.length;r<a;r++){var o=this._model.meshInstances[r];o.cull=!e,o.material=this._material,o.screenSpace=e,i?(o.cull=!0,o.isVisibleFunc=n):o.isVisibleFunc=null}},t._updateMaterialEmissive=function(){this._symbolColors?(this._colorUniform[0]=1,this._colorUniform[1]=1,this._colorUniform[2]=1):(this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b)},t._updateMaterialOutline=function(){this._symbolOutlineParams?(this._outlineColorUniform[0]=0,this._outlineColorUniform[1]=0,this._outlineColorUniform[2]=0,this._outlineColorUniform[3]=1):(this._outlineColorUniform[0]=this._outlineColor.r,this._outlineColorUniform[1]=this._outlineColor.g,this._outlineColorUniform[2]=this._outlineColor.b,this._outlineColorUniform[3]=this._outlineColor.a)},t._updateMaterialShadow=function(){this._symbolOutlineParams?(this._shadowColorUniform[0]=0,this._shadowColorUniform[1]=0,this._shadowColorUniform[2]=0,this._shadowColorUniform[3]=0):(this._shadowColorUniform[0]=this._shadowColor.r,this._shadowColorUniform[1]=this._shadowColor.g,this._shadowColorUniform[2]=this._shadowColor.b,this._shadowColorUniform[3]=this._shadowColor.a)},t._isWordBoundary=function(e){return Fg.test(e)},t._isValidNextChar=function(e){return null!==e&&!Ug.test(e)},t._isNextCJKBoundary=function(e,t){return Ng.test(e)&&(Fg.test(t)||Bg.test(t))},t._isNextCJKWholeWord=function(e){return Ng.test(e)},t._updateMeshes=function(){var e=this._font.data,t=this,i=Math.min(this._minFontSize,this._maxFontSize),n=this._maxFontSize,s=this._shouldAutoFit();s&&(this._fontSize=this._maxFontSize);var r=this._symbols.length,a=0,o=0,h=0,l=0,c=1,u=0,d=0,f=0,p=0,m=0,_=0,g=Math.abs(this._element.anchor.x-this._element.anchor.z)>=1e-4,v=this._element.calculatedWidth;(this.autoWidth&&!g||!this._wrapLines)&&(v=Number.POSITIVE_INFINITY);var y,x,b,S,w=0,T=0;function A(e,i,n){t._lineWidths.push(Math.abs(n));var s=f>i?i+1:f,r=f>i?f+1:i,h=e.slice(s,r);if(_)for(var l=h.length;l--&&_>0;)kg.test(h[l])&&(h.splice(l,1),_--);t._lineContents.push(h.join("")),a=0,o-=t._scaledLineHeight,c++,p=0,m=0,_=0,u=0,f=i}for(var M=!0;M;){M=!1,this._scaledLineHeight=s?this._lineHeight*this._fontSize/(this._maxFontSize||1e-4):this._lineHeight,this.width=0,this.height=0,this._lineWidths=[],this._lineContents=[],a=0,o=0,h=0,l=0,c=1,u=0,d=0,f=0,p=0,m=0,_=0;var C=this._fontSize/32;w=this._fontMinY*C,T=this._fontMaxY*C;for(var E=0;E<this._meshInfo.length;E++)this._meshInfo[E].quad=0,this._meshInfo[E].lines={};for(var P=255,R=255,I=255,L=65535,D=65535,k=0,O=65535,F=65535,B=32639,N=0;N<r;N++){if(y=this._symbols[N],S=N+1>=r?null:this._symbols[N+1],kg.test(y))_++,(!this._wrapLines||this._maxLines<0||c<this._maxLines)&&(A(this._symbols,N,l),d=N+1,f=N+1);else{var U=0,z=0,V=0,G=1,W=void 0;if(!(x=e.chars[y]))if(-1!==zg.indexOf(y))x=Vg;else if(e.chars[" "])x=e.chars[" "];else for(var H in e.chars){x=e.chars[H];break}if(x){var X=0;if(m>0){var j=this._font.data.kerning;if(j){var Y=j[q.getCodePoint(this._symbols[N-1])||0];Y&&(X=Y[q.getCodePoint(this._symbols[N])||0]||0)}}W=x.scale||1,G=C*((x.width+x.height)/2)/W,V=(x.xadvance+X)*C,U=(x.xoffset-X)*C,z=x.yoffset*C}else console.error("Couldn't substitute missing character: '"+y+"'");var K=Og.test(y),Z=x&&x.map||0,$=-this._font.data.info.maps[Z].width/this._font.data.info.maps[Z].height,Q=this._meshInfo[Z],J=a+this._spacing*V;if(J>v&&m>0&&!K&&(this._maxLines<0||c<this._maxLines)){if(0!==p){var ee=Math.max(N-d,0);if(this._meshInfo.length<=1)Q.lines[c-1]-=ee,Q.quad-=ee;else for(var te=N,ie=d;ie<te;ie++){var ne=this._symbols[ie],se=e.chars[ne],re=this._meshInfo[se&&se.map||0];re.lines[c-1]-=1,re.quad-=1}N-=ee+1,A(this._symbols,d,u);continue}d=N,A(this._symbols,N,l)}b=Q.quad,Q.lines[c-1]=b;var ae=a-U,oe=ae+G,he=o-z,le=he+G;if(this._rtl){var ce=G-U-this._spacing*V-U;ae-=ce,oe-=ce}Q.positions[4*b*3+0]=ae,Q.positions[4*b*3+1]=he,Q.positions[4*b*3+2]=h,Q.positions[4*b*3+3]=oe,Q.positions[4*b*3+4]=he,Q.positions[4*b*3+5]=h,Q.positions[4*b*3+6]=oe,Q.positions[4*b*3+7]=le,Q.positions[4*b*3+8]=h,Q.positions[4*b*3+9]=ae,Q.positions[4*b*3+10]=le,Q.positions[4*b*3+11]=h,this.width=Math.max(this.width,J);var ue=void 0;if(this._shouldAutoFitWidth()&&this.width>this._element.calculatedWidth&&(ue=Math.floor(this._element.fontSize*this._element.calculatedWidth/(this.width||1e-4)),(ue=de.clamp(ue,i,n))!==this._element.fontSize)){this._fontSize=ue,M=!0;break}if(this.height=Math.max(this.height,T-(o+w)),this._shouldAutoFitHeight()&&this.height>this._element.calculatedHeight&&(ue=de.clamp(this._fontSize-1,i,n))!==this._element.fontSize){this._fontSize=ue,M=!0;break}a+=this._spacing*V,K||(l=a),(this._isWordBoundary(y)||this._isValidNextChar(S)&&(this._isNextCJKBoundary(y,S)||this._isNextCJKWholeWord(S)))&&(p++,u=l,d=N+1),m++;var fe=this._getUv(y);if(Q.uvs[4*b*2+0]=fe[0],Q.uvs[4*b*2+1]=1-fe[1],Q.uvs[4*b*2+2]=fe[2],Q.uvs[4*b*2+3]=1-fe[1],Q.uvs[4*b*2+4]=fe[2],Q.uvs[4*b*2+5]=1-fe[3],Q.uvs[4*b*2+6]=fe[0],Q.uvs[4*b*2+7]=1-fe[3],this._symbolColors){var pe=3*this._symbolColors[N];P=this._colorPalette[pe],R=this._colorPalette[pe+1],I=this._colorPalette[pe+2]}if(Q.colors[4*b*4+0]=P,Q.colors[4*b*4+1]=R,Q.colors[4*b*4+2]=I,Q.colors[4*b*4+3]=255,Q.colors[4*b*4+4]=P,Q.colors[4*b*4+5]=R,Q.colors[4*b*4+6]=I,Q.colors[4*b*4+7]=255,Q.colors[4*b*4+8]=P,Q.colors[4*b*4+9]=R,Q.colors[4*b*4+10]=I,Q.colors[4*b*4+11]=255,Q.colors[4*b*4+12]=P,Q.colors[4*b*4+13]=R,Q.colors[4*b*4+14]=I,Q.colors[4*b*4+15]=255,this._symbolOutlineParams){var me=5*this._symbolOutlineParams[N];L=this._outlinePalette[me]+256*this._outlinePalette[me+1],D=this._outlinePalette[me+2]+256*this._outlinePalette[me+3],k=this._outlinePalette[me+4]}if(Q.outlines[4*b*3+0]=L,Q.outlines[4*b*3+1]=D,Q.outlines[4*b*3+2]=k,Q.outlines[4*b*3+3]=L,Q.outlines[4*b*3+4]=D,Q.outlines[4*b*3+5]=k,Q.outlines[4*b*3+6]=L,Q.outlines[4*b*3+7]=D,Q.outlines[4*b*3+8]=k,Q.outlines[4*b*3+9]=L,Q.outlines[4*b*3+10]=D,Q.outlines[4*b*3+11]=k,this._symbolShadowParams){var _e=6*this._symbolShadowParams[N];O=this._shadowPalette[_e]+256*this._shadowPalette[_e+1],F=this._shadowPalette[_e+2]+256*this._shadowPalette[_e+3],B=this._shadowPalette[_e+4]+127+256*Math.round($*this._shadowPalette[_e+5]+127)}Q.shadows[4*b*3+0]=O,Q.shadows[4*b*3+1]=F,Q.shadows[4*b*3+2]=B,Q.shadows[4*b*3+3]=O,Q.shadows[4*b*3+4]=F,Q.shadows[4*b*3+5]=B,Q.shadows[4*b*3+6]=O,Q.shadows[4*b*3+7]=F,Q.shadows[4*b*3+8]=B,Q.shadows[4*b*3+9]=O,Q.shadows[4*b*3+10]=F,Q.shadows[4*b*3+11]=B,Q.quad++}}M||f<r&&A(this._symbols,r,a)}this._noResize=!0,this.autoWidth=this._autoWidth,this.autoHeight=this._autoHeight,this._noResize=!1;for(var ge=this._element.pivot.x,ve=this._element.pivot.y,ye=this._alignment.x,xe=this._alignment.y,be=0;be<this._meshInfo.length;be++)if(0!==this._meshInfo[be].count){var Se=0;for(var we in this._meshInfo[be].lines){for(var Te=this._meshInfo[be].lines[we],Ae=this._lineWidths[parseInt(we,10)],Me=-ge*this._element.calculatedWidth+ye*(this._element.calculatedWidth-Ae)*(this._rtl?-1:1),Ce=(1-ve)*this._element.calculatedHeight-T-(1-xe)*(this._element.calculatedHeight-this.height),Ee=Se;Ee<=Te;Ee++)this._meshInfo[be].positions[4*Ee*3]+=Me,this._meshInfo[be].positions[4*Ee*3+3]+=Me,this._meshInfo[be].positions[4*Ee*3+6]+=Me,this._meshInfo[be].positions[4*Ee*3+9]+=Me,this._meshInfo[be].positions[4*Ee*3+1]+=Ce,this._meshInfo[be].positions[4*Ee*3+4]+=Ce,this._meshInfo[be].positions[4*Ee*3+7]+=Ce,this._meshInfo[be].positions[4*Ee*3+10]+=Ce;if(this._rtl)for(var Pe=Se;Pe<=Te;Pe++){for(var Re=4*Pe*3,Ie=0;Ie<4;++Ie)this._meshInfo[be].positions[Re+3*Ie]=this._element.calculatedWidth-this._meshInfo[be].positions[Re+3*Ie]+2*Me;var Le=this._meshInfo[be].positions[Re+3],De=this._meshInfo[be].positions[Re+6];this._meshInfo[be].positions[Re+3]=this._meshInfo[be].positions[Re+0],this._meshInfo[be].positions[Re+6]=this._meshInfo[be].positions[Re+9],this._meshInfo[be].positions[Re+0]=Le,this._meshInfo[be].positions[Re+9]=De}Se=Te+1}for(var ke=4*this._meshInfo[be].count,Oe=4*this._meshInfo[be].quad,Fe=new Pr(this._meshInfo[be].meshInstance.mesh.vertexBuffer),Be=0;Be<ke;Be++)Be>=Oe?(Fe.element.POSITION.set(0,0,0),Fe.element.TEXCOORD0.set(0,0),Fe.element.COLOR.set(0,0,0,0),Fe.element.ATTR8.set(0,0,0,0),Fe.element.ATTR9.set(0,0,0,0)):(Fe.element.POSITION.set(this._meshInfo[be].positions[3*Be+0],this._meshInfo[be].positions[3*Be+1],this._meshInfo[be].positions[3*Be+2]),Fe.element.TEXCOORD0.set(this._meshInfo[be].uvs[2*Be+0],this._meshInfo[be].uvs[2*Be+1]),Fe.element.COLOR.set(this._meshInfo[be].colors[4*Be+0],this._meshInfo[be].colors[4*Be+1],this._meshInfo[be].colors[4*Be+2],this._meshInfo[be].colors[4*Be+3]),Fe.element.ATTR8.set(this._meshInfo[be].outlines[3*Be+0],this._meshInfo[be].outlines[3*Be+1],this._meshInfo[be].outlines[3*Be+2]),Fe.element.ATTR9.set(this._meshInfo[be].shadows[3*Be+0],this._meshInfo[be].shadows[3*Be+1],this._meshInfo[be].shadows[3*Be+2])),Fe.next();Fe.end(),this._meshInfo[be].meshInstance.mesh.aabb.compute(this._meshInfo[be].positions),this._meshInfo[be].meshInstance._aabbVer=-1}this._aabbDirty=!0},t._onFontRender=function(){this.font=this._font},t._onFontLoad=function(e){this.font!==e.resource&&(this.font=e.resource)},t._onFontChange=function(e,t,i,n){if("data"===t){this._font.data=i;for(var s=this._font.data.info.maps.length,r=0;r<s;r++)if(this._meshInfo[r]){var a=this._meshInfo[r].meshInstance;a&&(a.setParameter("font_sdfIntensity",this._font.intensity),a.setParameter("font_pxrange",this._getPxRange(this._font)),a.setParameter("font_textureWidth",this._font.data.info.maps[r].width))}}},t._onFontRemove=function(e){},t._setTextureParams=function(e,t){this._font&&(this._font.type===ud?(e.deleteParameter("texture_emissiveMap"),e.deleteParameter("texture_opacityMap"),e.setParameter("texture_msdfMap",t)):this._font.type===dd&&(e.deleteParameter("texture_msdfMap"),e.setParameter("texture_emissiveMap",t),e.setParameter("texture_opacityMap",t)))},t._getPxRange=function(e){for(var t=Object.keys(this._font.data.chars),i=0;i<t.length;i++){var n=this._font.data.chars[t[i]];if(n.range)return(n.scale||1)*n.range}return 2},t._getUv=function(e){var t=this._font.data;if(!t.chars[e]){return t.chars[" "]?this._getUv(" "):[0,0,0,0]}var i=t.chars[e].map,n=t.info.maps[i].width,s=t.info.maps[i].height,r=t.chars[e].x,a=t.chars[e].y,o=r,h=a,l=r+t.chars[e].width,c=a-t.chars[e].height,u=1-t.chars[e].height/s;return[o/n,u-h/s,l/n,u-c/s]},t.onEnable=function(){this._fontAsset.autoLoad=!0,this._model&&this._element.addModelToLayers(this._model)},t.onDisable=function(){this._fontAsset.autoLoad=!1,this._model&&this._element.removeModelFromLayers(this._model)},t._setStencil=function(e){if(this._model)for(var t=this._model.meshInstances,i=0;i<t.length;i++)t[i].stencilFront=e,t[i].stencilBack=e},t._shouldAutoFitWidth=function(){return this._autoFitWidth&&!this._autoWidth},t._shouldAutoFitHeight=function(){return this._autoFitHeight&&!this._autoHeight},t._shouldAutoFit=function(){return this._autoFitWidth&&!this._autoWidth||this._autoFitHeight&&!this._autoHeight},t._calculateCharsPerTexture=function(e){var t={};void 0===e&&(e=this._symbols.length);for(var i=0,n=e;i<n;i++){var s=this._symbols[i],r=this._font.data.chars[s];r||(r=this._font.data.chars[" "])||(r=this._font.data.chars[Object.keys(this._font.data.chars)[0]]);var a=r.map;t[a]?t[a]++:t[a]=1}return t},t._updateRenderRange=function(){for(var e=0===this._rangeStart?0:this._calculateCharsPerTexture(this._rangeStart),t=0===this._rangeEnd?0:this._calculateCharsPerTexture(this._rangeEnd),i=0,n=this._meshInfo.length;i<n;i++){var s=e[i]||0,r=t[i]||0,a=this._meshInfo[i].meshInstance;if(a){var o=a.mesh;o&&(o.primitive[0].base=3*s*2,o.primitive[0].count=3*(r-s)*2)}}},$(e,[{key:"text",get:function(){return this._text},set:function(e){this._i18nKey=null;var t=null!=e&&e.toString()||"";this._setText(t)}},{key:"key",get:function(){return this._i18nKey},set:function(e){var t=null!==e?e.toString():null;this._i18nKey!==t&&(this._i18nKey=t,t?(this._fontAsset.disableLocalization=!1,this._resetLocalizedText()):this._fontAsset.disableLocalization=!0)}},{key:"color",get:function(){return this._color},set:function(e){var t=e.r,i=e.g,n=e.b;if((this._color.r!==t||this._color.g!==i||this._color.b!==n)&&(this._color.r=t,this._color.g=i,this._color.b=n,this._model)){if(this._symbolColors)this._font&&this._updateText();else{this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b;for(var s=0,r=this._model.meshInstances.length;s<r;s++){this._model.meshInstances[s].setParameter("material_emissive",this._colorUniform)}}this._element&&this._element.fire("set:color",this._color)}}},{key:"opacity",get:function(){return this._color.a},set:function(e){if(this._color.a!==e&&(this._color.a=e,this._model))for(var t=0,i=this._model.meshInstances.length;t<i;t++){this._model.meshInstances[t].setParameter("material_opacity",e)}this._element&&this._element.fire("set:opacity",e)}},{key:"lineHeight",get:function(){return this._lineHeight},set:function(e){var t=this._lineHeight;this._lineHeight=e,this._scaledLineHeight=e,t!==e&&this._font&&this._updateText()}},{key:"wrapLines",get:function(){return this._wrapLines},set:function(e){var t=this._wrapLines;this._wrapLines=e,t!==e&&this._font&&this._updateText()}},{key:"lines",get:function(){return this._lineContents}},{key:"spacing",get:function(){return this._spacing},set:function(e){var t=this._spacing;this._spacing=e,t!==e&&this._font&&this._updateText()}},{key:"fontSize",get:function(){return this._fontSize},set:function(e){var t=this._fontSize;this._fontSize=e,this._originalFontSize=e,t!==e&&this._font&&this._updateText()}},{key:"fontAsset",get:function(){return this._fontAsset.localizedAsset},set:function(e){this._fontAsset.defaultAsset=e}},{key:"font",get:function(){return this._font},set:function(e){var t;if(this._font&&(t=this._font.type,this._font.off&&this._font.off("render",this._onFontRender,this)),this._font=e,this._fontMinY=0,this._fontMaxY=0,e){var i=this._font.data;for(var n in i.chars){var s=i.chars[n];s.bounds&&(this._fontMinY=Math.min(this._fontMinY,s.bounds[1]),this._fontMaxY=Math.max(this._fontMaxY,s.bounds[3]))}if(this._font.on&&this._font.on("render",this._onFontRender,this),this._fontAsset.localizedAsset)this._system.app.assets.get(this._fontAsset.localizedAsset).resource!==this._font&&(this._fontAsset.defaultAsset=null);if(e.type!==t){var r=this._element._isScreenSpace();this._updateMaterial(r)}for(var a=0,o=this._font.textures.length;a<o;a++)if(this._meshInfo[a]){var h=this._meshInfo[a].meshInstance;h&&(h.setParameter("font_sdfIntensity",this._font.intensity),h.setParameter("font_pxrange",this._getPxRange(this._font)),h.setParameter("font_textureWidth",this._font.data.info.maps[a].width),this._setTextureParams(h,this._font.textures[a]))}else this._meshInfo[a]=new Lg;for(var l=!1,c=this._font.textures.length;c<this._meshInfo.length;c++)this._meshInfo[c].meshInstance&&(l||(this._element.removeModelFromLayers(this._model),l=!0),this._removeMeshInstance(this._meshInfo[c].meshInstance));this._meshInfo.length>this._font.textures.length&&(this._meshInfo.length=this._font.textures.length),this._updateText()}}},{key:"alignment",get:function(){return this._alignment},set:function(e){e instanceof be?this._alignment.set(e.x,e.y):this._alignment.set(e[0],e[1]),this._font&&this._updateText()}},{key:"autoWidth",get:function(){return this._autoWidth},set:function(e){var t=this._autoWidth;if(this._autoWidth=e,e&&Math.abs(this._element.anchor.x-this._element.anchor.z)<1e-4&&(this._element.width=this.width),t!==e){var i=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;i!==this._fontSize&&(this._fontSize=i,this._font&&this._updateText())}}},{key:"autoHeight",get:function(){return this._autoHeight},set:function(e){var t=this._autoHeight;if(this._autoHeight=e,e&&Math.abs(this._element.anchor.y-this._element.anchor.w)<1e-4&&(this._element.height=this.height),t!==e){var i=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;i!==this._fontSize&&(this._fontSize=i,this._font&&this._updateText())}}},{key:"rtlReorder",get:function(){return this._rtlReorder},set:function(e){this._rtlReorder!==e&&(this._rtlReorder=e,this._font&&this._updateText())}},{key:"unicodeConverter",get:function(){return this._unicodeConverter},set:function(e){this._unicodeConverter!==e&&(this._unicodeConverter=e,this._setText(this._text))}},{key:"aabb",get:function(){if(this._aabbDirty){for(var e=!1,t=0;t<this._meshInfo.length;t++)this._meshInfo[t].meshInstance&&(e?this._aabb.add(this._meshInfo[t].meshInstance.aabb):(this._aabb.copy(this._meshInfo[t].meshInstance.aabb),e=!0));this._aabbDirty=!1}return this._aabb}},{key:"outlineColor",get:function(){return this._outlineColor},set:function(e){var t=e instanceof me?e.r:e[0],i=e instanceof me?e.g:e[1],n=e instanceof me?e.b:e[2],s=e instanceof me?e.a:e[3];if((this._outlineColor.r!==t||this._outlineColor.g!==i||this._outlineColor.b!==n||this._outlineColor.a!==s)&&(this._outlineColor.r=t,this._outlineColor.g=i,this._outlineColor.b=n,this._outlineColor.a=s,this._model)){if(this._symbolOutlineParams)this._font&&this._updateText();else{this._outlineColorUniform[0]=this._outlineColor.r,this._outlineColorUniform[1]=this._outlineColor.g,this._outlineColorUniform[2]=this._outlineColor.b,this._outlineColorUniform[3]=this._outlineColor.a;for(var r=0,a=this._model.meshInstances.length;r<a;r++){this._model.meshInstances[r].setParameter("outline_color",this._outlineColorUniform)}}this._element&&this._element.fire("set:outline",this._color)}}},{key:"outlineThickness",get:function(){return this._outlineThickness},set:function(e){var t=this._outlineThickness;if(this._outlineThickness=e,t!==e&&this._font){if(!this._model)return;if(this._symbolOutlineParams)this._font&&this._updateText();else for(var i=0,n=this._model.meshInstances.length;i<n;i++){this._model.meshInstances[i].setParameter("outline_thickness",this._outlineThicknessScale*this._outlineThickness)}}}},{key:"shadowColor",get:function(){return this._shadowColor},set:function(e){var t=e instanceof me?e.r:e[0],i=e instanceof me?e.g:e[1],n=e instanceof me?e.b:e[2],s=e instanceof me?e.a:e[3];if((this._shadowColor.r!==t||this._shadowColor.g!==i||this._shadowColor.b!==n||this._shadowColor.a!==s)&&(this._shadowColor.r=t,this._shadowColor.g=i,this._shadowColor.b=n,this._shadowColor.a=s,this._model))if(this._symbolShadowParams)this._font&&this._updateText();else{this._shadowColorUniform[0]=this._shadowColor.r,this._shadowColorUniform[1]=this._shadowColor.g,this._shadowColorUniform[2]=this._shadowColor.b,this._shadowColorUniform[3]=this._shadowColor.a;for(var r=0,a=this._model.meshInstances.length;r<a;r++){this._model.meshInstances[r].setParameter("shadow_color",this._shadowColorUniform)}}}},{key:"shadowOffset",get:function(){return this._shadowOffset},set:function(e){var t=e instanceof be?e.x:e[0],i=e instanceof be?e.y:e[1];if((this._shadowOffset.x!==t||this._shadowOffset.y!==i)&&(this._shadowOffset.set(t,i),this._font&&this._model))if(this._symbolShadowParams)this._updateText();else for(var n=0,s=this._model.meshInstances.length;n<s;n++){var r=-this._font.data.info.maps[n].width/this._font.data.info.maps[n].height;this._shadowOffsetUniform[0]=this._shadowOffsetScale*this._shadowOffset.x,this._shadowOffsetUniform[1]=r*this._shadowOffsetScale*this._shadowOffset.y,this._model.meshInstances[n].setParameter("shadow_offset",this._shadowOffsetUniform)}}},{key:"minFontSize",get:function(){return this._minFontSize},set:function(e){this._minFontSize!==e&&(this._minFontSize=e,this.font&&this._shouldAutoFit()&&this._updateText())}},{key:"maxFontSize",get:function(){return this._maxFontSize},set:function(e){this._maxFontSize!==e&&(this._maxFontSize=e,this.font&&this._shouldAutoFit()&&this._updateText())}},{key:"autoFitWidth",get:function(){return this._autoFitWidth},set:function(e){this._autoFitWidth!==e&&(this._autoFitWidth=e,this._fontSize=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize,this.font&&this._updateText())}},{key:"autoFitHeight",get:function(){return this._autoFitHeight},set:function(e){this._autoFitHeight!==e&&(this._autoFitHeight=e,this._fontSize=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize,this.font&&this._updateText())}},{key:"maxLines",get:function(){return this._maxLines},set:function(e){this._maxLines!==e&&(null===e&&-1===this._maxLines||(this._maxLines=null===e?-1:e,this.font&&this._wrapLines&&this._updateText()))}},{key:"enableMarkup",get:function(){return this._enableMarkup},set:function(e){if(e=!!e,this._enableMarkup!==e){this._enableMarkup=e,this.font&&this._updateText();var t=this._element._isScreenSpace();this._updateMaterial(t)}}},{key:"symbols",get:function(){return this._symbols}},{key:"symbolColors",get:function(){return null===this._symbolColors?null:this._symbolColors.map((function(e){return this._colorPalette.slice(3*e,3*e+3)}),this)}},{key:"symbolOutlineParams",get:function(){return null===this._symbolOutlineParams?null:this._symbolOutlineParams.map((function(e){return this._outlinePalette.slice(5*e,5*e+5)}),this)}},{key:"symbolShadowParams",get:function(){return null===this._symbolShadowParams?null:this._symbolShadowParams.map((function(e){return this._shadowPalette.slice(6*e,6*e+6)}),this)}},{key:"rtl",get:function(){return this._rtl}},{key:"rangeStart",get:function(){return this._rangeStart},set:function(e){(e=Math.max(0,Math.min(e,this._symbols.length)))!==this._rangeStart&&(this._rangeStart=e,this._updateRenderRange())}},{key:"rangeEnd",get:function(){return this._rangeEnd},set:function(e){(e=Math.max(this._rangeStart,Math.min(e,this._symbols.length)))!==this._rangeEnd&&(this._rangeEnd=e,this._updateRenderRange())}}]),e}(),Xg=new ye,qg=new Ee,jg=new ye,Yg=new ye,Kg=new Ee,Zg=new Ee,$g=new Ee,Qg=new Ee,Jg=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._beingInitialized=!1,n._anchor=new Se,n._localAnchor=new Se,n._pivot=new be,n._width=n._calculatedWidth=32,n._height=n._calculatedHeight=32,n._margin=new Se(0,0,-32,-32),n._modelTransform=new Ee,n._screenToWorld=new Ee,n._anchorTransform=new Ee,n._anchorDirty=!0,n._parentWorldTransform=new Ee,n._screenTransform=new Ee,n._screenCorners=[new ye,new ye,new ye,new ye],n._canvasCorners=[new be,new be,new be,new be],n._worldCorners=[new ye,new ye,new ye,new ye],n._cornersDirty=!0,n._canvasCornersDirty=!0,n._worldCornersDirty=!0,n.entity.on("insert",n._onInsert,te(n)),n._patch(),n.screen=null,n._type=k_,n._image=null,n._text=null,n._group=null,n._drawOrder=0,n._fitMode=B_,n._useInput=!1,n._layers=[4],n._addedModels=[],n._batchGroupId=-1,n._offsetReadAt=0,n._maskOffset=.5,n._maskedBy=null,n}J(t,e);var i=t.prototype;return i._patch=function(){this.entity._sync=this._sync,this.entity.setPosition=this._setPosition,this.entity.setLocalPosition=this._setLocalPosition},i._unpatch=function(){this.entity._sync=$l.prototype._sync,this.entity.setPosition=$l.prototype.setPosition,this.entity.setLocalPosition=$l.prototype.setLocalPosition},i._setPosition=function(e,t,i){this.element.screen?(e instanceof ye?Xg.copy(e):Xg.set(e,t,i),this.getWorldTransform(),qg.copy(this.element._screenToWorld).invert(),qg.transformPoint(Xg,this.localPosition),this._dirtyLocal||this._dirtifyLocal()):$l.prototype.setPosition.call(this,e,t,i)},i._setLocalPosition=function(e,t,i){e instanceof ye?this.localPosition.copy(e):this.localPosition.set(e,t,i);var n=this.element,s=this.localPosition,r=n._pivot;n._margin.x=s.x-n._calculatedWidth*r.x,n._margin.z=n._localAnchor.z-n._localAnchor.x-n._calculatedWidth-n._margin.x,n._margin.y=s.y-n._calculatedHeight*r.y,n._margin.w=n._localAnchor.w-n._localAnchor.y-n._calculatedHeight-n._margin.y,this._dirtyLocal||this._dirtifyLocal()},i._sync=function(){var e=this.element,t=e.screen;if(t){if(e._anchorDirty){var i=0,n=0,s=0,r=1;if(this._parent&&this._parent.element)i=this._parent.element.calculatedWidth,n=this._parent.element.calculatedHeight,s=this._parent.element.pivot.x,r=this._parent.element.pivot.y;else{var a=t.screen.resolution;i=a.x/t.screen.scale,n=a.y/t.screen.scale}e._anchorTransform.setTranslate(i*(e.anchor.x-s),-n*(r-e.anchor.y),0),e._anchorDirty=!1,e._calculateLocalAnchors()}e._sizeDirty&&e._calculateSize(!1,!1)}if(this._dirtyLocal){this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale);var o=this.localPosition,h=e._pivot;e._margin.x=o.x-e._calculatedWidth*h.x,e._margin.z=e._localAnchor.z-e._localAnchor.x-e._calculatedWidth-e._margin.x,e._margin.y=o.y-e._calculatedHeight*h.y,e._margin.w=e._localAnchor.w-e._localAnchor.y-e._calculatedHeight-e._margin.y,this._dirtyLocal=!1}if(!t)return this._dirtyWorld&&(e._cornersDirty=!0,e._canvasCornersDirty=!0,e._worldCornersDirty=!0),$l.prototype._sync.call(this);if(this._dirtyWorld){if(null===this._parent)this.worldTransform.copy(this.localTransform);else if(this._parent.element?e._screenToWorld.mul2(this._parent.element._modelTransform,e._anchorTransform):e._screenToWorld.copy(e._anchorTransform),e._modelTransform.mul2(e._screenToWorld,this.localTransform),t){e._screenToWorld.mul2(t.screen._screenMatrix,e._screenToWorld),t.screen.screenSpace||e._screenToWorld.mul2(t.worldTransform,e._screenToWorld),this.worldTransform.mul2(e._screenToWorld,this.localTransform);var l=e._parentWorldTransform;l.setIdentity();var c=this._parent;c&&c.element&&c!==t&&(Kg.setTRS(ye.ZERO,c.getLocalRotation(),c.getLocalScale()),l.mul2(c.element._parentWorldTransform,Kg));var u=jg;u.set(0,0,this.localPosition.z);var d=Yg;d.set(e._absLeft+e._pivot.x*e.calculatedWidth,e._absBottom+e._pivot.y*e.calculatedHeight,0),Kg.setTranslate(-d.x,-d.y,-d.z),Zg.setTRS(u,this.getLocalRotation(),this.getLocalScale()),$g.setTranslate(d.x,d.y,d.z),e._screenTransform.mul2(e._parentWorldTransform,$g).mul(Zg).mul(Kg),e._cornersDirty=!0,e._canvasCornersDirty=!0,e._worldCornersDirty=!0}else this.worldTransform.copy(e._modelTransform);this._dirtyWorld=!1}},i._onInsert=function(e){var t=this._parseUpToScreen();this.entity._dirtifyWorld(),this._updateScreen(t.screen),this._dirtifyMask()},i._dirtifyMask=function(){for(var e=this.entity;e;){var t=e.parent;if((null===t||t.screen)&&e.element){this.system._prerender&&this.system._prerender.length||(this.system._prerender=[],this.system.app.once("prerender",this._onPrerender,this));var i=this.system._prerender.indexOf(this.entity);i>=0&&this.system._prerender.splice(i,1),this.system._prerender.indexOf(e)<0&&this.system._prerender.push(e)}e=t}},i._onPrerender=function(){for(var e=0;e<this.system._prerender.length;e++){var t=this.system._prerender[e];if(t.element){t.element.syncMask(1)}}this.system._prerender.length=0},i._bindScreen=function(e){e._bindElement(this)},i._unbindScreen=function(e){e._unbindElement(this)},i._updateScreen=function(e){this.screen&&this.screen!==e&&this._unbindScreen(this.screen.screen);var t=this.screen;this.screen=e,this.screen&&this._bindScreen(this.screen.screen),this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY),this.fire("set:screen",this.screen,t),this._anchorDirty=!0;for(var i=this.entity.children,n=0,s=i.length;n<s;n++)i[n].element&&i[n].element._updateScreen(e);this.screen&&this.screen.screen.syncDrawOrder()},i.syncMask=function(e){var t=this._parseUpToScreen();this._updateMask(t.mask,e)},i._setMaskedBy=function(e){var t=this._image||this._text;if(e){var i=e.element._image._maskRef,n=new du({ref:i,func:2});t&&t._setStencil&&t._setStencil(n),this._maskedBy=e}else t&&t._setStencil&&t._setStencil(null),this._maskedBy=null},i._updateMask=function(e,t){if(e){if(this._setMaskedBy(e),this.mask){var i=e.element._image._maskRef,n=new du({ref:i,func:2,zpass:3});this._image._setStencil(n),this._image._maskRef=t,t++,e=this.entity}for(var s=this.entity.children,r=0,a=s.length;r<a;r++)s[r].element&&s[r].element._updateMask(e,t);this.mask&&t--}else{if(this._setMaskedBy(null),this.mask){var o=new du({ref:t,func:7,zpass:2});this._image._setStencil(o),this._image._maskRef=t,t++,e=this.entity}for(var h=this.entity.children,l=0,c=h.length;l<c;l++)h[l].element&&h[l].element._updateMask(e,t);this.mask&&t--}},i._parseUpToScreen=function(){for(var e={screen:null,mask:null},t=this.entity._parent;t&&!t.screen;)t.element&&t.element.mask&&(e.mask||(e.mask=t)),t=t.parent;return t&&t.screen&&(e.screen=t),e},i._onScreenResize=function(e){this._anchorDirty=!0,this._cornersDirty=!0,this._worldCornersDirty=!0,this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY),this.fire("screen:set:resolution",e)},i._onScreenSpaceChange=function(){this.fire("screen:set:screenspace",this.screen.screen.screenSpace)},i._onScreenRemove=function(){this.screen&&(this.screen._destroying?this.screen=null:this._updateScreen(null))},i._calculateLocalAnchors=function(){var e=1e3,t=1e3,i=this.entity._parent;if(i&&i.element)e=i.element.calculatedWidth,t=i.element.calculatedHeight;else if(this.screen){var n=this.screen.screen.resolution,s=this.screen.screen.scale;e=n.x/s,t=n.y/s}this._localAnchor.set(this._anchor.x*e,this._anchor.y*t,this._anchor.z*e,this._anchor.w*t)},i.getOffsetPosition=function(e,t){var i=this.entity.getLocalPosition().clone();return i.x+=e,i.y+=t,this._screenToWorld.transformPoint(i,i),i},i.onLayersChanged=function(e,t){this.addModelToLayers(this._image?this._image._renderable.model:this._text._model),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(e){this.layers.indexOf(e.id)<0||(this._image?e.addMeshInstances(this._image._renderable.model.meshInstances):this._text&&e.addMeshInstances(this._text._model.meshInstances))},i.onLayerRemoved=function(e){this.layers.indexOf(e.id)<0||(this._image?e.removeMeshInstances(this._image._renderable.model.meshInstances):this._text&&e.removeMeshInstances(this._text._model.meshInstances))},i.onEnable=function(){var e;(this._image&&this._image.onEnable(),this._text&&this._text.onEnable(),this._group&&this._group.onEnable(),this.useInput&&this.system.app.elementInput&&this.system.app.elementInput.addElement(this),this.system.app.scene.on("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.on("add",this.onLayerAdded,this),this.system.app.scene.layers.on("remove",this.onLayerRemoved,this)),this._batchGroupId>=0)&&(null==(e=this.system.app.batcher)||e.insert(ya.ELEMENT,this.batchGroupId,this.entity));this.fire("enableelement")},i.onDisable=function(){var e;(this.system.app.scene.off("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.off("add",this.onLayerAdded,this),this.system.app.scene.layers.off("remove",this.onLayerRemoved,this)),this._image&&this._image.onDisable(),this._text&&this._text.onDisable(),this._group&&this._group.onDisable(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this._batchGroupId>=0)&&(null==(e=this.system.app.batcher)||e.remove(ya.ELEMENT,this.batchGroupId,this.entity));this.fire("disableelement")},i.onRemove=function(){this.entity.off("insert",this._onInsert,this),this._unpatch(),this._image&&this._image.destroy(),this._text&&this._text.destroy(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this.screen&&this.screen.screen&&(this._unbindScreen(this.screen.screen),this.screen.screen.syncDrawOrder()),this.off()},i._calculateSize=function(e,t){if(this.entity._parent||this.screen){this._calculateLocalAnchors();var i=this._absRight-this._absLeft,n=this._absTop-this._absBottom;e?this._setWidth(i):this._setCalculatedWidth(i,!1),t?this._setHeight(n):this._setCalculatedHeight(n,!1);var s=this.entity.getLocalPosition();s.x=this._margin.x+this._calculatedWidth*this._pivot.x,s.y=this._margin.y+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(s),this._sizeDirty=!1}},i._setWidth=function(e){this._width=e,this._setCalculatedWidth(e,!1),this.fire("set:width",this._width)},i._setHeight=function(e){this._height=e,this._setCalculatedHeight(e,!1),this.fire("set:height",this._height)},i._setCalculatedWidth=function(e,t){if(!(Math.abs(e-this._calculatedWidth)<=1e-4)){if(this._calculatedWidth=e,this.entity._dirtifyLocal(),t){var i=this.entity.getLocalPosition(),n=this._pivot;this._margin.x=i.x-this._calculatedWidth*n.x,this._margin.z=this._localAnchor.z-this._localAnchor.x-this._calculatedWidth-this._margin.x}this._flagChildrenAsDirty(),this.fire("set:calculatedWidth",this._calculatedWidth),this.fire("resize",this._calculatedWidth,this._calculatedHeight)}},i._setCalculatedHeight=function(e,t){if(!(Math.abs(e-this._calculatedHeight)<=1e-4)){if(this._calculatedHeight=e,this.entity._dirtifyLocal(),t){var i=this.entity.getLocalPosition(),n=this._pivot;this._margin.y=i.y-this._calculatedHeight*n.y,this._margin.w=this._localAnchor.w-this._localAnchor.y-this._calculatedHeight-this._margin.y}this._flagChildrenAsDirty(),this.fire("set:calculatedHeight",this._calculatedHeight),this.fire("resize",this._calculatedWidth,this._calculatedHeight)}},i._flagChildrenAsDirty=function(){for(var e=this.entity._children,t=0,i=e.length;t<i;t++)e[t].element&&(e[t].element._anchorDirty=!0,e[t].element._sizeDirty=!0)},i.addModelToLayers=function(e){this._addedModels.push(e);for(var t=0;t<this.layers.length;t++){var i=this.system.app.scene.layers.getLayerById(this.layers[t]);i&&i.addMeshInstances(e.meshInstances)}},i.removeModelFromLayers=function(e){var t=this._addedModels.indexOf(e);t>=0&&this._addedModels.splice(t,1);for(var i=0;i<this.layers.length;i++){var n=this.system.app.scene.layers.getLayerById(this.layers[i]);n&&n.removeMeshInstances(e.meshInstances)}},i.getMaskOffset=function(){var e=this.system.app.frame;this._offsetReadAt!==e&&(this._maskOffset=.5,this._offsetReadAt=e);var t=this._maskOffset;return this._maskOffset-=.001,t},i.isVisibleForCamera=function(e){var t,i,n,s;if(this.maskedBy){var r=this.maskedBy.element.screenCorners;t=Math.min(Math.min(r[0].x,r[1].x),Math.min(r[2].x,r[3].x)),i=Math.max(Math.max(r[0].x,r[1].x),Math.max(r[2].x,r[3].x)),s=Math.min(Math.min(r[0].y,r[1].y),Math.min(r[2].y,r[3].y)),n=Math.max(Math.max(r[0].y,r[1].y),Math.max(r[2].y,r[3].y))}else{var a=this.system.app.graphicsDevice.width,o=this.system.app.graphicsDevice.height,h=e._rect.z*a,l=e._rect.w*o;i=(t=e._rect.x*a)+h,s=(n=(1-e._rect.y)*o)-l}var c=this.screenCorners,u=Math.min(Math.min(c[0].x,c[1].x),Math.min(c[2].x,c[3].x)),d=Math.max(Math.max(c[0].x,c[1].x),Math.max(c[2].x,c[3].x)),f=Math.min(Math.min(c[0].y,c[1].y),Math.min(c[2].y,c[3].y)),p=Math.max(Math.max(c[0].y,c[1].y),Math.max(c[2].y,c[3].y));return!(d<t||u>i||f>n||p<s)},i._isScreenSpace=function(){return!(!this.screen||!this.screen.screen)&&this.screen.screen.screenSpace},i._isScreenCulled=function(){return!(!this.screen||!this.screen.screen)&&this.screen.screen.cull},i._dirtyBatch=function(){var e;-1!==this.batchGroupId&&(null==(e=this.system.app.batcher)||e.markGroupDirty(this.batchGroupId))},$(t,[{key:"_absLeft",get:function(){return this._localAnchor.x+this._margin.x}},{key:"_absRight",get:function(){return this._localAnchor.z-this._margin.z}},{key:"_absTop",get:function(){return this._localAnchor.w-this._margin.w}},{key:"_absBottom",get:function(){return this._localAnchor.y+this._margin.y}},{key:"_hasSplitAnchorsX",get:function(){return Math.abs(this._anchor.x-this._anchor.z)>.001}},{key:"_hasSplitAnchorsY",get:function(){return Math.abs(this._anchor.y-this._anchor.w)>.001}},{key:"aabb",get:function(){return this._image?this._image.aabb:this._text?this._text.aabb:null}},{key:"anchor",get:function(){return this._anchor},set:function(e){var t;e instanceof Se?this._anchor.copy(e):(t=this._anchor).set.apply(t,e);this.entity._parent||this.screen?this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY):this._calculateLocalAnchors(),this._anchorDirty=!0,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:anchor",this._anchor)}},{key:"batchGroupId",get:function(){return this._batchGroupId},set:function(e){if(this._batchGroupId!==e){var t,i;if(this.entity.enabled&&this._batchGroupId>=0)null==(t=this.system.app.batcher)||t.remove(ya.ELEMENT,this.batchGroupId,this.entity);if(this.entity.enabled&&e>=0)null==(i=this.system.app.batcher)||i.insert(ya.ELEMENT,e,this.entity);e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&(this._image&&this._image._renderable.model?this.addModelToLayers(this._image._renderable.model):this._text&&this._text._model&&this.addModelToLayers(this._text._model)),this._batchGroupId=e}}},{key:"bottom",get:function(){return this._margin.y},set:function(e){this._margin.y=e;var t=this.entity.getLocalPosition(),i=this._absTop,n=this._localAnchor.y+e;this._setHeight(i-n),t.y=e+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(t)}},{key:"calculatedWidth",get:function(){return this._calculatedWidth},set:function(e){this._setCalculatedWidth(e,!0)}},{key:"calculatedHeight",get:function(){return this._calculatedHeight},set:function(e){this._setCalculatedHeight(e,!0)}},{key:"canvasCorners",get:function(){if(!this._canvasCornersDirty||!this.screen||!this.screen.screen.screenSpace)return this._canvasCorners;for(var e=this.system.app.graphicsDevice,t=this.screenCorners,i=e.canvas.clientWidth/e.width,n=e.canvas.clientHeight/e.height,s=0;s<4;s++)this._canvasCorners[s].set(t[s].x*i,(e.height-t[s].y)*n);return this._canvasCornersDirty=!1,this._canvasCorners}},{key:"drawOrder",get:function(){return this._drawOrder},set:function(e){var t=0;this.screen&&(t=this.screen.screen.priority),e>16777215&&(e=16777215),this._drawOrder=(t<<24)+e,this.fire("set:draworder",this._drawOrder)}},{key:"height",get:function(){return this._height},set:function(e){this._height=e,this._hasSplitAnchorsY||this._setCalculatedHeight(e,!0),this.fire("set:height",this._height)}},{key:"layers",get:function(){return this._layers},set:function(e){if(this._addedModels.length)for(var t=0;t<this._layers.length;t++){var i=this.system.app.scene.layers.getLayerById(this._layers[t]);if(i)for(var n=0;n<this._addedModels.length;n++)i.removeMeshInstances(this._addedModels[n].meshInstances)}if(this._layers=e,this.enabled&&this.entity.enabled&&this._addedModels.length)for(var s=0;s<this._layers.length;s++){var r=this.system.app.scene.layers.getLayerById(this._layers[s]);if(r)for(var a=0;a<this._addedModels.length;a++)r.addMeshInstances(this._addedModels[a].meshInstances)}}},{key:"left",get:function(){return this._margin.x},set:function(e){this._margin.x=e;var t=this.entity.getLocalPosition(),i=this._absRight,n=this._localAnchor.x+e;this._setWidth(i-n),t.x=e+this._calculatedWidth*this._pivot.x,this.entity.setLocalPosition(t)}},{key:"margin",get:function(){return this._margin},set:function(e){this._margin.copy(e),this._calculateSize(!0,!0),this.fire("set:margin",this._margin)}},{key:"maskedBy",get:function(){return this._maskedBy}},{key:"pivot",get:function(){return this._pivot},set:function(e){var t=this.pivot,i=this.margin,n=t.x,s=t.y;e instanceof be?t.copy(e):t.set.apply(t,e);var r=i.x+i.z,a=t.x-n;i.x+=r*a,i.z-=r*a;var o=i.y+i.w,h=t.y-s;i.y+=o*h,i.w-=o*h,this._anchorDirty=!0,this._cornersDirty=!0,this._worldCornersDirty=!0,this._calculateSize(!1,!1),this._flagChildrenAsDirty(),this.fire("set:pivot",t)}},{key:"right",get:function(){return this._margin.z},set:function(e){this._margin.z=e;var t=this.entity.getLocalPosition(),i=this._absLeft,n=this._localAnchor.z-e;this._setWidth(n-i),t.x=this._localAnchor.z-this._localAnchor.x-e-this._calculatedWidth*(1-this._pivot.x),this.entity.setLocalPosition(t)}},{key:"screenCorners",get:function(){if(!this._cornersDirty||!this.screen)return this._screenCorners;var e=this.entity.parent&&this.entity.parent.element&&this.entity.parent.element.screenCorners[0];this._screenCorners[0].set(this._absLeft,this._absBottom,0),this._screenCorners[1].set(this._absRight,this._absBottom,0),this._screenCorners[2].set(this._absRight,this._absTop,0),this._screenCorners[3].set(this._absLeft,this._absTop,0);for(var t=this.screen.screen.screenSpace,i=0;i<4;i++)this._screenTransform.transformPoint(this._screenCorners[i],this._screenCorners[i]),t&&this._screenCorners[i].mulScalar(this.screen.screen.scale),e&&this._screenCorners[i].add(e);return this._cornersDirty=!1,this._canvasCornersDirty=!0,this._worldCornersDirty=!0,this._screenCorners}},{key:"textWidth",get:function(){return this._text?this._text.width:0}},{key:"textHeight",get:function(){return this._text?this._text.height:0}},{key:"top",get:function(){return this._margin.w},set:function(e){this._margin.w=e;var t=this.entity.getLocalPosition(),i=this._absBottom,n=this._localAnchor.w-e;this._setHeight(n-i),t.y=this._localAnchor.w-this._localAnchor.y-e-this._calculatedHeight*(1-this._pivot.y),this.entity.setLocalPosition(t)}},{key:"type",get:function(){return this._type},set:function(e){e!==this._type&&(this._type=e,this._image&&(this._image.destroy(),this._image=null),this._text&&(this._text.destroy(),this._text=null),e===O_?this._image=new Tg(this):e===F_&&(this._text=new Hg(this)))}},{key:"useInput",get:function(){return this._useInput},set:function(e){this._useInput!==e&&(this._useInput=e,this.system.app.elementInput?e?this.enabled&&this.entity.enabled&&this.system.app.elementInput.addElement(this):this.system.app.elementInput.removeElement(this):this._useInput,this.fire("set:useInput",e))}},{key:"fitMode",get:function(){return this._fitMode},set:function(e){this._fitMode=e,this._calculateSize(!0,!0),this._image&&this._image.refreshMesh()}},{key:"width",get:function(){return this._width},set:function(e){this._width=e,this._hasSplitAnchorsX||this._setCalculatedWidth(e,!0),this.fire("set:width",this._width)}},{key:"worldCorners",get:function(){if(!this._worldCornersDirty)return this._worldCorners;if(this.screen){var e=this.screenCorners;if(!this.screen.screen.screenSpace){Kg.copy(this.screen.screen._screenMatrix),Kg.data[13]=-Kg.data[13],Kg.mul2(this.screen.getWorldTransform(),Kg);for(var t=0;t<4;t++)Kg.transformPoint(e[t],this._worldCorners[t])}}else{var i=this.entity.getLocalPosition();Kg.setTranslate(-i.x,-i.y,-i.z),Zg.setTRS(ye.ZERO,this.entity.getLocalRotation(),this.entity.getLocalScale()),$g.setTranslate(i.x,i.y,i.z);var n=this.entity.parent?this.entity.parent:this.entity;Qg.copy(n.getWorldTransform()),Qg.mul($g).mul(Zg).mul(Kg),jg.set(i.x-this.pivot.x*this.calculatedWidth,i.y-this.pivot.y*this.calculatedHeight,i.z),Qg.transformPoint(jg,this._worldCorners[0]),jg.set(i.x+(1-this.pivot.x)*this.calculatedWidth,i.y-this.pivot.y*this.calculatedHeight,i.z),Qg.transformPoint(jg,this._worldCorners[1]),jg.set(i.x+(1-this.pivot.x)*this.calculatedWidth,i.y+(1-this.pivot.y)*this.calculatedHeight,i.z),Qg.transformPoint(jg,this._worldCorners[2]),jg.set(i.x-this.pivot.x*this.calculatedWidth,i.y+(1-this.pivot.y)*this.calculatedHeight,i.z),Qg.transformPoint(jg,this._worldCorners[3])}return this._worldCornersDirty=!1,this._worldCorners}}]),t}(Cl);function ev(e){Object.defineProperty(Jg.prototype,e,{get:function(){return this._text?this._text[e]:this._image?this._image[e]:null},set:function(t){this._text?(this._text[e]!==t&&this._dirtyBatch(),this._text[e]=t):this._image&&(this._image[e]!==t&&this._dirtyBatch(),this._image[e]=t)}})}ev("fontSize"),ev("minFontSize"),ev("maxFontSize"),ev("maxLines"),ev("autoFitWidth"),ev("autoFitHeight"),ev("color"),ev("font"),ev("fontAsset"),ev("spacing"),ev("lineHeight"),ev("wrapLines"),ev("lines"),ev("alignment"),ev("autoWidth"),ev("autoHeight"),ev("rtlReorder"),ev("unicodeConverter"),ev("text"),ev("key"),ev("texture"),ev("textureAsset"),ev("material"),ev("materialAsset"),ev("sprite"),ev("spriteAsset"),ev("spriteFrame"),ev("pixelsPerUnit"),ev("opacity"),ev("rect"),ev("mask"),ev("outlineColor"),ev("outlineThickness"),ev("shadowColor"),ev("shadowOffset"),ev("enableMarkup"),ev("rangeStart"),ev("rangeEnd");var tv=function(){this.enabled=!0},iv=["enabled"],nv=function(e){function t(t){var i;(i=e.call(this,t)||this).id="element",i.ComponentType=Jg,i.DataType=tv,i.schema=iv,i._unicodeConverter=null,i._rtlReorder=null,i._defaultTexture=new wn(t.graphicsDevice,{width:1,height:1,format:7,name:"element-system"});var n=i._defaultTexture.lock(),s=new Uint8Array(4);return s[0]=255,s[1]=255,s[2]=255,s[3]=255,n.set(s),i._defaultTexture.unlock(),i.defaultImageMaterial=null,i.defaultImage9SlicedMaterial=null,i.defaultImage9TiledMaterial=null,i.defaultImageMaskMaterial=null,i.defaultImage9SlicedMaskMaterial=null,i.defaultImage9TiledMaskMaterial=null,i.defaultScreenSpaceImageMaterial=null,i.defaultScreenSpaceImage9SlicedMaterial=null,i.defaultScreenSpaceImage9TiledMaterial=null,i.defaultScreenSpaceImageMask9SlicedMaterial=null,i.defaultScreenSpaceImageMask9TiledMaterial=null,i.defaultScreenSpaceImageMaskMaterial=null,i._defaultTextMaterials={},i.defaultImageMaterials=[],i.on("beforeremove",i.onRemoveComponent,te(i)),i}J(t,e);var i=t.prototype;return i.destroy=function(){e.prototype.destroy.call(this),this._defaultTexture.destroy()},i.initializeComponentData=function(t,i,n){t._beingInitialized=!0,void 0!==i.anchor&&(i.anchor instanceof Se?t.anchor.copy(i.anchor):t.anchor.set(i.anchor[0],i.anchor[1],i.anchor[2],i.anchor[3])),void 0!==i.pivot&&(i.pivot instanceof be?t.pivot.copy(i.pivot):t.pivot.set(i.pivot[0],i.pivot[1]));var s,r=Math.abs(t.anchor.x-t.anchor.z)>.001,a=Math.abs(t.anchor.y-t.anchor.w)>.001,o=!1;void 0!==i.margin&&(i.margin instanceof Se?t.margin.copy(i.margin):t._margin.set(i.margin[0],i.margin[1],i.margin[2],i.margin[3]),o=!0),void 0!==i.left&&(t._margin.x=i.left,o=!0),void 0!==i.bottom&&(t._margin.y=i.bottom,o=!0),void 0!==i.right&&(t._margin.z=i.right,o=!0),void 0!==i.top&&(t._margin.w=i.top,o=!0),o&&(t.margin=t._margin);var h=!1;void 0===i.width||r?r&&(h=!0):t.width=i.width,void 0===i.height||a?a&&(h=!0):t.height=i.height,h&&(t.anchor=t.anchor),void 0!==i.enabled&&(t.enabled=i.enabled),void 0!==i.useInput&&(t.useInput=i.useInput),void 0!==i.fitMode&&(t.fitMode=i.fitMode),t.batchGroupId=void 0===i.batchGroupId||null===i.batchGroupId?-1:i.batchGroupId,i.layers&&Array.isArray(i.layers)&&(t.layers=i.layers.slice(0)),void 0!==i.type&&(t.type=i.type),t.type===O_?(void 0!==i.rect&&(t.rect=i.rect),void 0!==i.color&&((s=i.color)instanceof me||(s=new me(i.color[0],i.color[1],i.color[2])),t.color=s),void 0!==i.opacity&&(t.opacity=i.opacity),void 0!==i.textureAsset&&(t.textureAsset=i.textureAsset),i.texture&&(t.texture=i.texture),void 0!==i.spriteAsset&&(t.spriteAsset=i.spriteAsset),i.sprite&&(t.sprite=i.sprite),void 0!==i.spriteFrame&&(t.spriteFrame=i.spriteFrame),void 0!==i.pixelsPerUnit&&null!==i.pixelsPerUnit&&(t.pixelsPerUnit=i.pixelsPerUnit),void 0!==i.materialAsset&&(t.materialAsset=i.materialAsset),i.material&&(t.material=i.material),void 0!==i.mask&&(t.mask=i.mask)):t.type===F_&&(void 0!==i.autoWidth&&(t.autoWidth=i.autoWidth),void 0!==i.autoHeight&&(t.autoHeight=i.autoHeight),void 0!==i.rtlReorder&&(t.rtlReorder=i.rtlReorder),void 0!==i.unicodeConverter&&(t.unicodeConverter=i.unicodeConverter),null!==i.text&&void 0!==i.text?t.text=i.text:null!==i.key&&void 0!==i.key&&(t.key=i.key),void 0!==i.color&&((s=i.color)instanceof me||(s=new me(s[0],s[1],s[2])),t.color=s),void 0!==i.opacity&&(t.opacity=i.opacity),void 0!==i.spacing&&(t.spacing=i.spacing),void 0!==i.fontSize&&(t.fontSize=i.fontSize,i.lineHeight||(t.lineHeight=i.fontSize)),void 0!==i.lineHeight&&(t.lineHeight=i.lineHeight),void 0!==i.maxLines&&(t.maxLines=i.maxLines),void 0!==i.wrapLines&&(t.wrapLines=i.wrapLines),void 0!==i.minFontSize&&(t.minFontSize=i.minFontSize),void 0!==i.maxFontSize&&(t.maxFontSize=i.maxFontSize),i.autoFitWidth&&(t.autoFitWidth=i.autoFitWidth),i.autoFitHeight&&(t.autoFitHeight=i.autoFitHeight),void 0!==i.fontAsset&&(t.fontAsset=i.fontAsset),void 0!==i.font&&(t.font=i.font),void 0!==i.alignment&&(t.alignment=i.alignment),void 0!==i.outlineColor&&(t.outlineColor=i.outlineColor),void 0!==i.outlineThickness&&(t.outlineThickness=i.outlineThickness),void 0!==i.shadowColor&&(t.shadowColor=i.shadowColor),void 0!==i.shadowOffset&&(t.shadowOffset=i.shadowOffset),void 0!==i.enableMarkup&&(t.enableMarkup=i.enableMarkup));var l=t._parseUpToScreen();l.screen&&t._updateScreen(l.screen),e.prototype.initializeComponentData.call(this,t,i,n),t._beingInitialized=!1,t.type===O_&&t._image._meshDirty&&t._image._updateMesh(t._image.mesh)},i.onRemoveComponent=function(e,t){t.onRemove()},i.cloneComponent=function(e,t){var i=e.element,n={enabled:i.enabled,width:i.width,height:i.height,anchor:i.anchor.clone(),pivot:i.pivot.clone(),margin:i.margin.clone(),alignment:i.alignment&&i.alignment.clone()||i.alignment,autoWidth:i.autoWidth,autoHeight:i.autoHeight,type:i.type,rect:i.rect&&i.rect.clone()||i.rect,rtlReorder:i.rtlReorder,unicodeConverter:i.unicodeConverter,materialAsset:i.materialAsset,material:i.material,color:i.color&&i.color.clone()||i.color,opacity:i.opacity,textureAsset:i.textureAsset,texture:i.texture,spriteAsset:i.spriteAsset,sprite:i.sprite,spriteFrame:i.spriteFrame,pixelsPerUnit:i.pixelsPerUnit,spacing:i.spacing,lineHeight:i.lineHeight,wrapLines:i.wrapLines,layers:i.layers,fontSize:i.fontSize,minFontSize:i.minFontSize,maxFontSize:i.maxFontSize,autoFitWidth:i.autoFitWidth,autoFitHeight:i.autoFitHeight,maxLines:i.maxLines,fontAsset:i.fontAsset,font:i.font,useInput:i.useInput,fitMode:i.fitMode,batchGroupId:i.batchGroupId,mask:i.mask,outlineColor:i.outlineColor&&i.outlineColor.clone()||i.outlineColor,outlineThickness:i.outlineThickness,shadowColor:i.shadowColor&&i.shadowColor.clone()||i.shadowColor,shadowOffset:i.shadowOffset&&i.shadowOffset.clone()||i.shadowOffset,enableMarkup:i.enableMarkup};return void 0!==i.key&&null!==i.key?n.key=i.key:n.text=i.text,this.addComponent(t,n)},i.getTextElementMaterial=function(e,t,i){var n=(e&&1)|(t&&2)|(i&&4),s=this._defaultTextMaterials[n];if(s)return s;var r="TextMaterial";return s=new Zs,t?(s.msdfMap=this._defaultTexture,s.msdfTextAttribute=i,s.emissive.set(1,1,1)):(r="Bitmap"+r,s.emissive.set(.5,.5,.5),s.emissiveMap=this._defaultTexture,s.emissiveTint=!0,s.opacityMap=this._defaultTexture,s.opacityMapChannel="a"),e&&(r="ScreenSpace"+r,s.depthTest=!1),s.name="default"+r,s.useLighting=!1,s.useGammaTonemap=!1,s.useFog=!1,s.useSkybox=!1,s.diffuse.set(0,0,0),s.opacity=.5,s.blendType=4,s.depthWrite=!1,s.emissiveVertexColor=!0,s.update(),this._defaultTextMaterials[n]=s,s},i._createBaseImageMaterial=function(){var e=new Zs;return e.diffuse.set(0,0,0),e.emissive.set(.5,.5,.5),e.emissiveMap=this._defaultTexture,e.emissiveTint=!0,e.opacityMap=this._defaultTexture,e.opacityMapChannel="a",e.opacityTint=!0,e.opacity=0,e.useLighting=!1,e.useGammaTonemap=!1,e.useFog=!1,e.useSkybox=!1,e.blendType=4,e.depthWrite=!1,e},i.getImageElementMaterial=function(e,t,i,n){return e?t?i?(this.defaultScreenSpaceImageMask9SlicedMaterial||(this.defaultScreenSpaceImageMask9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMask9SlicedMaterial.name="defaultScreenSpaceImageMask9SlicedMaterial",this.defaultScreenSpaceImageMask9SlicedMaterial.nineSlicedMode=1,this.defaultScreenSpaceImageMask9SlicedMaterial.depthTest=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9SlicedMaterial.redWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.greenWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.blueWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9SlicedMaterial)),this.defaultScreenSpaceImageMask9SlicedMaterial):n?(this.defaultScreenSpaceImageMask9TiledMaterial||(this.defaultScreenSpaceImageMask9TiledMaterial=this.defaultScreenSpaceImage9TiledMaterial.clone(),this.defaultScreenSpaceImageMask9TiledMaterial.name="defaultScreenSpaceImageMask9TiledMaterial",this.defaultScreenSpaceImageMask9TiledMaterial.nineSlicedMode=2,this.defaultScreenSpaceImageMask9TiledMaterial.depthTest=!1,this.defaultScreenSpaceImageMask9TiledMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9TiledMaterial.redWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.greenWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.blueWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9TiledMaterial)),this.defaultScreenSpaceImageMask9TiledMaterial):(this.defaultScreenSpaceImageMaskMaterial||(this.defaultScreenSpaceImageMaskMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaskMaterial.name="defaultScreenSpaceImageMaskMaterial",this.defaultScreenSpaceImageMaskMaterial.depthTest=!1,this.defaultScreenSpaceImageMaskMaterial.alphaTest=1,this.defaultScreenSpaceImageMaskMaterial.redWrite=!1,this.defaultScreenSpaceImageMaskMaterial.greenWrite=!1,this.defaultScreenSpaceImageMaskMaterial.blueWrite=!1,this.defaultScreenSpaceImageMaskMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaskMaterial)),this.defaultScreenSpaceImageMaskMaterial):i?(this.defaultScreenSpaceImage9SlicedMaterial||(this.defaultScreenSpaceImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9SlicedMaterial.name="defaultScreenSpaceImage9SlicedMaterial",this.defaultScreenSpaceImage9SlicedMaterial.nineSlicedMode=1,this.defaultScreenSpaceImage9SlicedMaterial.depthTest=!1,this.defaultScreenSpaceImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9SlicedMaterial)),this.defaultScreenSpaceImage9SlicedMaterial):n?(this.defaultScreenSpaceImage9TiledMaterial||(this.defaultScreenSpaceImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9TiledMaterial.name="defaultScreenSpaceImage9TiledMaterial",this.defaultScreenSpaceImage9TiledMaterial.nineSlicedMode=2,this.defaultScreenSpaceImage9TiledMaterial.depthTest=!1,this.defaultScreenSpaceImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9TiledMaterial)),this.defaultScreenSpaceImage9TiledMaterial):(this.defaultScreenSpaceImageMaterial||(this.defaultScreenSpaceImageMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaterial.name="defaultScreenSpaceImageMaterial",this.defaultScreenSpaceImageMaterial.depthTest=!1,this.defaultScreenSpaceImageMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaterial)),this.defaultScreenSpaceImageMaterial):t?i?(this.defaultImage9SlicedMaskMaterial||(this.defaultImage9SlicedMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaskMaterial.name="defaultImage9SlicedMaskMaterial",this.defaultImage9SlicedMaskMaterial.nineSlicedMode=1,this.defaultImage9SlicedMaskMaterial.alphaTest=1,this.defaultImage9SlicedMaskMaterial.redWrite=!1,this.defaultImage9SlicedMaskMaterial.greenWrite=!1,this.defaultImage9SlicedMaskMaterial.blueWrite=!1,this.defaultImage9SlicedMaskMaterial.alphaWrite=!1,this.defaultImage9SlicedMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaskMaterial)),this.defaultImage9SlicedMaskMaterial):n?(this.defaultImage9TiledMaskMaterial||(this.defaultImage9TiledMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaskMaterial.name="defaultImage9TiledMaskMaterial",this.defaultImage9TiledMaskMaterial.nineSlicedMode=2,this.defaultImage9TiledMaskMaterial.alphaTest=1,this.defaultImage9TiledMaskMaterial.redWrite=!1,this.defaultImage9TiledMaskMaterial.greenWrite=!1,this.defaultImage9TiledMaskMaterial.blueWrite=!1,this.defaultImage9TiledMaskMaterial.alphaWrite=!1,this.defaultImage9TiledMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaskMaterial)),this.defaultImage9TiledMaskMaterial):(this.defaultImageMaskMaterial||(this.defaultImageMaskMaterial=this._createBaseImageMaterial(),this.defaultImageMaskMaterial.name="defaultImageMaskMaterial",this.defaultImageMaskMaterial.alphaTest=1,this.defaultImageMaskMaterial.redWrite=!1,this.defaultImageMaskMaterial.greenWrite=!1,this.defaultImageMaskMaterial.blueWrite=!1,this.defaultImageMaskMaterial.alphaWrite=!1,this.defaultImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaskMaterial)),this.defaultImageMaskMaterial):i?(this.defaultImage9SlicedMaterial||(this.defaultImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaterial.name="defaultImage9SlicedMaterial",this.defaultImage9SlicedMaterial.nineSlicedMode=1,this.defaultImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaterial)),this.defaultImage9SlicedMaterial):n?(this.defaultImage9TiledMaterial||(this.defaultImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaterial.name="defaultImage9TiledMaterial",this.defaultImage9TiledMaterial.nineSlicedMode=2,this.defaultImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaterial)),this.defaultImage9TiledMaterial):(this.defaultImageMaterial||(this.defaultImageMaterial=this._createBaseImageMaterial(),this.defaultImageMaterial.name="defaultImageMaterial",this.defaultImageMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaterial)),this.defaultImageMaterial)},i.registerUnicodeConverter=function(e){this._unicodeConverter=e},i.registerRtlReorder=function(e){this._rtlReorder=e},i.getUnicodeConverter=function(){return this._unicodeConverter},i.getRtlReorder=function(){return this._rtlReorder},t}(h_);Cl._buildAccessors(Jg.prototype,iv);var sv="free",rv="limited",av="locked",ov=["angularDampingX","angularDampingY","angularDampingZ","angularEquilibriumX","angularEquilibriumY","angularEquilibriumZ","angularLimitsX","angularLimitsY","angularLimitsZ","angularMotionX","angularMotionY","angularMotionZ","angularSpringX","angularSpringY","angularSpringZ","angularStiffnessX","angularStiffnessY","angularStiffnessZ","breakForce","enableCollision","enabled","entityA","entityB","linearDampingX","linearDampingY","linearDampingZ","linearEquilibriumX","linearEquilibriumY","linearEquilibriumZ","linearLimitsX","linearLimitsY","linearLimitsZ","linearMotionX","linearMotionY","linearMotionZ","linearSpringX","linearSpringY","linearSpringZ","linearStiffnessX","linearStiffnessY","linearStiffnessZ"],hv=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._constraint=null,n._entityA=null,n._entityB=null,n._breakForce=34e37,n._enableCollision=!0,n._linearMotionX=av,n._linearLimitsX=new be(0,0),n._linearSpringX=!1,n._linearStiffnessX=0,n._linearDampingX=1,n._linearEquilibriumX=0,n._linearMotionY=av,n._linearLimitsY=new be(0,0),n._linearSpringY=!1,n._linearStiffnessY=0,n._linearDampingY=1,n._linearEquilibriumY=0,n._linearMotionZ=av,n._linearLimitsZ=new be(0,0),n._linearSpringZ=!1,n._linearStiffnessZ=0,n._linearDampingZ=1,n._linearEquilibriumZ=0,n._angularMotionX=av,n._angularLimitsX=new be(0,0),n._angularSpringX=!1,n._angularStiffnessX=0,n._angularDampingX=1,n._angularEquilibriumX=0,n._angularMotionY=av,n._angularLimitsY=new be(0,0),n._angularSpringY=!1,n._angularStiffnessY=0,n._angularDampingY=1,n._angularEquilibriumY=0,n._angularMotionZ=av,n._angularLimitsZ=new be(0,0),n._angularSpringZ=!1,n._angularEquilibriumZ=0,n._angularDampingZ=1,n._angularStiffnessZ=0,n.on("set_enabled",n._onSetEnabled,te(n)),n}J(t,e);var i=t.prototype;return i._convertTransform=function(e,t){var i=e.getTranslation(),n=new Pe;n.setFromMat4(e);var s=new Ammo.btVector3(i.x,i.y,i.z),r=new Ammo.btQuaternion(n.x,n.y,n.z,n.w);t.setOrigin(s),t.setRotation(r),Ammo.destroy(s),Ammo.destroy(r)},i._updateAngularLimits=function(){var e=this._constraint;if(e){var t,i,n,s,r,a;this._angularMotionX===rv?(t=this._angularLimitsX.x*de.DEG_TO_RAD,s=this._angularLimitsX.y*de.DEG_TO_RAD):this._angularMotionX===sv?(t=1,s=0):t=s=0,this._angularMotionY===rv?(i=this._angularLimitsY.x*de.DEG_TO_RAD,r=this._angularLimitsY.y*de.DEG_TO_RAD):this._angularMotionY===sv?(i=1,r=0):i=r=0,this._angularMotionZ===rv?(n=this._angularLimitsZ.x*de.DEG_TO_RAD,a=this._angularLimitsZ.y*de.DEG_TO_RAD):this._angularMotionZ===sv?(n=1,a=0):n=a=0;var o=new Ammo.btVector3(t,i,n);e.setAngularLowerLimit(o),o.setValue(s,r,a),e.setAngularUpperLimit(o),Ammo.destroy(o)}},i._updateLinearLimits=function(){var e=this._constraint;if(e){var t,i,n,s,r,a;this._linearMotionX===rv?(t=this._linearLimitsX.x,s=this._linearLimitsX.y):this._linearMotionX===sv?(t=1,s=0):t=s=0,this._linearMotionY===rv?(i=this._linearLimitsY.x,r=this._linearLimitsY.y):this._linearMotionY===sv?(i=1,r=0):i=r=0,this._linearMotionZ===rv?(n=this._linearLimitsZ.x,a=this._linearLimitsZ.y):this._linearMotionZ===sv?(n=1,a=0):n=a=0;var o=new Ammo.btVector3(t,i,n);e.setLinearLowerLimit(o),o.setValue(s,r,a),e.setLinearUpperLimit(o),Ammo.destroy(o)}},i._createConstraint=function(){if(this._entityA&&this._entityA.rigidbody){this._destroyConstraint();var e=new Ee,t=this._entityA.rigidbody.body;t.activate();var i=this.entity.getWorldTransform(),n=this._entityA.getWorldTransform().clone().invert();e.mul2(n,i);var s=new Ammo.btTransform;if(this._convertTransform(e,s),this._entityB&&this._entityB.rigidbody){var r=this._entityB.rigidbody.body;r.activate();var a=this._entityB.getWorldTransform().clone().invert();e.mul2(a,i);var o=new Ammo.btTransform;this._convertTransform(e,o),this._constraint=new Ammo.btGeneric6DofSpringConstraint(t,r,s,o,!this._enableCollision),Ammo.destroy(o)}else this._constraint=new Ammo.btGeneric6DofSpringConstraint(t,s,!this._enableCollision);Ammo.destroy(s);for(var h=["X","Y","Z","X","Y","Z"],l=0;l<6;l++){var c=l<3?"_linear":"_angular";this._constraint.enableSpring(l,this[c+"Spring"+h[l]]),this._constraint.setDamping(l,this[c+"Damping"+h[l]]),this._constraint.setEquilibriumPoint(l,this[c+"Equilibrium"+h[l]]),this._constraint.setStiffness(l,this[c+"Stiffness"+h[l]])}this._constraint.setBreakingImpulseThreshold(this._breakForce),this._updateLinearLimits(),this._updateAngularLimits(),this.system.app.systems.rigidbody.dynamicsWorld.addConstraint(this._constraint,!this._enableCollision)}},i._destroyConstraint=function(){this._constraint&&(this.system.app.systems.rigidbody.dynamicsWorld.removeConstraint(this._constraint),Ammo.destroy(this._constraint),this._constraint=null)},i.initFromData=function(e){for(var t,i=ne(ov);!(t=i()).done;){var n=t.value;e.hasOwnProperty(n)&&(e[n]instanceof be?this["_"+n].copy(e[n]):this["_"+n]=e[n])}this._createConstraint()},i.onEnable=function(){this._createConstraint()},i.onDisable=function(){this._destroyConstraint()},i._onSetEnabled=function(e,t,i){},i._onBeforeRemove=function(){this.fire("remove")},$(t,[{key:"entityA",get:function(){return this._entityA},set:function(e){this._destroyConstraint(),this._entityA=e,this._createConstraint()}},{key:"entityB",get:function(){return this._entityB},set:function(e){this._destroyConstraint(),this._entityB=e,this._createConstraint()}},{key:"breakForce",get:function(){return this._breakForce},set:function(e){this._constraint&&this._breakForce!==e&&(this._constraint.setBreakingImpulseThreshold(e),this._breakForce=e)}},{key:"enableCollision",get:function(){return this._enableCollision},set:function(e){this._destroyConstraint(),this._enableCollision=e,this._createConstraint()}},{key:"angularLimitsX",get:function(){return this._angularLimitsX},set:function(e){this._angularLimitsX.equals(e)||(this._angularLimitsX.copy(e),this._updateAngularLimits())}},{key:"angularMotionX",get:function(){return this._angularMotionX},set:function(e){this._angularMotionX!==e&&(this._angularMotionX=e,this._updateAngularLimits())}},{key:"angularLimitsY",get:function(){return this._angularLimitsY},set:function(e){this._angularLimitsY.equals(e)||(this._angularLimitsY.copy(e),this._updateAngularLimits())}},{key:"angularMotionY",get:function(){return this._angularMotionY},set:function(e){this._angularMotionY!==e&&(this._angularMotionY=e,this._updateAngularLimits())}},{key:"angularLimitsZ",get:function(){return this._angularLimitsZ},set:function(e){this._angularLimitsZ.equals(e)||(this._angularLimitsZ.copy(e),this._updateAngularLimits())}},{key:"angularMotionZ",get:function(){return this._angularMotionZ},set:function(e){this._angularMotionZ!==e&&(this._angularMotionZ=e,this._updateAngularLimits())}},{key:"linearLimitsX",get:function(){return this._linearLimitsX},set:function(e){this._linearLimitsX.equals(e)||(this._linearLimitsX.copy(e),this._updateLinearLimits())}},{key:"linearMotionX",get:function(){return this._linearMotionX},set:function(e){this._linearMotionX!==e&&(this._linearMotionX=e,this._updateLinearLimits())}},{key:"linearLimitsY",get:function(){return this._linearLimitsY},set:function(e){this._linearLimitsY.equals(e)||(this._linearLimitsY.copy(e),this._updateLinearLimits())}},{key:"linearMotionY",get:function(){return this._linearMotionY},set:function(e){this._linearMotionY!==e&&(this._linearMotionY=e,this._updateLinearLimits())}},{key:"linearLimitsZ",get:function(){return this._linearLimitsZ},set:function(e){this._linearLimitsZ.equals(e)||(this._linearLimitsZ.copy(e),this._updateLinearLimits())}},{key:"linearMotionZ",get:function(){return this._linearMotionZ},set:function(e){this._linearMotionZ!==e&&(this._linearMotionZ=e,this._updateLinearLimits())}}]),t}(Cl),lv={Damping:"setDamping",Equilibrium:"setEquilibriumPoint",Spring:"enableSpring",Stiffness:"setStiffness"};["linear","angular"].forEach((function(e){["Damping","Equilibrium","Spring","Stiffness"].forEach((function(t){["X","Y","Z"].forEach((function(i){var n=e+t+i,s="_"+n,r="linear"===e?0:3;"Y"===i&&(r+=1),"Z"===i&&(r+=2),Object.defineProperty(hv.prototype,n,{get:function(){return this[s]},set:function(e){this[s]!==e&&(this[s]=e,this._constraint[lv[t]](r,e))}})}))}))}));var cv=function(){this.enabled=!0},uv=["enabled"],dv=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="joint",i.app=t,i.ComponentType=hv,i.DataType=cv,i.schema=uv,i}return J(t,e),t.prototype.initializeComponentData=function(e,t,i){e.initFromData(t)},t}(h_);Cl._buildAccessors(hv.prototype,uv);var fv=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._minWidth=0,n._minHeight=0,n._maxWidth=null,n._maxHeight=null,n._fitWidthProportion=0,n._fitHeightProportion=0,n._excludeFromLayout=!1,n}return J(t,e),$(t,[{key:"minWidth",get:function(){return this._minWidth},set:function(e){e!==this._minWidth&&(this._minWidth=e,this.fire("resize"))}},{key:"minHeight",get:function(){return this._minHeight},set:function(e){e!==this._minHeight&&(this._minHeight=e,this.fire("resize"))}},{key:"maxWidth",get:function(){return this._maxWidth},set:function(e){e!==this._maxWidth&&(this._maxWidth=e,this.fire("resize"))}},{key:"maxHeight",get:function(){return this._maxHeight},set:function(e){e!==this._maxHeight&&(this._maxHeight=e,this.fire("resize"))}},{key:"fitWidthProportion",get:function(){return this._fitWidthProportion},set:function(e){e!==this._fitWidthProportion&&(this._fitWidthProportion=e,this.fire("resize"))}},{key:"fitHeightProportion",get:function(){return this._fitHeightProportion},set:function(e){e!==this._fitHeightProportion&&(this._fitHeightProportion=e,this.fire("resize"))}},{key:"excludeFromLayout",get:function(){return this._excludeFromLayout},set:function(e){e!==this._excludeFromLayout&&(this._excludeFromLayout=e,this.fire("resize"))}}]),t}(Cl),pv=function(){this.enabled=!0},mv=["enabled"],_v=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="layoutchild",i.ComponentType=fv,i.DataType=pv,i.schema=mv,i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){void 0!==i.enabled&&(t.enabled=i.enabled),void 0!==i.minWidth&&(t.minWidth=i.minWidth),void 0!==i.minHeight&&(t.minHeight=i.minHeight),void 0!==i.maxWidth&&(t.maxWidth=i.maxWidth),void 0!==i.maxHeight&&(t.maxHeight=i.maxHeight),void 0!==i.fitWidthProportion&&(t.fitWidthProportion=i.fitWidthProportion),void 0!==i.fitHeightProportion&&(t.fitHeightProportion=i.fitHeightProportion),void 0!==i.excludeFromLayout&&(t.excludeFromLayout=i.excludeFromLayout),e.prototype.initializeComponentData.call(this,t,i,n)},i.cloneComponent=function(e,t){var i=e.layoutchild;return this.addComponent(t,{enabled:i.enabled,minWidth:i.minWidth,minHeight:i.minHeight,maxWidth:i.maxWidth,maxHeight:i.maxHeight,fitWidthProportion:i.fitWidthProportion,fitHeightProportion:i.fitHeightProportion,excludeFromLayout:i.excludeFromLayout})},t}(h_);Cl._buildAccessors(fv.prototype,mv);var gv={0:{axis:"x",size:"width",calculatedSize:"calculatedWidth",minSize:"minWidth",maxSize:"maxWidth",fitting:"widthFitting",fittingProportion:"fitWidthProportion"},1:{axis:"y",size:"height",calculatedSize:"calculatedHeight",minSize:"minHeight",maxSize:"maxHeight",fitting:"heightFitting",fittingProportion:"fitHeightProportion"}},vv={0:1,1:0},yv={minWidth:0,minHeight:0,maxWidth:Number.POSITIVE_INFINITY,maxHeight:Number.POSITIVE_INFINITY,width:null,height:null,fitWidthProportion:0,fitHeightProportion:0},xv="NONE",bv="APPLY_STRETCHING",Sv="APPLY_SHRINKING",wv=new be;function Tv(e){var t,i=gv[e],n=gv[vv[e]];function s(e,t){return-t[i.size]*e.pivot[i.axis]}function r(e,t){return-t[n.size]*e.pivot[n.axis]}function a(e,t){return t[i.size]*(1-e.pivot[i.axis])}function o(e){var t=e.entity.layoutchild;return!t||!t.enabled||!t.excludeFromLayout}function h(e,t,i){switch(e){case 0:return xv;case 1:return t<i?bv:xv;case 2:return t>=i?Sv:xv;case 3:return t<i?bv:Sv;default:throw new Error("Unrecognized fitting mode: "+e)}}function l(e,i){return _(e,i.size)+(e.length-1)*t.spacing[i.axis]}function c(e,t,i){for(var n=v(e,i.maxSize),s=g(e,i.fittingProportion),r=b(s,n),a=wv[i.axis]-t,o=0;o<e.length;++o){var h=n[o],l=d(h,a,s,r),c=e[h][i.size]+l,u=e[h][i.maxSize],f=Math.min(c,u);e[h][i.size]=f,a-=l-Math.max(c-f,0)}}function u(e,t,i){for(var n=v(e,i.minSize,!0),s=function(e){if(1===e.length)return[1];for(var t=[],i=e.length,n=0;n<i;++n)t.push((1-e[n])/(i-1));return t}(g(e,i.fittingProportion)),r=b(s,n),a=t-wv[i.axis],o=0;o<e.length;++o){var h=n[o],l=d(h,a,s,r),c=e[h][i.size]-l,u=e[h][i.minSize],f=Math.max(c,u);e[h][i.size]=f,a-=l-Math.max(f-c,0)}}function d(e,t,i,n){var s=i[e],r=n[e];return Math.abs(s)<1e-5&&Math.abs(r)<1e-5?t:t*s/r}function f(e){for(var t=[],i=0;i<e.length;++i){var n=e[i],s=Math.max(p(n,"minWidth"),0),r=Math.max(p(n,"minHeight"),0),a=Math.max(p(n,"maxWidth"),s),o=Math.max(p(n,"maxHeight"),r),h=m(p(n,"width"),s,a),l=m(p(n,"height"),r,o),c=p(n,"fitWidthProportion"),u=p(n,"fitHeightProportion");t.push({minWidth:s,minHeight:r,maxWidth:a,maxHeight:o,width:h,height:l,fitWidthProportion:c,fitHeightProportion:u})}return t}function p(e,t){var i=e.entity.layoutchild;return i&&i.enabled&&void 0!==i[t]&&null!==i[t]?i[t]:void 0!==e[t]?e[t]:yv[t]}function m(e,t,i){return Math.min(Math.max(e,t),i)}function _(e,t){return e.reduce((function(e,i){return e+i[t]}),0)}function g(e,t){var i=_(e,t),n=[],s=e.length;if(0===i)for(var r=0;r<s;++r)n.push(1/s);else for(var a=0;a<s;++a)n.push(e[a][t]/i);return n}function v(e,t,i){return e.forEach(y),e.slice().sort((function(e,n){return i?n[t]-e[t]:e[t]-n[t]})).map(x)}function y(e,t){e.index=t}function x(e){return e.index}function b(e,t){var i=[];i[t[e.length-1]]=e[t[e.length-1]];for(var n=e.length-2;n>=0;--n)i[t[n]]=i[t[n+1]]+e[t[n]];return i}return function(e,d){e=e.filter(o),t=d,wv.x=t.containerSize.x-t.padding.x-t.padding.z,wv.y=t.containerSize.y-t.padding.y-t.padding.w,function(e){for(var t=0;t<e.length;++t){var i=e[t],n=i.anchor;0===n.x&&0===n.y&&0===n.z&&0===n.w||(i.anchor=Se.ZERO)}}(e);var p=function(e){var i=0===t.orientation&&t.reverseX||1===t.orientation&&t.reverseY,n=0===t.orientation&&t.reverseY||1===t.orientation&&t.reverseX;if(i)for(var s=0;s<e.length;++s)i&&e[s].reverse();n&&e.reverse();return e}(function(e){if(!t.wrap)return[e];for(var n=[[]],s=f(e),r=0,a=2===t[i.fitting],o=0;o<e.length;++o){n[n.length-1].length>0&&(r+=t.spacing[i.axis]);var h=s[o][i.size];r+=h,!a&&r>wv[i.axis]&&0!==n[n.length-1].length&&(r=h,n.push([])),n[n.length-1].push(e[o]),a&&r>wv[i.axis]&&o!==e.length-1&&(r=0,n.push([]))}return n}(e)),m=function(e,i){for(var s=[],r=[],a=0;a<e.length;++a){var o=e[a];o.largestElement=null,o.largestSize={width:Number.NEGATIVE_INFINITY,height:Number.NEGATIVE_INFINITY};for(var d=0;d<o.length;++d){var f=i[a][d];f[n.size]>o.largestSize[n.size]&&(o.largestElement=o[d],o.largestSize=f)}s.push(o.largestElement),r.push(o.largestSize)}var p=l(r,n),m=h(t[n.fitting],p,wv[n.axis]);m===bv?c(r,p,n):m===Sv&&u(r,p,n);for(var _=0;_<e.length;++_)for(var g=e[_],v=0;v<g.length;++v){var y=i[_][v],x=y[n.size],b=1===e.length?wv[n.axis]:g.largestSize[n.size],S=h(t[n.fitting],x,b);S===bv?y[n.size]=Math.min(b,y[n.maxSize]):S===Sv&&(y[n.size]=Math.max(b,y[n.minSize]))}return i}(p,function(e){for(var n=[],s=0;s<e.length;++s){var r=f(e[s]),a=l(r,i),o=h(t[i.fitting],a,wv[i.axis]);o===bv?c(r,a,i):o===Sv&&u(r,a,i),n.push(r)}return n}(p)),_=function(e,o){var h={};h[i.axis]=0,h[n.axis]=0,e[i.size]=Number.NEGATIVE_INFINITY;for(var l=[],c=0;c<e.length;++c){var u=e[c];if(0!==u.length){for(var d=[],f=o[c],p=0;p<u.length;++p){var m=u[p],_=f[p];h[n.axis]-=r(m,_),h[i.axis]-=s(m,_),d[p]={},d[p][i.axis]=h[i.axis],d[p][n.axis]=h[n.axis],h[n.axis]+=r(m,_),h[i.axis]+=a(m,_)+t.spacing[i.axis]}u[i.size]=h[i.axis]-t.spacing[i.axis],u[n.size]=u.largestSize[n.size],e[i.size]=Math.max(e[i.size],u[i.size]),h[i.axis]=0,h[n.axis]+=u[n.size]+t.spacing[n.axis],l.push(d)}else l.push([])}return e[n.size]=h[n.axis]-t.spacing[n.axis],l}(p,m);return function(e,s,r){for(var a=t.alignment[i.axis],o=t.alignment[n.axis],h=t.padding[i.axis],l=t.padding[n.axis],c=0;c<e.length;++c)for(var u=e[c],d=s[c],f=r[c],p=(wv[i.axis]-u[i.size])*a+h,m=(wv[n.axis]-e[n.size])*o+l,_=0;_<u.length;++_){var g=(u[n.size]-d[_][n.size])*t.alignment[n.axis];f[_][i.axis]+=p,f[_][n.axis]+=m+g}}(p,m,_),function(e,s,r){for(var a=0;a<e.length;++a)for(var o=e[a],h=s[a],l=r[a],c=0;c<o.length;++c){var u=o[c];u[i.calculatedSize]=h[c][i.size],u[n.calculatedSize]=h[c][n.size],0===t.orientation?u.entity.setLocalPosition(l[c][i.axis],l[c][n.axis],u.entity.getLocalPosition().z):u.entity.setLocalPosition(l[c][n.axis],l[c][i.axis],u.entity.getLocalPosition().z)}}(p,m,_),function(e){var i=e.width,n=e.height,s=(wv.x-i)*t.alignment.x+t.padding.x,r=(wv.y-n)*t.alignment.y+t.padding.y;return{bounds:new Se(s,r,i,n)}}(p)}}var Av={};Av[0]=Tv(0),Av[1]=Tv(1);var Mv=function(){function e(){}return e.prototype.calculateLayout=function(e,t){var i=Av[t.orientation];if(i)return i(e,t);throw new Error("Unrecognized orientation value: "+t.orientation)},e}();function Cv(e){return e.element}function Ev(e){return e.enabled&&e.element&&e.element.enabled}var Pv=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._orientation=0,n._reverseX=!1,n._reverseY=!0,n._alignment=new be(0,1),n._padding=new Se,n._spacing=new be,n._widthFitting=0,n._heightFitting=0,n._wrap=!1,n._layoutCalculator=new Mv,n._listenForReflowEvents(n.entity,"on"),n.entity.children.forEach((function(e){n._listenForReflowEvents(e,"on")})),n.entity.on("childinsert",n._onChildInsert,te(n)),n.entity.on("childremove",n._onChildRemove,te(n)),t.app.systems.element.on("add",n._onElementOrLayoutComponentAdd,te(n)),t.app.systems.element.on("beforeremove",n._onElementOrLayoutComponentRemove,te(n)),t.app.systems.layoutchild.on("add",n._onElementOrLayoutComponentAdd,te(n)),t.app.systems.layoutchild.on("beforeremove",n._onElementOrLayoutComponentRemove,te(n)),n}J(t,e);var i=t.prototype;return i._isSelfOrChild=function(e){return e===this.entity||-1!==this.entity.children.indexOf(e)},i._listenForReflowEvents=function(e,t){e.element&&(e.element[t]("enableelement",this._scheduleReflow,this),e.element[t]("disableelement",this._scheduleReflow,this),e.element[t]("resize",this._scheduleReflow,this),e.element[t]("set:pivot",this._scheduleReflow,this)),e.layoutchild&&(e.layoutchild[t]("set_enabled",this._scheduleReflow,this),e.layoutchild[t]("resize",this._scheduleReflow,this))},i._onElementOrLayoutComponentAdd=function(e){this._isSelfOrChild(e)&&(this._listenForReflowEvents(e,"on"),this._scheduleReflow())},i._onElementOrLayoutComponentRemove=function(e){this._isSelfOrChild(e)&&(this._listenForReflowEvents(e,"off"),this._scheduleReflow())},i._onChildInsert=function(e){this._listenForReflowEvents(e,"on"),this._scheduleReflow()},i._onChildRemove=function(e){this._listenForReflowEvents(e,"off"),this._scheduleReflow()},i._scheduleReflow=function(){this.enabled&&this.entity&&this.entity.enabled&&!this._isPerformingReflow&&this.system.scheduleReflow(this)},i.reflow=function(){var e=Cv(this.entity),t=this.entity.children.filter(Ev).map(Cv);if(e&&0!==t.length){var i=Math.max(e.calculatedWidth,0),n=Math.max(e.calculatedHeight,0),s={orientation:this._orientation,reverseX:this._reverseX,reverseY:this._reverseY,alignment:this._alignment,padding:this._padding,spacing:this._spacing,widthFitting:this._widthFitting,heightFitting:this._heightFitting,wrap:this._wrap,containerSize:new be(i,n)};this._isPerformingReflow=!0;var r=this._layoutCalculator.calculateLayout(t,s);this._isPerformingReflow=!1,this.fire("reflow",r)}},i.onEnable=function(){this._scheduleReflow()},i.onRemove=function(){var e=this;this.entity.off("childinsert",this._onChildInsert,this),this.entity.off("childremove",this._onChildRemove,this),this._listenForReflowEvents(this.entity,"off"),this.entity.children.forEach((function(t){e._listenForReflowEvents(t,"off")})),this.system.app.systems.element.off("add",this._onElementOrLayoutComponentAdd,this),this.system.app.systems.element.off("beforeremove",this._onElementOrLayoutComponentRemove,this),this.system.app.systems.layoutchild.off("add",this._onElementOrLayoutComponentAdd,this),this.system.app.systems.layoutchild.off("beforeremove",this._onElementOrLayoutComponentRemove,this)},$(t,[{key:"orientation",get:function(){return this._orientation},set:function(e){e!==this._orientation&&(this._orientation=e,this._scheduleReflow())}},{key:"reverseX",get:function(){return this._reverseX},set:function(e){e!==this._reverseX&&(this._reverseX=e,this._scheduleReflow())}},{key:"reverseY",get:function(){return this._reverseY},set:function(e){e!==this._reverseY&&(this._reverseY=e,this._scheduleReflow())}},{key:"alignment",get:function(){return this._alignment},set:function(e){e.equals(this._alignment)||(this._alignment.copy(e),this._scheduleReflow())}},{key:"padding",get:function(){return this._padding},set:function(e){e.equals(this._padding)||(this._padding.copy(e),this._scheduleReflow())}},{key:"spacing",get:function(){return this._spacing},set:function(e){e.equals(this._spacing)||(this._spacing.copy(e),this._scheduleReflow())}},{key:"widthFitting",get:function(){return this._widthFitting},set:function(e){e!==this._widthFitting&&(this._widthFitting=e,this._scheduleReflow())}},{key:"heightFitting",get:function(){return this._heightFitting},set:function(e){e!==this._heightFitting&&(this._heightFitting=e,this._scheduleReflow())}},{key:"wrap",get:function(){return this._wrap},set:function(e){e!==this._wrap&&(this._wrap=e,this._scheduleReflow())}}]),t}(Cl),Rv=function(){this.enabled=!0},Iv=["enabled"],Lv=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="layoutgroup",i.ComponentType=Pv,i.DataType=Rv,i.schema=Iv,i._reflowQueue=[],i.on("beforeremove",i._onRemoveComponent,te(i)),i.app.systems.on("postUpdate",i._onPostUpdate,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){void 0!==i.enabled&&(t.enabled=i.enabled),void 0!==i.orientation&&(t.orientation=i.orientation),void 0!==i.reverseX&&(t.reverseX=i.reverseX),void 0!==i.reverseY&&(t.reverseY=i.reverseY),void 0!==i.alignment&&(t.alignment=Array.isArray(i.alignment)?new be(i.alignment):i.alignment),void 0!==i.padding&&(t.padding=Array.isArray(i.padding)?new Se(i.padding):i.padding),void 0!==i.spacing&&(t.spacing=Array.isArray(i.spacing)?new be(i.spacing):i.spacing),void 0!==i.widthFitting&&(t.widthFitting=i.widthFitting),void 0!==i.heightFitting&&(t.heightFitting=i.heightFitting),void 0!==i.wrap&&(t.wrap=i.wrap),e.prototype.initializeComponentData.call(this,t,i,n)},i.cloneComponent=function(e,t){var i=e.layoutgroup;return this.addComponent(t,{enabled:i.enabled,orientation:i.orientation,reverseX:i.reverseX,reverseY:i.reverseY,alignment:i.alignment,padding:i.padding,spacing:i.spacing,widthFitting:i.widthFitting,heightFitting:i.heightFitting,wrap:i.wrap})},i.scheduleReflow=function(e){-1===this._reflowQueue.indexOf(e)&&this._reflowQueue.push(e)},i._onPostUpdate=function(){this._processReflowQueue()},i._processReflowQueue=function(){if(0!==this._reflowQueue.length)for(var e=0;this._reflowQueue.length>0;){var t=this._reflowQueue.slice();this._reflowQueue.length=0,t.sort((function(e,t){return e.entity.graphDepth-t.entity.graphDepth}));for(var i=0;i<t.length;++i)t[i].reflow();if(++e>=100){console.warn("Max reflow iterations limit reached, bailing.");break}}},i._onRemoveComponent=function(e,t){t.onRemove()},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("postUpdate",this._onPostUpdate,this)},t}(h_);Cl._buildAccessors(Pv.prototype,Iv);var Dv=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._type="asset",n._asset=null,n._model=null,n._mapping={},n._castShadows=!0,n._receiveShadows=!0,n._materialAsset=null,n._material=void 0,n._castShadowsLightmap=!0,n._lightmapped=!1,n._lightmapSizeMultiplier=1,n._isStatic=!1,n._layers=[0],n._batchGroupId=-1,n._customAabb=null,n._area=null,n._materialEvents=null,n._clonedModel=!1,n._material=t.defaultMaterial,i.on("remove",n.onRemoveChild,te(n)),i.on("removehierarchy",n.onRemoveChild,te(n)),i.on("insert",n.onInsertChild,te(n)),i.on("inserthierarchy",n.onInsertChild,te(n)),n}J(t,e);var i=t.prototype;return i.addModelToLayers=function(){for(var e=this.system.app.scene.layers,t=0;t<this._layers.length;t++){var i=e.getLayerById(this._layers[t]);i&&i.addMeshInstances(this.meshInstances)}},i.removeModelFromLayers=function(){for(var e=this.system.app.scene.layers,t=0;t<this._layers.length;t++){var i=e.getLayerById(this._layers[t]);i&&i.removeMeshInstances(this.meshInstances)}},i.onRemoveChild=function(){this._model&&this.removeModelFromLayers()},i.onInsertChild=function(){this._model&&this.enabled&&this.entity.enabled&&this.addModelToLayers()},i.onRemove=function(){this.asset=null,this.model=null,this.materialAsset=null,this._unsetMaterialEvents(),this.entity.off("remove",this.onRemoveChild,this),this.entity.off("insert",this.onInsertChild,this)},i.onLayersChanged=function(e,t){this.addModelToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(e){this.layers.indexOf(e.id)<0||e.addMeshInstances(this.meshInstances)},i.onLayerRemoved=function(e){this.layers.indexOf(e.id)<0||e.removeMeshInstances(this.meshInstances)},i._setMaterialEvent=function(e,t,i,n){var s=t+":"+i;this.system.app.assets.on(s,n,this),this._materialEvents||(this._materialEvents=[]),this._materialEvents[e]||(this._materialEvents[e]={}),this._materialEvents[e][s]={id:i,handler:n}},i._unsetMaterialEvents=function(){var e=this.system.app.assets,t=this._materialEvents;if(t){for(var i=0,n=t.length;i<n;i++)if(t[i]){var s=t[i];for(var r in s)e.off(r,s[r].handler,this)}this._materialEvents=null}},i._getAssetByIdOrPath=function(e){var t=null;if(isNaN(parseInt(e,10))){if(this.asset){var i=this._getMaterialAssetUrl(e);i&&(t=this.system.app.assets.getByUrl(i))}}else t=this.system.app.assets.get(e);return t},i._getMaterialAssetUrl=function(e){if(!this.asset)return null;var t=this.system.app.assets.get(this.asset);return t?t.getAbsoluteUrl(e):null},i._loadAndSetMeshInstanceMaterial=function(e,t,i){var n=this.system.app.assets;e&&(e.resource?(t.material=e.resource,this._setMaterialEvent(i,"remove",e.id,(function(){t.material=this.system.defaultMaterial}))):(this._setMaterialEvent(i,"load",e.id,(function(n){t.material=n.resource,this._setMaterialEvent(i,"remove",e.id,(function(){t.material=this.system.defaultMaterial}))})),this.enabled&&this.entity.enabled&&n.load(e)))},i.onEnable=function(){var e=this.system.app,t=e.scene;t.on("set:layers",this.onLayersChanged,this),t.layers&&(t.layers.on("add",this.onLayerAdded,this),t.layers.on("remove",this.onLayerRemoved,this));var i,n,s="asset"===this._type;if(this._model?this.addModelToLayers():s&&this._asset&&(i=e.assets.get(this._asset))&&i.resource!==this._model&&this._bindModelAsset(i),this._materialAsset&&(i=e.assets.get(this._materialAsset))&&i.resource!==this._material&&this._bindMaterialAsset(i),s&&this._mapping)for(var r in this._mapping)this._mapping[r]&&(i=this._getAssetByIdOrPath(this._mapping[r]))&&!i.resource&&e.assets.load(i);this._batchGroupId>=0&&(null==(n=e.batcher)||n.insert(ya.MODEL,this.batchGroupId,this.entity))},i.onDisable=function(){var e,t=this.system.app,i=t.scene;(i.off("set:layers",this.onLayersChanged,this),i.layers&&(i.layers.off("add",this.onLayerAdded,this),i.layers.off("remove",this.onLayerRemoved,this)),this._batchGroupId>=0)&&(null==(e=t.batcher)||e.remove(ya.MODEL,this.batchGroupId,this.entity));this._model&&this.removeModelFromLayers()},i.hide=function(){if(this._model)for(var e=this._model.meshInstances,t=0,i=e.length;t<i;t++)e[t].visible=!1},i.show=function(){if(this._model)for(var e=this._model.meshInstances,t=0,i=e.length;t<i;t++)e[t].visible=!0},i._bindMaterialAsset=function(e){if(e.on("load",this._onMaterialAssetLoad,this),e.on("unload",this._onMaterialAssetUnload,this),e.on("remove",this._onMaterialAssetRemove,this),e.on("change",this._onMaterialAssetChange,this),e.resource)this._onMaterialAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}},i._unbindMaterialAsset=function(e){e.off("load",this._onMaterialAssetLoad,this),e.off("unload",this._onMaterialAssetUnload,this),e.off("remove",this._onMaterialAssetRemove,this),e.off("change",this._onMaterialAssetChange,this)},i._onMaterialAssetAdd=function(e){this.system.app.assets.off("add:"+e.id,this._onMaterialAssetAdd,this),this._materialAsset===e.id&&this._bindMaterialAsset(e)},i._onMaterialAssetLoad=function(e){this._setMaterial(e.resource)},i._onMaterialAssetUnload=function(e){this._setMaterial(this.system.defaultMaterial)},i._onMaterialAssetRemove=function(e){this._onMaterialAssetUnload(e)},i._onMaterialAssetChange=function(e){},i._bindModelAsset=function(e){if(this._unbindModelAsset(e),e.on("load",this._onModelAssetLoad,this),e.on("unload",this._onModelAssetUnload,this),e.on("change",this._onModelAssetChange,this),e.on("remove",this._onModelAssetRemove,this),e.resource)this._onModelAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}},i._unbindModelAsset=function(e){e.off("load",this._onModelAssetLoad,this),e.off("unload",this._onModelAssetUnload,this),e.off("change",this._onModelAssetChange,this),e.off("remove",this._onModelAssetRemove,this)},i._onModelAssetAdded=function(e){this.system.app.assets.off("add:"+e.id,this._onModelAssetAdded,this),e.id===this._asset&&this._bindModelAsset(e)},i._onModelAssetLoad=function(e){this.model=e.resource.clone(),this._clonedModel=!0},i._onModelAssetUnload=function(e){this.model=null},i._onModelAssetChange=function(e,t,i,n){"data"===t&&(this.mapping=this._mapping)},i._onModelAssetRemove=function(e){this.model=null},i._setMaterial=function(e){if(this._material!==e){this._material=e;var t=this._model;if(t&&"asset"!==this._type)for(var i=t.meshInstances,n=0,s=i.length;n<s;n++)i[n].material=e}},$(t,[{key:"meshInstances",get:function(){return this._model?this._model.meshInstances:null},set:function(e){this._model&&(this._model.meshInstances=e)}},{key:"customAabb",get:function(){return this._customAabb},set:function(e){if(this._customAabb=e,this._model){var t=this._model.meshInstances;if(t)for(var i=0;i<t.length;i++)t[i].setCustomAabb(this._customAabb)}}},{key:"type",get:function(){return this._type},set:function(e){if(this._type!==e)if(this._area=null,this._type=e,"asset"===e)null!==this._asset?this._bindModelAsset(this._asset):this.model=null;else{var t=ma(this.system.app.graphicsDevice,e);this._area=t.area;var i=t.mesh,n=new Hn,s=new hc;s.graph=n,s.meshInstances=[new ka(i,this._material,n)],this.model=s,this._asset=null}}},{key:"asset",get:function(){return this._asset},set:function(e){var t=this.system.app.assets,i=e;if(e instanceof ml&&(i=e.id),this._asset!==i){if(this._asset){t.off("add:"+this._asset,this._onModelAssetAdded,this);var n=t.get(this._asset);n&&this._unbindModelAsset(n)}if(this._asset=i,this._asset){var s=t.get(this._asset);s?this._bindModelAsset(s):(this.model=null,t.on("add:"+this._asset,this._onModelAssetAdded,this))}else this.model=null}}},{key:"model",get:function(){return this._model},set:function(e){if(this._model!==e&&(!e||!e._immutable)&&(this._model&&(this._model._immutable=!1,this.removeModelFromLayers(),this.entity.removeChild(this._model.getGraph()),delete this._model._entity,this._clonedModel&&(this._model.destroy(),this._clonedModel=!1)),this._model=e,this._model)){this._model._immutable=!0;for(var t=this._model.meshInstances,i=0;i<t.length;i++)t[i].castShadow=this._castShadows,t[i].receiveShadow=this._receiveShadows,t[i].isStatic=this._isStatic,t[i].setCustomAabb(this._customAabb);this.lightmapped=this._lightmapped,this.entity.addChild(this._model.graph),this.enabled&&this.entity.enabled&&this.addModelToLayers(),this._model._entity=this.entity,this.entity.animation&&this.entity.animation.setModel(this._model),this.entity.anim&&this.entity.anim.rebind(),"asset"===this.type?this.mapping=this._mapping:this._unsetMaterialEvents()}}},{key:"lightmapped",get:function(){return this._lightmapped},set:function(e){if(e!==this._lightmapped&&(this._lightmapped=e,this._model))for(var t=this._model.meshInstances,i=0;i<t.length;i++)t[i].setLightmapped(e)}},{key:"castShadows",get:function(){return this._castShadows},set:function(e){if(this._castShadows!==e){var t=this._model;if(t){var i=this.layers,n=this.system.app.scene;if(this._castShadows&&!e)for(var s=0;s<i.length;s++){var r=this.system.app.scene.layers.getLayerById(this.layers[s]);r&&r.removeShadowCasters(t.meshInstances)}for(var a=t.meshInstances,o=0;o<a.length;o++)a[o].castShadow=e;if(!this._castShadows&&e)for(var h=0;h<i.length;h++){var l=n.layers.getLayerById(i[h]);l&&l.addShadowCasters(t.meshInstances)}}this._castShadows=e}}},{key:"receiveShadows",get:function(){return this._receiveShadows},set:function(e){if(this._receiveShadows!==e&&(this._receiveShadows=e,this._model))for(var t=this._model.meshInstances,i=0,n=t.length;i<n;i++)t[i].receiveShadow=e}},{key:"castShadowsLightmap",get:function(){return this._castShadowsLightmap},set:function(e){this._castShadowsLightmap=e}},{key:"lightmapSizeMultiplier",get:function(){return this._lightmapSizeMultiplier},set:function(e){this._lightmapSizeMultiplier=e}},{key:"isStatic",get:function(){return this._isStatic},set:function(e){if(this._isStatic!==e&&(this._isStatic=e,this._model))for(var t=this._model.meshInstances,i=0;i<t.length;i++){t[i].isStatic=e}}},{key:"layers",get:function(){return this._layers},set:function(e){var t=this.system.app.scene.layers;if(this.meshInstances)for(var i=0;i<this._layers.length;i++){var n=t.getLayerById(this._layers[i]);n&&n.removeMeshInstances(this.meshInstances)}this._layers.length=0;for(var s=0;s<e.length;s++)this._layers[s]=e[s];if(this.enabled&&this.entity.enabled&&this.meshInstances)for(var r=0;r<this._layers.length;r++){var a=t.getLayerById(this._layers[r]);a&&a.addMeshInstances(this.meshInstances)}}},{key:"batchGroupId",get:function(){return this._batchGroupId},set:function(e){if(this._batchGroupId!==e){var t,i;if(this.entity.enabled&&this._batchGroupId>=0)null==(t=this.system.app.batcher)||t.remove(ya.MODEL,this.batchGroupId,this.entity);if(this.entity.enabled&&e>=0)null==(i=this.system.app.batcher)||i.insert(ya.MODEL,e,this.entity);e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addModelToLayers(),this._batchGroupId=e}}},{key:"materialAsset",get:function(){return this._materialAsset},set:function(e){var t=e;e instanceof ml&&(t=e.id);var i=this.system.app.assets;if(t!==this._materialAsset){if(this._materialAsset){i.off("add:"+this._materialAsset,this._onMaterialAssetAdd,this);var n=i.get(this._materialAsset);n&&this._unbindMaterialAsset(n)}if(this._materialAsset=t,this._materialAsset){var s=i.get(this._materialAsset);s?this._bindMaterialAsset(s):(this._setMaterial(this.system.defaultMaterial),i.on("add:"+this._materialAsset,this._onMaterialAssetAdd,this))}else this._setMaterial(this.system.defaultMaterial)}}},{key:"material",get:function(){return this._material},set:function(e){this._material!==e&&(this.materialAsset=null,this._setMaterial(e))}},{key:"mapping",get:function(){return this._mapping},set:function(e){if("asset"===this._type&&(this._unsetMaterialEvents(),e||(e={}),this._mapping=e,this._model))for(var t=this._model.meshInstances,i=this.asset?this.system.app.assets.get(this.asset):null,n=i?i.data.mapping:null,s=null,r=0,a=t.length;r<a;r++)if(void 0!==e[r])e[r]?(s=this.system.app.assets.get(e[r]),this._loadAndSetMeshInstanceMaterial(s,t[r],r)):t[r].material=this.system.defaultMaterial;else if(n)if(n[r]&&(n[r].material||n[r].path)){if(void 0!==n[r].material)s=this.system.app.assets.get(n[r].material);else if(void 0!==n[r].path){var o=this._getMaterialAssetUrl(n[r].path);o&&(s=this.system.app.assets.getByUrl(o))}this._loadAndSetMeshInstanceMaterial(s,t[r],r)}else t[r].material=this.system.defaultMaterial}}]),t}(Cl),kv=function(){this.enabled=!0},Ov=["enabled"],Fv=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="model",i.ComponentType=Dv,i.DataType=kv,i.schema=Ov,i.defaultMaterial=ks(t.graphicsDevice),i.on("beforeremove",i.onRemove,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){n=["material","materialAsset","asset","castShadows","receiveShadows","castShadowsLightmap","lightmapped","lightmapSizeMultiplier","type","mapping","layers","isStatic","batchGroupId"],null!==i.batchGroupId&&void 0!==i.batchGroupId||(i.batchGroupId=-1),i.layers&&i.layers.length&&(i.layers=i.layers.slice(0));for(var s=0;s<n.length;s++)i.hasOwnProperty(n[s])&&(t[n[s]]=i[n[s]]);i.aabbCenter&&i.aabbHalfExtents&&(t.customAabb=new Oe(new ye(i.aabbCenter),new ye(i.aabbHalfExtents))),e.prototype.initializeComponentData.call(this,t,i,["enabled"])},i.cloneComponent=function(e,t){var i={type:e.model.type,asset:e.model.asset,castShadows:e.model.castShadows,receiveShadows:e.model.receiveShadows,castShadowsLightmap:e.model.castShadowsLightmap,lightmapped:e.model.lightmapped,lightmapSizeMultiplier:e.model.lightmapSizeMultiplier,isStatic:e.model.isStatic,enabled:e.model.enabled,layers:e.model.layers,batchGroupId:e.model.batchGroupId,mapping:f({},e.model.mapping)},n=e.model.materialAsset;n instanceof ml||null==n||(n=this.app.assets.get(n));var s=e.model.material;s&&s!==this.defaultMaterial&&n&&s!==n.resource||(i.materialAsset=n);var r=this.addComponent(t,i);if(e.model.model&&"asset"===e.model.type&&!e.model.asset&&(r.model=e.model.model.clone(),r._clonedModel=!0),i.materialAsset||(r.material=s),e.model.model)for(var a=e.model.model.meshInstances,o=r.model.meshInstances,h=0;h<a.length;h++)o[h].mask=a[h].mask,o[h].material=a[h].material,o[h].layer=a[h].layer,o[h].receiveShadow=a[h].receiveShadow;return e.model.customAabb&&(r.customAabb=e.model.customAabb.clone()),r},i.onRemove=function(e,t){t.onRemove()},t}(h_);Cl._buildAccessors(Dv.prototype,Ov);var Bv,Nv=["emitterExtents","emitterRadius","emitterExtentsInner","emitterRadiusInner","loop","initialVelocity","animSpeed","normalMap","particleNormal"],Uv=["numParticles","lifetime","rate","rate2","startAngle","startAngle2","lighting","halfLambert","intensity","wrap","wrapBounds","depthWrite","noFog","sort","stretch","alignToMotion","preWarm","emitterShape","animTilesX","animTilesY","animStartFrame","animNumFrames","animNumAnimations","animIndex","randomizeAnimIndex","animLoop","colorMap","localSpace","screenSpace","orientation"],zv=["scaleGraph","scaleGraph2","colorGraph","colorGraph2","alphaGraph","alphaGraph2","velocityGraph","velocityGraph2","localVelocityGraph","localVelocityGraph2","rotationSpeedGraph","rotationSpeedGraph2","radialSpeedGraph","radialSpeedGraph2"],Vv=["colorMapAsset","normalMapAsset","meshAsset","renderAsset"],Gv=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._requestedDepth=!1,n._drawOrder=0,n.on("set_colorMapAsset",n.onSetColorMapAsset,te(n)),n.on("set_normalMapAsset",n.onSetNormalMapAsset,te(n)),n.on("set_meshAsset",n.onSetMeshAsset,te(n)),n.on("set_mesh",n.onSetMesh,te(n)),n.on("set_renderAsset",n.onSetRenderAsset,te(n)),n.on("set_loop",n.onSetLoop,te(n)),n.on("set_blendType",n.onSetBlendType,te(n)),n.on("set_depthSoftening",n.onSetDepthSoftening,te(n)),n.on("set_layers",n.onSetLayers,te(n)),Nv.forEach((function(e){n.on("set_"+e,n.onSetSimpleProperty,te(n))})),Uv.forEach((function(e){n.on("set_"+e,n.onSetComplexProperty,te(n))})),zv.forEach((function(e){n.on("set_"+e,n.onSetGraphProperty,te(n))})),n}J(t,e);var i=t.prototype;return i.addMeshInstanceToLayers=function(){if(this.emitter)for(var e=0;e<this.layers.length;e++){var t=this.system.app.scene.layers.getLayerById(this.layers[e]);t&&(t.addMeshInstances([this.emitter.meshInstance]),this.emitter._layer=t)}},i.removeMeshInstanceFromLayers=function(){if(this.emitter)for(var e=0;e<this.layers.length;e++){var t=this.system.app.scene.layers.getLayerById(this.layers[e]);t&&t.removeMeshInstances([this.emitter.meshInstance])}},i.onSetLayers=function(e,t,i){if(this.emitter){for(var n=0;n<t.length;n++){var s=this.system.app.scene.layers.getLayerById(t[n]);s&&s.removeMeshInstances([this.emitter.meshInstance])}if(this.enabled&&this.entity.enabled)for(var r=0;r<i.length;r++){var a=this.system.app.scene.layers.getLayerById(i[r]);a&&a.addMeshInstances([this.emitter.meshInstance])}}},i.onLayersChanged=function(e,t){this.addMeshInstanceToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(e){this.emitter&&(this.layers.indexOf(e.id)<0||e.addMeshInstances([this.emitter.meshInstance]))},i.onLayerRemoved=function(e){this.emitter&&(this.layers.indexOf(e.id)<0||e.removeMeshInstances([this.emitter.meshInstance]))},i._bindColorMapAsset=function(e){if(e.on("load",this._onColorMapAssetLoad,this),e.on("unload",this._onColorMapAssetUnload,this),e.on("remove",this._onColorMapAssetRemove,this),e.on("change",this._onColorMapAssetChange,this),e.resource)this._onColorMapAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}},i._unbindColorMapAsset=function(e){e.off("load",this._onColorMapAssetLoad,this),e.off("unload",this._onColorMapAssetUnload,this),e.off("remove",this._onColorMapAssetRemove,this),e.off("change",this._onColorMapAssetChange,this)},i._onColorMapAssetLoad=function(e){this.colorMap=e.resource},i._onColorMapAssetUnload=function(e){this.colorMap=null},i._onColorMapAssetRemove=function(e){this._onColorMapAssetUnload(e)},i._onColorMapAssetChange=function(e){},i.onSetColorMapAsset=function(e,t,i){var n=this,s=this.system.app.assets;if(t){var r=s.get(t);r&&this._unbindColorMapAsset(r)}if(i){i instanceof ml&&(this.data.colorMapAsset=i.id,i=i.id);var a=s.get(i);a?this._bindColorMapAsset(a):s.once("add:"+i,(function(e){n._bindColorMapAsset(e)}))}else this.colorMap=null},i._bindNormalMapAsset=function(e){if(e.on("load",this._onNormalMapAssetLoad,this),e.on("unload",this._onNormalMapAssetUnload,this),e.on("remove",this._onNormalMapAssetRemove,this),e.on("change",this._onNormalMapAssetChange,this),e.resource)this._onNormalMapAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}},i._unbindNormalMapAsset=function(e){e.off("load",this._onNormalMapAssetLoad,this),e.off("unload",this._onNormalMapAssetUnload,this),e.off("remove",this._onNormalMapAssetRemove,this),e.off("change",this._onNormalMapAssetChange,this)},i._onNormalMapAssetLoad=function(e){this.normalMap=e.resource},i._onNormalMapAssetUnload=function(e){this.normalMap=null},i._onNormalMapAssetRemove=function(e){this._onNormalMapAssetUnload(e)},i._onNormalMapAssetChange=function(e){},i.onSetNormalMapAsset=function(e,t,i){var n=this,s=this.system.app.assets;if(t){var r=s.get(t);r&&this._unbindNormalMapAsset(r)}if(i){i instanceof ml&&(this.data.normalMapAsset=i.id,i=i.id);var a=s.get(i);a?this._bindNormalMapAsset(a):s.once("add:"+i,(function(e){n._bindNormalMapAsset(e)}))}else this.normalMap=null},i._bindMeshAsset=function(e){if(e.on("load",this._onMeshAssetLoad,this),e.on("unload",this._onMeshAssetUnload,this),e.on("remove",this._onMeshAssetRemove,this),e.on("change",this._onMeshAssetChange,this),e.resource)this._onMeshAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}},i._unbindMeshAsset=function(e){e.off("load",this._onMeshAssetLoad,this),e.off("unload",this._onMeshAssetUnload,this),e.off("remove",this._onMeshAssetRemove,this),e.off("change",this._onMeshAssetChange,this)},i._onMeshAssetLoad=function(e){this._onMeshChanged(e.resource)},i._onMeshAssetUnload=function(e){this.mesh=null},i._onMeshAssetRemove=function(e){this._onMeshAssetUnload(e)},i._onMeshAssetChange=function(e){},i.onSetMeshAsset=function(e,t,i){var n=this.system.app.assets;if(t){var s=n.get(t);s&&this._unbindMeshAsset(s)}if(i){i instanceof ml&&(this.data.meshAsset=i.id,i=i.id);var r=n.get(i);r&&this._bindMeshAsset(r)}else this._onMeshChanged(null)},i.onSetMesh=function(e,t,i){!i||i instanceof ml||"number"==typeof i?this.meshAsset=i:this._onMeshChanged(i)},i._onMeshChanged=function(e){!e||e instanceof ea||(e=e.meshInstances[0]?e.meshInstances[0].mesh:null),this.data.mesh=e,this.emitter&&(this.emitter.mesh=e,this.emitter.resetMaterial(),this.rebuild())},i.onSetRenderAsset=function(e,t,i){var n=this.system.app.assets;if(t){var s=n.get(t);s&&this._unbindRenderAsset(s)}if(i){i instanceof ml&&(this.data.renderAsset=i.id,i=i.id);var r=n.get(i);r&&this._bindRenderAsset(r)}else this._onRenderChanged(null)},i._bindRenderAsset=function(e){if(e.on("load",this._onRenderAssetLoad,this),e.on("unload",this._onRenderAssetUnload,this),e.on("remove",this._onRenderAssetRemove,this),e.resource)this._onRenderAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}},i._unbindRenderAsset=function(e){e.off("load",this._onRenderAssetLoad,this),e.off("unload",this._onRenderAssetUnload,this),e.off("remove",this._onRenderAssetRemove,this),e.resource&&e.resource.off("set:meshes",this._onRenderSetMeshes,this)},i._onRenderAssetLoad=function(e){this._onRenderChanged(e.resource)},i._onRenderAssetUnload=function(e){this._onRenderChanged(null)},i._onRenderAssetRemove=function(e){this._onRenderAssetUnload(e)},i._onRenderChanged=function(e){e?(e.off("set:meshes",this._onRenderSetMeshes,this),e.on("set:meshes",this._onRenderSetMeshes,this),e.meshes&&this._onRenderSetMeshes(e.meshes)):this._onMeshChanged(null)},i._onRenderSetMeshes=function(e){this._onMeshChanged(e&&e[0])},i.onSetLoop=function(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetTime())},i.onSetBlendType=function(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.material.blendType=i,this.emitter.resetMaterial(),this.rebuild())},i._requestDepth=function(){this._requestedDepth||(Bv||(Bv=this.system.app.scene.layers.getLayerById(1)),Bv&&(Bv.incrementCounter(),this._requestedDepth=!0))},i._releaseDepth=function(){this._requestedDepth&&Bv&&(Bv.decrementCounter(),this._requestedDepth=!1)},i.onSetDepthSoftening=function(e,t,i){t!==i&&(i?(this.enabled&&this.entity.enabled&&this._requestDepth(),this.emitter&&(this.emitter[e]=i)):(this.enabled&&this.entity.enabled&&this._releaseDepth(),this.emitter&&(this.emitter[e]=i)),this.emitter&&(this.reset(),this.emitter.resetMaterial(),this.rebuild()))},i.onSetSimpleProperty=function(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetMaterial())},i.onSetComplexProperty=function(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetMaterial(),this.rebuild(),this.reset())},i.onSetGraphProperty=function(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.rebuildGraphs(),this.emitter.resetMaterial())},i.onEnable=function(){for(var e=this.data,t=0,i=Vv.length;t<i;t++){var n=e[Vv[t]];if(n){if(!(n instanceof ml)){if(!(parseInt(n,10)>=0))continue;n=this.system.app.assets.get(n)}n&&!n.resource&&this.system.app.assets.load(n)}}if(!this.emitter){var s=e.mesh;s instanceof ea||(s=null),this.emitter=new su(this.system.app.graphicsDevice,{numParticles:e.numParticles,emitterExtents:e.emitterExtents,emitterExtentsInner:e.emitterExtentsInner,emitterRadius:e.emitterRadius,emitterRadiusInner:e.emitterRadiusInner,emitterShape:e.emitterShape,initialVelocity:e.initialVelocity,wrap:e.wrap,localSpace:e.localSpace,screenSpace:e.screenSpace,wrapBounds:e.wrapBounds,lifetime:e.lifetime,rate:e.rate,rate2:e.rate2,orientation:e.orientation,particleNormal:e.particleNormal,animTilesX:e.animTilesX,animTilesY:e.animTilesY,animStartFrame:e.animStartFrame,animNumFrames:e.animNumFrames,animNumAnimations:e.animNumAnimations,animIndex:e.animIndex,randomizeAnimIndex:e.randomizeAnimIndex,animSpeed:e.animSpeed,animLoop:e.animLoop,startAngle:e.startAngle,startAngle2:e.startAngle2,scaleGraph:e.scaleGraph,scaleGraph2:e.scaleGraph2,colorGraph:e.colorGraph,colorGraph2:e.colorGraph2,alphaGraph:e.alphaGraph,alphaGraph2:e.alphaGraph2,localVelocityGraph:e.localVelocityGraph,localVelocityGraph2:e.localVelocityGraph2,velocityGraph:e.velocityGraph,velocityGraph2:e.velocityGraph2,rotationSpeedGraph:e.rotationSpeedGraph,rotationSpeedGraph2:e.rotationSpeedGraph2,radialSpeedGraph:e.radialSpeedGraph,radialSpeedGraph2:e.radialSpeedGraph2,colorMap:e.colorMap,normalMap:e.normalMap,loop:e.loop,preWarm:e.preWarm,sort:e.sort,stretch:e.stretch,alignToMotion:e.alignToMotion,lighting:e.lighting,halfLambert:e.halfLambert,intensity:e.intensity,depthSoftening:e.depthSoftening,scene:this.system.app.scene,mesh:s,depthWrite:e.depthWrite,noFog:e.noFog,node:this.entity,blendType:e.blendType}),this.emitter.meshInstance.node=this.entity,this.emitter.drawOrder=this.drawOrder,e.autoPlay||(this.pause(),this.emitter.meshInstance.visible=!1)}this.emitter.colorMap&&this.addMeshInstanceToLayers(),this.system.app.scene.on("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.on("add",this.onLayerAdded,this),this.system.app.scene.layers.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&e.depthSoftening&&this._requestDepth()},i.onDisable=function(){this.system.app.scene.off("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.off("add",this.onLayerAdded,this),this.system.app.scene.layers.off("remove",this.onLayerRemoved,this)),this.emitter&&(this.removeMeshInstanceFromLayers(),this.data.depthSoftening&&this._releaseDepth(),this.emitter.camera=null)},i.onBeforeRemove=function(){this.enabled&&(this.enabled=!1),this.emitter&&(this.emitter.destroy(),this.emitter=null);for(var e=0;e<Vv.length;e++){var t=Vv[e];this.data[t]&&(this[t]=null)}this.off()},i.reset=function(){this.emitter&&this.emitter.reset()},i.stop=function(){this.emitter&&(this.emitter.loop=!1,this.emitter.resetTime(),this.emitter.addTime(0,!0))},i.pause=function(){this.data.paused=!0},i.unpause=function(){this.data.paused=!1},i.play=function(){this.data.paused=!1,this.emitter&&(this.emitter.meshInstance.visible=!0,this.emitter.loop=this.data.loop,this.emitter.resetTime())},i.isPlaying=function(){return!this.data.paused&&(!(!this.emitter||!this.emitter.loop)||Date.now()<=this.emitter.endTime)},i.rebuild=function(){var e=this.enabled;this.enabled=!1,this.emitter&&(this.emitter.rebuild(),this.emitter.meshInstance.node=this.entity),this.enabled=e},$(t,[{key:"drawOrder",get:function(){return this._drawOrder},set:function(e){this._drawOrder=e,this.emitter&&(this.emitter.drawOrder=e)}}]),t}(Cl),Wv=function(){this.numParticles=1,this.rate=1,this.rate2=null,this.startAngle=0,this.startAngle2=null,this.lifetime=50,this.emitterExtents=new ye,this.emitterExtentsInner=new ye,this.emitterRadius=0,this.emitterRadiusInner=0,this.emitterShape=0,this.initialVelocity=0,this.wrapBounds=new ye,this.localSpace=!1,this.screenSpace=!1,this.colorMap=null,this.colorMapAsset=null,this.normalMap=null,this.normalMapAsset=null,this.loop=!0,this.preWarm=!1,this.sort=0,this.mode=0,this.scene=null,this.lighting=!1,this.halfLambert=!1,this.intensity=1,this.stretch=0,this.alignToMotion=!1,this.depthSoftening=0,this.meshAsset=null,this.mesh=null,this.depthWrite=!1,this.noFog=!1,this.orientation=0,this.particleNormal=new ye(0,1,0),this.animTilesX=1,this.animTilesY=1,this.animStartFrame=0,this.animNumFrames=1,this.animNumAnimations=1,this.animIndex=0,this.randomizeAnimIndex=!1,this.animSpeed=1,this.animLoop=!0,this.scaleGraph=null,this.scaleGraph2=null,this.colorGraph=null,this.colorGraph2=null,this.alphaGraph=null,this.alphaGraph2=null,this.localVelocityGraph=null,this.localVelocityGraph2=null,this.velocityGraph=null,this.velocityGraph2=null,this.rotationSpeedGraph=null,this.rotationSpeedGraph2=null,this.radialSpeedGraph=null,this.radialSpeedGraph2=null,this.blendType=2,this.enabled=!0,this.paused=!1,this.autoPlay=!0,this.layers=[0]},Hv=["enabled","autoPlay","numParticles","lifetime","rate","rate2","startAngle","startAngle2","loop","preWarm","lighting","halfLambert","intensity","depthWrite","noFog","depthSoftening","sort","blendType","stretch","alignToMotion","emitterShape","emitterExtents","emitterExtentsInner","emitterRadius","emitterRadiusInner","initialVelocity","wrap","wrapBounds","localSpace","screenSpace","colorMapAsset","normalMapAsset","mesh","meshAsset","renderAsset","orientation","particleNormal","localVelocityGraph","localVelocityGraph2","velocityGraph","velocityGraph2","rotationSpeedGraph","rotationSpeedGraph2","radialSpeedGraph","radialSpeedGraph2","scaleGraph","scaleGraph2","colorGraph","colorGraph2","alphaGraph","alphaGraph2","colorMap","normalMap","animTilesX","animTilesY","animStartFrame","animNumFrames","animNumAnimations","animIndex","randomizeAnimIndex","animSpeed","animLoop","layers"],Xv=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="particlesystem",i.ComponentType=Gv,i.DataType=Wv,i.schema=Hv,i.propertyTypes={emitterExtents:"vec3",emitterExtentsInner:"vec3",particleNormal:"vec3",wrapBounds:"vec3",localVelocityGraph:"curveset",localVelocityGraph2:"curveset",velocityGraph:"curveset",velocityGraph2:"curveset",colorGraph:"curveset",colorGraph2:"curveset",alphaGraph:"curve",alphaGraph2:"curve",rotationSpeedGraph:"curve",rotationSpeedGraph2:"curve",radialSpeedGraph:"curve",radialSpeedGraph2:"curve",scaleGraph:"curve",scaleGraph2:"curve"},i.on("beforeremove",i.onBeforeRemove,te(i)),i.app.systems.on("update",i.onUpdate,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){var s={};n=[];var r=this.propertyTypes;for(var a in(i.mesh instanceof ml||"number"==typeof i.mesh)&&(i.meshAsset=i.mesh,delete i.mesh),i){if(i.hasOwnProperty(a)&&(n.push(a),s[a]=i[a]),"vec3"===r[a])Array.isArray(s[a])&&(s[a]=new ye(s[a][0],s[a][1],s[a][2]));else if("curve"===r[a]){if(!(s[a]instanceof ge)){var o=s[a].type;s[a]=new ge(s[a].keys),s[a].type=o}}else if("curveset"===r[a]&&!(s[a]instanceof ve)){var h=s[a].type;s[a]=new ve(s[a].keys),s[a].type=h}s.layers&&Array.isArray(s.layers)&&(s.layers=s.layers.slice(0))}e.prototype.initializeComponentData.call(this,t,s,n)},i.cloneComponent=function(e,t){for(var i=e.particlesystem.data,n=this.schema,s={},r=0,a=n.length;r<a;r++){var o=n[r],h=i[o];h instanceof ye||h instanceof ge||h instanceof ve?(h=h.clone(),s[o]=h):"layers"===o?s.layers=i.layers.slice(0):null!=h&&(s[o]=h)}return this.addComponent(t,s)},i.onUpdate=function(e){var t,i=this.store,n=this.app.stats.particles;for(var s in i)if(i.hasOwnProperty(s)){var r=i[s],a=r.entity,o=r.data;if(o.enabled&&a.enabled){var h=a.particlesystem.emitter;if(!h.meshInstance.visible)continue;if(h.lighting){for(var l=o.layers,c=void 0,u=0;u<l.length;u++){var d=this.app.scene.layers.getLayerById(l[u]);if(d){d._lightCube||(d._lightCube=new Float32Array(18)),c=d._lightCube;for(var f=0;f<6;f++)c[3*f]=this.app.scene.ambientLight.r,c[3*f+1]=this.app.scene.ambientLight.g,c[3*f+2]=this.app.scene.ambientLight.b;for(var p=d._splitLights[0],m=0;m<p.length;m++)for(var _=0;_<6;_++){var g=Math.max(h.lightCubeDir[_].dot(p[m]._direction),0)*p[m]._intensity;c[3*_]+=p[m]._color.r*g,c[3*_+1]+=p[m]._color.g*g,c[3*_+2]+=p[m]._color.b*g}}}h.constantLightCube.setValue(c)}if(!o.paused){if(h.simTime+=e,h.simTime>h.fixedTimeStep&&(t=Math.floor(h.simTime/h.fixedTimeStep),h.simTime-=t*h.fixedTimeStep),t){t=Math.min(t,h.maxSubSteps);for(var v=0;v<t;v++)h.addTime(h.fixedTimeStep,!1);n._updatesPerFrame+=t,n._frameTime+=h._addTimeTime,h._addTimeTime=0}h.finishFrame()}}}},i.onBeforeRemove=function(e,t){t.onBeforeRemove()},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},t}(h_);Cl._buildAccessors(Gv.prototype,Hv);var qv=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._type="asset",n._castShadows=!0,n._receiveShadows=!0,n._castShadowsLightmap=!0,n._lightmapped=!1,n._lightmapSizeMultiplier=1,n._isStatic=!1,n._batchGroupId=-1,n._layers=[0],n._renderStyle=0,n._meshInstances=[],n._customAabb=null,n._area=null,n._assetReference=[],n._materialReferences=[],n._material=void 0,n._rootBone=void 0,n._rootBone=new D_(te(n),"rootBone"),n._rootBone.on("set:entity",n._onSetRootBone,te(n)),n._assetReference=new hp("asset",te(n),t.app.assets,{add:n._onRenderAssetAdded,load:n._onRenderAssetLoad,remove:n._onRenderAssetRemove,unload:n._onRenderAssetUnload},te(n)),n._material=t.defaultMaterial,i.on("remove",n.onRemoveChild,te(n)),i.on("removehierarchy",n.onRemoveChild,te(n)),i.on("insert",n.onInsertChild,te(n)),i.on("inserthierarchy",n.onInsertChild,te(n)),n}J(t,e);var i=t.prototype;return i.assignAsset=function(e){var t=e instanceof ml?e.id:e;this._assetReference.id=t},i._onSetRootBone=function(e){e&&this._onRootBoneChanged()},i._onRootBoneChanged=function(){this._clearSkinInstances(),this.enabled&&this.entity.enabled&&this._cloneSkinInstances()},i.destroyMeshInstances=function(){var e=this._meshInstances;if(e){this.removeFromLayers(),this._clearSkinInstances();for(var t=0;t<e.length;t++)e[t].destroy();this._meshInstances.length=0}},i.addToLayers=function(){for(var e=this.system.app.scene.layers,t=0;t<this._layers.length;t++){var i=e.getLayerById(this._layers[t]);i&&i.addMeshInstances(this._meshInstances)}},i.removeFromLayers=function(){if(this._meshInstances&&this._meshInstances.length)for(var e=this.system.app.scene.layers,t=0;t<this._layers.length;t++){var i=e.getLayerById(this._layers[t]);i&&i.removeMeshInstances(this._meshInstances)}},i.onRemoveChild=function(){this.removeFromLayers()},i.onInsertChild=function(){this._meshInstances&&this.enabled&&this.entity.enabled&&this.addToLayers()},i.onRemove=function(){this.destroyMeshInstances(),this.asset=null,this.materialAsset=null,this._assetReference.id=null;for(var e=0;e<this._materialReferences.length;e++)this._materialReferences[e].id=null;this.entity.off("remove",this.onRemoveChild,this),this.entity.off("insert",this.onInsertChild,this)},i.onLayersChanged=function(e,t){this.addToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(e){this.layers.indexOf(e.id)<0||e.addMeshInstances(this._meshInstances)},i.onLayerRemoved=function(e){this.layers.indexOf(e.id)<0||e.removeMeshInstances(this._meshInstances)},i.onEnable=function(){var e=this.system.app,t=e.scene;this._rootBone.onParentComponentEnable(),this._cloneSkinInstances(),t.on("set:layers",this.onLayersChanged,this),t.layers&&(t.layers.on("add",this.onLayerAdded,this),t.layers.on("remove",this.onLayerRemoved,this));var i,n="asset"===this._type;this._meshInstances&&this._meshInstances.length?this.addToLayers():n&&this.asset&&this._onRenderAssetAdded();for(var s=0;s<this._materialReferences.length;s++)this._materialReferences[s].asset&&this.system.app.assets.load(this._materialReferences[s].asset);this._batchGroupId>=0&&(null==(i=e.batcher)||i.insert(ya.RENDER,this.batchGroupId,this.entity))},i.onDisable=function(){var e,t=this.system.app,i=t.scene;(i.off("set:layers",this.onLayersChanged,this),i.layers&&(i.layers.off("add",this.onLayerAdded,this),i.layers.off("remove",this.onLayerRemoved,this)),this._batchGroupId>=0)&&(null==(e=t.batcher)||e.remove(ya.RENDER,this.batchGroupId,this.entity));this.removeFromLayers()},i.hide=function(){if(this._meshInstances)for(var e=0;e<this._meshInstances.length;e++)this._meshInstances[e].visible=!1},i.show=function(){if(this._meshInstances)for(var e=0;e<this._meshInstances.length;e++)this._meshInstances[e].visible=!0},i._onRenderAssetAdded=function(){this._assetReference.asset&&(this._assetReference.asset.resource?this._onRenderAssetLoad():this.enabled&&this.entity.enabled&&this.system.app.assets.load(this._assetReference.asset))},i._onRenderAssetLoad=function(){if(this.destroyMeshInstances(),this._assetReference.asset){var e=this._assetReference.asset.resource;e.off("set:meshes",this._onSetMeshes,this),e.on("set:meshes",this._onSetMeshes,this),e.meshes&&this._onSetMeshes(e.meshes)}},i._onSetMeshes=function(e){this._cloneMeshes(e)},i._clearSkinInstances=function(){for(var e=0;e<this._meshInstances.length;e++){var t=this._meshInstances[e];Yd.removeCachedSkinInstance(t.skinInstance),t.skinInstance=null}},i._cloneSkinInstances=function(){if(this._meshInstances.length&&this._rootBone.entity instanceof Hn)for(var e=0;e<this._meshInstances.length;e++){var t=this._meshInstances[e],i=t.mesh;i.skin&&!t.skinInstance&&(t.skinInstance=Yd.createCachedSkinInstance(i.skin,this._rootBone.entity,this.entity))}},i._cloneMeshes=function(e){if(e&&e.length){for(var t=[],i=0;i<e.length;i++){var n=e[i],s=this._materialReferences[i]&&this._materialReferences[i].asset&&this._materialReferences[i].asset.resource,r=new ka(n,s||this.system.defaultMaterial,this.entity);t.push(r),n.morph&&(r.morphInstance=new oc(n.morph))}this.meshInstances=t,this._cloneSkinInstances()}},i._onRenderAssetUnload=function(){"asset"===this._type&&this.destroyMeshInstances()},i._onRenderAssetRemove=function(){this._assetReference.asset&&this._assetReference.asset.resource&&this._assetReference.asset.resource.off("set:meshes",this._onSetMeshes,this),this._onRenderAssetUnload()},i._onMaterialAdded=function(e,t,i){i.resource?this._onMaterialLoad(e,t,i):this.enabled&&this.entity.enabled&&this.system.app.assets.load(i)},i._updateMainMaterial=function(e,t){0===e&&(this.material=t)},i._onMaterialLoad=function(e,t,i){this._meshInstances[e]&&(this._meshInstances[e].material=i.resource),this._updateMainMaterial(e,i.resource)},i._onMaterialRemove=function(e,t,i){this._meshInstances[e]&&(this._meshInstances[e].material=this.system.defaultMaterial),this._updateMainMaterial(e,this.system.defaultMaterial)},i._onMaterialUnload=function(e,t,i){this._meshInstances[e]&&(this._meshInstances[e].material=this.system.defaultMaterial),this._updateMainMaterial(e,this.system.defaultMaterial)},i.resolveDuplicatedEntityReferenceProperties=function(e,t){e.rootBone&&t[e.rootBone]&&(this.rootBone=t[e.rootBone]),this._clearSkinInstances()},$(t,[{key:"renderStyle",get:function(){return this._renderStyle},set:function(e){this._renderStyle!==e&&(this._renderStyle=e,ka._prepareRenderStyleForArray(this._meshInstances,e))}},{key:"customAabb",get:function(){return this._customAabb},set:function(e){this._customAabb=e;var t=this._meshInstances;if(t)for(var i=0;i<t.length;i++)t[i].setCustomAabb(this._customAabb)}},{key:"type",get:function(){return this._type},set:function(e){if(this._type!==e&&(this._area=null,this._type=e,this.destroyMeshInstances(),"asset"!==e)){var t=this._material;t&&t!==this.system.defaultMaterial||(t=this._materialReferences[0]&&this._materialReferences[0].asset&&this._materialReferences[0].asset.resource);var i=ma(this.system.app.graphicsDevice,e);this._area=i.area,this.meshInstances=[new ka(i.mesh,t||this.system.defaultMaterial,this.entity)]}}},{key:"meshInstances",get:function(){return this._meshInstances},set:function(e){if(this.destroyMeshInstances(),this._meshInstances=e,this._meshInstances){for(var t=this._meshInstances,i=0;i<t.length;i++)t[i].node||(t[i].node=this.entity),t[i].castShadow=this._castShadows,t[i].receiveShadow=this._receiveShadows,t[i].isStatic=this._isStatic,t[i].renderStyle=this._renderStyle,t[i].setLightmapped(this._lightmapped),t[i].setCustomAabb(this._customAabb);this.enabled&&this.entity.enabled&&this.addToLayers()}}},{key:"lightmapped",get:function(){return this._lightmapped},set:function(e){if(e!==this._lightmapped){this._lightmapped=e;var t=this._meshInstances;if(t)for(var i=0;i<t.length;i++)t[i].setLightmapped(e)}}},{key:"castShadows",get:function(){return this._castShadows},set:function(e){if(this._castShadows!==e){var t=this._meshInstances;if(t){var i=this.layers,n=this.system.app.scene;if(this._castShadows&&!e)for(var s=0;s<i.length;s++){var r=n.layers.getLayerById(this.layers[s]);r&&r.removeShadowCasters(t)}for(var a=0;a<t.length;a++)t[a].castShadow=e;if(!this._castShadows&&e)for(var o=0;o<i.length;o++){var h=n.layers.getLayerById(i[o]);h&&h.addShadowCasters(t)}}this._castShadows=e}}},{key:"receiveShadows",get:function(){return this._receiveShadows},set:function(e){if(this._receiveShadows!==e){this._receiveShadows=e;var t=this._meshInstances;if(t)for(var i=0;i<t.length;i++)t[i].receiveShadow=e}}},{key:"castShadowsLightmap",get:function(){return this._castShadowsLightmap},set:function(e){this._castShadowsLightmap=e}},{key:"lightmapSizeMultiplier",get:function(){return this._lightmapSizeMultiplier},set:function(e){this._lightmapSizeMultiplier=e}},{key:"isStatic",get:function(){return this._isStatic},set:function(e){if(this._isStatic!==e){this._isStatic=e;var t=this._meshInstances;if(t)for(var i=0;i<t.length;i++)t[i].isStatic=e}}},{key:"layers",get:function(){return this._layers},set:function(e){var t,i=this.system.app.scene.layers;if(this._meshInstances)for(var n=0;n<this._layers.length;n++)(t=i.getLayerById(this._layers[n]))&&t.removeMeshInstances(this._meshInstances);this._layers.length=0;for(var s=0;s<e.length;s++)this._layers[s]=e[s];if(this.enabled&&this.entity.enabled&&this._meshInstances)for(var r=0;r<this._layers.length;r++)(t=i.getLayerById(this._layers[r]))&&t.addMeshInstances(this._meshInstances)}},{key:"batchGroupId",get:function(){return this._batchGroupId},set:function(e){if(this._batchGroupId!==e){var t,i;if(this.entity.enabled&&this._batchGroupId>=0)null==(t=this.system.app.batcher)||t.remove(ya.RENDER,this.batchGroupId,this.entity);if(this.entity.enabled&&e>=0)null==(i=this.system.app.batcher)||i.insert(ya.RENDER,e,this.entity);e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addToLayers(),this._batchGroupId=e}}},{key:"material",get:function(){return this._material},set:function(e){if(this._material!==e&&(this._material=e,this._meshInstances&&"asset"!==this._type))for(var t=0;t<this._meshInstances.length;t++)this._meshInstances[t].material=e}},{key:"materialAssets",get:function(){return this._materialReferences.map((function(e){return e.id}))},set:function(e){if(void 0===e&&(e=[]),this._materialReferences.length>e.length){for(var t=e.length;t<this._materialReferences.length;t++)this._materialReferences[t].id=null;this._materialReferences.length=e.length}for(var i=0;i<e.length;i++)if(this._materialReferences[i]||this._materialReferences.push(new hp(i,this,this.system.app.assets,{add:this._onMaterialAdded,load:this._onMaterialLoad,remove:this._onMaterialRemove,unload:this._onMaterialUnload},this)),e[i]){var n=e[i]instanceof ml?e[i].id:e[i];this._materialReferences[i].id!==n&&(this._materialReferences[i].id=n),this._materialReferences[i].asset&&this._onMaterialAdded(i,this,this._materialReferences[i].asset)}else this._materialReferences[i].id=null,this._meshInstances[i]&&(this._meshInstances[i].material=this.system.defaultMaterial)}},{key:"asset",get:function(){return this._assetReference.id},set:function(e){var t=e instanceof ml?e.id:e;this._assetReference.id!==t&&(this._assetReference.asset&&this._assetReference.asset.resource&&this._onRenderAssetRemove(),this._assetReference.id=t,this._assetReference.asset&&this._onRenderAssetAdded())}}]),t}(Cl),jv=function(){this.enabled=!0,this.rootBone=null},Yv=[{name:"rootBone",type:"entity"},"enabled"],Kv=["material","meshInstances","asset","materialAssets","castShadows","receiveShadows","castShadowsLightmap","lightmapped","lightmapSizeMultiplier","renderStyle","type","layers","isStatic","batchGroupId"],Zv=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="render",i.ComponentType=qv,i.DataType=jv,i.schema=Yv,i.defaultMaterial=ks(t.graphicsDevice),i.on("beforeremove",i.onRemove,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){null!==i.batchGroupId&&void 0!==i.batchGroupId||(i.batchGroupId=-1),i.layers&&i.layers.length&&(i.layers=i.layers.slice(0));for(var s=0;s<Kv.length;s++)i.hasOwnProperty(Kv[s])&&(t[Kv[s]]=i[Kv[s]]);i.aabbCenter&&i.aabbHalfExtents&&(t.customAabb=new Oe(new ye(i.aabbCenter),new ye(i.aabbHalfExtents))),e.prototype.initializeComponentData.call(this,t,i,Yv)},i.cloneComponent=function(e,t){for(var i={},n=0;n<Kv.length;n++)i[Kv[n]]=e.render[Kv[n]];i.enabled=e.render.enabled,delete i.meshInstances;var s=this.addComponent(t,i),r=e.render.meshInstances,a=r.map((function(e){return e.mesh}));s._onSetMeshes(a);for(var o=0;o<r.length;o++)s.meshInstances[o].material=r[o].material;return e.render.customAabb&&(s.customAabb=e.render.customAabb.clone()),s},i.onRemove=function(e,t){t.onRemove()},t}(h_);Cl._buildAccessors(qv.prototype,Yv);var $v,Qv,Jv,ey,ty,iy,ny,sy=function(){function e(e,t){this._constructor=e,this._pool=[],this._count=0,this._resize(t)}var t=e.prototype;return t._resize=function(e){if(e>this._pool.length)for(var t=this._pool.length;t<e;t++)this._pool[t]=new this._constructor},t.allocate=function(){return this._count>=this._pool.length&&this._resize(2*this._pool.length),this._pool[this._count++]},t.freeAll=function(){this._count=0},e}(),ry=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._angularDamping=0,n._angularFactor=new ye(1,1,1),n._angularVelocity=new ye,n._body=null,n._friction=.5,n._group=2,n._linearDamping=0,n._linearFactor=new ye(1,1,1),n._linearVelocity=new ye,n._mask=og,n._mass=1,n._restitution=0,n._rollingFriction=0,n._simulationEnabled=!1,n._type=ng,n}J(t,e),t.onLibraryLoaded=function(){"undefined"!=typeof Ammo&&($v=new Ammo.btTransform,Qv=new Ammo.btVector3,Jv=new Ammo.btVector3,ey=new Ammo.btQuaternion,ty=new Ammo.btVector3(0,0,0))};var i=t.prototype;return i.createBody=function(){var e,t=this.entity;if(t.collision&&(e=t.collision.shape,t.trigger&&(t.trigger.destroy(),delete t.trigger)),e){this._body&&this.system.onRemove(t,this);var i=this._type===sg?this._mass:0;this._getEntityTransform($v);var n=this.system.createBody(i,e,$v);if(n.setRestitution(this._restitution),n.setFriction(this._friction),n.setRollingFriction(this._rollingFriction),n.setDamping(this._linearDamping,this._angularDamping),this._type===sg){var s=this._linearFactor;Qv.setValue(s.x,s.y,s.z),n.setLinearFactor(Qv);var r=this._angularFactor;Qv.setValue(r.x,r.y,r.z),n.setAngularFactor(Qv)}else this._type===rg&&(n.setCollisionFlags(2|n.getCollisionFlags()),n.setActivationState(4));n.entity=t,this.body=n,this.enabled&&t.enabled&&this.enableSimulation()}},i.isActive=function(){return!!this._body&&this._body.isActive()},i.activate=function(){this._body&&this._body.activate()},i.enableSimulation=function(){var e=this.entity;if(e.collision&&e.collision.enabled&&!this._simulationEnabled){var t=this._body;if(t){switch(this.system.addBody(t,this._group,this._mask),this._type){case sg:this.system._dynamic.push(this),t.forceActivationState(1),this.syncEntityToBody();break;case rg:this.system._kinematic.push(this),t.forceActivationState(4);break;case ng:t.forceActivationState(1),this.syncEntityToBody()}"compound"===e.collision.type&&this.system._compounds.push(e.collision),t.activate(),this._simulationEnabled=!0}}},i.disableSimulation=function(){var e=this._body;if(e&&this._simulationEnabled){var t=this.system,i=t._compounds.indexOf(this.entity.collision);i>-1&&t._compounds.splice(i,1),(i=t._dynamic.indexOf(this))>-1&&t._dynamic.splice(i,1),(i=t._kinematic.indexOf(this))>-1&&t._kinematic.splice(i,1),t.removeBody(e),e.forceActivationState(5),this._simulationEnabled=!1}},i.applyForce=function(){var e,t,i,n,s,r;switch(arguments.length){case 1:e=arguments[0].x,t=arguments[0].y,i=arguments[0].z;break;case 2:e=arguments[0].x,t=arguments[0].y,i=arguments[0].z,n=arguments[1].x,s=arguments[1].y,r=arguments[1].z;break;case 3:e=arguments[0],t=arguments[1],i=arguments[2];break;case 6:e=arguments[0],t=arguments[1],i=arguments[2],n=arguments[3],s=arguments[4],r=arguments[5]}var a=this._body;a&&(a.activate(),Qv.setValue(e,t,i),void 0!==n?(Jv.setValue(n,s,r),a.applyForce(Qv,Jv)):a.applyForce(Qv,ty))},i.applyTorque=function(){var e,t,i;switch(arguments.length){case 1:e=arguments[0].x,t=arguments[0].y,i=arguments[0].z;break;case 3:e=arguments[0],t=arguments[1],i=arguments[2];break;default:return}var n=this._body;n&&(n.activate(),Qv.setValue(e,t,i),n.applyTorque(Qv))},i.applyImpulse=function(){var e,t,i,n,s,r;switch(arguments.length){case 1:e=arguments[0].x,t=arguments[0].y,i=arguments[0].z;break;case 2:e=arguments[0].x,t=arguments[0].y,i=arguments[0].z,n=arguments[1].x,s=arguments[1].y,r=arguments[1].z;break;case 3:e=arguments[0],t=arguments[1],i=arguments[2];break;case 6:e=arguments[0],t=arguments[1],i=arguments[2],n=arguments[3],s=arguments[4],r=arguments[5];break;default:return}var a=this._body;a&&(a.activate(),Qv.setValue(e,t,i),void 0!==n?(Jv.setValue(n,s,r),a.applyImpulse(Qv,Jv)):a.applyImpulse(Qv,ty))},i.applyTorqueImpulse=function(){var e,t,i;switch(arguments.length){case 1:e=arguments[0].x,t=arguments[0].y,i=arguments[0].z;break;case 3:e=arguments[0],t=arguments[1],i=arguments[2];break;default:return}var n=this._body;n&&(n.activate(),Qv.setValue(e,t,i),n.applyTorqueImpulse(Qv))},i.isStatic=function(){return this._type===ng},i.isStaticOrKinematic=function(){return this._type===ng||this._type===rg},i.isKinematic=function(){return this._type===rg},i._getEntityTransform=function(e){var t=this.entity,i=t.getPosition(),n=t.getRotation();Qv.setValue(i.x,i.y,i.z),ey.setValue(n.x,n.y,n.z,n.w),e.setOrigin(Qv),e.setRotation(ey)},i.syncEntityToBody=function(){var e=this._body;if(e){if(this._getEntityTransform($v),e.setWorldTransform($v),this._type===rg){var t=e.getMotionState();t&&t.setWorldTransform($v)}e.activate()}},i._updateDynamic=function(){var e=this._body;if(e.isActive()){var t=e.getMotionState();if(t){t.getWorldTransform($v);var i=$v.getOrigin(),n=$v.getRotation();this.entity.setPosition(i.x(),i.y(),i.z()),this.entity.setRotation(n.x(),n.y(),n.z(),n.w())}}},i._updateKinematic=function(){var e=this._body.getMotionState();e&&(this._getEntityTransform($v),e.setWorldTransform($v))},i.teleport=function(){arguments.length<3?(arguments[0]&&this.entity.setPosition(arguments[0]),arguments[1]&&(arguments[1]instanceof Pe?this.entity.setRotation(arguments[1]):this.entity.setEulerAngles(arguments[1]))):(6===arguments.length&&this.entity.setEulerAngles(arguments[3],arguments[4],arguments[5]),this.entity.setPosition(arguments[0],arguments[1],arguments[2])),this.syncEntityToBody()},i.onEnable=function(){this._body||this.createBody(),this.enableSimulation()},i.onDisable=function(){this.disableSimulation()},$(t,[{key:"angularDamping",get:function(){return this._angularDamping},set:function(e){this._angularDamping!==e&&(this._angularDamping=e,this._body&&this._body.setDamping(this._linearDamping,e))}},{key:"angularFactor",get:function(){return this._angularFactor},set:function(e){this._angularFactor.equals(e)||(this._angularFactor.copy(e),this._body&&this._type===sg&&(Qv.setValue(e.x,e.y,e.z),this._body.setAngularFactor(Qv)))}},{key:"angularVelocity",get:function(){if(this._body&&this._type===sg){var e=this._body.getAngularVelocity();this._angularVelocity.set(e.x(),e.y(),e.z())}return this._angularVelocity},set:function(e){this._body&&this._type===sg&&(this._body.activate(),Qv.setValue(e.x,e.y,e.z),this._body.setAngularVelocity(Qv),this._angularVelocity.copy(e))}},{key:"body",get:function(){return this._body},set:function(e){this._body!==e&&(this._body=e,e&&this._simulationEnabled&&e.activate())}},{key:"friction",get:function(){return this._friction},set:function(e){this._friction!==e&&(this._friction=e,this._body&&this._body.setFriction(e))}},{key:"group",get:function(){return this._group},set:function(e){this._group!==e&&(this._group=e,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()))}},{key:"linearDamping",get:function(){return this._linearDamping},set:function(e){this._linearDamping!==e&&(this._linearDamping=e,this._body&&this._body.setDamping(e,this._angularDamping))}},{key:"linearFactor",get:function(){return this._linearFactor},set:function(e){this._linearFactor.equals(e)||(this._linearFactor.copy(e),this._body&&this._type===sg&&(Qv.setValue(e.x,e.y,e.z),this._body.setLinearFactor(Qv)))}},{key:"linearVelocity",get:function(){if(this._body&&this._type===sg){var e=this._body.getLinearVelocity();this._linearVelocity.set(e.x(),e.y(),e.z())}return this._linearVelocity},set:function(e){this._body&&this._type===sg&&(this._body.activate(),Qv.setValue(e.x,e.y,e.z),this._body.setLinearVelocity(Qv),this._linearVelocity.copy(e))}},{key:"mask",get:function(){return this._mask},set:function(e){this._mask!==e&&(this._mask=e,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()))}},{key:"mass",get:function(){return this._mass},set:function(e){if(this._mass!==e&&(this._mass=e,this._body&&this._type===sg)){var t=this.enabled&&this.entity.enabled;t&&this.disableSimulation(),this._body.getCollisionShape().calculateLocalInertia(e,Qv),this._body.setMassProps(e,Qv),this._body.updateInertiaTensor(),t&&this.enableSimulation()}}},{key:"restitution",get:function(){return this._restitution},set:function(e){this._restitution!==e&&(this._restitution=e,this._body&&this._body.setRestitution(e))}},{key:"rollingFriction",get:function(){return this._rollingFriction},set:function(e){this._rollingFriction!==e&&(this._rollingFriction=e,this._body&&this._body.setRollingFriction(e))}},{key:"type",get:function(){return this._type},set:function(e){if(this._type!==e){switch(this._type=e,this.disableSimulation(),e){case sg:this._group=1,this._mask=ag;break;case rg:this._group=4,this._mask=ag;break;default:this._group=2,this._mask=og}this.createBody()}}}]),t}(Cl),ay=function(){this.enabled=!0},oy=function(e,t,i){this.entity=e,this.point=t,this.normal=i},hy=function(e,t,i){0===arguments.length?(this.a=null,this.b=null,this.impulse=0,this.localPointA=new ye,this.localPointB=new ye,this.pointA=new ye,this.pointB=new ye,this.normal=new ye):(this.a=e,this.b=t,this.impulse=i.impulse,this.localPointA=i.localPoint,this.localPointB=i.localPointOther,this.pointA=i.point,this.pointB=i.pointOther,this.normal=i.normal)},ly=function(e,t,i,n,s,r){void 0===e&&(e=new ye),void 0===t&&(t=new ye),void 0===i&&(i=new ye),void 0===n&&(n=new ye),void 0===s&&(s=new ye),void 0===r&&(r=0),this.localPoint=e,this.localPointOther=t,this.point=i,this.pointOther=n,this.normal=s,this.impulse=r},cy=function(e,t){this.other=e,this.contacts=t},uy=["enabled"],dy=function(e){function t(t){var i;return(i=e.call(this,t)||this).maxSubSteps=10,i.fixedTimeStep=1/60,i.gravity=new ye(0,-9.81,0),i._dynamic=[],i._kinematic=[],i._triggers=[],i._compounds=[],i.id="rigidbody",i._stats=t.stats.frame,i.ComponentType=ry,i.DataType=ay,i.contactPointPool=null,i.contactResultPool=null,i.singleContactResultPool=null,i.schema=uy,i.collisions={},i.frameCollisions={},i.on("beforeremove",i.onBeforeRemove,te(i)),i.on("remove",i.onRemove,te(i)),i}J(t,e);var i=t.prototype;return i.onLibraryLoaded=function(){if("undefined"!=typeof Ammo){if(this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.overlappingPairCache=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.dynamicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.overlappingPairCache,this.solver,this.collisionConfiguration),this.dynamicsWorld.setInternalTickCallback){var e=Ammo.addFunction(this._checkForCollisions.bind(this),"vif");this.dynamicsWorld.setInternalTickCallback(e)}iy=new Ammo.btVector3,ny=new Ammo.btVector3,ry.onLibraryLoaded(),this.contactPointPool=new sy(ly,1),this.contactResultPool=new sy(cy,1),this.singleContactResultPool=new sy(hy,1),this.app.systems.on("update",this.onUpdate,this)}else this.app.systems.off("update",this.onUpdate,this)},i.initializeComponentData=function(t,i,n){for(var s=0,r=["mass","linearDamping","angularDamping","linearFactor","angularFactor","friction","rollingFriction","restitution","type","group","mask"];s<r.length;s++){var a=r[s];if(i.hasOwnProperty(a)){var o=i[a];Array.isArray(o)?t[a]=new ye(o[0],o[1],o[2]):t[a]=o}}e.prototype.initializeComponentData.call(this,t,i,["enabled"])},i.cloneComponent=function(e,t){var i=e.rigidbody,n={enabled:i.enabled,mass:i.mass,linearDamping:i.linearDamping,angularDamping:i.angularDamping,linearFactor:[i.linearFactor.x,i.linearFactor.y,i.linearFactor.z],angularFactor:[i.angularFactor.x,i.angularFactor.y,i.angularFactor.z],friction:i.friction,rollingFriction:i.rollingFriction,restitution:i.restitution,type:i.type,group:i.group,mask:i.mask};return this.addComponent(t,n)},i.onBeforeRemove=function(e,t){t.enabled&&(t.enabled=!1)},i.onRemove=function(e,t){var i=t.body;i&&(this.removeBody(i),this.destroyBody(i),t.body=null)},i.addBody=function(e,t,i){void 0!==t&&void 0!==i?this.dynamicsWorld.addRigidBody(e,t,i):this.dynamicsWorld.addRigidBody(e)},i.removeBody=function(e){this.dynamicsWorld.removeRigidBody(e)},i.createBody=function(e,t,i){var n=new Ammo.btVector3(0,0,0);0!==e&&t.calculateLocalInertia(e,n);var s=new Ammo.btDefaultMotionState(i),r=new Ammo.btRigidBodyConstructionInfo(e,s,t,n),a=new Ammo.btRigidBody(r);return Ammo.destroy(r),Ammo.destroy(n),a},i.destroyBody=function(e){var t=e.getMotionState();t&&Ammo.destroy(t),Ammo.destroy(e)},i.raycastFirst=function(e,t){var i=null;iy.setValue(e.x,e.y,e.z),ny.setValue(t.x,t.y,t.z);var n=new Ammo.ClosestRayResultCallback(iy,ny);if(this.dynamicsWorld.rayTest(iy,ny,n),n.hasHit()){var s=n.get_m_collisionObject(),r=Ammo.castObject(s,Ammo.btRigidBody);if(r){var a=n.get_m_hitPointWorld(),o=n.get_m_hitNormalWorld();if(i=new oy(r.entity,new ye(a.x(),a.y(),a.z()),new ye(o.x(),o.y(),o.z())),arguments.length>2){var h=arguments[2];h(i)}}}return Ammo.destroy(n),i},i.raycastAll=function(e,t){var i=[];iy.setValue(e.x,e.y,e.z),ny.setValue(t.x,t.y,t.z);var n=new Ammo.AllHitsRayResultCallback(iy,ny);if(this.dynamicsWorld.rayTest(iy,ny,n),n.hasHit())for(var s=n.get_m_collisionObjects(),r=n.get_m_hitPointWorld(),a=n.get_m_hitNormalWorld(),o=s.size(),h=0;h<o;h++){var l=Ammo.castObject(s.at(h),Ammo.btRigidBody);if(l){var c=r.at(h),u=a.at(h),d=new oy(l.entity,new ye(c.x(),c.y(),c.z()),new ye(u.x(),u.y(),u.z()));i.push(d)}}return Ammo.destroy(n),i},i._storeCollision=function(e,t){var i=!1,n=e.getGuid();return this.collisions[n]=this.collisions[n]||{others:[],entity:e},this.collisions[n].others.indexOf(t)<0&&(this.collisions[n].others.push(t),i=!0),this.frameCollisions[n]=this.frameCollisions[n]||{others:[],entity:e},this.frameCollisions[n].others.push(t),i},i._createContactPointFromAmmo=function(e){var t=e.get_m_localPointA(),i=e.get_m_localPointB(),n=e.getPositionWorldOnA(),s=e.getPositionWorldOnB(),r=e.get_m_normalWorldOnB(),a=this.contactPointPool.allocate();return a.localPoint.set(t.x(),t.y(),t.z()),a.localPointOther.set(i.x(),i.y(),i.z()),a.point.set(n.x(),n.y(),n.z()),a.pointOther.set(s.x(),s.y(),s.z()),a.normal.set(r.x(),r.y(),r.z()),a.impulse=e.getAppliedImpulse(),a},i._createReverseContactPointFromAmmo=function(e){var t=e.get_m_localPointA(),i=e.get_m_localPointB(),n=e.getPositionWorldOnA(),s=e.getPositionWorldOnB(),r=e.get_m_normalWorldOnB(),a=this.contactPointPool.allocate();return a.localPointOther.set(t.x(),t.y(),t.z()),a.localPoint.set(i.x(),i.y(),i.z()),a.pointOther.set(n.x(),n.y(),n.z()),a.point.set(s.x(),s.y(),s.z()),a.normal.set(r.x(),r.y(),r.z()),a.impulse=e.getAppliedImpulse(),a},i._createSingleContactResult=function(e,t,i){var n=this.singleContactResultPool.allocate();return n.a=e,n.b=t,n.localPointA=i.localPoint,n.localPointB=i.localPointOther,n.pointA=i.point,n.pointB=i.pointOther,n.normal=i.normal,n.impulse=i.impulse,n},i._createContactResult=function(e,t){var i=this.contactResultPool.allocate();return i.other=e,i.contacts=t,i},i._cleanOldCollisions=function(){for(var e in this.collisions)if(this.collisions.hasOwnProperty(e)){for(var t=this.frameCollisions[e],i=this.collisions[e],n=i.entity,s=n.collision,r=n.rigidbody,a=i.others,o=a.length;o--;){var h=a[o];(!t||t.others.indexOf(h)<0)&&(a.splice(o,1),n.trigger?(s&&s.fire("triggerleave",h),h.rigidbody&&h.rigidbody.fire("triggerleave",n)):h.trigger||(r&&r.fire("collisionend",h),s&&s.fire("collisionend",h)))}0===a.length&&delete this.collisions[e]}},i._hasContactEvent=function(e){var t=e.collision;if(t&&(t.hasEvent("collisionstart")||t.hasEvent("collisionend")||t.hasEvent("contact")))return!0;var i=e.rigidbody;return i&&(i.hasEvent("collisionstart")||i.hasEvent("collisionend")||i.hasEvent("contact"))},i._checkForCollisions=function(e,t){var i=Ammo.wrapPointer(e,Ammo.btDynamicsWorld).getDispatcher(),n=i.getNumManifolds();this.frameCollisions={};for(var s=0;s<n;s++){var r=i.getManifoldByIndexInternal(s),a=r.getBody0(),o=r.getBody1(),h=Ammo.castObject(a,Ammo.btRigidBody),l=Ammo.castObject(o,Ammo.btRigidBody),c=h.entity,u=l.entity;if(c&&u){var d=h.getCollisionFlags(),f=l.getCollisionFlags(),p=r.getNumContacts(),m=[],_=[],g=void 0;if(p>0)if(4&d||4&f){var v=c.collision&&(c.collision.hasEvent("triggerenter")||c.collision.hasEvent("triggerleave")),y=u.collision&&(u.collision.hasEvent("triggerenter")||u.collision.hasEvent("triggerleave")),x=c.rigidbody&&(c.rigidbody.hasEvent("triggerenter")||c.rigidbody.hasEvent("triggerleave")),b=u.rigidbody&&(u.rigidbody.hasEvent("triggerenter")||u.rigidbody.hasEvent("triggerleave"));v&&(!(g=this._storeCollision(c,u))||4&f||c.collision.fire("triggerenter",u)),y&&(!(g=this._storeCollision(u,c))||4&d||u.collision.fire("triggerenter",c)),x&&(g||(g=this._storeCollision(u,c)),g&&c.rigidbody.fire("triggerenter",u)),b&&(g||(g=this._storeCollision(c,u)),g&&u.rigidbody.fire("triggerenter",c))}else{var S=this._hasContactEvent(c),w=this._hasContactEvent(u),T=this.hasEvent("contact");if(T||S||w){for(var A=0;A<p;A++){var M=r.getContactPoint(A),C=this._createContactPointFromAmmo(M);if(S||w){m.push(C);var E=this._createReverseContactPointFromAmmo(M);_.push(E)}if(T){var P=this._createSingleContactResult(c,u,C);this.fire("contact",P)}}if(S){var R=this._createContactResult(u,m);g=this._storeCollision(c,u),c.collision&&(c.collision.fire("contact",R),g&&c.collision.fire("collisionstart",R)),c.rigidbody&&(c.rigidbody.fire("contact",R),g&&c.rigidbody.fire("collisionstart",R))}if(w){var I=this._createContactResult(c,_);g=this._storeCollision(u,c),u.collision&&(u.collision.fire("contact",I),g&&u.collision.fire("collisionstart",I)),u.rigidbody&&(u.rigidbody.fire("contact",I),g&&u.rigidbody.fire("collisionstart",I))}}}}}this._cleanOldCollisions(),this.contactPointPool.freeAll(),this.contactResultPool.freeAll(),this.singleContactResultPool.freeAll()},i.onUpdate=function(e){var t,i,n=this.dynamicsWorld.getGravity();n.x()===this.gravity.x&&n.y()===this.gravity.y&&n.z()===this.gravity.z||(n.setValue(this.gravity.x,this.gravity.y,this.gravity.z),this.dynamicsWorld.setGravity(n));var s=this._triggers;for(t=0,i=s.length;t<i;t++)s[t].updateTransform();var r=this._compounds;for(t=0,i=r.length;t<i;t++)r[t]._updateCompound();var a=this._kinematic;for(t=0,i=a.length;t<i;t++)a[t]._updateKinematic();this.dynamicsWorld.stepSimulation(e,this.maxSubSteps,this.fixedTimeStep);var o=this._dynamic;for(t=0,i=o.length;t<i;t++)o[t]._updateDynamic();this.dynamicsWorld.setInternalTickCallback||this._checkForCollisions(Ammo.getPointer(this.dynamicsWorld),e)},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this),"undefined"!=typeof Ammo&&(Ammo.destroy(this.dynamicsWorld),Ammo.destroy(this.solver),Ammo.destroy(this.overlappingPairCache),Ammo.destroy(this.dispatcher),Ammo.destroy(this.collisionConfiguration),this.dynamicsWorld=null,this.solver=null,this.overlappingPairCache=null,this.dispatcher=null,this.collisionConfiguration=null)},t}(h_);Cl._buildAccessors(ry.prototype,uy);var fy="none",py="blend",my=new Ee,_y=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._resolution=new be(640,320),n._referenceResolution=new be(640,320),n._scaleMode=fy,n.scale=1,n._scaleBlend=.5,n._priority=0,n._screenSpace=!1,n.cull=n._screenSpace,n._screenMatrix=new Ee,n._elements=new Set,t.app.graphicsDevice.on("resizecanvas",n._onResize,te(n)),n}J(t,e);var i=t.prototype;return i.syncDrawOrder=function(){this.system.queueDrawOrderSync(this.entity.getGuid(),this._processDrawOrderSync,this)},i._recurseDrawOrderSync=function(e,t){if(!(e instanceof $l))return t;if(e.element){var i,n=e.element.drawOrder;if(e.element.drawOrder=t++,e.element._batchGroupId>=0&&n!==e.element.drawOrder)null==(i=this.system.app.batcher)||i.markGroupDirty(e.element._batchGroupId)}e.particlesystem&&(e.particlesystem.drawOrder=t++);for(var s=e.children,r=0;r<s.length;r++)t=this._recurseDrawOrderSync(s[r],t);return t},i._processDrawOrderSync=function(){this._recurseDrawOrderSync(this.entity,1),this.fire("syncdraworder")},i._calcProjectionMatrix=function(){var e=this._resolution.x/this.scale,t=this._resolution.y/this.scale,i=e,n=-t;this._screenMatrix.setOrtho(0,i,n,0,1,-1),this._screenSpace||(my.setScale(.5*e,.5*t,1),this._screenMatrix.mul2(my,this._screenMatrix))},i._updateScale=function(){this.scale=this._calcScale(this._resolution,this.referenceResolution)},i._calcScale=function(e,t){var i=Math.log2(e.x/t.x),n=Math.log2(e.y/t.y);return Math.pow(2,i*(1-this._scaleBlend)+n*this._scaleBlend)},i._onResize=function(e,t){this._screenSpace&&(this._resolution.set(e,t),this.resolution=this._resolution)},i._bindElement=function(e){this._elements.add(e)},i._unbindElement=function(e){this._elements.delete(e)},i.onRemove=function(){this.system.app.graphicsDevice.off("resizecanvas",this._onResize,this),this.fire("remove"),this._elements.forEach((function(e){return e._onScreenRemove()})),this._elements.clear(),this.off()},$(t,[{key:"resolution",get:function(){return this._resolution},set:function(e){var t=this;this._screenSpace?this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height):this._resolution.set(e.x,e.y),this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:resolution",this._resolution),this._elements.forEach((function(e){return e._onScreenResize(t._resolution)}))}},{key:"referenceResolution",get:function(){return this._scaleMode===fy?this._resolution:this._referenceResolution},set:function(e){var t=this;this._referenceResolution.set(e.x,e.y),this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:referenceresolution",this._resolution),this._elements.forEach((function(e){return e._onScreenResize(t._resolution)}))}},{key:"screenSpace",get:function(){return this._screenSpace},set:function(e){this._screenSpace=e,this._screenSpace&&this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height),this.resolution=this._resolution,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:screenspace",this._screenSpace),this._elements.forEach((function(e){return e._onScreenSpaceChange()}))}},{key:"scaleMode",get:function(){return this._scaleMode},set:function(e){e!==fy&&e!==py&&(e=fy),this._screenSpace||e===fy||(e=fy),this._scaleMode=e,this.resolution=this._resolution,this.fire("set:scalemode",this._scaleMode)}},{key:"scaleBlend",get:function(){return this._scaleBlend},set:function(e){var t=this;this._scaleBlend=e,this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:scaleblend",this._scaleBlend),this._elements.forEach((function(e){return e._onScreenResize(t._resolution)}))}},{key:"priority",get:function(){return this._priority},set:function(e){e>255&&(e=255),this._priority!==e&&(this._priority=e,this.syncDrawOrder())}}]),t}(Cl),gy=function(){this.enabled=!0},vy=["enabled"],yy=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="screen",i.ComponentType=_y,i.DataType=gy,i.schema=vy,i.windowResolution=new be,i._drawOrderSyncQueue=new j,i.app.graphicsDevice.on("resizecanvas",i._onResize,te(i)),i.app.systems.on("update",i._onUpdate,te(i)),i.on("beforeremove",i.onRemoveComponent,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){void 0!==i.priority&&(t.priority=i.priority),void 0!==i.screenSpace&&(t.screenSpace=i.screenSpace),t.cull=t.screenSpace,void 0!==i.scaleMode&&(t.scaleMode=i.scaleMode),void 0!==i.scaleBlend&&(t.scaleBlend=i.scaleBlend),void 0!==i.resolution&&(i.resolution instanceof be?t._resolution.copy(i.resolution):t._resolution.set(i.resolution[0],i.resolution[1]),t.resolution=t._resolution),void 0!==i.referenceResolution&&(i.referenceResolution instanceof be?t._referenceResolution.copy(i.referenceResolution):t._referenceResolution.set(i.referenceResolution[0],i.referenceResolution[1]),t.referenceResolution=t._referenceResolution),t.syncDrawOrder(),e.prototype.initializeComponentData.call(this,t,i,n)},i.destroy=function(){e.prototype.destroy.call(this),this.app.graphicsDevice.off("resizecanvas",this._onResize,this),this.app.systems.off("update",this._onUpdate,this)},i._onUpdate=function(e){var t=this.store;for(var i in t)t[i].entity.screen.update&&t[i].entity.screen.update(e)},i._onResize=function(e,t){this.windowResolution.x=e,this.windowResolution.y=t},i.cloneComponent=function(e,t){var i=e.screen;return this.addComponent(t,{enabled:i.enabled,screenSpace:i.screenSpace,scaleMode:i.scaleMode,resolution:i.resolution.clone(),referenceResolution:i.referenceResolution.clone()})},i.onRemoveComponent=function(e,t){t.onRemove()},i.processDrawOrderSyncQueue=function(){for(var e=this._drawOrderSyncQueue.list(),t=0;t<e.length;t++){var i=e[t];i.callback.call(i.scope)}this._drawOrderSyncQueue.clear()},i.queueDrawOrderSync=function(e,t,i){this._drawOrderSyncQueue.list().length||this.app.once("prerender",this.processDrawOrderSyncQueue,this),this._drawOrderSyncQueue.has(e)||this._drawOrderSyncQueue.push(e,{callback:t,scope:i})},t}(h_);Cl._buildAccessors(_y.prototype,vy);var xy=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this).on("set_scripts",n.onSetScripts,te(n)),n}J(t,e);var i=t.prototype;return i.send=function(e,t){var i,n=Array.prototype.slice.call(arguments,2),s=this.entity.script.instances;if(s&&s[e]&&(i=s[e].instance[t]))return i.apply(s[e].instance,n)},i.onEnable=function(){this.data.areScriptsLoaded&&!this.system.preloading&&(this.data.initialized?this.system._enableScriptComponent(this):this.system._initializeScriptComponent(this),this.data.postInitialized||this.system._postInitializeScriptComponent(this))},i.onDisable=function(){this.system._disableScriptComponent(this)},i.onSetScripts=function(e,t,i){if(!this.system._inTools||this.runInTools){if(this._updateScriptAttributes(t,i))return;this.enabled&&this.system._disableScriptComponent(this),this.system._destroyScriptComponent(this),this.data.areScriptsLoaded=!1;var n=i.map((function(e){return e.url}));if(this._loadFromCache(n))return;this._loadScripts(n)}},i._updateScriptAttributes=function(e,t){var i=!0;if(e.length!==t.length)i=!1;else for(var n=0,s=t.length;n<s;n++)if(e[n].url!==t[n].url){i=!1;break}if(i)for(var r in this.instances)this.instances.hasOwnProperty(r)&&this.system._updateAccessors(this.entity,this.instances[r]);return i},i._loadFromCache=function(e){for(var t=[],i=this.system.app._scriptPrefix||"",n=/^http(s)?:\/\//i,s=0,r=e.length;s<r;s++){var a=e[s];n.test(a)||(a=v.join(i,a));var o=this.system.app.loader.getFromCache(a,"script");if(!o)return!1;t.push(o)}for(var h=0,l=t.length;h<l;h++){var c=t[h];if(!0!==c&&(c&&this.entity.script&&!this.entity.script.instances[c._pcScriptName])){var u=new c(this.entity);this.system._preRegisterInstance(this.entity,e[h],c._pcScriptName,u)}}return this.data&&(this.data.areScriptsLoaded=!0),this.system.preloading||(this.system.onInitialize(this.entity),this.system.onPostInitialize(this.entity)),!0},i._loadScripts=function(e){var t=this,i=e.length,n=this.system.app._scriptPrefix||"";e.forEach((function(e){var s=null,r=null;e.toLowerCase().startsWith("http://")||e.toLowerCase().startsWith("https://")?(r=e,s=e):(r=e,s=v.join(n,e)),t.system.app.loader.load(s,"script",(function(e,n){if(i--,e)console.error(e);else if(n&&t.entity.script&&!t.entity.script.instances[n._pcScriptName]){var s=new n(t.entity);t.system._preRegisterInstance(t.entity,r,n._pcScriptName,s)}0===i&&(t.data.areScriptsLoaded=!0,t.system.preloading||(t.system.onInitialize(t.entity),t.system.onPostInitialize(t.entity)))}))}))},t}(Cl),by=function(){this.scripts=[],this.enabled=!0,this.instances={},this._instances={},this.runInTools=!1,this.attributes={},this.initialized=!1,this.postInitialized=!1,this.areScriptsLoaded=!1},Sy=["enabled","scripts","instances","runInTools"],wy="initialize",Ty="postInitialize",Ay="update",My="postUpdate",Cy="fixedUpdate",Ey="toolsUpdate",Py=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="script",i.ComponentType=xy,i.DataType=by,i.schema=Sy,i.preloading=!1,i.instancesWithUpdate=[],i.instancesWithFixedUpdate=[],i.instancesWithPostUpdate=[],i.instancesWithToolsUpdate=[],i.on("beforeremove",i.onBeforeRemove,te(i)),i.app.systems.on(wy,i.onInitialize,te(i)),i.app.systems.on(Ty,i.onPostInitialize,te(i)),i.app.systems.on(Ay,i.onUpdate,te(i)),i.app.systems.on(Cy,i.onFixedUpdate,te(i)),i.app.systems.on(My,i.onPostUpdate,te(i)),i.app.systems.on(Ey,i.onToolsUpdate,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){n=["runInTools","enabled","scripts"],i.scripts&&i.scripts.length&&i.scripts.forEach((function(e){if(e.attributes&&Array.isArray(e.attributes)){for(var t={},i=0;i<e.attributes.length;i++)t[e.attributes[i].name]=e.attributes[i];e.attributes=t}})),e.prototype.initializeComponentData.call(this,t,i,n)},i.cloneComponent=function(e,t){for(var i=this.store[e.getGuid()],n={runInTools:i.data.runInTools,scripts:[],enabled:i.data.enabled},s=i.data.scripts,r=0,a=s.length;r<a;r++){var o=s[r].attributes;o&&delete s[r].attributes,n.scripts.push(f({},s[r])),o&&(n.scripts[r].attributes=this._cloneAttributes(o),s[r].attributes=o)}return this.addComponent(t,n)},i.onBeforeRemove=function(e,t){t.enabled&&this._disableScriptComponent(t),this._destroyScriptComponent(t)},i.onInitialize=function(e){if(this._registerInstances(e),e.enabled){e.script&&e.script.enabled&&this._initializeScriptComponent(e.script);for(var t=e._children,i=0,n=t.length;i<n;i++)t[i]instanceof $l&&this.onInitialize(t[i])}},i.onPostInitialize=function(e){if(e.enabled){e.script&&e.script.enabled&&this._postInitializeScriptComponent(e.script);for(var t=e._children,i=0,n=t.length;i<n;i++)t[i]instanceof $l&&this.onPostInitialize(t[i])}},i._callInstancesMethod=function(e,t){var i=e.data.instances;for(var n in i)if(i.hasOwnProperty(n)){var s=i[n].instance;s[t]&&s[t]()}},i._initializeScriptComponent=function(e){this._callInstancesMethod(e,wy),e.data.initialized=!0,e.enabled&&e.entity.enabled&&this._enableScriptComponent(e)},i._enableScriptComponent=function(e){this._callInstancesMethod(e,"onEnable")},i._disableScriptComponent=function(e){this._callInstancesMethod(e,"onDisable")},i._destroyScriptComponent=function(e){var t=e.data.instances;for(var i in t)if(t.hasOwnProperty(i)){var n=t[i].instance;if(n.destroy&&n.destroy(),n.update){var s=this.instancesWithUpdate.indexOf(n);s>=0&&this.instancesWithUpdate.splice(s,1)}if(n.fixedUpdate){var r=this.instancesWithFixedUpdate.indexOf(n);r>=0&&this.instancesWithFixedUpdate.splice(r,1)}if(n.postUpdate){var a=this.instancesWithPostUpdate.indexOf(n);a>=0&&this.instancesWithPostUpdate.splice(a,1)}if(n.toolsUpdate){var o=this.instancesWithToolsUpdate.indexOf(n);o>=0&&this.instancesWithToolsUpdate.splice(o,1)}e.instances[i].instance===e[i]&&delete e[i],delete e.instances[i]}},i._postInitializeScriptComponent=function(e){this._callInstancesMethod(e,Ty),e.data.postInitialized=!0},i._updateInstances=function(e,t,i){for(var n=0,s=t.length;n<s;n++){var r=t[n];r&&r.entity&&r.entity.enabled&&r.entity.script.enabled&&r[e](i)}},i.onUpdate=function(e){this._updateInstances(Ay,this.instancesWithUpdate,e)},i.onFixedUpdate=function(e){this._updateInstances(Cy,this.instancesWithFixedUpdate,e)},i.onPostUpdate=function(e){this._updateInstances(My,this.instancesWithPostUpdate,e)},i.onToolsUpdate=function(e){this._updateInstances(Ey,this.instancesWithToolsUpdate,e)},i.broadcast=function(e,t){var i=Array.prototype.slice.call(arguments,2),n=this.store;for(var s in n)if(n.hasOwnProperty(s)){var r=n[s].data;if(r.instances[e]){var a=r.instances[e].instance[t];a&&a.apply(r.instances[e].instance,i)}}},i._preRegisterInstance=function(e,t,i,n){if(e.script){if(e.script.data._instances=e.script.data._instances||{},e.script.data._instances[i])throw Error("Script name collision '"+i+"'. Scripts from '"+t+"' and '"+e.script.data._instances[i].url+"' {"+e.getGuid()+"}");e.script.data._instances[i]={url:t,name:i,instance:n}}},i._registerInstances=function(e){if(e.script&&e.script.data._instances){for(var t in e.script.instances=e.script.data._instances,e.script.instances){var i=e.script.instances[t],n=i.instance;if(_.attach(n),n.update&&this.instancesWithUpdate.push(n),n.fixedUpdate&&this.instancesWithFixedUpdate.push(n),n.postUpdate&&this.instancesWithPostUpdate.push(n),n.toolsUpdate&&this.instancesWithToolsUpdate.push(n),e.script.scripts&&this._createAccessors(e,i),e.script[t])throw Error("Script with name '"+t+"' is already attached to Script Component");e.script[t]=n}delete e.script.data._instances}for(var s=e._children,r=0,a=s.length;r<a;r++)s[r]instanceof $l&&this._registerInstances(s[r])},i._cloneAttributes=function(e){var t={};for(var i in e)if(e.hasOwnProperty(i))if("entity"!==e[i].type)t[i]=f({},e[i]);else{var n=e[i].value;delete e[i].value,t[i]=f({},e[i]),t[i].value=n,e[i].value=n}return t},i._createAccessors=function(e,t){for(var i=e.script.scripts.length,n=t.url,s=0;s<i;s++){var r=e.script.scripts[s];if(r.url===n){var a=r.attributes;if(r.name&&a){for(var o in a)a.hasOwnProperty(o)&&this._createAccessor(a[o],t);e.script.data.attributes[r.name]=this._cloneAttributes(a)}break}}},i._createAccessor=function(e,t){var i=this;e={name:e.name,value:e.value,type:e.type},this._convertAttributeValue(e),Object.defineProperty(t.instance,e.name,{get:function(){return e.value},set:function(n){var s=e.value;e.value=n,i._convertAttributeValue(e),t.instance.fire("set",e.name,s,e.value)},configurable:!0})},i._updateAccessors=function(e,t){for(var i=e.script.scripts.length,n=t.url,s=0;s<i;s++){var r=e.script,a=r.scripts[s];if(a.url===n){var o=a.name,h=a.attributes;if(o){if(h)for(var l in h)h.hasOwnProperty(l)&&this._createAccessor(h[l],t);var c=r.data.attributes[o];if(c)for(var u in c){var d=c[u];u in h?h[u].value!==d.value&&t.instance.onAttributeChanged&&t.instance.onAttributeChanged(d.name,d.value,h[u].value):delete t.instance[d.name]}h?r.data.attributes[o]=this._cloneAttributes(h):delete r.data.attributes[o]}break}}},i._convertAttributeValue=function(e){if("rgb"===e.type||"rgba"===e.type)Array.isArray(e.value)&&(e.value=3===e.value.length?new me(e.value[0],e.value[1],e.value[2]):new me(e.value[0],e.value[1],e.value[2],e.value[3]));else if("vec2"===e.type)Array.isArray(e.value)&&(e.value=new be(e.value[0],e.value[1]));else if("vec3"===e.type||"vector"===e.type)Array.isArray(e.value)&&(e.value=new ye(e.value[0],e.value[1],e.value[2]));else if("vec4"===e.type)Array.isArray(e.value)&&(e.value=new Se(e.value[0],e.value[1],e.value[2],e.value[3]));else if("entity"===e.type)null!==e.value&&"string"==typeof e.value&&(e.value=this.app.root.findByGuid(e.value));else if("curve"===e.type||"colorcurve"===e.type){var t=e.value.keys[0]instanceof Array?ve:ge;e.value=new t(e.value.keys),e.value.type=e.value.type}},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off(wy,this.onInitialize,this),this.app.systems.off(Ty,this.onPostInitialize,this),this.app.systems.off(Ay,this.onUpdate,this),this.app.systems.off(Cy,this.onFixedUpdate,this),this.app.systems.off(My,this.onPostUpdate,this),this.app.systems.off(Ey,this.onToolsUpdate,this)},t}(h_);Cl._buildAccessors(xy.prototype,Sy);var Ry=new be,Iy=new ye,Ly=new et,Dy=new ot,ky=new Pe,Oy={x:"y",y:"x"},Fy=function(e){function t(t,i){var n;if(n=e.call(this)||this,!(t&&t instanceof Jg))throw new Error("Element was null or not an ElementComponent");if(i&&"x"!==i&&"y"!==i)throw new Error("Unrecognized axis: "+i);return n._element=t,n._app=t.system.app,n._axis=i||null,n._enabled=!0,n._dragScale=new ye,n._dragStartMousePosition=new ye,n._dragStartHandlePosition=new ye,n._deltaMousePosition=new ye,n._deltaHandlePosition=new ye,n._isDragging=!1,n._toggleLifecycleListeners("on"),n}J(t,e);var i=t.prototype;return i._toggleLifecycleListeners=function(e){this._element[e]("mousedown",this._onMouseDownOrTouchStart,this),this._element[e]("touchstart",this._onMouseDownOrTouchStart,this)},i._toggleDragListeners=function(e){var t="on"===e;this._hasDragListeners&&t||(this._handleMouseUpOrTouchEnd||(this._handleMouseUpOrTouchEnd=this._onMouseUpOrTouchEnd.bind(this)),this._app.mouse&&(this._element[e]("mousemove",this._onMove,this),this._element[e]("mouseup",this._handleMouseUpOrTouchEnd,!1)),L.touch&&(this._element[e]("touchmove",this._onMove,this),this._element[e]("touchend",this._handleMouseUpOrTouchEnd,this),this._element[e]("touchcancel",this._handleMouseUpOrTouchEnd,this)),this._hasDragListeners=t)},i._onMouseDownOrTouchStart=function(e){if(this._element&&!this._isDragging&&this.enabled){this._dragCamera=e.camera,this._calculateDragScale();var t=this._screenToLocal(e);t&&(this._toggleDragListeners("on"),this._isDragging=!0,this._dragStartMousePosition.copy(t),this._dragStartHandlePosition.copy(this._element.entity.getLocalPosition()),this.fire("drag:start"))}},i._onMouseUpOrTouchEnd=function(){this._isDragging&&(this._isDragging=!1,this._toggleDragListeners("off"),this.fire("drag:end"))},i._screenToLocal=function(e){this._determineInputPosition(e),this._chooseRayOriginAndDirection(),Dy.point.copy(this._element.entity.getLocalPosition()),Dy.normal.copy(this._element.entity.forward).mulScalar(-1);var t=Dy.normal.dot(Ly.direction);if(Math.abs(t)>0){var i=Dy.point.sub(Ly.origin).dot(Dy.normal)/t,n=Ly.origin.add(Ly.direction.mulScalar(i));return ky.copy(this._element.entity.getRotation()).invert().transformVector(n,n),n.mul(this._dragScale),n}return null},i._determineInputPosition=function(e){var t=this._app.graphicsDevice.maxPixelRatio;void 0!==e.x&&void 0!==e.y?(Ry.x=e.x*t,Ry.y=e.y*t):e.changedTouches?(Ry.x=e.changedTouches[0].x*t,Ry.y=e.changedTouches[0].y*t):console.warn("Could not determine position from input event")},i._chooseRayOriginAndDirection=function(){this._element.screen&&this._element.screen.screen.screenSpace?(Ly.origin.set(Ry.x,-Ry.y,0),Ly.direction.copy(ye.FORWARD)):(Iy.copy(this._dragCamera.screenToWorld(Ry.x,Ry.y,1)),Ly.origin.copy(this._dragCamera.entity.getPosition()),Ly.direction.copy(Iy).sub(Ly.origin).normalize())},i._calculateDragScale=function(){var e=this._element.entity.parent,t=this._element.screen&&this._element.screen.screen,i=t&&t.screenSpace,n=i?t.scale:1,s=this._dragScale;for(s.set(n,n,n);e&&(s.mul(e.getLocalScale()),e=e.parent,!i||!e.screen););s.x=1/s.x,s.y=1/s.y,s.z=1/s.z},i._onMove=function(e){var t=this._element,i=this._deltaMousePosition,n=this._deltaHandlePosition,s=this._axis;if(t&&this._isDragging&&this.enabled&&t.enabled&&t.entity.enabled){var r=this._screenToLocal(e);if(r){if(i.sub2(r,this._dragStartMousePosition),n.add2(this._dragStartHandlePosition,i),s){var a=t.entity.getLocalPosition(),o=Oy[s];n[o]=a[o]}t.entity.setLocalPosition(n),this.fire("drag:move",n)}}},i.destroy=function(){this._toggleLifecycleListeners("off"),this._toggleDragListeners("off")},$(t,[{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"isDragging",get:function(){return this._isDragging}}]),t}(m),By=new be,Ny=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._viewportReference=new D_(te(n),"viewportEntity",{"element#gain":n._onViewportElementGain,"element#resize":n._onSetContentOrViewportSize}),n._contentReference=new D_(te(n),"contentEntity",{"element#gain":n._onContentElementGain,"element#lose":n._onContentElementLose,"element#resize":n._onSetContentOrViewportSize}),n._scrollbarUpdateFlags={},n._scrollbarReferences={},n._scrollbarReferences[0]=new D_(te(n),"horizontalScrollbarEntity",{"scrollbar#set:value":n._onSetHorizontalScrollbarValue,"scrollbar#gain":n._onHorizontalScrollbarGain}),n._scrollbarReferences[1]=new D_(te(n),"verticalScrollbarEntity",{"scrollbar#set:value":n._onSetVerticalScrollbarValue,"scrollbar#gain":n._onVerticalScrollbarGain}),n._prevContentSizes={},n._prevContentSizes[0]=null,n._prevContentSizes[1]=null,n._scroll=new be,n._velocity=new ye,n._dragStartPosition=new ye,n._disabledContentInput=!1,n._disabledContentInputEntities=[],n._toggleLifecycleListeners("on",t),n._toggleElementListeners("on"),n}J(t,e);var i=t.prototype;return i._toggleLifecycleListeners=function(e,t){this[e]("set_horizontal",this._onSetHorizontalScrollingEnabled,this),this[e]("set_vertical",this._onSetVerticalScrollingEnabled,this),t.app.systems.element[e]("add",this._onElementComponentAdd,this),t.app.systems.element[e]("beforeremove",this._onElementComponentRemove,this)},i._toggleElementListeners=function(e){if(this.entity.element){if("on"===e&&this._hasElementListeners)return;this.entity.element[e]("resize",this._onSetContentOrViewportSize,this),this.entity.element[e](lm,this._onMouseWheel,this),this._hasElementListeners="on"===e}},i._onElementComponentAdd=function(e){this.entity===e&&this._toggleElementListeners("on")},i._onElementComponentRemove=function(e){this.entity===e&&this._toggleElementListeners("off")},i._onViewportElementGain=function(){this._syncAll()},i._onContentElementGain=function(){this._destroyDragHelper(),this._contentDragHelper=new Fy(this._contentReference.entity.element),this._contentDragHelper.on("drag:start",this._onContentDragStart,this),this._contentDragHelper.on("drag:end",this._onContentDragEnd,this),this._contentDragHelper.on("drag:move",this._onContentDragMove,this),this._prevContentSizes[0]=null,this._prevContentSizes[1]=null,this._syncAll()},i._onContentElementLose=function(){this._destroyDragHelper()},i._onContentDragStart=function(){this._contentReference.entity&&this.enabled&&this.entity.enabled&&this._dragStartPosition.copy(this._contentReference.entity.getLocalPosition())},i._onContentDragEnd=function(){this._prevContentDragPosition=null,this._enableContentInput()},i._onContentDragMove=function(e){if(this._contentReference.entity&&this.enabled&&this.entity.enabled&&(this._wasDragged=!0,this._setScrollFromContentPosition(e),this._setVelocityFromContentPositionDelta(e),!this._disabledContentInput)){var t=e.x-this._dragStartPosition.x,i=e.y-this._dragStartPosition.y;(Math.abs(t)>this.dragThreshold||Math.abs(i)>this.dragThreshold)&&this._disableContentInput()}},i._onSetContentOrViewportSize=function(){this._syncAll()},i._onSetHorizontalScrollbarValue=function(e){!this._scrollbarUpdateFlags[0]&&this.enabled&&this.entity.enabled&&this._onSetScroll(e,null)},i._onSetVerticalScrollbarValue=function(e){!this._scrollbarUpdateFlags[1]&&this.enabled&&this.entity.enabled&&this._onSetScroll(null,e)},i._onSetHorizontalScrollingEnabled=function(){this._syncScrollbarEnabledState(0)},i._onSetVerticalScrollingEnabled=function(){this._syncScrollbarEnabledState(1)},i._onHorizontalScrollbarGain=function(){this._syncScrollbarEnabledState(0),this._syncScrollbarPosition(0)},i._onVerticalScrollbarGain=function(){this._syncScrollbarEnabledState(1),this._syncScrollbarPosition(1)},i._onSetScroll=function(e,t,i){!1!==i&&this._velocity.set(0,0,0);var n=this._updateAxis(e,"x",0),s=this._updateAxis(t,"y",1);(n||s)&&this.fire("set:scroll",this._scroll)},i._updateAxis=function(e,t,i){var n=null!==e&&Math.abs(e-this._scroll[t])>1e-5;return(n||this._isDragging()||0===e)&&(this._scroll[t]=this._determineNewScrollValue(e,t,i),this._syncContentPosition(i),this._syncScrollbarPosition(i)),n},i._determineNewScrollValue=function(e,t,i){if(!this._getScrollingEnabled(i))return this._scroll[t];switch(this.scrollMode){case 0:return de.clamp(e,0,this._getMaxScrollValue(i));case 1:return this._setVelocityFromOvershoot(e,t,i),e;case 2:return e;default:return console.warn("Unhandled scroll mode:"+this.scrollMode),e}},i._syncAll=function(){this._syncContentPosition(0),this._syncContentPosition(1),this._syncScrollbarPosition(0),this._syncScrollbarPosition(1),this._syncScrollbarEnabledState(0),this._syncScrollbarEnabledState(1)},i._syncContentPosition=function(e){var t=this._getAxis(e),i=this._getSign(e),n=this._contentReference.entity;if(n){var s=this._prevContentSizes[e],r=this._getContentSize(e);if(null!==s&&Math.abs(s-r)>1e-4){var a=this._getMaxOffset(e,s),o=this._getMaxOffset(e,r);this._scroll[t]=0===o?1:de.clamp(this._scroll[t]*a/o,0,1)}var h=this._scroll[t]*this._getMaxOffset(e),l=n.getLocalPosition();l[t]=h*i,n.setLocalPosition(l),this._prevContentSizes[e]=r}},i._syncScrollbarPosition=function(e){var t=this._getAxis(e),i=this._scrollbarReferences[e].entity;i&&i.scrollbar&&(this._scrollbarUpdateFlags[e]=!0,i.scrollbar.value=this._scroll[t],i.scrollbar.handleSize=this._getScrollbarHandleSize(t,e),this._scrollbarUpdateFlags[e]=!1)},i._syncScrollbarEnabledState=function(e){var t=this._scrollbarReferences[e].entity;if(t){var i=this._getScrollingEnabled(e),n=this._getScrollbarVisibility(e);switch(n){case 0:return void(t.enabled=i);case 1:return void(t.enabled=i&&this._contentIsLargerThanViewport(e));default:console.warn("Unhandled scrollbar visibility:"+n),t.enabled=i}}},i._contentIsLargerThanViewport=function(e){return this._getContentSize(e)>this._getViewportSize(e)},i._contentPositionToScrollValue=function(e){var t=this._getMaxOffset(0),i=this._getMaxOffset(1);return By.x=0===t?0:e.x/t,By.y=0===i?0:e.y/-i,By},i._getMaxOffset=function(e,t){t=void 0===t?this._getContentSize(e):t;var i=this._getViewportSize(e);return t<i?-this._getViewportSize(e):i-t},i._getMaxScrollValue=function(e){return this._contentIsLargerThanViewport(e)?1:0},i._getScrollbarHandleSize=function(e,t){var i=this._getViewportSize(t),n=this._getContentSize(t);if(Math.abs(n)<.001)return 1;var s=Math.min(i/n,1),r=this._toOvershoot(this._scroll[e],t);return 0===r?s:s/(1+Math.abs(r))},i._getViewportSize=function(e){return this._getSize(e,this._viewportReference)},i._getContentSize=function(e){return this._getSize(e,this._contentReference)},i._getSize=function(e,t){return t.entity&&t.entity.element?t.entity.element[this._getCalculatedDimension(e)]:0},i._getScrollingEnabled=function(e){return 0===e?this.horizontal:1===e?this.vertical:void 0},i._getScrollbarVisibility=function(e){return 0===e?this.horizontalScrollbarVisibility:1===e?this.verticalScrollbarVisibility:void 0},i._getSign=function(e){return 0===e?1:-1},i._getAxis=function(e){return 0===e?"x":"y"},i._getCalculatedDimension=function(e){return 0===e?"calculatedWidth":"calculatedHeight"},i._destroyDragHelper=function(){this._contentDragHelper&&this._contentDragHelper.destroy()},i.onUpdate=function(){this._contentReference.entity&&(this._updateVelocity(),this._syncScrollbarEnabledState(0),this._syncScrollbarEnabledState(1))},i._updateVelocity=function(){if(!this._isDragging()){if(1===this.scrollMode&&(this._hasOvershoot("x",0)&&this._setVelocityFromOvershoot(this.scroll.x,"x",0),this._hasOvershoot("y",1)&&this._setVelocityFromOvershoot(this.scroll.y,"y",1)),Math.abs(this._velocity.x)>1e-4||Math.abs(this._velocity.y)>1e-4){var e=this._contentReference.entity.getLocalPosition();e.x+=this._velocity.x,e.y+=this._velocity.y,this._contentReference.entity.setLocalPosition(e),this._setScrollFromContentPosition(e)}this._velocity.x*=1-this.friction,this._velocity.y*=1-this.friction}},i._hasOvershoot=function(e,t){return Math.abs(this._toOvershoot(this.scroll[e],t))>.001},i._toOvershoot=function(e,t){var i=this._getMaxScrollValue(t);return e<0?e:e>i?e-i:0},i._setVelocityFromOvershoot=function(e,t,i){var n=this._toOvershoot(e,i)*this._getMaxOffset(i)*this._getSign(i);Math.abs(n)>0&&(this._velocity[t]=-n/(50*this.bounceAmount+1))},i._setVelocityFromContentPositionDelta=function(e){this._prevContentDragPosition?(this._velocity.sub2(e,this._prevContentDragPosition),this._prevContentDragPosition.copy(e)):(this._velocity.set(0,0,0),this._prevContentDragPosition=e.clone())},i._setScrollFromContentPosition=function(e){var t=this._contentPositionToScrollValue(e);this._isDragging()&&(t=this._applyScrollValueTension(t)),this._onSetScroll(t.x,t.y,!1)},i._applyScrollValueTension=function(e){var t=this._getMaxScrollValue(0),i=this._toOvershoot(e.x,0);return i>0?e.x=t+1*Math.log10(1+i):i<0&&(e.x=-1*Math.log10(1-i)),t=this._getMaxScrollValue(1),(i=this._toOvershoot(e.y,1))>0?e.y=t+1*Math.log10(1+i):i<0&&(e.y=-1*Math.log10(1-i)),e},i._isDragging=function(){return this._contentDragHelper&&this._contentDragHelper.isDragging},i._setScrollbarComponentsEnabled=function(e){this._scrollbarReferences[0].hasComponent("scrollbar")&&(this._scrollbarReferences[0].entity.scrollbar.enabled=e),this._scrollbarReferences[1].hasComponent("scrollbar")&&(this._scrollbarReferences[1].entity.scrollbar.enabled=e)},i._setContentDraggingEnabled=function(e){this._contentDragHelper&&(this._contentDragHelper.enabled=e)},i._onMouseWheel=function(e){if(this.useMouseWheel){var t=e.event,i=t.deltaX/this._contentReference.entity.element.calculatedWidth*this.mouseWheelSensitivity.x,n=t.deltaY/this._contentReference.entity.element.calculatedHeight*this.mouseWheelSensitivity.y,s=de.clamp(this._scroll.x+i,0,this._getMaxScrollValue(0)),r=de.clamp(this._scroll.y+n,0,this._getMaxScrollValue(1));this.scroll=new be(s,r)}},i._enableContentInput=function(){for(;this._disabledContentInputEntities.length;){var e=this._disabledContentInputEntities.pop();e.element&&(e.element.useInput=!0)}this._disabledContentInput=!1},i._disableContentInput=function(){var e=this,t=function t(i){i.element&&i.element.useInput&&(e._disabledContentInputEntities.push(i),i.element.useInput=!1);for(var n=i.children,s=0,r=n.length;s<r;s++)t(n[s])},i=this._contentReference.entity;if(i)for(var n=i.children,s=0,r=n.length;s<r;s++)t(n[s]);this._disabledContentInput=!0},i.onEnable=function(){this._viewportReference.onParentComponentEnable(),this._contentReference.onParentComponentEnable(),this._scrollbarReferences[0].onParentComponentEnable(),this._scrollbarReferences[1].onParentComponentEnable(),this._setScrollbarComponentsEnabled(!0),this._setContentDraggingEnabled(!0),this._syncAll()},i.onDisable=function(){this._setScrollbarComponentsEnabled(!1),this._setContentDraggingEnabled(!1)},i.onRemove=function(){this._toggleLifecycleListeners("off",this.system),this._toggleElementListeners("off"),this._destroyDragHelper()},$(t,[{key:"scroll",get:function(){return this._scroll},set:function(e){this._onSetScroll(e.x,e.y)}}]),t}(Cl),Uy=function(){this.enabled=!0},zy=[{name:"enabled",type:"boolean"},{name:"horizontal",type:"boolean"},{name:"vertical",type:"boolean"},{name:"scrollMode",type:"number"},{name:"bounceAmount",type:"number"},{name:"friction",type:"number"},{name:"dragThreshold",type:"number"},{name:"useMouseWheel",type:"boolean"},{name:"mouseWheelSensitivity",type:"vec2"},{name:"horizontalScrollbarVisibility",type:"number"},{name:"verticalScrollbarVisibility",type:"number"},{name:"viewportEntity",type:"entity"},{name:"contentEntity",type:"entity"},{name:"horizontalScrollbarEntity",type:"entity"},{name:"verticalScrollbarEntity",type:"entity"}],Vy=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="scrollview",i.ComponentType=Ny,i.DataType=Uy,i.schema=zy,i.on("beforeremove",i._onRemoveComponent,te(i)),i.app.systems.on("update",i.onUpdate,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){void 0===i.dragThreshold&&(i.dragThreshold=10),void 0===i.useMouseWheel&&(i.useMouseWheel=!0),void 0===i.mouseWheelSensitivity&&(i.mouseWheelSensitivity=new be(1,1)),e.prototype.initializeComponentData.call(this,t,i,zy)},i.onUpdate=function(e){var t=this.store;for(var i in t){var n=t[i].entity,s=n.scrollview;s.enabled&&n.enabled&&s.onUpdate()}},i._onRemoveComponent=function(e,t){t.onRemove()},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},t}(h_);Cl._buildAccessors(Ny.prototype,zy);var Gy=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._handleReference=new D_(te(n),"handleEntity",{"element#gain":n._onHandleElementGain,"element#lose":n._onHandleElementLose,"element#set:anchor":n._onSetHandleAlignment,"element#set:margin":n._onSetHandleAlignment,"element#set:pivot":n._onSetHandleAlignment}),n._toggleLifecycleListeners("on"),n}J(t,e);var i=t.prototype;return i._toggleLifecycleListeners=function(e){this[e]("set_value",this._onSetValue,this),this[e]("set_handleSize",this._onSetHandleSize,this),this[e]("set_orientation",this._onSetOrientation,this)},i._onHandleElementGain=function(){this._destroyDragHelper(),this._handleDragHelper=new Fy(this._handleReference.entity.element,this._getAxis()),this._handleDragHelper.on("drag:move",this._onHandleDrag,this),this._updateHandlePositionAndSize()},i._onHandleElementLose=function(){this._destroyDragHelper()},i._onHandleDrag=function(e){this._handleReference.entity&&this.enabled&&this.entity.enabled&&(this.value=this._handlePositionToScrollValue(e[this._getAxis()]))},i._onSetValue=function(e,t,i){Math.abs(i-t)>1e-5&&(this.data.value=de.clamp(i,0,1),this._updateHandlePositionAndSize(),this.fire("set:value",this.data.value))},i._onSetHandleSize=function(e,t,i){Math.abs(i-t)>1e-5&&(this.data.handleSize=de.clamp(i,0,1),this._updateHandlePositionAndSize())},i._onSetHandleAlignment=function(){this._updateHandlePositionAndSize()},i._onSetOrientation=function(e,t,i){i!==t&&this._handleReference.hasComponent("element")&&(this._handleReference.entity.element[this._getOppositeDimension()]=0)},i._updateHandlePositionAndSize=function(){var e=this._handleReference.entity,t=e&&e.element;if(e){var i=e.getLocalPosition();i[this._getAxis()]=this._getHandlePosition(),this._handleReference.entity.setLocalPosition(i)}t&&(t[this._getDimension()]=this._getHandleLength())},i._handlePositionToScrollValue=function(e){return e*this._getSign()/this._getUsableTrackLength()},i._scrollValueToHandlePosition=function(e){return e*this._getSign()*this._getUsableTrackLength()},i._getUsableTrackLength=function(){return Math.max(this._getTrackLength()-this._getHandleLength(),.001)},i._getTrackLength=function(){return this.entity.element?0===this.orientation?this.entity.element.calculatedWidth:this.entity.element.calculatedHeight:0},i._getHandleLength=function(){return this._getTrackLength()*this.handleSize},i._getHandlePosition=function(){return this._scrollValueToHandlePosition(this.value)},i._getSign=function(){return 0===this.orientation?1:-1},i._getAxis=function(){return 0===this.orientation?"x":"y"},i._getDimension=function(){return 0===this.orientation?"width":"height"},i._getOppositeDimension=function(){return 0===this.orientation?"height":"width"},i._destroyDragHelper=function(){this._handleDragHelper&&this._handleDragHelper.destroy()},i._setHandleDraggingEnabled=function(e){this._handleDragHelper&&(this._handleDragHelper.enabled=e)},i.onEnable=function(){this._handleReference.onParentComponentEnable(),this._setHandleDraggingEnabled(!0)},i.onDisable=function(){this._setHandleDraggingEnabled(!1)},i.onRemove=function(){this._destroyDragHelper(),this._toggleLifecycleListeners("off")},t}(Cl),Wy=function(){this.enabled=!0},Hy=[{name:"enabled",type:"boolean"},{name:"orientation",type:"number"},{name:"value",type:"number"},{name:"handleSize",type:"number"},{name:"handleEntity",type:"entity"}],Xy=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="scrollbar",i.ComponentType=Gy,i.DataType=Wy,i.schema=Hy,i.on("beforeremove",i._onRemoveComponent,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){e.prototype.initializeComponentData.call(this,t,i,Hy)},i._onRemoveComponent=function(e,t){t.onRemove()},t}(h_);Cl._buildAccessors(Gy.prototype,Hy);var qy={volume:0,pitch:0,loop:!1,startTime:0,duration:0,position:new ye,maxDistance:0,refDistance:0,rollOffFactor:0,distanceModel:0,onPlay:null,onPause:null,onResume:null,onStop:null,onEnd:null},jy=function(e){function t(t,i,n){var s;return void 0===i&&(i="Untitled"),void 0===n&&(n={}),(s=e.call(this)||this).name=void 0,s.instances=[],s._component=t,s._assets=t.system.app.assets,s._manager=t.system.manager,s.name=i,s._volume=void 0!==n.volume?de.clamp(Number(n.volume)||0,0,1):1,s._pitch=void 0!==n.pitch?Math.max(.01,Number(n.pitch)||0):1,s._loop=!(void 0===n.loop||!n.loop),s._duration=n.duration>0?n.duration:null,s._startTime=Math.max(0,Number(n.startTime)||0),s._overlap=!!n.overlap,s._autoPlay=!!n.autoPlay,s._firstNode=null,s._lastNode=null,s._asset=n.asset,s._asset instanceof ml&&(s._asset=s._asset.id),s._onInstancePlayHandler=s._onInstancePlay.bind(te(s)),s._onInstancePauseHandler=s._onInstancePause.bind(te(s)),s._onInstanceResumeHandler=s._onInstanceResume.bind(te(s)),s._onInstanceStopHandler=s._onInstanceStop.bind(te(s)),s._onInstanceEndHandler=s._onInstanceEnd.bind(te(s)),s}J(t,e);var i=t.prototype;return i.play=function(){if(this.overlap||this.stop(),this.isLoaded||this._hasAsset()){var e=this._createInstance();if(this.instances.push(e),this.isLoaded)e.play();else{var t=function(t){var i=e._playWhenLoaded;e.sound=t,i&&e.play()};this.off("load",t),this.once("load",t),this.load()}return e}},i.pause=function(){for(var e=!1,t=this.instances,i=0,n=t.length;i<n;i++)t[i].pause()&&(e=!0);return e},i.resume=function(){for(var e=!1,t=this.instances,i=0,n=t.length;i<n;i++)t[i].resume()&&(e=!0);return e},i.stop=function(){for(var e=!1,t=this.instances,i=t.length;i--;)t[i].stop(),e=!0;return t.length=0,e},i.load=function(){if(this._hasAsset()){var e=this._assets.get(this._asset);if(!e)return this._assets.off("add:"+this._asset,this._onAssetAdd,this),void this._assets.once("add:"+this._asset,this._onAssetAdd,this);if(e.off("remove",this._onAssetRemoved,this),e.on("remove",this._onAssetRemoved,this),!e.resource)return e.off("load",this._onAssetLoad,this),e.once("load",this._onAssetLoad,this),void this._assets.load(e);this.fire("load",e.resource)}},i.setExternalNodes=function(e,t){if(e){if(t||(t=e),this._firstNode=e,this._lastNode=t,!this._overlap)for(var i=this.instances,n=0,s=i.length;n<s;n++)i[n].setExternalNodes(e,t)}else console.error("The firstNode must have a valid AudioNode")},i.clearExternalNodes=function(){if(this._firstNode=null,this._lastNode=null,!this._overlap)for(var e=this.instances,t=0,i=e.length;t<i;t++)e[t].clearExternalNodes()},i.getExternalNodes=function(){return[this._firstNode,this._lastNode]},i._hasAsset=function(){return null!=this._asset},i._createInstance=function(){var e=null,t=this._component,i=null;if(this._hasAsset()){var n=this._assets.get(this._asset);n&&(i=n.resource)}var s=qy;return s.volume=this._volume*t.volume,s.pitch=this._pitch*t.pitch,s.loop=this._loop,s.startTime=this._startTime,s.duration=this._duration,s.onPlay=this._onInstancePlayHandler,s.onPause=this._onInstancePauseHandler,s.onResume=this._onInstanceResumeHandler,s.onStop=this._onInstanceStopHandler,s.onEnd=this._onInstanceEndHandler,t.positional?(s.position.copy(t.entity.getPosition()),s.maxDistance=t.maxDistance,s.refDistance=t.refDistance,s.rollOffFactor=t.rollOffFactor,s.distanceModel=t.distanceModel,e=new Rd(this._manager,i,s)):e=new Pd(this._manager,i,s),this._firstNode&&e.setExternalNodes(this._firstNode,this._lastNode),e},i._onInstancePlay=function(e){this.fire("play",e),this._component.fire("play",this,e)},i._onInstancePause=function(e){this.fire("pause",e),this._component.fire("pause",this,e)},i._onInstanceResume=function(e){this.fire("resume",e),this._component.fire("resume",this,e)},i._onInstanceStop=function(e){var t=this.instances.indexOf(e);-1!==t&&this.instances.splice(t,1),this.fire("stop",e),this._component.fire("stop",this,e)},i._onInstanceEnd=function(e){var t=this.instances.indexOf(e);-1!==t&&this.instances.splice(t,1),this.fire("end",e),this._component.fire("end",this,e)},i._onAssetAdd=function(e){this.load()},i._onAssetLoad=function(e){this.load()},i._onAssetRemoved=function(e){e.off("remove",this._onAssetRemoved,this),this._assets.off("add:"+e.id,this._onAssetAdd,this),this.stop()},i.updatePosition=function(e){for(var t=this.instances,i=0,n=t.length;i<n;i++)t[i].position=e},$(t,[{key:"asset",get:function(){return this._asset},set:function(e){var t=this._asset;if(t){this._assets.off("add:"+t,this._onAssetAdd,this);var i=this._assets.get(t);i&&i.off("remove",this._onAssetRemoved,this)}this._asset=e,this._asset instanceof ml&&(this._asset=this._asset.id),this._hasAsset()&&this._component.enabled&&this._component.entity.enabled&&this.load()}},{key:"autoPlay",get:function(){return this._autoPlay},set:function(e){this._autoPlay=!!e}},{key:"duration",get:function(){var e=0;if(this._hasAsset()){var t=this._assets.get(this._asset);e=null!=t&&t.resource?t.resource.duration:0}return null!=this._duration?this._duration%(e||1):e},set:function(e){if(this._duration=Math.max(0,Number(e)||0)||null,!this._overlap)for(var t=this.instances,i=0,n=t.length;i<n;i++)t[i].duration=this._duration}},{key:"isLoaded",get:function(){if(this._hasAsset()){var e=this._assets.get(this._asset);if(e)return!!e.resource}return!1}},{key:"isPaused",get:function(){var e=this.instances,t=e.length;if(0===t)return!1;for(var i=0;i<t;i++)if(!e[i].isPaused)return!1;return!0}},{key:"isPlaying",get:function(){for(var e=this.instances,t=0,i=e.length;t<i;t++)if(e[t].isPlaying)return!0;return!1}},{key:"isStopped",get:function(){for(var e=this.instances,t=0,i=e.length;t<i;t++)if(!e[t].isStopped)return!1;return!0}},{key:"loop",get:function(){return this._loop},set:function(e){this._loop=!!e;for(var t=this.instances,i=0,n=t.length;i<n;i++)t[i].loop=this._loop}},{key:"overlap",get:function(){return this._overlap},set:function(e){this._overlap=!!e}},{key:"pitch",get:function(){return this._pitch},set:function(e){if(this._pitch=Math.max(Number(e)||0,.01),!this._overlap)for(var t=this.instances,i=0,n=t.length;i<n;i++)t[i].pitch=this.pitch*this._component.pitch}},{key:"startTime",get:function(){return this._startTime},set:function(e){if(this._startTime=Math.max(0,Number(e)||0),!this._overlap)for(var t=this.instances,i=0,n=t.length;i<n;i++)t[i].startTime=this._startTime}},{key:"volume",get:function(){return this._volume},set:function(e){if(this._volume=de.clamp(Number(e)||0,0,1),!this._overlap)for(var t=this.instances,i=0,n=t.length;i<n;i++)t[i].volume=this._volume*this._component.volume}}]),t}(m),Yy=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._volume=1,n._pitch=1,n._positional=!0,n._refDistance=1,n._maxDistance=1e4,n._rollOffFactor=1,n._distanceModel=_d,n._slots={},n._playingBeforeDisable={},n}J(t,e);var i=t.prototype;return i._updateSoundInstances=function(e,t,i){var n=this._slots;for(var s in n){var r=n[s];if(!r.overlap)for(var a=r.instances,o=0,h=a.length;o<h;o++)a[o][e]=i?r[e]*t:t}},i.onEnable=function(){if(!this.system._inTools){var e=this._slots,t=this._playingBeforeDisable;for(var i in e){var n=e[i];n.autoPlay&&n.isStopped?n.play():t[i]?n.resume():n.isLoaded||n.load()}}},i.onDisable=function(){var e=this._slots,t={};for(var i in e)e[i].overlap||e[i].isPlaying&&(e[i].pause(),t[i]=!0);this._playingBeforeDisable=t},i.onRemove=function(){this.off()},i.addSlot=function(e,t){var i=this._slots;if(i[e])return null;var n=new jy(this,e,t);return i[e]=n,n.autoPlay&&this.enabled&&this.entity.enabled&&n.play(),n},i.removeSlot=function(e){var t=this._slots;t[e]&&(t[e].stop(),delete t[e])},i.slot=function(e){return this._slots[e]},i.play=function(e){if(!this.enabled||!this.entity.enabled)return null;var t=this._slots[e];return t?t.play():null},i.pause=function(e){var t=this._slots;if(e){var i=t[e];if(!i)return;i.pause()}else for(var n in t)t[n].pause()},i.resume=function(e){var t=this._slots;if(e){var i=t[e];if(!i)return;i.isPaused&&i.resume()}else for(var n in t)t[n].resume()},i.stop=function(e){var t=this._slots;if(e){var i=t[e];if(!i)return;i.stop()}else for(var n in t)t[n].stop()},$(t,[{key:"distanceModel",get:function(){return this._distanceModel},set:function(e){this._distanceModel=e,this._updateSoundInstances("distanceModel",e,!1)}},{key:"maxDistance",get:function(){return this._maxDistance},set:function(e){this._maxDistance=e,this._updateSoundInstances("maxDistance",e,!1)}},{key:"refDistance",get:function(){return this._refDistance},set:function(e){this._refDistance=e,this._updateSoundInstances("refDistance",e,!1)}},{key:"rollOffFactor",get:function(){return this._rollOffFactor},set:function(e){this._rollOffFactor=e,this._updateSoundInstances("rollOffFactor",e,!1)}},{key:"pitch",get:function(){return this._pitch},set:function(e){this._pitch=e,this._updateSoundInstances("pitch",e,!0)}},{key:"volume",get:function(){return this._volume},set:function(e){this._volume=e,this._updateSoundInstances("volume",e,!0)}},{key:"positional",get:function(){return this._positional},set:function(e){this._positional=e;var t=this._slots;for(var i in t){var n=t[i];if(!n.overlap)for(var s=n.instances,r=s.length-1;r>=0;r--){var a=s[r].isPlaying||s[r].isSuspended,o=s[r].currentTime;a&&s[r].stop();var h=n._createInstance();a&&(h.play(),h.currentTime=o),s.push(h)}}}},{key:"slots",get:function(){return this._slots},set:function(e){var t=this._slots;if(t)for(var i in t)t[i].stop();var n={};for(var s in e)e[s]instanceof jy?n[e[s].name]=e[s]:e[s].name&&(n[e[s].name]=new jy(this,e[s].name,e[s]));this._slots=n,this.enabled&&this.entity.enabled&&this.onEnable()}}]),t}(Cl),Ky=function(){this.enabled=!0},Zy=["enabled"],$y=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="sound",i.ComponentType=Yy,i.DataType=Ky,i.schema=Zy,i.manager=t.soundManager,i.app.systems.on("update",i.onUpdate,te(i)),i.on("beforeremove",i.onBeforeRemove,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){n=["volume","pitch","positional","refDistance","maxDistance","rollOffFactor","distanceModel","slots"];for(var s=0;s<n.length;s++)i.hasOwnProperty(n[s])&&(t[n[s]]=i[n[s]]);e.prototype.initializeComponentData.call(this,t,i,["enabled"])},i.cloneComponent=function(e,t){var i=e.sound,n=i.slots,s={};for(var r in n){var a=n[r];s[r]={name:a.name,volume:a.volume,pitch:a.pitch,loop:a.loop,duration:a.duration,startTime:a.startTime,overlap:a.overlap,autoPlay:a.autoPlay,asset:a.asset}}var o={distanceModel:i.distanceModel,enabled:i.enabled,maxDistance:i.maxDistance,pitch:i.pitch,positional:i.positional,refDistance:i.refDistance,rollOffFactor:i.rollOffFactor,slots:s,volume:i.volume};return this.addComponent(t,o)},i.onUpdate=function(e){var t=this.store;for(var i in t)if(t.hasOwnProperty(i)){var n=t[i].entity;if(n.enabled){var s=n.sound;if(s.enabled&&s.positional){var r=n.getPosition(),a=s.slots;for(var o in a)a[o].updatePosition(r)}}}},i.onBeforeRemove=function(e,t){var i=t.slots;for(var n in i)i[n].overlap||i[n].stop();t.onRemove()},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},$(t,[{key:"volume",get:function(){return this.manager.volume},set:function(e){this.manager.volume=e}},{key:"context",get:function(){return yd()?this.manager.context:null}}]),t}(h_);Cl._buildAccessors(Yy.prototype,Zy);var Qy="simple",Jy="animated",ex=function(e){function t(t,i){var n;return(n=e.call(this)||this)._component=t,n._frame=0,n._sprite=null,n._spriteAsset=null,n.spriteAsset=i.spriteAsset,n.name=i.name,n.fps=i.fps||0,n.loop=i.loop||!1,n._playing=!1,n._paused=!1,n._time=0,n}J(t,e);var i=t.prototype;return i._onSpriteAssetAdded=function(e){this._component.system.app.assets.off("add:"+e.id,this._onSpriteAssetAdded,this),this._spriteAsset===e.id&&this._bindSpriteAsset(e)},i._bindSpriteAsset=function(e){e.on("load",this._onSpriteAssetLoad,this),e.on("remove",this._onSpriteAssetRemove,this),e.resource?this._onSpriteAssetLoad(e):this._component.system.app.assets.load(e)},i._unbindSpriteAsset=function(e){e.off("load",this._onSpriteAssetLoad,this),e.off("remove",this._onSpriteAssetRemove,this),e.resource&&e.resource.atlas&&this._component.system.app.assets.off("load:"+e.data.textureAtlasAsset,this._onTextureAtlasLoad,this)},i._onSpriteAssetLoad=function(e){if(e.resource)if(e.resource.atlas)this.sprite=e.resource;else{var t=e.data.textureAtlasAsset,i=this._component.system.app.assets;i.off("load:"+t,this._onTextureAtlasLoad,this),i.once("load:"+t,this._onTextureAtlasLoad,this)}else this.sprite=null},i._onTextureAtlasLoad=function(e){var t=this._spriteAsset;t instanceof ml?this._onSpriteAssetLoad(t):this._onSpriteAssetLoad(this._component.system.app.assets.get(t))},i._onSpriteAssetRemove=function(e){this.sprite=null},i._onSpriteMeshesChange=function(){this._component.currentClip===this&&this._component._showFrame(this.frame)},i._onSpritePpuChanged=function(){this._component.currentClip===this&&0!==this.sprite.renderMode&&this._component._showFrame(this.frame)},i._update=function(e){if(0!==this.fps&&this._playing&&!this._paused&&this._sprite){var t=this.fps<0?-1:1,i=this._time+e*this._component.speed*t,n=this.duration,s=i>n||i<0;this._setTime(i);var r=this.frame;(r=this._sprite?Math.floor(this._sprite.frameKeys.length*this._time/n):0)!==this._frame&&this._setFrame(r),s&&(this.loop?(this.fire("loop"),this._component.fire("loop",this)):(this._playing=!1,this._paused=!1,this.fire("end"),this._component.fire("end",this)))}},i._setTime=function(e){this._time=e;var t=this.duration;this._time<0?this.loop?this._time=this._time%t+t:this._time=0:this._time>t&&(this.loop?this._time%=t:this._time=t)},i._setFrame=function(e){this._sprite?this._frame=de.clamp(e,0,this._sprite.frameKeys.length-1):this._frame=e,this._component.currentClip===this&&this._component._showFrame(this._frame)},i._destroy=function(){this._sprite&&(this.sprite=null),this._spriteAsset&&(this.spriteAsset=null)},i.play=function(){this._playing||(this._playing=!0,this._paused=!1,this.frame=0,this.fire("play"),this._component.fire("play",this))},i.pause=function(){this._playing&&!this._paused&&(this._paused=!0,this.fire("pause"),this._component.fire("pause",this))},i.resume=function(){this._paused&&(this._paused=!1,this.fire("resume"),this._component.fire("resume",this))},i.stop=function(){this._playing&&(this._playing=!1,this._paused=!1,this._time=0,this.frame=0,this.fire("stop"),this._component.fire("stop",this))},$(t,[{key:"duration",get:function(){if(this._sprite){var e=this.fps||Number.MIN_VALUE;return this._sprite.frameKeys.length/Math.abs(e)}return 0}},{key:"frame",get:function(){return this._frame},set:function(e){this._setFrame(e);var t=this.fps||Number.MIN_VALUE;this._setTime(this._frame/t)}},{key:"isPaused",get:function(){return this._paused}},{key:"isPlaying",get:function(){return this._playing}},{key:"sprite",get:function(){return this._sprite},set:function(e){var t;(this._sprite&&(this._sprite.off("set:meshes",this._onSpriteMeshesChange,this),this._sprite.off("set:pixelsPerUnit",this._onSpritePpuChanged,this),this._sprite.off("set:atlas",this._onSpriteMeshesChange,this),this._sprite.atlas&&this._sprite.atlas.off("set:texture",this._onSpriteMeshesChange,this)),this._sprite=e,this._sprite&&(this._sprite.on("set:meshes",this._onSpriteMeshesChange,this),this._sprite.on("set:pixelsPerUnit",this._onSpritePpuChanged,this),this._sprite.on("set:atlas",this._onSpriteMeshesChange,this),this._sprite.atlas&&this._sprite.atlas.on("set:texture",this._onSpriteMeshesChange,this)),this._component.currentClip===this)&&(e&&e.atlas?(e.atlas.texture&&((t=this._component._meshInstance)&&(t.setParameter("texture_emissiveMap",e.atlas.texture),t.setParameter("texture_opacityMap",e.atlas.texture)),this._component.enabled&&this._component.entity.enabled&&this._component._showModel()),this.time&&this.fps?this.time=this.time:this.frame=this.frame):((t=this._component._meshInstance)&&(t.deleteParameter("texture_emissiveMap"),t.deleteParameter("texture_opacityMap")),this._component._hideModel()))}},{key:"spriteAsset",get:function(){return this._spriteAsset},set:function(e){var t=this._component.system.app.assets,i=e;if(e instanceof ml&&(i=e.id),this._spriteAsset!==i){if(this._spriteAsset){var n=t.get(this._spriteAsset);n&&this._unbindSpriteAsset(n)}if(this._spriteAsset=i,this._spriteAsset){var s=t.get(this._spriteAsset);s?this._bindSpriteAsset(s):(this.sprite=null,t.on("add:"+this._spriteAsset,this._onSpriteAssetAdded,this))}else this.sprite=null}}},{key:"time",get:function(){return this._time},set:function(e){this._setTime(e),this._sprite?this.frame=Math.min(this._sprite.frameKeys.length-1,Math.floor(this._time*Math.abs(this.fps))):this.frame=0}}]),t}(m),tx="texture_emissiveMap",ix="texture_opacityMap",nx="material_emissive",sx="material_opacity",rx=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._type=Qy,n._material=t.defaultMaterial,n._color=new me(1,1,1,1),n._colorUniform=new Float32Array(3),n._speed=1,n._flipX=!1,n._flipY=!1,n._width=1,n._height=1,n._drawOrder=0,n._layers=[0],n._outerScale=new be(1,1),n._outerScaleUniform=new Float32Array(2),n._innerOffset=new Se,n._innerOffsetUniform=new Float32Array(4),n._atlasRect=new Se,n._atlasRectUniform=new Float32Array(4),n._batchGroupId=-1,n._batchGroup=null,n._node=new Hn,n._model=new hc,n._model.graph=n._node,n._meshInstance=null,i.addChild(n._model.graph),n._model._entity=i,n._updateAabbFunc=n._updateAabb.bind(te(n)),n._addedModel=!1,n._autoPlayClip=null,n._clips={},n._defaultClip=new ex(te(n),{name:n.entity.name,fps:0,loop:!1,spriteAsset:null}),n._currentClip=n._defaultClip,n}J(t,e);var i=t.prototype;return i.onEnable=function(){var e,t=this.system.app,i=t.scene;(i.on("set:layers",this._onLayersChanged,this),i.layers&&(i.layers.on("add",this._onLayerAdded,this),i.layers.on("remove",this._onLayerRemoved,this)),this._showModel(),this._autoPlayClip&&this._tryAutoPlay(),this._batchGroupId>=0)&&(null==(e=t.batcher)||e.insert(ya.SPRITE,this._batchGroupId,this.entity))},i.onDisable=function(){var e,t=this.system.app,i=t.scene;(i.off("set:layers",this._onLayersChanged,this),i.layers&&(i.layers.off("add",this._onLayerAdded,this),i.layers.off("remove",this._onLayerRemoved,this)),this.stop(),this._hideModel(),this._batchGroupId>=0)&&(null==(e=t.batcher)||e.remove(ya.SPRITE,this._batchGroupId,this.entity))},i.onDestroy=function(){for(var e in this._currentClip=null,this._defaultClip&&(this._defaultClip._destroy(),this._defaultClip=null),this._clips)this._clips[e]._destroy();this._clips=null,this._hideModel(),this._model=null,this._node&&(this._node.parent&&this._node.parent.removeChild(this._node),this._node=null),this._meshInstance&&(this._meshInstance.material=null,this._meshInstance.mesh=null,this._meshInstance=null)},i._showModel=function(){if(!this._addedModel&&this._meshInstance){for(var e=[this._meshInstance],t=0,i=this._layers.length;t<i;t++){var n=this.system.app.scene.layers.getLayerById(this._layers[t]);n&&n.addMeshInstances(e)}this._addedModel=!0}},i._hideModel=function(){if(this._addedModel&&this._meshInstance){for(var e=[this._meshInstance],t=0,i=this._layers.length;t<i;t++){var n=this.system.app.scene.layers.getLayerById(this._layers[t]);n&&n.removeMeshInstances(e)}this._addedModel=!1}},i._showFrame=function(e){if(this.sprite){var t=this.sprite.meshes[e];if(t){var i;if(i=1===this.sprite.renderMode?this.system.default9SlicedMaterialSlicedMode:2===this.sprite.renderMode?this.system.default9SlicedMaterialTiledMode:this.system.defaultMaterial,this._meshInstance||(this._meshInstance=new ka(t,this._material,this._node),this._meshInstance.castShadow=!1,this._meshInstance.receiveShadow=!1,this._meshInstance.drawOrder=this._drawOrder,this._model.meshInstances.push(this._meshInstance),this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._meshInstance.setParameter(nx,this._colorUniform),this._meshInstance.setParameter(sx,this._color.a),this.enabled&&this.entity.enabled&&this._showModel()),this._meshInstance.material!==i&&(this._meshInstance.material=i),this._meshInstance.mesh!==t&&(this._meshInstance.mesh=t,this._meshInstance.visible=!0,this._meshInstance._aabbVer=-1),this.sprite.atlas&&this.sprite.atlas.texture?(this._meshInstance.setParameter(tx,this.sprite.atlas.texture),this._meshInstance.setParameter(ix,this.sprite.atlas.texture)):(this._meshInstance.deleteParameter(tx),this._meshInstance.deleteParameter(ix)),!this.sprite.atlas||1!==this.sprite.renderMode&&2!==this.sprite.renderMode)this._meshInstance._updateAabbFunc=null;else{this._meshInstance._updateAabbFunc=this._updateAabbFunc;var n=this.sprite.atlas.frames[this.sprite.frameKeys[e]];if(n){var s=2/n.rect.z,r=2/n.rect.w;this._innerOffset.set(n.border.x*s,n.border.y*r,n.border.z*s,n.border.w*r);var a=this.sprite.atlas.texture;this._atlasRect.set(n.rect.x/a.width,n.rect.y/a.height,n.rect.z/a.width,n.rect.w/a.height)}else this._innerOffset.set(0,0,0,0);this._innerOffsetUniform[0]=this._innerOffset.x,this._innerOffsetUniform[1]=this._innerOffset.y,this._innerOffsetUniform[2]=this._innerOffset.z,this._innerOffsetUniform[3]=this._innerOffset.w,this._meshInstance.setParameter("innerOffset",this._innerOffsetUniform),this._atlasRectUniform[0]=this._atlasRect.x,this._atlasRectUniform[1]=this._atlasRect.y,this._atlasRectUniform[2]=this._atlasRect.z,this._atlasRectUniform[3]=this._atlasRect.w,this._meshInstance.setParameter("atlasRect",this._atlasRectUniform)}this._updateTransform()}else this._meshInstance&&(this._meshInstance.mesh=null,this._meshInstance.visible=!1)}},i._updateTransform=function(){var e=this.flipX?-1:1,t=this.flipY?-1:1,i=0,n=0;if(this.sprite&&(1===this.sprite.renderMode||2===this.sprite.renderMode)){var s=1,r=1;if(this.sprite.atlas){var a=this.sprite.atlas.frames[this.sprite.frameKeys[this.frame]];a&&(s=a.rect.z,r=a.rect.w,i=(.5-a.pivot.x)*this._width,n=(.5-a.pivot.y)*this._height)}var o=s/this.sprite.pixelsPerUnit,h=r/this.sprite.pixelsPerUnit;this._outerScale.set(Math.max(this._width,this._innerOffset.x*o),Math.max(this._height,this._innerOffset.y*h)),e*=o,t*=h,this._outerScale.x/=o,this._outerScale.y/=h,e*=de.clamp(this._width/(this._innerOffset.x*o),1e-4,1),t*=de.clamp(this._height/(this._innerOffset.y*h),1e-4,1),this._meshInstance&&(this._outerScaleUniform[0]=this._outerScale.x,this._outerScaleUniform[1]=this._outerScale.y,this._meshInstance.setParameter("outerScale",this._outerScaleUniform))}this._node.setLocalScale(e,t,1),this._node.setLocalPosition(i,n,0)},i._updateAabb=function(e){return e.center.set(0,0,0),e.halfExtents.set(.5*this._outerScale.x,.5*this._outerScale.y,.001),e.setFromTransformedAabb(e,this._node.getWorldTransform()),e},i._tryAutoPlay=function(){if(this._autoPlayClip&&this.type===Jy){var e=this._clips[this._autoPlayClip];!e||e.isPlaying||this._currentClip&&this._currentClip.isPlaying||this.enabled&&this.entity.enabled&&this.play(e.name)}},i._onLayersChanged=function(e,t){e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this),this.enabled&&this.entity.enabled&&this._showModel()},i._onLayerAdded=function(e){this.layers.indexOf(e.id)<0||this._addedModel&&this.enabled&&this.entity.enabled&&this._meshInstance&&e.addMeshInstances([this._meshInstance])},i._onLayerRemoved=function(e){this._meshInstance&&(this.layers.indexOf(e.id)<0||e.removeMeshInstances([this._meshInstance]))},i.removeModelFromLayers=function(){for(var e=0;e<this.layers.length;e++){var t=this.system.app.scene.layers.getLayerById(this.layers[e]);t&&t.removeMeshInstances([this._meshInstance])}},i.addClip=function(e){var t=new ex(this,{name:e.name,fps:e.fps,loop:e.loop,spriteAsset:e.spriteAsset});return this._clips[e.name]=t,t.name&&t.name===this._autoPlayClip&&this._tryAutoPlay(),t},i.removeClip=function(e){delete this._clips[e]},i.clip=function(e){return this._clips[e]},i.play=function(e){var t=this._clips[e],i=this._currentClip;return i&&i!==t&&(i._playing=!1),this._currentClip=t,this._currentClip&&(this._currentClip=t,this._currentClip.play()),t},i.pause=function(){this._currentClip!==this._defaultClip&&this._currentClip.isPlaying&&this._currentClip.pause()},i.resume=function(){this._currentClip!==this._defaultClip&&this._currentClip.isPaused&&this._currentClip.resume()},i.stop=function(){this._currentClip!==this._defaultClip&&this._currentClip.stop()},$(t,[{key:"type",get:function(){return this._type},set:function(e){this._type!==e&&(this._type=e,this._type===Qy?(this.stop(),this._currentClip=this._defaultClip,this.enabled&&this.entity.enabled&&(this._currentClip.frame=this.frame,this._currentClip.sprite?this._showModel():this._hideModel())):this._type===Jy&&(this.stop(),this._autoPlayClip&&this._tryAutoPlay(),this._currentClip&&this._currentClip.isPlaying&&this.enabled&&this.entity.enabled?this._showModel():this._hideModel()))}},{key:"frame",get:function(){return this._currentClip.frame},set:function(e){this._currentClip.frame=e}},{key:"spriteAsset",get:function(){return this._defaultClip._spriteAsset},set:function(e){this._defaultClip.spriteAsset=e}},{key:"sprite",get:function(){return this._currentClip.sprite},set:function(e){this._currentClip.sprite=e}},{key:"material",get:function(){return this._material},set:function(e){this._material=e,this._meshInstance&&(this._meshInstance.material=e)}},{key:"color",get:function(){return this._color},set:function(e){this._color.r=e.r,this._color.g=e.g,this._color.b=e.b,this._meshInstance&&(this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._meshInstance.setParameter(nx,this._colorUniform))}},{key:"opacity",get:function(){return this._color.a},set:function(e){this._color.a=e,this._meshInstance&&this._meshInstance.setParameter(sx,e)}},{key:"clips",get:function(){return this._clips},set:function(e){if(e){for(var t in this._clips){var i=!1;for(var n in e)if(e[n].name===t){i=!0,this._clips[t].fps=e[n].fps,this._clips[t].loop=e[n].loop,e[n].hasOwnProperty("sprite")?this._clips[t].sprite=e[n].sprite:e[n].hasOwnProperty("spriteAsset")&&(this._clips[t].spriteAsset=e[n].spriteAsset);break}i||this.removeClip(t)}for(var s in e)this._clips[e[s].name]||this.addClip(e[s]);this._autoPlayClip&&this._tryAutoPlay(),this._currentClip&&this._currentClip.sprite||this._hideModel()}else for(var r in this._clips)this.removeClip(r)}},{key:"currentClip",get:function(){return this._currentClip}},{key:"speed",get:function(){return this._speed},set:function(e){this._speed=e}},{key:"flipX",get:function(){return this._flipX},set:function(e){this._flipX!==e&&(this._flipX=e,this._updateTransform())}},{key:"flipY",get:function(){return this._flipY},set:function(e){this._flipY!==e&&(this._flipY=e,this._updateTransform())}},{key:"width",get:function(){return this._width},set:function(e){e!==this._width&&(this._width=e,this._outerScale.x=this._width,!this.sprite||2!==this.sprite.renderMode&&1!==this.sprite.renderMode||this._updateTransform())}},{key:"height",get:function(){return this._height},set:function(e){e!==this._height&&(this._height=e,this._outerScale.y=this.height,!this.sprite||2!==this.sprite.renderMode&&1!==this.sprite.renderMode||this._updateTransform())}},{key:"batchGroupId",get:function(){return this._batchGroupId},set:function(e){if(this._batchGroupId!==e){var t,i,n=this._batchGroupId;if(this._batchGroupId=e,this.entity.enabled&&n>=0)null==(t=this.system.app.batcher)||t.remove(ya.SPRITE,n,this.entity);if(this.entity.enabled&&e>=0)null==(i=this.system.app.batcher)||i.insert(ya.SPRITE,e,this.entity);else n>=0&&this._currentClip&&this._currentClip.sprite&&this.enabled&&this.entity.enabled&&this._showModel()}}},{key:"autoPlayClip",get:function(){return this._autoPlayClip},set:function(e){this._autoPlayClip=e instanceof ex?e.name:e,this._tryAutoPlay()}},{key:"drawOrder",get:function(){return this._drawOrder},set:function(e){this._drawOrder=e,this._meshInstance&&(this._meshInstance.drawOrder=e)}},{key:"layers",get:function(){return this._layers},set:function(e){this._addedModel&&this._hideModel(),this._layers=e,this._meshInstance&&this.enabled&&this.entity.enabled&&this._showModel()}},{key:"aabb",get:function(){return this._meshInstance?this._meshInstance.aabb:null}}]),t}(Cl),ax=function(){this.enabled=!0},ox=["enabled"],hx=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="sprite",i.ComponentType=rx,i.DataType=ax,i.schema=ox,i._defaultTexture=null,i._defaultMaterial=null,i._default9SlicedMaterialSlicedMode=null,i._default9SlicedMaterialTiledMode=null,i.app.systems.on("update",i.onUpdate,te(i)),i.on("beforeremove",i.onBeforeRemove,te(i)),i}J(t,e);var i=t.prototype;return i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this),this._defaultTexture&&(this._defaultTexture.destroy(),this._defaultTexture=null)},i.initializeComponentData=function(t,i,n){if(void 0!==i.enabled&&(t.enabled=i.enabled),t.type=i.type,i.layers&&Array.isArray(i.layers)&&(t.layers=i.layers.slice(0)),void 0!==i.drawOrder&&(t.drawOrder=i.drawOrder),void 0!==i.color&&(i.color instanceof me?t.color.set(i.color.r,i.color.g,i.color.b,void 0!==i.opacity?i.opacity:1):t.color.set(i.color[0],i.color[1],i.color[2],void 0!==i.opacity?i.opacity:1),t.color=t.color),void 0!==i.opacity&&(t.opacity=i.opacity),void 0!==i.flipX&&(t.flipX=i.flipX),void 0!==i.flipY&&(t.flipY=i.flipY),void 0!==i.width&&(t.width=i.width),void 0!==i.height&&(t.height=i.height),void 0!==i.spriteAsset&&(t.spriteAsset=i.spriteAsset),i.sprite&&(t.sprite=i.sprite),void 0!==i.frame&&(t.frame=i.frame),i.clips)for(var s in i.clips)t.addClip(i.clips[s]);void 0!==i.speed&&(t.speed=i.speed),i.autoPlayClip&&(t.autoPlayClip=i.autoPlayClip),t.batchGroupId=void 0===i.batchGroupId||null===i.batchGroupId?-1:i.batchGroupId,e.prototype.initializeComponentData.call(this,t,i,n)},i.cloneComponent=function(e,t){var i=e.sprite;return this.addComponent(t,{enabled:i.enabled,type:i.type,spriteAsset:i.spriteAsset,sprite:i.sprite,frame:i.frame,color:i.color.clone(),opacity:i.opacity,flipX:i.flipX,flipY:i.flipY,speed:i.speed,clips:i.clips,autoPlayClip:i.autoPlayClip,batchGroupId:i.batchGroupId,drawOrder:i.drawOrder,layers:i.layers.slice(0)})},i.onUpdate=function(e){var t=this.store;for(var i in t)if(t.hasOwnProperty(i)){var n=t[i];if(n.data.enabled&&n.entity.enabled){var s=n.entity.sprite;s._currentClip&&s._currentClip._update(e)}}},i.onBeforeRemove=function(e,t){t.onDestroy()},$(t,[{key:"defaultMaterial",get:function(){if(!this._defaultMaterial){var e=new wn(this.app.graphicsDevice,{width:1,height:1,format:7,name:"sprite"}),t=new Uint8Array(e.lock());t[0]=t[1]=t[2]=t[3]=255,e.unlock();var i=new Zs;i.diffuse.set(0,0,0),i.emissive.set(.5,.5,.5),i.emissiveMap=e,i.emissiveTint=!0,i.opacityMap=e,i.opacityMapChannel="a",i.opacityTint=!0,i.opacity=0,i.useLighting=!1,i.useGammaTonemap=!1,i.useFog=!1,i.useSkybox=!1,i.blendType=4,i.depthWrite=!1,i.pixelSnap=!1,i.cull=0,i.update(),this._defaultTexture=e,this._defaultMaterial=i}return this._defaultMaterial},set:function(e){this._defaultMaterial=e}},{key:"default9SlicedMaterialSlicedMode",get:function(){if(!this._default9SlicedMaterialSlicedMode){var e=this.defaultMaterial.clone();e.nineSlicedMode=1,e.update(),this._default9SlicedMaterialSlicedMode=e}return this._default9SlicedMaterialSlicedMode},set:function(e){this._default9SlicedMaterialSlicedMode=e}},{key:"default9SlicedMaterialTiledMode",get:function(){if(!this._default9SlicedMaterialTiledMode){var e=this.defaultMaterial.clone();e.nineSlicedMode=2,e.update(),this._default9SlicedMaterialTiledMode=e}return this._default9SlicedMaterialTiledMode},set:function(e){this._default9SlicedMaterialTiledMode=e}}]),t}(h_);Cl._buildAccessors(rx.prototype,ox);var lx=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._oldState=!0,n._size=new ye,n.on("set_enabled",n._onSetEnabled,te(n)),n}J(t,e);var i=t.prototype;return i.onEnable=function(){this._checkState()},i.onDisable=function(){this._checkState()},i._onSetEnabled=function(e,t,i){this._checkState()},i._checkState=function(){var e=this.enabled&&this.entity.enabled;e!==this._oldState&&(this._oldState=e,this.fire("enable"),this.fire("state",this.enabled))},i._onBeforeRemove=function(){this.fire("remove")},$(t,[{key:"size",get:function(){return this._size},set:function(e){e instanceof ye?this._size.copy(e):e instanceof Array&&e.length>=3&&this.size.set(e[0],e[1],e[2])}}]),t}(Cl),cx=function(){this.enabled=!0},ux=["enabled"],dx=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="zone",i.ComponentType=lx,i.DataType=cx,i.schema=ux,i.on("beforeremove",i._onBeforeRemove,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(e,t,i){e.enabled=!t.hasOwnProperty("enabled")||!!t.enabled,t.size&&(t.size instanceof ye?e.size.copy(t.size):t.size instanceof Array&&t.size.length>=3&&e.size.set(t.size[0],t.size[1],t.size[2]))},i.cloneComponent=function(e,t){var i={size:e.zone.size};return this.addComponent(t,i)},i._onBeforeRemove=function(e,t){t._onBeforeRemove()},t}(h_);Cl._buildAccessors(lx.prototype,ux);var fx=function(e,t){this.effect=e,this.inputTarget=t,this.outputTarget=null,this.name=e.constructor.name},px=function(){function e(e,t){this.app=e,this.camera=t,this.destinationRenderTarget=null,this.effects=[],this.enabled=!1,this.depthTarget=null,t.on("set:rect",this.onCameraRectChanged,this)}var t=e.prototype;return t._allocateColorBuffer=function(e,t){var i=this.camera.rect,n=Math.floor(i.z*this.app.graphicsDevice.width),s=Math.floor(i.w*this.app.graphicsDevice.height);return new wn(this.app.graphicsDevice,{name:t,format:e,width:n,height:s,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1})},t._createOffscreenTarget=function(e,t){var i=this.app.graphicsDevice,n=t?i.getHdrFormat():7,s=this.camera.entity.name+"-posteffect-"+this.effects.length,r=this._allocateColorBuffer(n,s);return new cr({colorBuffer:r,depth:e,stencil:e&&this.app.graphicsDevice.supportsStencil,samples:e?i.samples:1})},t._resizeOffscreenTarget=function(e){var t=e.colorBuffer.format,i=e.colorBuffer.name;e.destroyFrameBuffers(),e.destroyTextureBuffers(),e._colorBuffer=this._allocateColorBuffer(t,i)},t._destroyOffscreenTarget=function(e){e.destroyTextureBuffers(),e.destroy()},t.addEffect=function(e){var t=this.effects,i=0===t.length,n=this._createOffscreenTarget(i,e.hdr),s=new fx(e,n);t.push(s),this._sourceTarget=s.inputTarget,t.length>1&&(t[t.length-2].outputTarget=s.inputTarget),this._newPostEffect=e,e.needsDepthBuffer&&this._requestDepthMap(),this.enable(),this._newPostEffect=void 0},t.removeEffect=function(e){for(var t=-1,i=0,n=this.effects.length;i<n;i++)if(this.effects[i].effect===e){t=i;break}t>=0&&(t>0?this.effects[t-1].outputTarget=t+1<this.effects.length?this.effects[t+1].inputTarget:null:this.effects.length>1&&(this.effects[1].inputTarget._depth||(this._destroyOffscreenTarget(this.effects[1].inputTarget),this.effects[1].inputTarget=this._createOffscreenTarget(!0,this.effects[1].hdr),this._sourceTarget=this.effects[1].inputTarget),this.camera.renderTarget=this.effects[1].inputTarget),this._destroyOffscreenTarget(this.effects[t].inputTarget),this.effects.splice(t,1)),this.enabled&&e.needsDepthBuffer&&this._releaseDepthMap(),0===this.effects.length&&this.disable()},t._requestDepthMaps=function(){for(var e=0,t=this.effects.length;e<t;e++){var i=this.effects[e].effect;this._newPostEffect!==i&&(i.needsDepthBuffer&&this._requestDepthMap())}},t._releaseDepthMaps=function(){for(var e=0,t=this.effects.length;e<t;e++){this.effects[e].effect.needsDepthBuffer&&this._releaseDepthMap()}},t._requestDepthMap=function(){var e=this.app.scene.layers.getLayerById(1);e&&(e.incrementCounter(),this.camera.requestSceneDepthMap(!0))},t._releaseDepthMap=function(){var e=this.app.scene.layers.getLayerById(1);e&&(e.decrementCounter(),this.camera.requestSceneDepthMap(!1))},t.destroy=function(){for(var e=0,t=this.effects.length;e<t;e++)this.effects[e].inputTarget.destroy();this.effects.length=0,this.disable()},t.enable=function(){var e=this;!this.enabled&&this.effects.length&&(this.enabled=!0,this._requestDepthMaps(),this.app.graphicsDevice.on("resizecanvas",this._onCanvasResized,this),this.destinationRenderTarget=this.camera.renderTarget,this.camera.renderTarget=this.effects[0].inputTarget,this.camera.onPostprocessing=function(){if(e.enabled){var t=null,i=e.effects.length;if(i)for(var n=0;n<i;n++){var s=e.effects[n],r=s.outputTarget;n===i-1&&(t=e.camera.rect,e.destinationRenderTarget&&(r=e.destinationRenderTarget)),s.effect.render(s.inputTarget,r,t)}}})},t.disable=function(){this.enabled&&(this.enabled=!1,this.app.graphicsDevice.off("resizecanvas",this._onCanvasResized,this),this._releaseDepthMaps(),this._destroyOffscreenTarget(this._sourceTarget),this.camera.renderTarget=null,this.camera.onPostprocessing=null)},t._onCanvasResized=function(e,t){var i=this.camera.rect,n=this.app.graphicsDevice;this.camera.camera.aspectRatio=n.width*i.z/(n.height*i.w),this.resizeRenderTargets()},t.resizeRenderTargets=function(){for(var e=this.camera.rect,t=Math.floor(e.z*this.app.graphicsDevice.width),i=Math.floor(e.w*this.app.graphicsDevice.height),n=this.effects,s=0,r=n.length;s<r;s++){var a=n[s];a.inputTarget.width===t&&a.inputTarget.height===i||this._resizeOffscreenTarget(a.inputTarget)}},t.onCameraRectChanged=function(e,t,i){this.enabled&&this.resizeRenderTargets()},e}(),mx=[{name:"aspectRatio",readonly:!1},{name:"aspectRatioMode",readonly:!1},{name:"calculateProjection",readonly:!1},{name:"calculateTransform",readonly:!1},{name:"clearColor",readonly:!1},{name:"cullFaces",readonly:!1},{name:"farClip",readonly:!1},{name:"flipFaces",readonly:!1},{name:"fov",readonly:!1},{name:"frustumCulling",readonly:!1},{name:"horizontalFov",readonly:!1},{name:"nearClip",readonly:!1},{name:"orthoHeight",readonly:!1},{name:"projection",readonly:!1},{name:"scissorRect",readonly:!1},{name:"aperture",readonly:!1},{name:"shutter",readonly:!1},{name:"sensitivity",readonly:!1}],_x=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this).onPostprocessing=null,n.onPreRender=null,n.onPostRender=null,n._renderSceneDepthMap=0,n._renderSceneColorMap=0,n._camera=new En,n._camera.node=i,n._priority=0,n._disablePostEffectsLayer=4,n._postEffects=new px(t.app,te(n)),n}J(t,e);var i=t.prototype;return i._enableDepthLayer=function(e){if(this.layers.find((function(e){return 1===e}))){var t=this.system.app.scene.layers.getLayerById(1);e?null==t||t.incrementCounter():null==t||t.decrementCounter()}else if(e)return!1;return!0},i.requestSceneColorMap=function(e){this._renderSceneColorMap+=e?1:-1,this._enableDepthLayer(e)},i.requestSceneDepthMap=function(e){this._renderSceneDepthMap+=e?1:-1,this._enableDepthLayer(e)},i.dirtyLayerCompositionCameras=function(){this.system.app.scene.layers._dirtyCameras=!0},i.screenToWorld=function(e,t,i,n){var s=this.system.app.graphicsDevice,r=s.clientRect.width,a=s.clientRect.height;return this._camera.screenToWorld(e,t,i,r,a,n)},i.worldToScreen=function(e,t){var i=this.system.app.graphicsDevice,n=i.clientRect.width,s=i.clientRect.height;return this._camera.worldToScreen(e,n,s,t)},i.onAppPrerender=function(){this._camera._viewMatDirty=!0,this._camera._viewProjMatDirty=!0},i.addCameraToLayers=function(){for(var e=this.layers,t=0;t<e.length;t++){var i=this.system.app.scene.layers.getLayerById(e[t]);i&&i.addCamera(this)}},i.removeCameraFromLayers=function(){for(var e=this.layers,t=0;t<e.length;t++){var i=this.system.app.scene.layers.getLayerById(e[t]);i&&i.removeCamera(this)}},i.onLayersChanged=function(e,t){this.addCameraToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(e){this.layers.indexOf(e.id)<0||e.addCamera(this)},i.onLayerRemoved=function(e){this.layers.indexOf(e.id)<0||e.removeCamera(this)},i.onEnable=function(){var e=this.system,t=e.app.scene,i=t.layers;e.addCamera(this),t.on("set:layers",this.onLayersChanged,this),i&&(i.on("add",this.onLayerAdded,this),i.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&this.addCameraToLayers(),this.postEffects.enable()},i.onDisable=function(){var e=this.system,t=e.app.scene,i=t.layers;this.postEffects.disable(),this.removeCameraFromLayers(),t.off("set:layers",this.onLayersChanged,this),i&&(i.off("add",this.onLayerAdded,this),i.off("remove",this.onLayerRemoved,this)),e.removeCamera(this)},i.onRemove=function(){this.onDisable(),this.off()},i.calculateAspectRatio=function(e){var t=this.system.app.graphicsDevice,i=e?e.width:t.width,n=e?e.height:t.height;return i*this.rect.z/(n*this.rect.w)},i.frameUpdate=function(e){0===this.aspectRatioMode&&(this.aspectRatio=this.calculateAspectRatio(e))},i.startXr=function(e,t,i){this.system.app.xr.start(this,e,t,i)},i.endXr=function(e){this._camera.xr?this._camera.xr.end(e):e&&e(new Error("Camera is not in XR"))},i.copy=function(e){var t=this;mx.forEach((function(i){if(!i.readonly){var n=i.name;t[n]=e[n]}})),this.clearColorBuffer=e.clearColorBuffer,this.clearDepthBuffer=e.clearDepthBuffer,this.clearStencilBuffer=e.clearStencilBuffer,this.disablePostEffectsLayer=e.disablePostEffectsLayer,this.layers=e.layers,this.priority=e.priority,this.renderTarget=e.renderTarget,this.rect=e.rect,this.aperture=e.aperture,this.sensitivity=e.sensitivity,this.shutter=e.shutter},$(t,[{key:"camera",get:function(){return this._camera}},{key:"clearColorBuffer",get:function(){return this._camera.clearColorBuffer},set:function(e){this._camera.clearColorBuffer=e,this.dirtyLayerCompositionCameras()}},{key:"clearDepthBuffer",get:function(){return this._camera.clearDepthBuffer},set:function(e){this._camera.clearDepthBuffer=e,this.dirtyLayerCompositionCameras()}},{key:"clearStencilBuffer",get:function(){return this._camera.clearStencilBuffer},set:function(e){this._camera.clearStencilBuffer=e,this.dirtyLayerCompositionCameras()}},{key:"disablePostEffectsLayer",get:function(){return this._disablePostEffectsLayer},set:function(e){this._disablePostEffectsLayer=e,this.dirtyLayerCompositionCameras()}},{key:"renderSceneColorMap",get:function(){return this._renderSceneColorMap>0}},{key:"renderSceneDepthMap",get:function(){return this._renderSceneDepthMap>0}},{key:"frustum",get:function(){return this._camera.frustum}},{key:"layers",get:function(){return this._camera.layers},set:function(e){for(var t=this._camera.layers,i=0;i<t.length;i++){var n=this.system.app.scene.layers.getLayerById(t[i]);n&&n.removeCamera(this)}if(this._camera.layers=e,this.enabled&&this.entity.enabled)for(var s=0;s<e.length;s++){var r=this.system.app.scene.layers.getLayerById(e[s]);r&&r.addCamera(this)}}},{key:"layersSet",get:function(){return this._camera.layersSet}},{key:"postEffectsEnabled",get:function(){return this._postEffects.enabled}},{key:"postEffects",get:function(){return this._postEffects}},{key:"priority",get:function(){return this._priority},set:function(e){this._priority=e,this.dirtyLayerCompositionCameras()}},{key:"projectionMatrix",get:function(){return this._camera.projectionMatrix}},{key:"aperture",get:function(){return this._camera.aperture},set:function(e){this._camera.aperture=e}},{key:"sensitivity",get:function(){return this._camera.sensitivity},set:function(e){this._camera.sensitivity=e}},{key:"shutter",get:function(){return this._camera.shutter},set:function(e){this._camera.shutter=e}},{key:"rect",get:function(){return this._camera.rect},set:function(e){this._camera.rect=e,this.fire("set:rect",this._camera.rect)}},{key:"renderTarget",get:function(){return this._camera.renderTarget},set:function(e){this._camera.renderTarget=e,this.dirtyLayerCompositionCameras()}},{key:"viewMatrix",get:function(){return this._camera.viewMatrix}}]),t}(Cl);mx.forEach((function(e){var t=e.name,i={get:function(){return this._camera[t]}};e.readonly||(i.set=function(e){this._camera[t]=e}),Object.defineProperty(_x.prototype,t,i)}));var gx=function(){this.enabled=!0},vx=["enabled"],yx=function(e){function t(t){var i;return(i=e.call(this,t)||this).cameras=[],i.id="camera",i.ComponentType=_x,i.DataType=gx,i.schema=vx,i.on("beforeremove",i.onBeforeRemove,te(i)),i.app.on("prerender",i.onAppPrerender,te(i)),i.app.systems.on("update",i.onUpdate,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){n=["aspectRatio","aspectRatioMode","calculateProjection","calculateTransform","clearColor","clearColorBuffer","clearDepthBuffer","clearStencilBuffer","cullFaces","farClip","flipFaces","fov","frustumCulling","horizontalFov","layers","renderTarget","nearClip","orthoHeight","projection","priority","rect","scissorRect","aperture","shutter","sensitivity"];for(var s=0;s<n.length;s++){var r=n[s];if(i.hasOwnProperty(r)){var a=i[r];switch(r){case"rect":case"scissorRect":Array.isArray(a)?t[r]=new Se(a[0],a[1],a[2],a[3]):t[r]=a;break;case"clearColor":Array.isArray(a)?t[r]=new me(a[0],a[1],a[2],a[3]):t[r]=a;break;default:t[r]=a}}}e.prototype.initializeComponentData.call(this,t,i,["enabled"])},i.cloneComponent=function(e,t){var i=e.camera;return this.addComponent(t,{aspectRatio:i.aspectRatio,aspectRatioMode:i.aspectRatioMode,calculateProjection:i.calculateProjection,calculateTransform:i.calculateTransform,clearColor:i.clearColor,clearColorBuffer:i.clearColorBuffer,clearDepthBuffer:i.clearDepthBuffer,clearStencilBuffer:i.clearStencilBuffer,cullFaces:i.cullFaces,enabled:i.enabled,farClip:i.farClip,flipFaces:i.flipFaces,fov:i.fov,frustumCulling:i.frustumCulling,horizontalFov:i.horizontalFov,layers:i.layers,renderTarget:i.renderTarget,nearClip:i.nearClip,orthoHeight:i.orthoHeight,projection:i.projection,priority:i.priority,rect:i.rect,scissorRect:i.scissorRect,aperture:i.aperture,sensitivity:i.sensitivity,shutter:i.shutter})},i.onBeforeRemove=function(e,t){this.removeCamera(t)},i.onUpdate=function(e){},i.onAppPrerender=function(){for(var e=0,t=this.cameras.length;e<t;e++)this.cameras[e].onAppPrerender()},i.addCamera=function(e){this.cameras.push(e),_h(this.cameras)},i.removeCamera=function(e){var t=this.cameras.indexOf(e);t>=0&&(this.cameras.splice(t,1),_h(this.cameras))},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},t}(h_);Cl._buildAccessors(_x.prototype,vx);var xx=[],bx=[],Sx=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._cookieAsset=null,n._cookieAssetId=null,n._cookieAssetAdd=!1,n._cookieMatrix=null,n}J(t,e);var i=t.prototype;return i.addLightToLayers=function(){for(var e=0;e<this.layers.length;e++){var t=this.system.app.scene.layers.getLayerById(this.layers[e]);t&&t.addLight(this)}},i.removeLightFromLayers=function(){for(var e=0;e<this.layers.length;e++){var t=this.system.app.scene.layers.getLayerById(this.layers[e]);t&&t.removeLight(this)}},i.onLayersChanged=function(e,t){this.enabled&&this.entity.enabled&&this.addLightToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(e){this.layers.indexOf(e.id)>=0&&this.enabled&&this.entity.enabled&&e.addLight(this)},i.onLayerRemoved=function(e){this.layers.indexOf(e.id)>=0&&e.removeLight(this)},i.refreshProperties=function(){for(var e=0;e<xx.length;e++){var t=xx[e];this[t]=this[t]}this.enabled&&this.entity.enabled&&this.onEnable()},i.updateShadow=function(){this.light.updateShadow()},i.onCookieAssetSet=function(){var e=!1;"cubemap"!==this._cookieAsset.type||this._cookieAsset.loadFaces||(this._cookieAsset.loadFaces=!0,e=!0),this._cookieAsset.resource&&!e||this.system.app.assets.load(this._cookieAsset),this._cookieAsset.resource&&this.onCookieAssetLoad()},i.onCookieAssetAdd=function(e){this._cookieAssetId===e.id&&(this._cookieAsset=e,this.light.enabled&&this.onCookieAssetSet(),this._cookieAsset.on("load",this.onCookieAssetLoad,this),this._cookieAsset.on("remove",this.onCookieAssetRemove,this))},i.onCookieAssetLoad=function(){this._cookieAsset&&this._cookieAsset.resource&&(this.cookie=this._cookieAsset.resource)},i.onCookieAssetRemove=function(){this._cookieAssetId&&(this._cookieAssetAdd&&(this.system.app.assets.off("add:"+this._cookieAssetId,this.onCookieAssetAdd,this),this._cookieAssetAdd=!1),this._cookieAsset&&(this._cookieAsset.off("load",this.onCookieAssetLoad,this),this._cookieAsset.off("remove",this.onCookieAssetRemove,this),this._cookieAsset=null),this.cookie=null)},i.onEnable=function(){this.light.enabled=!0,this.system.app.scene.on("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.on("add",this.onLayerAdded,this),this.system.app.scene.layers.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&this.addLightToLayers(),this._cookieAsset&&!this.cookie&&this.onCookieAssetSet()},i.onDisable=function(){this.light.enabled=!1,this.system.app.scene.off("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.off("add",this.onLayerAdded,this),this.system.app.scene.layers.off("remove",this.onLayerRemoved,this)),this.removeLightFromLayers()},i.onRemove=function(){this.onDisable(),this.light.destroy(),this.cookieAsset=null},t}(Cl);function wx(e,t,i,n){var s=Sx.prototype;xx.push(e),bx.push(t),Object.defineProperty(s,e,{get:function(){return this.data[e]},set:function(t){var s=this.data,r=s[e];(n||r!==t)&&(s[e]=t,i&&i.call(this,t,r))},configurable:!0})}wx("enabled",!0,(function(e,t){this.onSetEnabled(null,t,e)})),wx("light",null),wx("type","directional",(function(e,t){this.system.changeType(this,t,e),this.refreshProperties()})),wx("color",new me(1,1,1),(function(e,t){this.light.setColor(e)}),!0),wx("intensity",1,(function(e,t){this.light.intensity=e})),wx("luminance",0,(function(e,t){this.light.luminance=e})),wx("shape",0,(function(e,t){this.light.shape=e})),wx("castShadows",!1,(function(e,t){this.light.castShadows=e})),wx("shadowDistance",40,(function(e,t){this.light.shadowDistance=e})),wx("shadowIntensity",1,(function(e,t){this.light.shadowIntensity=e})),wx("shadowResolution",1024,(function(e,t){this.light.shadowResolution=e})),wx("shadowBias",.05,(function(e,t){this.light.shadowBias=-.01*de.clamp(e,0,1)})),wx("numCascades",1,(function(e,t){this.light.numCascades=de.clamp(Math.floor(e),1,4)})),wx("bakeNumSamples",1,(function(e,t){this.light.bakeNumSamples=de.clamp(Math.floor(e),1,255)})),wx("bakeArea",0,(function(e,t){this.light.bakeArea=de.clamp(e,0,180)})),wx("cascadeDistribution",.5,(function(e,t){this.light.cascadeDistribution=de.clamp(e,0,1)})),wx("normalOffsetBias",0,(function(e,t){this.light.normalOffsetBias=de.clamp(e,0,1)})),wx("range",10,(function(e,t){this.light.attenuationEnd=e})),wx("innerConeAngle",40,(function(e,t){this.light.innerConeAngle=e})),wx("outerConeAngle",45,(function(e,t){this.light.outerConeAngle=e})),wx("falloffMode",0,(function(e,t){this.light.falloffMode=e})),wx("shadowType",0,(function(e,t){this.light.shadowType=e})),wx("vsmBlurSize",11,(function(e,t){this.light.vsmBlurSize=e})),wx("vsmBlurMode",1,(function(e,t){this.light.vsmBlurMode=e})),wx("vsmBias",.0025,(function(e,t){this.light.vsmBias=de.clamp(e,0,1)})),wx("cookieAsset",null,(function(e,t){if(!this._cookieAssetId||!(e instanceof ml&&e.id===this._cookieAssetId||e===this._cookieAssetId))if(this.onCookieAssetRemove(),this._cookieAssetId=null,e instanceof ml)this.data.cookieAsset=e.id,this._cookieAssetId=e.id,this.onCookieAssetAdd(e);else if("number"==typeof e){this._cookieAssetId=e;var i=this.system.app.assets.get(e);i?this.onCookieAssetAdd(i):(this._cookieAssetAdd=!0,this.system.app.assets.on("add:"+this._cookieAssetId,this.onCookieAssetAdd,this))}})),wx("cookie",null,(function(e,t){this.light.cookie=e})),wx("cookieIntensity",1,(function(e,t){this.light.cookieIntensity=de.clamp(e,0,1)})),wx("cookieFalloff",!0,(function(e,t){this.light.cookieFalloff=e})),wx("cookieChannel","rgb",(function(e,t){this.light.cookieChannel=e})),wx("cookieAngle",0,(function(e,t){if(0!==e||null!==this.cookieScale){this._cookieMatrix||(this._cookieMatrix=new Se);var i=1,n=1;this.cookieScale&&(i=this.cookieScale.x,n=this.cookieScale.y);var s=Math.cos(e*de.DEG_TO_RAD),r=Math.sin(e*de.DEG_TO_RAD);this._cookieMatrix.set(s/i,-r/i,r/n,s/n),this.light.cookieTransform=this._cookieMatrix}else this.light.cookieTransform=null})),wx("cookieScale",null,(function(e,t){if(null!==e||0!==this.cookieAngle){this._cookieMatrix||(this._cookieMatrix=new Se);var i=e.x,n=e.y,s=Math.cos(this.cookieAngle*de.DEG_TO_RAD),r=Math.sin(this.cookieAngle*de.DEG_TO_RAD);this._cookieMatrix.set(s/i,-r/i,r/n,s/n),this.light.cookieTransform=this._cookieMatrix}else this.light.cookieTransform=null}),!0),wx("cookieOffset",null,(function(e,t){this.light.cookieOffset=e}),!0),wx("shadowUpdateMode",2,(function(e,t){this.light.shadowUpdateMode=e}),!0),wx("mask",1,(function(e,t){this.light.mask=e})),wx("affectDynamic",!0,(function(e,t){e?this.light.mask|=1:this.light.mask&=-2,this.light.layersDirty()})),wx("affectLightmapped",!1,(function(e,t){e?(this.light.mask|=2,this.bake&&(this.light.mask&=-5)):(this.light.mask&=-3,this.bake&&(this.light.mask|=4))})),wx("bake",!1,(function(e,t){e?(this.light.mask|=4,this.affectLightmapped&&(this.light.mask&=-3)):(this.light.mask&=-5,this.affectLightmapped&&(this.light.mask|=2)),this.light.layersDirty()})),wx("bakeDir",!0,(function(e,t){this.light.bakeDir=e})),wx("isStatic",!1,(function(e,t){this.light.isStatic=e})),wx("layers",[0],(function(e,t){for(var i=0;i<t.length;i++){var n=this.system.app.scene.layers.getLayerById(t[i]);n&&n.removeLight(this)}for(var s=0;s<e.length;s++){var r=this.system.app.scene.layers.getLayerById(e[s]);r&&this.enabled&&this.entity.enabled&&r.addLight(this)}}));for(var Tx=function(){for(var e=xx,t=bx,i=0;i<e.length;i++){var n=t[i];n&&n.clone?this[e[i]]=n.clone():this[e[i]]=n}},Ax=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="light",i.ComponentType=Sx,i.DataType=Tx,i.on("beforeremove",i._onRemoveComponent,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i){for(var n=xx,s={},r=0,a=n.length;r<a;r++){var o=n[r];s[o]=i[o]}s.type||(s.type=t.data.type),t.data.type=s.type,s.layers&&Array.isArray(s.layers)&&(s.layers=s.layers.slice(0)),s.color&&Array.isArray(s.color)&&(s.color=new me(s.color[0],s.color[1],s.color[2])),s.cookieOffset&&s.cookieOffset instanceof Array&&(s.cookieOffset=new be(s.cookieOffset[0],s.cookieOffset[1])),s.cookieScale&&s.cookieScale instanceof Array&&(s.cookieScale=new be(s.cookieScale[0],s.cookieScale[1])),s.enable&&(console.warn("WARNING: enable: Property is deprecated. Set enabled property instead."),s.enabled=s.enable),s.shape||(s.shape=0);var h=new Ih(this.app.graphicsDevice);h.type=Ch[s.type],h._node=t.entity,h._scene=this.app.scene,t.data.light=h,e.prototype.initializeComponentData.call(this,t,s,n)},i._onRemoveComponent=function(e,t){t.onRemove()},i.cloneComponent=function(e,t){for(var i,n=e.light,s=[],r=xx,a=0;a<r.length;a++)"light"!==(i=r[a])&&(n[i]&&n[i].clone?s[i]=n[i].clone():s[i]=n[i]);return this.addComponent(t,s)},i.changeType=function(e,t,i){t!==i&&(e.light.type=Ch[i])},t}(h_),Mx=function(){this.enabled=!0},Cx=0,Ex=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="script",i.ComponentType=El,i.DataType=Mx,i._components=new re({sortBy:"_executionOrder"}),i._enabledComponents=new re({sortBy:"_executionOrder"}),i.preloading=!0,i.on("beforeremove",i._onBeforeRemove,te(i)),i.app.systems.on("initialize",i._onInitialize,te(i)),i.app.systems.on("postInitialize",i._onPostInitialize,te(i)),i.app.systems.on("update",i._onUpdate,te(i)),i.app.systems.on("postUpdate",i._onPostUpdate,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(e,t){if(e._executionOrder=Cx++,this._components.append(e),Cx>Number.MAX_SAFE_INTEGER&&this._resetExecutionOrder(),e.enabled=!t.hasOwnProperty("enabled")||!!t.enabled,e.enabled&&e.entity.enabled&&this._enabledComponents.append(e),t.hasOwnProperty("order")&&t.hasOwnProperty("scripts")){e._scriptsData=t.scripts;for(var i=0;i<t.order.length;i++)e.create(t.order[i],{enabled:t.scripts[t.order[i]].enabled,attributes:t.scripts[t.order[i]].attributes,preloading:this.preloading})}},i.cloneComponent=function(e,t){for(var i=[],n={},s=0;s<e.script._scripts.length;s++){var r=e.script._scripts[s],a=r.__scriptType.__name;i.push(a);var o={};for(var h in r.__attributes)o[h]=r.__attributes[h];n[a]={enabled:r._enabled,attributes:o}}for(var l in e.script._scriptsIndex)l.awaiting&&i.splice(l.ind,0,l);var c={enabled:e.script.enabled,order:i,scripts:n};return this.addComponent(t,c)},i._resetExecutionOrder=function(){Cx=0;for(var e=0,t=this._components.length;e<t;e++)this._components.items[e]._executionOrder=Cx++},i._callComponentMethod=function(e,t,i){for(e.loopIndex=0;e.loopIndex<e.length;e.loopIndex++)e.items[e.loopIndex][t](i)},i._onInitialize=function(){this.preloading=!1,this._callComponentMethod(this._components,"_onInitializeAttributes"),this._callComponentMethod(this._enabledComponents,"_onInitialize")},i._onPostInitialize=function(){this._callComponentMethod(this._enabledComponents,"_onPostInitialize")},i._onUpdate=function(e){this._callComponentMethod(this._enabledComponents,"_onUpdate",e)},i._onPostUpdate=function(e){this._callComponentMethod(this._enabledComponents,"_onPostUpdate",e)},i._addComponentToEnabled=function(e){this._enabledComponents.insert(e)},i._removeComponentFromEnabled=function(e){this._enabledComponents.remove(e)},i._onBeforeRemove=function(e,t){this._components.items.indexOf(t)>=0&&t._onBeforeRemove(),this._removeComponentFromEnabled(t),this._components.remove(t)},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("initialize",this._onInitialize,this),this.app.systems.off("postInitialize",this._onPostInitialize,this),this.app.systems.off("update",this._onUpdate,this),this.app.systems.off("postUpdate",this._onPostUpdate,this)},t}(h_),Px="inline",Rx="immersive-vr",Ix="immersive-ar",Lx="viewer",Dx="left",kx="cpu-optimized",Ox="gpu-optimized",Fx="luminance-alpha",Bx=[],Nx=[],Ux=function(e){function t(t,i,n){var s;return(s=e.call(this)||this).manager=void 0,s._xrHitTestSource=void 0,s._transient=void 0,s.manager=t,s._xrHitTestSource=i,s._transient=n,s}J(t,e);var i=t.prototype;return i.remove=function(){if(this._xrHitTestSource){var e=this.manager.hitTest.sources,t=e.indexOf(this);-1!==t&&e.splice(t,1),this.onStop()}},i.onStop=function(){this._xrHitTestSource.cancel(),this._xrHitTestSource=null,this.fire("remove"),this.manager.hitTest.fire("remove",this)},i.update=function(e){if(this._transient)for(var t=e.getHitTestResultsForTransientInput(this._xrHitTestSource),i=0;i<t.length;i++){var n=t[i],s=void 0;n.inputSource&&(s=this.manager.input._getByInputSource(n.inputSource)),this.updateHitResults(n.results,s)}else this.updateHitResults(e.getHitTestResults(this._xrHitTestSource))},i.updateHitResults=function(e,t){for(var i=0;i<e.length;i++){var n=e[i].getPose(this.manager._referenceSpace),s=Bx.pop();s||(s=new ye),s.copy(n.transform.position);var r=Nx.pop();r||(r=new Pe),r.copy(n.transform.orientation),this.fire("result",s,r,t),this.manager.hitTest.fire("result",this,s,r,t),Bx.push(s),Nx.push(r)}},t}(m),zx=function(e){function t(t){var i;return(i=e.call(this)||this).manager=void 0,i._supported=L.browser&&!(!window.XRSession||!window.XRSession.prototype.requestHitTestSource),i._session=null,i.sources=[],i.manager=t,i._supported&&(i.manager.on("start",i._onSessionStart,te(i)),i.manager.on("end",i._onSessionEnd,te(i))),i}J(t,e);var i=t.prototype;return i._onSessionStart=function(){this.manager.type===Ix&&(this._session=this.manager.session)},i._onSessionEnd=function(){if(this._session){this._session=null;for(var e=0;e<this.sources.length;e++)this.sources[e].onStop();this.sources=[]}},i.isAvailable=function(e,t){var i;return this._supported||(i=new Error("XR HitTest is not supported")),this._session||(i=new Error("XR Session is not started (1)")),this.manager.type!==Ix&&(i=new Error("XR HitTest is available only for AR")),!i||(e&&e(i),t&&t.fire("error",i),!1)},i.start=function(e){var t=this;if(void 0===e&&(e={}),this.isAvailable(e.callback,this)){var i;e.profile||e.spaceType||(e.spaceType=Lx);var n=e.offsetRay;if(n){var s=new DOMPoint(n.origin.x,n.origin.y,n.origin.z,1),r=new DOMPoint(n.direction.x,n.direction.y,n.direction.z,0);i=new XRRay(s,r)}var a=e.callback;e.spaceType?this._session.requestReferenceSpace(e.spaceType).then((function(n){if(!t._session){var s=new Error("XR Session is not started (2)");return a&&a(s),void t.fire("error",s)}t._session.requestHitTestSource({space:n,entityTypes:e.entityTypes||void 0,offsetRay:i}).then((function(e){t._onHitTestSource(e,!1,a)})).catch((function(e){a&&a(e),t.fire("error",e)}))})).catch((function(e){a&&a(e),t.fire("error",e)})):this._session.requestHitTestSourceForTransientInput({profile:e.profile,entityTypes:e.entityTypes||void 0,offsetRay:i}).then((function(e){t._onHitTestSource(e,!0,a)})).catch((function(e){a&&a(e),t.fire("error",e)}))}},i._onHitTestSource=function(e,t,i){if(!this._session){e.cancel();var n=new Error("XR Session is not started (3)");return i&&i(n),void this.fire("error",n)}var s=new Ux(this.manager,e,t);this.sources.push(s),i&&i(null,s),this.fire("add",s)},i.update=function(e){for(var t=0;t<this.sources.length;t++)this.sources[t].update(e)},$(t,[{key:"supported",get:function(){return this._supported}}]),t}(m),Vx=function(){function e(e,t){this._index=void 0,this._hand=void 0,this._joints=[],this._tip=null,this._index=e,this._hand=t,this._hand._fingers.push(this)}return $(e,[{key:"index",get:function(){return this._index}},{key:"hand",get:function(){return this._hand}},{key:"joints",get:function(){return this._joints}},{key:"tip",get:function(){return this._tip}}]),e}(),Gx=L.browser&&window.XRHand?["thumb-tip","index-finger-tip","middle-finger-tip","ring-finger-tip","pinky-finger-tip"]:[],Wx={},Hx=0;Hx<Gx.length;Hx++)Wx[Gx[Hx]]=!0;var Xx=function(){function e(e,t,i,n){void 0===n&&(n=null),this._index=void 0,this._id=void 0,this._hand=void 0,this._finger=void 0,this._wrist=void 0,this._tip=void 0,this._radius=null,this._localTransform=new Ee,this._worldTransform=new Ee,this._localPosition=new ye,this._localRotation=new Pe,this._position=new ye,this._rotation=new Pe,this._dirtyLocal=!0,this._index=e,this._id=t,this._hand=i,this._finger=n,this._wrist="wrist"===t,this._tip=this._finger&&!!Wx[t]}var t=e.prototype;return t.update=function(e){this._dirtyLocal=!0,this._radius=e.radius,this._localPosition.copy(e.transform.position),this._localRotation.copy(e.transform.orientation)},t._updateTransforms=function(){this._dirtyLocal&&(this._dirtyLocal=!1,this._localTransform.setTRS(this._localPosition,this._localRotation,ye.ONE));var e=this._hand._manager.camera.parent;e?this._worldTransform.mul2(e.getWorldTransform(),this._localTransform):this._worldTransform.copy(this._localTransform)},t.getPosition=function(){return this._updateTransforms(),this._worldTransform.getTranslation(this._position),this._position},t.getRotation=function(){return this._updateTransforms(),this._rotation.setFromMat4(this._worldTransform),this._rotation},$(e,[{key:"index",get:function(){return this._index}},{key:"hand",get:function(){return this._hand}},{key:"finger",get:function(){return this._finger}},{key:"wrist",get:function(){return this._wrist}},{key:"tip",get:function(){return this._tip}},{key:"radius",get:function(){return this._radius||.005}}]),e}(),qx=[],jx=new ye,Yx=new ye,Kx=new ye;L.browser&&window.XRHand&&(qx=[["thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip"],["index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip"],["middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip"],["ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip"],["pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"]]);var Zx=function(e){function t(t){var i;(i=e.call(this)||this)._manager=void 0,i._inputSource=void 0,i._tracking=!1,i._fingers=[],i._joints=[],i._jointsById={},i._tips=[],i._wrist=null;var n=t._xrInputSource.hand;if(i._manager=t._manager,i._inputSource=t,n.get("wrist")){var s=new Xx(0,"wrist",te(i),null);i._wrist=s,i._joints.push(s),i._jointsById.wrist=s}for(var r=0;r<qx.length;r++)for(var a=new Vx(r,te(i)),o=0;o<qx[r].length;o++){var h=qx[r][o];if(n.get(h)){var l=new Xx(o,h,te(i),a);i._joints.push(l),i._jointsById[h]=l,l.tip&&(i._tips.push(l),a._tip=l),a._joints.push(l)}}return i}J(t,e);var i=t.prototype;return i.update=function(e){for(var t=this._inputSource._xrInputSource,i=0;i<this._joints.length;i++){var n=this._joints[i],s=t.hand.get(n._id);if(s){var r=void 0;if("hidden"!==e.session.visibilityState&&(r=e.getJointPose(s,this._manager._referenceSpace)),r)n.update(r),n.wrist&&!this._tracking&&(this._tracking=!0,this.fire("tracking"));else if(n.wrist){this._tracking&&(this._tracking=!1,this.fire("trackinglost"));break}}}var a=this._jointsById["thumb-metacarpal"],o=this._jointsById["thumb-tip"],h=this._jointsById["index-finger-phalanx-proximal"],l=this._jointsById["index-finger-tip"],c=this._jointsById["ring-finger-phalanx-proximal"],u=this._jointsById["pinky-finger-phalanx-proximal"];if(a&&o&&h&&l&&c&&u){this._inputSource._dirtyRay=!0,this._inputSource._rayLocal.origin.lerp(o._localPosition,l._localPosition,.5);var d=a,f=u;if(this._inputSource.handedness===Dx){var p=d;d=f,f=p}jx.sub2(d._localPosition,this._wrist._localPosition),Yx.sub2(f._localPosition,this._wrist._localPosition),Kx.cross(jx,Yx).normalize(),jx.lerp(h._localPosition,c._localPosition,.5),jx.sub(this._wrist._localPosition).normalize(),this._inputSource._rayLocal.direction.lerp(Kx,jx,.5).normalize()}this._fingerIsClosed(1)&&this._fingerIsClosed(2)&&this._fingerIsClosed(3)&&this._fingerIsClosed(4)?this._inputSource._squeezing||(this._inputSource._squeezing=!0,this._inputSource.fire("squeezestart"),this._manager.input.fire("squeezestart",this._inputSource)):this._inputSource._squeezing&&(this._inputSource._squeezing=!1,this._inputSource.fire("squeeze"),this._manager.input.fire("squeeze",this._inputSource),this._inputSource.fire("squeezeend"),this._manager.input.fire("squeezeend",this._inputSource))},i._fingerIsClosed=function(e){var t=this._fingers[e];return jx.sub2(t.joints[0]._localPosition,t.joints[1]._localPosition).normalize(),Yx.sub2(t.joints[2]._localPosition,t.joints[3]._localPosition).normalize(),jx.dot(Yx)<-.8},i.getJointById=function(e){return this._jointsById[e]||null},$(t,[{key:"fingers",get:function(){return this._fingers}},{key:"joints",get:function(){return this._joints}},{key:"tips",get:function(){return this._tips}},{key:"wrist",get:function(){return this._wrist}},{key:"tracking",get:function(){return this._tracking}}]),t}(m),$x=new Pe,Qx=0,Jx=function(e){function t(t,i){var n;return(n=e.call(this)||this)._id=void 0,n._manager=void 0,n._xrInputSource=void 0,n._ray=new et,n._rayLocal=new et,n._grip=!1,n._hand=null,n._localTransform=null,n._worldTransform=null,n._position=new ye,n._rotation=new Pe,n._localPosition=null,n._localRotation=null,n._dirtyLocal=!0,n._dirtyRay=!1,n._selecting=!1,n._squeezing=!1,n._elementInput=!0,n._elementEntity=null,n._hitTestSources=[],n._id=++Qx,n._manager=t,n._xrInputSource=i,i.hand&&(n._hand=new Zx(te(n))),n}J(t,e);var i=t.prototype;return i.update=function(e){if(this._hand)this._hand.update(e);else{if(this._xrInputSource.gripSpace){var t=e.getPose(this._xrInputSource.gripSpace,this._manager._referenceSpace);t&&(this._grip||(this._grip=!0,this._localTransform=new Ee,this._worldTransform=new Ee,this._localPosition=new ye,this._localRotation=new Pe),this._dirtyLocal=!0,this._localPosition.copy(t.transform.position),this._localRotation.copy(t.transform.orientation))}var i=e.getPose(this._xrInputSource.targetRaySpace,this._manager._referenceSpace);i&&(this._dirtyRay=!0,this._rayLocal.origin.copy(i.transform.position),this._rayLocal.direction.set(0,0,-1),$x.copy(i.transform.orientation),$x.transformVector(this._rayLocal.direction,this._rayLocal.direction))}},i._updateTransforms=function(){this._dirtyLocal&&(this._dirtyLocal=!1,this._localTransform.setTRS(this._localPosition,this._localRotation,ye.ONE));var e=this._manager.camera.parent;e?this._worldTransform.mul2(e.getWorldTransform(),this._localTransform):this._worldTransform.copy(this._localTransform)},i._updateRayTransforms=function(){var e=this._dirtyRay;if(this._dirtyRay=!1,this._manager.camera.parent){var t=this._manager.camera.parent.getWorldTransform();t.getTranslation(this._position),this._rotation.setFromMat4(t),this._rotation.transformVector(this._rayLocal.origin,this._ray.origin),this._ray.origin.add(this._position),this._rotation.transformVector(this._rayLocal.direction,this._ray.direction)}else e&&(this._ray.origin.copy(this._rayLocal.origin),this._ray.direction.copy(this._rayLocal.direction))},i.getPosition=function(){return this._position?(this._updateTransforms(),this._worldTransform.getTranslation(this._position),this._position):null},i.getLocalPosition=function(){return this._localPosition},i.getRotation=function(){return this._rotation?(this._updateTransforms(),this._rotation.setFromMat4(this._worldTransform),this._rotation):null},i.getLocalRotation=function(){return this._localRotation},i.getOrigin=function(){return this._updateRayTransforms(),this._ray.origin},i.getDirection=function(){return this._updateRayTransforms(),this._ray.direction},i.hitTestStart=function(e){var t=this;void 0===e&&(e={}),e.profile=this._xrInputSource.profiles[0];var i=e.callback;e.callback=function(e,n){n&&t.onHitTestSourceAdd(n),i&&i(e,n)},this._manager.hitTest.start(e)},i.onHitTestSourceAdd=function(e){this._hitTestSources.push(e),this.fire("hittest:add",e),e.on("result",(function(t,i,n){n===this&&this.fire("hittest:result",e,t,i)}),this),e.once("remove",(function(){this.onHitTestSourceRemove(e),this.fire("hittest:remove",e)}),this)},i.onHitTestSourceRemove=function(e){var t=this._hitTestSources.indexOf(e);-1!==t&&this._hitTestSources.splice(t,1)},$(t,[{key:"id",get:function(){return this._id}},{key:"inputSource",get:function(){return this._xrInputSource}},{key:"targetRayMode",get:function(){return this._xrInputSource.targetRayMode}},{key:"handedness",get:function(){return this._xrInputSource.handedness}},{key:"profiles",get:function(){return this._xrInputSource.profiles}},{key:"grip",get:function(){return this._grip}},{key:"hand",get:function(){return this._hand}},{key:"gamepad",get:function(){return this._xrInputSource.gamepad||null}},{key:"selecting",get:function(){return this._selecting}},{key:"squeezing",get:function(){return this._squeezing}},{key:"elementInput",get:function(){return this._elementInput},set:function(e){this._elementInput!==e&&(this._elementInput=e,this._elementInput||(this._elementEntity=null))}},{key:"elementEntity",get:function(){return this._elementEntity}},{key:"hitTestSources",get:function(){return this._hitTestSources}}]),t}(m),eb=function(e){function t(t){var i;return(i=e.call(this)||this).manager=void 0,i._inputSources=[],i._onInputSourcesChangeEvt=void 0,i.manager=t,i._onInputSourcesChangeEvt=function(e){i._onInputSourcesChange(e)},i.manager.on("start",i._onSessionStart,te(i)),i.manager.on("end",i._onSessionEnd,te(i)),i}J(t,e);var i=t.prototype;return i._onSessionStart=function(){var e=this,t=this.manager.session;t.addEventListener("inputsourceschange",this._onInputSourcesChangeEvt),t.addEventListener("select",(function(t){var i=e._getByInputSource(t.inputSource);i.update(t.frame),i.fire("select",t),e.fire("select",i,t)})),t.addEventListener("selectstart",(function(t){var i=e._getByInputSource(t.inputSource);i.update(t.frame),i._selecting=!0,i.fire("selectstart",t),e.fire("selectstart",i,t)})),t.addEventListener("selectend",(function(t){var i=e._getByInputSource(t.inputSource);i.update(t.frame),i._selecting=!1,i.fire("selectend",t),e.fire("selectend",i,t)})),t.addEventListener("squeeze",(function(t){var i=e._getByInputSource(t.inputSource);i.update(t.frame),i.fire("squeeze",t),e.fire("squeeze",i,t)})),t.addEventListener("squeezestart",(function(t){var i=e._getByInputSource(t.inputSource);i.update(t.frame),i._squeezing=!0,i.fire("squeezestart",t),e.fire("squeezestart",i,t)})),t.addEventListener("squeezeend",(function(t){var i=e._getByInputSource(t.inputSource);i.update(t.frame),i._squeezing=!1,i.fire("squeezeend",t),e.fire("squeezeend",i,t)}));for(var i=t.inputSources,n=0;n<i.length;n++)this._addInputSource(i[n])},i._onSessionEnd=function(){for(var e=this._inputSources.length;e--;){var t=this._inputSources[e];this._inputSources.splice(e,1),t.fire("remove"),this.fire("remove",t)}this.manager.session.removeEventListener("inputsourceschange",this._onInputSourcesChangeEvt)},i._onInputSourcesChange=function(e){for(var t=0;t<e.removed.length;t++)this._removeInputSource(e.removed[t]);for(var i=0;i<e.added.length;i++)this._addInputSource(e.added[i])},i._getByInputSource=function(e){for(var t=0;t<this._inputSources.length;t++)if(this._inputSources[t].inputSource===e)return this._inputSources[t];return null},i._addInputSource=function(e){if(!this._getByInputSource(e)){var t=new Jx(this.manager,e);this._inputSources.push(t),this.fire("add",t)}},i._removeInputSource=function(e){for(var t=0;t<this._inputSources.length;t++)if(this._inputSources[t].inputSource===e){var i=this._inputSources[t];this._inputSources.splice(t,1);for(var n=i.hitTestSources.length;n--;)i.hitTestSources[n].remove();return i.fire("remove"),void this.fire("remove",i)}},i.update=function(e){for(var t=0;t<this._inputSources.length;t++)this._inputSources[t].update(e)},$(t,[{key:"inputSources",get:function(){return this._inputSources}}]),t}(m),tb=new ye,ib=new ye,nb=new Ee,sb=new Ee,rb=function(e){function t(t){var i;return(i=e.call(this)||this)._manager=void 0,i._supported=!1,i._available=!1,i._lightProbeRequested=!1,i._lightProbe=null,i._intensity=0,i._rotation=new Pe,i._color=new me,i._sphericalHarmonics=new Float32Array(27),i._manager=t,i._manager.on("start",i._onSessionStart,te(i)),i._manager.on("end",i._onSessionEnd,te(i)),i}J(t,e);var i=t.prototype;return i._onSessionStart=function(){!!this._manager.session.requestLightProbe&&(this._supported=!0)},i._onSessionEnd=function(){this._supported=!1,this._available=!1,this._lightProbeRequested=!1,this._lightProbe=null},i.start=function(){var e,t=this;this._manager.session||(e=new Error("XR session is not running")),e||this._manager.type===Ix||(e=new Error("XR session type is not AR")),e||this._supported||(e=new Error("light-estimation is not supported")),(!e&&this._lightProbe||this._lightProbeRequested)&&(e=new Error("light estimation is already requested")),e?this.fire("error",e):(this._lightProbeRequested=!0,this._manager.session.requestLightProbe().then((function(e){var i=t._lightProbeRequested;t._lightProbeRequested=!1,t._manager.active?i&&(t._lightProbe=e):t.fire("error",new Error("XR session is not active"))})).catch((function(e){t._lightProbeRequested=!1,t.fire("error",e)})))},i.end=function(){this._lightProbeRequested=!1,this._lightProbe=null,this._available=!1},i.update=function(e){if(this._lightProbe){var t=e.getLightEstimate(this._lightProbe);if(t){this._available||(this._available=!0,this.fire("available"));var i=t.primaryLightIntensity;this._intensity=Math.max(1,Math.max(i.x,Math.max(i.y,i.z))),tb.copy(i).mulScalar(1/this._intensity),this._color.set(tb.x,tb.y,tb.z),tb.set(0,0,0),ib.copy(t.primaryLightDirection),nb.setLookAt(ib,tb,ye.UP),sb.setFromAxisAngle(ye.RIGHT,90),nb.mul(sb),this._rotation.setFromMat4(nb),this._sphericalHarmonics.set(t.sphericalHarmonicsCoefficients)}}},$(t,[{key:"supported",get:function(){return this._supported}},{key:"available",get:function(){return this._available}},{key:"intensity",get:function(){return this._available?this._intensity:null}},{key:"color",get:function(){return this._available?this._color:null}},{key:"rotation",get:function(){return this._available?this._rotation:null}},{key:"sphericalHarmonics",get:function(){return this._available?this._sphericalHarmonics:null}}]),t}(m),ab=function(e){function t(t,i){var n;return(n=e.call(this)||this)._image=void 0,n._width=void 0,n._bitmap=null,n._measuredWidth=0,n._trackable=!1,n._tracking=!1,n._emulated=!1,n._pose=null,n._position=new ye,n._rotation=new Pe,n._image=t,n._width=i,n}J(t,e);var i=t.prototype;return i.prepare=function(){var e=this;return this._bitmap?{image:this._bitmap,widthInMeters:this._width}:createImageBitmap(this._image).then((function(t){return e._bitmap=t,{image:e._bitmap,widthInMeters:e._width}}))},i.destroy=function(){this._image=null,this._pose=null,this._bitmap&&(this._bitmap.close(),this._bitmap=null)},i.getPosition=function(){return this._pose&&this._position.copy(this._pose.transform.position),this._position},i.getRotation=function(){return this._pose&&this._rotation.copy(this._pose.transform.orientation),this._rotation},$(t,[{key:"image",get:function(){return this._image}},{key:"width",get:function(){return this._width},set:function(e){this._width=e}},{key:"trackable",get:function(){return this._trackable}},{key:"tracking",get:function(){return this._tracking}},{key:"emulated",get:function(){return this._emulated}}]),t}(m),ob=function(e){function t(t){var i;return(i=e.call(this)||this)._manager=void 0,i._supported=L.browser&&!!window.XRImageTrackingResult,i._available=!1,i._images=[],i._manager=t,i._supported&&(i._manager.on("start",i._onSessionStart,te(i)),i._manager.on("end",i._onSessionEnd,te(i))),i}J(t,e);var i=t.prototype;return i.add=function(e,t){if(!this._supported||this._manager.active)return null;var i=new ab(e,t);return this._images.push(i),i},i.remove=function(e){if(!this._manager.active){var t=this._images.indexOf(e);-1!==t&&(e.destroy(),this._images.splice(t,1))}},i._onSessionStart=function(){var e=this;this._manager.session.getTrackedImageScores().then((function(t){e._available=!0;for(var i=0;i<t.length;i++)e._images[i]._trackable="trackable"===t[i]})).catch((function(t){e._available=!1,e.fire("error",t)}))},i._onSessionEnd=function(){this._available=!1;for(var e=0;e<this._images.length;e++){var t=this._images[e];t._pose=null,t._measuredWidth=0,t._tracking&&(t._tracking=!1,t.fire("untracked"))}},i.prepareImages=function(e){this._images.length?Promise.all(this._images.map((function(e){return e.prepare()}))).then((function(t){e(null,t)})).catch((function(t){e(t,null)})):e(null,null)},i.update=function(e){if(this._available){for(var t=e.getImageTrackingResults(),i={},n=0;n<t.length;n++){i[t[n].index]=t[n];var s=this._images[t[n].index];s._emulated="emulated"===t[n].trackingState,s._measuredWidth=t[n].measuredWidthInMeters,s._pose=e.getPose(t[n].imageSpace,this._manager._referenceSpace)}for(var r=0;r<this._images.length;r++)this._images[r]._tracking&&!i[r]?(this._images[r]._tracking=!1,this._images[r].fire("untracked")):!this._images[r]._tracking&&i[r]&&(this._images[r]._tracking=!0,this._images[r].fire("tracked"))}},$(t,[{key:"supported",get:function(){return this._supported}},{key:"available",get:function(){return this._available}},{key:"images",get:function(){return this._images}}]),t}(m),hb=function(){function e(e){this._manager=void 0,this._supported=L.browser&&!!window.XRDOMOverlayState,this._root=null,this._manager=e}return $(e,[{key:"supported",get:function(){return this._supported}},{key:"available",get:function(){return this._supported&&this._manager.active&&null!==this._manager._session.domOverlayState}},{key:"state",get:function(){return this._supported&&this._manager.active&&this._manager._session.domOverlayState?this._manager._session.domOverlayState.type:null}},{key:"root",get:function(){return this._root},set:function(e){this._supported&&!this._manager.active&&(this._root=e)}}]),e}(),lb=function(e){function t(t){var i;return(i=e.call(this)||this)._manager=void 0,i._available=!1,i._depthInfoCpu=null,i._depthInfoGpu=null,i._usage=null,i._dataFormat=null,i._matrixDirty=!1,i._matrix=new Ee,i._emptyBuffer=new Uint8Array(32),i._depthBuffer=null,i._texture=void 0,i._manager=t,i._texture=new wn(i._manager.app.graphicsDevice,{format:2,mipmaps:!1,addressU:1,addressV:1,minFilter:1,magFilter:1,name:"XRDepthSensing"}),i.supported&&(i._manager.on("start",i._onSessionStart,te(i)),i._manager.on("end",i._onSessionEnd,te(i))),i}J(t,e);var i=t.prototype;return i.destroy=function(){this._texture.destroy(),this._texture=null},i._onSessionStart=function(){var e=this._manager.session;try{this._usage=e.depthUsage,this._dataFormat=e.depthDataFormat}catch(e){this._usage=null,this._dataFormat=null,this._available=!1,this.fire("error",e)}},i._onSessionEnd=function(){this._depthInfoCpu=null,this._depthInfoGpu=null,this._usage=null,this._dataFormat=null,this._available&&(this._available=!1,this.fire("unavailable")),this._depthBuffer=null,this._texture._width=4,this._texture._height=4,this._texture._levels[0]=this._emptyBuffer,this._texture.upload()},i._updateTexture=function(){var e=this._depthInfoCpu||this._depthInfoGpu;if(e){var t=!1;if(e.width===this._texture.width&&e.height===this._texture.height||(this._texture._width=e.width,this._texture._height=e.height,this._matrixDirty=!0,t=!0),this._depthInfoCpu){var i=this._depthInfoCpu.data;this._depthBuffer=new Uint8Array(i),this._texture._levels[0]=this._depthBuffer,this._texture.upload()}else this._depthInfoGpu&&(this._texture._levels[0]=this._depthInfoGpu.texture,this._texture.upload());t&&this.fire("resize",e.width,e.height)}else this._depthBuffer&&(this._depthBuffer=null,this._texture._width=4,this._texture._height=4,this._texture._levels[0]=this._emptyBuffer,this._texture.upload())},i.update=function(e,t){if(this._usage){var i=null,n=null;if(this._usage===kx&&t?i=e.getDepthInformation(t):this._usage===Ox&&t&&(n=e.getDepthInformation(t)),(this._depthInfoCpu&&!i||!this._depthInfoCpu&&i||this.depthInfoGpu&&!n||!this._depthInfoGpu&&n)&&(this._matrixDirty=!0),this._depthInfoCpu=i,this._depthInfoGpu=n,this._updateTexture(),this._matrixDirty){this._matrixDirty=!1;var s=this._depthInfoCpu||this._depthInfoGpu;s?this._matrix.data.set(s.normDepthBufferFromNormView.matrix):this._matrix.setIdentity()}!this._depthInfoCpu&&!this._depthInfoGpu||this._available?this._depthInfoCpu||this._depthInfoGpu||!this._available||(this._available=!1,this.fire("unavailable")):(this._available=!0,this.fire("available"))}},i.getDepth=function(e,t){return this._depthInfoCpu?this._depthInfoCpu.getDepthInMeters(e,t):null},$(t,[{key:"supported",get:function(){return L.browser&&!!window.XRDepthInformation}},{key:"available",get:function(){return this._available}},{key:"usage",get:function(){return this._usage}},{key:"dataFormat",get:function(){return this._dataFormat}},{key:"width",get:function(){var e=this._depthInfoCpu||this._depthInfoGpu;return e&&e.width||0}},{key:"height",get:function(){var e=this._depthInfoCpu||this._depthInfoGpu;return e&&e.height||0}},{key:"texture",get:function(){return this._texture}},{key:"uvMatrix",get:function(){return this._matrix}},{key:"rawValueToMeters",get:function(){var e=this._depthInfoCpu||this._depthInfoGpu;return e&&e.rawValueToMeters||0}}]),t}(m),cb=0,ub=function(e){function t(t,i){var n;return(n=e.call(this)||this)._id=void 0,n._planeDetection=void 0,n._xrPlane=void 0,n._lastChangedTime=void 0,n._orientation=void 0,n._position=new ye,n._rotation=new Pe,n._id=++cb,n._planeDetection=t,n._xrPlane=i,n._lastChangedTime=i.lastChangedTime,n._orientation=i.orientation,n}J(t,e);var i=t.prototype;return i.destroy=function(){this.fire("remove")},i.update=function(e){var t=this._planeDetection._manager,i=e.getPose(this._xrPlane.planeSpace,t._referenceSpace);i&&(this._position.copy(i.transform.position),this._rotation.copy(i.transform.orientation)),this._lastChangedTime!==this._xrPlane.lastChangedTime&&(this._lastChangedTime=this._xrPlane.lastChangedTime,this.fire("change"))},i.getPosition=function(){return this._position},i.getRotation=function(){return this._rotation},$(t,[{key:"id",get:function(){return this._id}},{key:"orientation",get:function(){return this._orientation}},{key:"points",get:function(){return this._xrPlane.polygon}}]),t}(m),db=function(e){function t(t){var i;return(i=e.call(this)||this)._manager=void 0,i._supported=L.browser&&!!window.XRPlane,i._available=!1,i._planesIndex=new Map,i._planes=null,i._manager=t,i._supported&&i._manager.on("end",i._onSessionEnd,te(i)),i}J(t,e);var i=t.prototype;return i._onSessionEnd=function(){if(this._planes)for(var e=0;e<this._planes.length;e++)this._planes[e].destroy();this._planesIndex.clear(),this._planes=null,this._available&&(this._available=!1,this.fire("unavailable"))},i.update=function(e){var t;if(this._available)t=e.detectedPlanes;else try{t=e.detectedPlanes,this._planes=[],this._available=!0,this.fire("available")}catch(e){return}for(var i,n=ne(this._planesIndex);!(i=n()).done;){var s=i.value,r=s[0],a=s[1];t.has(r)||(this._planesIndex.delete(r),this._planes.splice(this._planes.indexOf(a),1),a.destroy(),this.fire("remove",a))}for(var o,h=ne(t);!(o=h()).done;){var l=o.value,c=this._planesIndex.get(l);c?c.update(e):(c=new ub(this,l),this._planesIndex.set(l,c),this._planes.push(c),c.update(e),this.fire("add",c))}},$(t,[{key:"supported",get:function(){return this._supported}},{key:"available",get:function(){return this._available}},{key:"planes",get:function(){return this._planes}}]),t}(m),fb=function(e){function t(t){var i;return(i=e.call(this)||this).app=void 0,i._supported=L.browser&&!!navigator.xr,i._available={},i._type=null,i._spaceType=null,i._session=null,i._baseLayer=null,i._referenceSpace=null,i.depthSensing=void 0,i.domOverlay=void 0,i.hitTest=void 0,i.imageTracking=void 0,i.planeDetection=void 0,i.input=void 0,i.lightEstimation=void 0,i._camera=null,i.views=[],i.viewsPool=[],i._localPosition=new ye,i._localRotation=new Pe,i._depthNear=.1,i._depthFar=1e3,i._width=0,i._height=0,i.app=t,i._available.inline=!1,i._available[Rx]=!1,i._available[Ix]=!1,i.depthSensing=new lb(te(i)),i.domOverlay=new hb(te(i)),i.hitTest=new zx(te(i)),i.imageTracking=new ob(te(i)),i.planeDetection=new db(te(i)),i.input=new eb(te(i)),i.lightEstimation=new rb(te(i)),i._supported&&(navigator.xr.addEventListener("devicechange",(function(){i._deviceAvailabilityCheck()})),i._deviceAvailabilityCheck()),i}J(t,e);var i=t.prototype;return i.destroy=function(){this.depthSensing.destroy(),this.depthSensing=null},i.start=function(e,t,i,n){var s=this,r=n;if("object"==typeof n&&(r=n.callback),this._available[t])if(this._session)r&&r(new Error("XR session is already started"));else{this._camera=e,this._camera.camera.xr=this,this._type=t,this._spaceType=i,this._setClipPlanes(e.nearClip,e.farClip);var a={requiredFeatures:[i],optionalFeatures:[]};if(t===Ix){if(a.optionalFeatures.push("light-estimation"),a.optionalFeatures.push("hit-test"),n&&(n.imageTracking&&this.imageTracking.supported&&a.optionalFeatures.push("image-tracking"),n.planeDetection&&a.optionalFeatures.push("plane-detection")),this.domOverlay.supported&&this.domOverlay.root&&(a.optionalFeatures.push("dom-overlay"),a.domOverlay={root:this.domOverlay.root}),n&&n.depthSensing&&this.depthSensing.supported){a.optionalFeatures.push("depth-sensing");var o=[kx],h=[Fx];if(n.depthSensing.usagePreference){var l=o.indexOf(n.depthSensing.usagePreference);-1!==l&&o.splice(l,1),o.unshift(n.depthSensing.usagePreference)}if(n.depthSensing.dataFormatPreference){var c=h.indexOf(n.depthSensing.dataFormatPreference);-1!==c&&h.splice(c,1),h.unshift(n.depthSensing.dataFormatPreference)}a.depthSensing={usagePreference:o,dataFormatPreference:h}}}else t===Rx&&a.optionalFeatures.push("hand-tracking");n&&n.optionalFeatures&&(a.optionalFeatures=a.optionalFeatures.concat(n.optionalFeatures)),this.imageTracking.supported&&this.imageTracking.images.length?this.imageTracking.prepareImages((function(e,n){if(e)return r&&r(e),void s.fire("error",e);null!==n&&(a.trackedImages=n),s._onStartOptionsReady(t,i,a,r)})):this._onStartOptionsReady(t,i,a,r)}else r&&r(new Error("XR is not available"))},i._onStartOptionsReady=function(e,t,i,n){var s=this;navigator.xr.requestSession(e,i).then((function(e){s._onSessionStart(e,t,n)})).catch((function(e){s._camera.camera.xr=null,s._camera=null,s._type=null,s._spaceType=null,n&&n(e),s.fire("error",e)}))},i.end=function(e){this._session?(e&&this.once("end",e),this._session.end()):e&&e(new Error("XR Session is not initialized"))},i.isAvailable=function(e){return this._available[e]},i._deviceAvailabilityCheck=function(){for(var e in this._available)this._sessionSupportCheck(e)},i._sessionSupportCheck=function(e){var t=this;navigator.xr.isSessionSupported(e).then((function(i){t._available[e]!==i&&(t._available[e]=i,t.fire("available",e,i),t.fire("available:"+e,i))})).catch((function(e){t.fire("error",e)}))},i._onSessionStart=function(e,t,i){var n=this,s=!1;this._session=e;var r=function(){n.fire("visibility:change",e.visibilityState)},a=function(){n._setClipPlanes(n._camera.nearClip,n._camera.farClip)};e.addEventListener("end",(function t(){n._camera&&(n._camera.off("set_nearClip",a),n._camera.off("set_farClip",a),n._camera.camera.xr=null,n._camera=null),e.removeEventListener("end",t),e.removeEventListener("visibilitychange",r),s||n.fire("end"),n._session=null,n._referenceSpace=null,n.views=[],n._width=0,n._height=0,n._type=null,n._spaceType=null,n.app.tick()})),e.addEventListener("visibilitychange",r),this._camera.on("set_nearClip",a),this._camera.on("set_farClip",a),this._baseLayer=new XRWebGLLayer(e,this.app.graphicsDevice.gl,{alpha:!0,depth:!0,stencil:!0}),e.updateRenderState({baseLayer:this._baseLayer,depthNear:this._depthNear,depthFar:this._depthFar}),e.requestReferenceSpace(t).then((function(e){n._referenceSpace=e,n.app.tick(),i&&i(null),n.fire("start")})).catch((function(t){s=!0,e.end(),i&&i(t),n.fire("error",t)}))},i._setClipPlanes=function(e,t){this._depthNear===e&&this._depthFar===t||(this._depthNear=e,this._depthFar=t,this._session&&this._session.updateRenderState({depthNear:this._depthNear,depthFar:this._depthFar}))},i.update=function(e){if(!this._session)return!1;var t=e.session.renderState.baseLayer.framebufferWidth,i=e.session.renderState.baseLayer.framebufferHeight;this._width===t&&this._height===i||(this._width=t,this._height=i,this.app.graphicsDevice.setResolution(t,i));var n=e.getViewerPose(this._referenceSpace);if(!n)return!1;var s=n.views.length;if(s>this.views.length)for(var r=0;r<=s-this.views.length;r++){var a=this.viewsPool.pop();a||(a={viewport:new Se,projMat:new Ee,viewMat:new Ee,viewOffMat:new Ee,viewInvMat:new Ee,viewInvOffMat:new Ee,projViewOffMat:new Ee,viewMat3:new xe,position:new Float32Array(3),rotation:new Pe}),this.views.push(a)}else if(s<=this.views.length)for(var o=0;o<this.views.length-s;o++)this.viewsPool.push(this.views.pop());var h=n.transform.position,l=n.transform.orientation;this._localPosition.set(h.x,h.y,h.z),this._localRotation.set(l.x,l.y,l.z,l.w);for(var c=e.session.renderState.baseLayer,u=0;u<n.views.length;u++){var d=n.views[u],f=this.views[u],p=c.getViewport(d);f.viewport.x=p.x,f.viewport.y=p.y,f.viewport.z=p.width,f.viewport.w=p.height,f.projMat.set(d.projectionMatrix),f.viewMat.set(d.transform.inverse.matrix),f.viewInvMat.set(d.transform.matrix)}return this._camera.camera._node.setLocalPosition(this._localPosition),this._camera.camera._node.setLocalRotation(this._localRotation),this.input.update(e),this._type===Ix&&(this.hitTest.supported&&this.hitTest.update(e),this.lightEstimation.supported&&this.lightEstimation.update(e),this.depthSensing.supported&&this.depthSensing.update(e,n&&n.views[0]),this.imageTracking.supported&&this.imageTracking.update(e),this.planeDetection.supported&&this.planeDetection.update(e)),this.fire("update",e),!0},$(t,[{key:"supported",get:function(){return this._supported}},{key:"active",get:function(){return!!this._session}},{key:"type",get:function(){return this._type}},{key:"spaceType",get:function(){return this._spaceType}},{key:"session",get:function(){return this._session}},{key:"camera",get:function(){return this._camera?this._camera.entity:null}},{key:"visibilityState",get:function(){return this._session?this._session.visibilityState:null}}]),t}(m),pb=function(e){function t(t,i){var n;void 0===i&&(i={}),n=e.call(this,t)||this;var s=new o_;return s.graphicsDevice=n.createDevice(t,i),n.addComponentSystems(s),n.addResourceHandles(s),s.elementInput=i.elementInput,s.keyboard=i.keyboard,s.mouse=i.mouse,s.touch=i.touch,s.gamepads=i.gamepads,s.scriptPrefix=i.scriptPrefix,s.assetPrefix=i.assetPrefix,s.scriptsOrder=i.scriptsOrder,s.soundManager=new Md(i),s.lightmapper=sc,s.batchManager=Ha,s.xr=fb,n.init(s),n}J(t,e);var i=t.prototype;return i.createDevice=function(e,t){return t.graphicsDeviceOptions||(t.graphicsDeviceOptions={}),L.browser&&navigator.xr&&(t.graphicsDeviceOptions.xrCompatible=!0),t.graphicsDeviceOptions.alpha=t.graphicsDeviceOptions.alpha||!1,new jr(e,t.graphicsDeviceOptions)},i.addComponentSystems=function(e){e.componentSystems=[dy,Sg,dv,f_,T_,Fv,Zv,yx,Ax,xl.legacy?Py:Ex,L_,$y,E_,Xv,yy,nv,$_,Vy,Xy,hx,Lv,_v,dx]},i.addResourceHandles=function(e){e.resourceHandlers=[Sp,Uf,Hd,Xd,vp,cp,qp,Lp,rp,Gf,gl,Tp,jf,sp,qf,Mp,np,Yf,Zf,Wf,Zp,Pp,Ip,Xf]},t}(jl),mb={write:function(e){console.log(e)},open:function(){mb.write("Powered by PlayCanvas 1.57.1 256dd83c2")},info:function(e){console.info("INFO: "+e)},debug:function(e){console.debug("DEBUG: "+e)},error:function(e){console.error("ERROR: "+e)},warning:function(e){console.warn("WARNING: "+e)},alert:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){mb.write("ALERT: "+e),alert(e)})),assert:function(e,t){!1===e&&mb.write("ASSERT: "+t)}};q.endsWith=function(e,t){return e.endsWith(t)},q.startsWith=function(e,t){return e.startsWith(t)};var _b={now:oe,Timer:he};Object.defineProperty(me.prototype,"data",{get:function(){return this._data||(this._data=new Float32Array(4)),this._data[0]=this.r,this._data[1]=this.g,this._data[2]=this.b,this._data[3]=this.a,this._data}}),Object.defineProperty(me.prototype,"data3",{get:function(){return this._data3||(this._data3=new Float32Array(3)),this._data3[0]=this.r,this._data3[1]=this.g,this._data3[2]=this.b,this._data3}}),de.INV_LOG2=Math.LOG2E,de.intToBytes=de.intToBytes32,de.bytesToInt=de.bytesToInt32,Object.defineProperty(be.prototype,"data",{get:function(){return this._data||(this._data=new Float32Array(2)),this._data[0]=this.x,this._data[1]=this.y,this._data}}),be.prototype.scale=be.prototype.mulScalar,Object.defineProperty(ye.prototype,"data",{get:function(){return this._data||(this._data=new Float32Array(3)),this._data[0]=this.x,this._data[1]=this.y,this._data[2]=this.z,this._data}}),ye.prototype.scale=ye.prototype.mulScalar,Object.defineProperty(Se.prototype,"data",{get:function(){return this._data||(this._data=new Float32Array(4)),this._data[0]=this.x,this._data[1]=this.y,this._data[2]=this.z,this._data[3]=this.w,this._data}}),Se.prototype.scale=Se.prototype.mulScalar;var gb={Aabb:Oe,Sphere:Ne,Plane:ot};Ne.prototype.intersectRay=Ne.prototype.intersectsRay,Je.prototype.update=function(e,t){var i=new Ee;i.mul2(e,t),this.setFromMat4(i)};function vb(e){this.name="UnsupportedBrowserError",this.message=e||""}function yb(e){this.name="ContextCreationError",this.message=e||""}vb.prototype=Error.prototype,yb.prototype=Error.prototype;var xb={begin:tn,dummyFragmentCode:en,end:nn,fogCode:ji,gammaCode:Xi,precisionCode:Ki,skinCode:Yi,tonemapCode:qi,versionCode:Zi},bb={ADDRESS_CLAMP_TO_EDGE:1,ADDRESS_MIRRORED_REPEAT:2,ADDRESS_REPEAT:0,BLENDMODE_ZERO:0,BLENDMODE_ONE:1,BLENDMODE_SRC_COLOR:2,BLENDMODE_ONE_MINUS_SRC_COLOR:3,BLENDMODE_DST_COLOR:4,BLENDMODE_ONE_MINUS_DST_COLOR:5,BLENDMODE_SRC_ALPHA:6,BLENDMODE_SRC_ALPHA_SATURATE:7,BLENDMODE_ONE_MINUS_SRC_ALPHA:8,BLENDMODE_DST_ALPHA:9,BLENDMODE_ONE_MINUS_DST_ALPHA:10,BUFFER_STATIC:0,BUFFER_DYNAMIC:1,BUFFER_STREAM:2,CULLFACE_NONE:0,CULLFACE_BACK:1,CULLFACE_FRONT:2,CULLFACE_FRONTANDBACK:3,ELEMENTTYPE_INT8:0,ELEMENTTYPE_UINT8:1,ELEMENTTYPE_INT16:2,ELEMENTTYPE_UINT16:3,ELEMENTTYPE_INT32:4,ELEMENTTYPE_UINT32:5,ELEMENTTYPE_FLOAT32:6,FILTER_NEAREST:0,FILTER_LINEAR:1,FILTER_NEAREST_MIPMAP_NEAREST:2,FILTER_NEAREST_MIPMAP_LINEAR:3,FILTER_LINEAR_MIPMAP_NEAREST:4,FILTER_LINEAR_MIPMAP_LINEAR:5,INDEXFORMAT_UINT8:0,INDEXFORMAT_UINT16:1,INDEXFORMAT_UINT32:2,PIXELFORMAT_R5_G6_B5:3,PIXELFORMAT_R8_G8_B8:6,PIXELFORMAT_R8_G8_B8_A8:7,PRIMITIVE_POINTS:0,PRIMITIVE_LINES:1,PRIMITIVE_LINELOOP:2,PRIMITIVE_LINESTRIP:3,PRIMITIVE_TRIANGLES:4,PRIMITIVE_TRISTRIP:5,PRIMITIVE_TRIFAN:6,SEMANTIC_POSITION:vt,SEMANTIC_NORMAL:yt,SEMANTIC_COLOR:wt,SEMANTIC_TEXCOORD:Tt,SEMANTIC_TEXCOORD0:At,SEMANTIC_TEXCOORD1:Mt,SEMANTIC_ATTR0:kt,SEMANTIC_ATTR1:Ot,SEMANTIC_ATTR2:Ft,SEMANTIC_ATTR3:Bt,TEXTURELOCK_READ:1,TEXTURELOCK_WRITE:2,drawQuadWithShader:Ei,programlib:xb,shaderChunks:Wi,ContextCreationError:yb,Device:or,IndexBuffer:mr,ProgramLibrary:rr,RenderTarget:cr,ScopeId:un,Shader:zi,ShaderInput:Nr,Texture:wn,UnsupportedBrowserError:vb,VertexBuffer:Si,VertexFormat:Ti,VertexIterator:Pr},Sb={createFullscreenQuad:Lr,drawFullscreenQuad:Dr,PostEffect:Ir,PostEffectQueue:px};Object.defineProperty(Wi,"transformSkinnedVS",{get:function(){return"#define SKIN\n"+Wi.transformVS}});var wb={"ambientPrefilteredCube.frag":"ambientEnv.frag","ambientPrefilteredCubeLod.frag":"ambientEnv.frag","dpAtlasQuad.frag":null,"genParaboloid.frag":null,"prefilterCubemap.frag":null,"reflectionDpAtlas.frag":"reflectionEnv.frag","reflectionPrefilteredCube.frag":"reflectionEnv.frag","reflectionPrefilteredCubeLod.frag":"reflectionEnv.frag"};Object.keys(wb).forEach((function(e){Object.defineProperty(Wi,e,{get:function(){return null},set:function(){}})})),Object.defineProperties(cr.prototype,{_glFrameBuffer:{get:function(){return this.impl._glFrameBuffer},set:function(e){}}}),Ti.prototype.update=function(){},Object.defineProperties(wn.prototype,{rgbm:{get:function(){return this.type===$t},set:function(e){this.type=e?$t:Zt}},swizzleGGGR:{get:function(){return this.type===ei},set:function(e){this.type=e?ei:Zt}},_glTexture:{get:function(){return this.impl._glTexture}}});var Tb=Zs,Ab={partitionSkin:pp,procedural:{calculateTangents:ra,createMesh:aa,createTorus:oa,createCylinder:la,createCapsule:ca,createCone:ua,createSphere:da,createPlane:fa,createBox:pa},BasicMaterial:ga,Command:Da,ForwardRenderer:ah,GraphNode:Hn,Material:Bs,Mesh:ea,MeshInstance:ka,Model:hc,ParticleEmitter:su,PhongMaterial:Zs,Picker:ou,Projection:{ORTHOGRAPHIC:1,PERSPECTIVE:0},Scene:Kh,Skin:hu,SkinInstance:ba};function Mb(e,t){Object.defineProperty(Zs.prototype,t,{get:function(){return this[e]},set:function(t){this[e]=t}})}Object.defineProperty(Kh.prototype,"defaultMaterial",{get:function(){return ks(Kr().graphicsDevice)}}),["128","64","32","16","8","4"].forEach((function(e,t){Object.defineProperty(Kh.prototype,"skyboxPrefiltered"+e,{get:function(){return this._prefilteredCubemaps[t]},set:function(e){this._prefilteredCubemaps[t]=e,this.updateShaders=!0}})})),Object.defineProperty(Kh.prototype,"models",{get:function(){return this._models||(this._models=[]),this._models}}),Kh.prototype._updateSkybox=function(e){this._updateSky(e)},Kh.prototype.addModel=function(e){if(!this.containsModel(e)){var t=this.layers.getLayerById(0);t&&(t.addMeshInstances(e.meshInstances),this.models.push(e))}},Kh.prototype.addShadowCaster=function(e){var t=this.layers.getLayerById(0);t&&t.addShadowCasters(e.meshInstances)},Kh.prototype.removeModel=function(e){var t=this.models.indexOf(e);if(-1!==t){var i=this.layers.getLayerById(0);if(!i)return;i.removeMeshInstances(e.meshInstances),this.models.splice(t,1)}},Kh.prototype.removeShadowCasters=function(e){var t=this.layers.getLayerById(0);t&&t.removeShadowCasters(e.meshInstances)},Kh.prototype.containsModel=function(e){return this.models.indexOf(e)>=0},Kh.prototype.getModels=function(e){return this.models},Object.defineProperty(va.prototype,"model",{get:function(){return null}}),ah.prototype.renderComposition=function(e){Kr().renderComposition(e)},ah.prototype.updateShader=function(e,t,i,n,s){var r=e.material._scene||Kr().scene;return e.updatePassShader(r,n,i,s)},ka.prototype.syncAabb=function(){},rc.prototype.getTarget=function(e){return this.targets[e]},Hn.prototype._dirtify=function(e){e?this._dirtifyLocal():this._dirtifyWorld()},Hn.prototype.addLabel=function(e){this._labels[e]=!0},Hn.prototype.getLabels=function(){return Object.keys(this._labels)},Hn.prototype.hasLabel=function(e){return!!this._labels[e]},Hn.prototype.removeLabel=function(e){delete this._labels[e]},Hn.prototype.findByLabel=function(e,t){void 0===t&&(t=[]),this.hasLabel(e)&&t.push(this);for(var i=0;i<this._children.length;++i)t=this._children[i].findByLabel(e,t);return t},Hn.prototype.getChildren=function(){return this.children},Hn.prototype.getName=function(){return this.name},Hn.prototype.getPath=function(){return this.path},Hn.prototype.getRoot=function(){return this.root},Hn.prototype.getParent=function(){return this.parent},Hn.prototype.setName=function(e){this.name=e},Bs.prototype.getName=function(){return this.name},Bs.prototype.setName=function(e){this.name=e},Bs.prototype.getShader=function(){return this.shader},Bs.prototype.setShader=function(e){this.shader=e},Mb("diffuseTint","diffuseMapTint"),Mb("specularTint","specularMapTint"),Mb("emissiveTint","emissiveMapTint"),Mb("aoVertexColor","aoMapVertexColor"),Mb("diffuseVertexColor","diffuseMapVertexColor"),Mb("specularVertexColor","specularMapVertexColor"),Mb("emissiveVertexColor","emissiveMapVertexColor"),Mb("metalnessVertexColor","metalnessMapVertexColor"),Mb("glossVertexColor","glossMapVertexColor"),Mb("opacityVertexColor","opacityMapVertexColor"),Mb("lightVertexColor","lightMapVertexColor");var Cb={Animation:_u,Key:pu,Node:mu,Skeleton:vu};_u.prototype.getDuration=function(){return this.duration},_u.prototype.getName=function(){return this.name},_u.prototype.getNodes=function(){return this.nodes},_u.prototype.setDuration=function(e){this.duration=e},_u.prototype.setName=function(e){this.name=e},vu.prototype.getAnimation=function(){return this.animation},vu.prototype.getCurrentTime=function(){return this.currentTime},vu.prototype.getLooping=function(){return this.looping},vu.prototype.getNumNodes=function(){return this.numNodes},vu.prototype.setAnimation=function(e){this.animation=e},vu.prototype.setCurrentTime=function(e){this.currentTime=e},vu.prototype.setLooping=function(e){this.looping=e};var Eb={AudioManager:Md,Channel:xd,Channel3d:bd,Listener:wd,Sound:Cd};Md.prototype.getListener=function(){return this.listener},Md.prototype.getVolume=function(){return this.volume},Md.prototype.setVolume=function(e){this.volume=e};bl.prototype.getAssetById=function(e){return this.get(e)},Object.defineProperty(Jx.prototype,"ray",{get:function(){return this._rayLocal}}),Object.defineProperty(Jx.prototype,"position",{get:function(){return this._localPosition}}),Object.defineProperty(Jx.prototype,"rotation",{get:function(){return this._localRotation}});var Pb={getTouchTargetCoords:n_,Controller:bm,GamePads:i_,Keyboard:mm,KeyboardEvent:cm,Mouse:xm,MouseEvent:ym,Touch:s_,TouchDevice:a_,TouchEvent:r_};Object.defineProperty(Jm.prototype,"wheel",{get:function(){return-2*this.wheelDelta}}),Object.defineProperty(ym.prototype,"wheel",{get:function(){return-2*this.wheelDelta}});var Rb={Application:pb,Component:Cl,ComponentSystem:h_,Entity:$l,FillMode:{NONE:Vl,FILL_WINDOW:Gl,KEEP_ASPECT:Wl},ResolutionMode:{AUTO:Hl,FIXED:Xl}};pb.prototype.isFullscreen=function(){return!!document.fullscreenElement},pb.prototype.enableFullscreen=function(e,t,i){e=e||this.graphicsDevice.canvas;t&&document.addEventListener("fullscreenchange",(function e(){t(),document.removeEventListener("fullscreenchange",e)}),!1),i&&document.addEventListener("fullscreenerror",(function e(){i(),document.removeEventListener("fullscreenerror",e)}),!1),e.requestFullscreen?e.requestFullscreen(Element.ALLOW_KEYBOARD_INPUT):i()},pb.prototype.disableFullscreen=function(e){e&&document.addEventListener("fullscreenchange",(function t(){e(),document.removeEventListener("fullscreenchange",t)}),!1),document.exitFullscreen()},pb.prototype.getSceneUrl=function(e){var t=this.scenes.find(e);return t?t.url:null},pb.prototype.loadScene=function(e,t){this.scenes.loadScene(e,t)},pb.prototype.loadSceneHierarchy=function(e,t){this.scenes.loadSceneHierarchy(e,t)},pb.prototype.loadSceneSettings=function(e,t){this.scenes.loadSceneSettings(e,t)},pb.prototype.renderMeshInstance=function(e,t){var i=null!=t&&t.layer?t.layer:this.scene.defaultDrawLayer;this.scene.immediate.drawMesh(null,null,null,e,i)},pb.prototype.renderMesh=function(e,t,i,n){var s=null!=n&&n.layer?n.layer:this.scene.defaultDrawLayer;this.scene.immediate.drawMesh(t,i,e,null,s)},pb.prototype._addLines=function(e,t,i){var n=i&&i.layer?i.layer:this.scene.layers.getLayerById(3),s=!i||void 0===i.depthTest||i.depthTest;this.scene.immediate.getBatch(n,s).addLines(e,t)},pb.prototype.renderLine=function(e,t,i){var n,s=i,r=arguments[3],a=arguments[4];r instanceof me?(s=r,n="number"==typeof a?1===a?{layer:this.scene.layers.getLayerById(3),depthTest:!1}:{layer:this.scene.layers.getLayerById(3),depthTest:!0}:a):"number"==typeof r?(s=i,n=1===r?{layer:this.scene.layers.getLayerById(3),depthTest:!1}:{layer:this.scene.layers.getLayerById(3),depthTest:!0}):r&&(n=r),this._addLines([e,t],[i,s],n)},pb.prototype.renderLines=function(e,t,i){i?"number"==typeof i&&(i=1===i?{layer:this.scene.layers.getLayerById(3),depthTest:!1}:{layer:this.scene.layers.getLayerById(3),depthTest:!0}):i={layer:this.scene.layers.getLayerById(3),depthTest:!0},!t.length||e.length===t.length?e.length%2==0?this._addLines(e,t,i):console.error("renderLines: array length is not divisible by 2"):console.error("renderLines: position/color arrays have different lengths")},pb.prototype.enableVr=function(){},Object.defineProperty(_x.prototype,"node",{get:function(){return this.entity}}),Object.defineProperty(Sx.prototype,"enable",{get:function(){return this.enabled},set:function(e){this.enabled=e}}),Dv.prototype.setVisible=function(e){this.enabled=e},Object.defineProperty(Dv.prototype,"aabb",{get:function(){return null},set:function(e){}}),Object.defineProperty(qv.prototype,"aabb",{get:function(){return null},set:function(e){}}),Object.defineProperty(ry.prototype,"bodyType",{get:function(){return this.type},set:function(e){this.type=e}}),ry.prototype.syncBodyToEntity=function(){this._updateDynamic()},dy.prototype.setGravity=function(){1===arguments.length?this.gravity.copy(arguments[0]):this.gravity.set(arguments[0],arguments[1],arguments[2])},e.ABSOLUTE_URL=cl,e.ACTION_GAMEPAD=rm,e.ACTION_KEYBOARD=sm,e.ACTION_MOUSE=nm,e.ADDRESS_CLAMP_TO_EDGE=1,e.ADDRESS_MIRRORED_REPEAT=2,e.ADDRESS_REPEAT=0,e.ANIM_BLEND_1D="1D",e.ANIM_BLEND_2D_CARTESIAN=Vu,e.ANIM_BLEND_2D_DIRECTIONAL=zu,e.ANIM_BLEND_DIRECT=Gu,e.ANIM_CONTROL_STATES=qu,e.ANIM_EQUAL_TO=ku,e.ANIM_GREATER_THAN=Ru,e.ANIM_GREATER_THAN_EQUAL_TO=Lu,e.ANIM_INTERRUPTION_NEXT=Cu,e.ANIM_INTERRUPTION_NEXT_PREV=Pu,e.ANIM_INTERRUPTION_NONE=Au,e.ANIM_INTERRUPTION_PREV=Mu,e.ANIM_INTERRUPTION_PREV_NEXT=Eu,e.ANIM_LAYER_ADDITIVE=Yu,e.ANIM_LAYER_OVERWRITE=ju,e.ANIM_LESS_THAN=Iu,e.ANIM_LESS_THAN_EQUAL_TO=Du,e.ANIM_NOT_EQUAL_TO=Ou,e.ANIM_PARAMETER_BOOLEAN=Nu,e.ANIM_PARAMETER_FLOAT=Bu,e.ANIM_PARAMETER_INTEGER=Fu,e.ANIM_PARAMETER_TRIGGER=Uu,e.ANIM_STATE_ANY=Xu,e.ANIM_STATE_END=Hu,e.ANIM_STATE_START=Wu,e.ASPECT_AUTO=0,e.ASPECT_MANUAL=1,e.ASSET_ANIMATION="animation",e.ASSET_AUDIO="audio",e.ASSET_CONTAINER="container",e.ASSET_CSS="css",e.ASSET_CUBEMAP="cubemap",e.ASSET_HTML="html",e.ASSET_IMAGE="image",e.ASSET_JSON="json",e.ASSET_MATERIAL="material",e.ASSET_MODEL="model",e.ASSET_SCRIPT="script",e.ASSET_SHADER="shader",e.ASSET_TEXT="text",e.ASSET_TEXTURE="texture",e.AXIS_KEY="key",e.AXIS_MOUSE_X="mousex",e.AXIS_MOUSE_Y="mousey",e.AXIS_PAD_L_X="padlx",e.AXIS_PAD_L_Y="padly",e.AXIS_PAD_R_X="padrx",e.AXIS_PAD_R_Y="padry",e.AnimBinder=yu,e.AnimClip=Su,e.AnimClipHandler=Hd,e.AnimComponent=b_,e.AnimComponentLayer=x_,e.AnimComponentSystem=T_,e.AnimController=ld,e.AnimCurve=wu,e.AnimData=Tu,e.AnimEvaluator=Zu,e.AnimEvents=Qu,e.AnimSnapshot=bu,e.AnimStateGraph=cd,e.AnimStateGraphHandler=Xd,e.AnimTarget=$u,e.AnimTrack=Ju,e.Animation=_u,e.AnimationComponent=c_,e.AnimationComponentSystem=f_,e.AnimationHandler=Uf,e.AppBase=jl,e.AppOptions=o_,e.Application=pb,e.Asset=ml,e.AssetListLoader=$p,e.AssetReference=hp,e.AssetRegistry=bl,e.AudioHandler=Gf,e.AudioListenerComponent=A_,e.AudioListenerComponentSystem=E_,e.AudioSourceComponent=P_,e.AudioSourceComponentSystem=L_,e.BAKE_COLOR=0,e.BAKE_COLORDIR=1,e.BINDGROUP_MESH=1,e.BINDGROUP_VIEW=0,e.BLENDEQUATION_ADD=0,e.BLENDEQUATION_MAX=4,e.BLENDEQUATION_MIN=3,e.BLENDEQUATION_REVERSE_SUBTRACT=2,e.BLENDEQUATION_SUBTRACT=1,e.BLENDMODE_CONSTANT_ALPHA=13,e.BLENDMODE_CONSTANT_COLOR=11,e.BLENDMODE_DST_ALPHA=9,e.BLENDMODE_DST_COLOR=4,e.BLENDMODE_ONE=1,e.BLENDMODE_ONE_MINUS_CONSTANT_ALPHA=14,e.BLENDMODE_ONE_MINUS_CONSTANT_COLOR=12,e.BLENDMODE_ONE_MINUS_DST_ALPHA=10,e.BLENDMODE_ONE_MINUS_DST_COLOR=5,e.BLENDMODE_ONE_MINUS_SRC_ALPHA=8,e.BLENDMODE_ONE_MINUS_SRC_COLOR=3,e.BLENDMODE_SRC_ALPHA=6,e.BLENDMODE_SRC_ALPHA_SATURATE=7,e.BLENDMODE_SRC_COLOR=2,e.BLENDMODE_ZERO=0,e.BLEND_ADDITIVE=1,e.BLEND_ADDITIVEALPHA=6,e.BLEND_MAX=10,e.BLEND_MIN=9,e.BLEND_MULTIPLICATIVE=5,e.BLEND_MULTIPLICATIVE2X=7,e.BLEND_NONE=3,e.BLEND_NORMAL=2,e.BLEND_PREMULTIPLIED=4,e.BLEND_SCREEN=8,e.BLEND_SUBTRACTIVE=0,e.BLUR_BOX=0,e.BLUR_GAUSSIAN=1,e.BODYFLAG_KINEMATIC_OBJECT=2,e.BODYFLAG_NORESPONSE_OBJECT=4,e.BODYFLAG_STATIC_OBJECT=1,e.BODYGROUP_DEFAULT=1,e.BODYGROUP_DYNAMIC=1,e.BODYGROUP_ENGINE_1=8,e.BODYGROUP_ENGINE_2=32,e.BODYGROUP_ENGINE_3=64,e.BODYGROUP_KINEMATIC=4,e.BODYGROUP_NONE=0,e.BODYGROUP_STATIC=2,e.BODYGROUP_TRIGGER=16,e.BODYGROUP_USER_1=128,e.BODYGROUP_USER_2=256,e.BODYGROUP_USER_3=512,e.BODYGROUP_USER_4=1024,e.BODYGROUP_USER_5=2048,e.BODYGROUP_USER_6=4096,e.BODYGROUP_USER_7=8192,e.BODYGROUP_USER_8=16384,e.BODYMASK_ALL=ag,e.BODYMASK_NONE=0,e.BODYMASK_NOT_STATIC=og,e.BODYMASK_NOT_STATIC_KINEMATIC=65529,e.BODYMASK_STATIC=2,e.BODYSTATE_ACTIVE_TAG=1,e.BODYSTATE_DISABLE_DEACTIVATION=4,e.BODYSTATE_DISABLE_SIMULATION=5,e.BODYSTATE_ISLAND_SLEEPING=2,e.BODYSTATE_WANTS_DEACTIVATION=3,e.BODYTYPE_DYNAMIC=sg,e.BODYTYPE_KINEMATIC=rg,e.BODYTYPE_STATIC=ng,e.BUFFER_DYNAMIC=1,e.BUFFER_GPUDYNAMIC=3,e.BUFFER_STATIC=0,e.BUFFER_STREAM=2,e.BUTTON_TRANSITION_MODE_SPRITE_CHANGE=1,e.BUTTON_TRANSITION_MODE_TINT=0,e.BasicMaterial=ga,e.Batch=va,e.BatchGroup=ya,e.BatchManager=Ha,e.BinaryHandler=Wf,e.BoundingBox=Oe,e.BoundingSphere=Ne,e.Bundle=Zh,e.BundleHandler=el,e.BundleRegistry=Sl,e.ButtonComponent=j_,e.ButtonComponentSystem=$_,e.CHUNKAPI_1_51="1.51",e.CHUNKAPI_1_55=yi,e.CHUNKAPI_1_56="1.56",e.CHUNKAPI_1_57=xi,e.CLEARFLAG_COLOR=1,e.CLEARFLAG_DEPTH=2,e.CLEARFLAG_STENCIL=4,e.COMPUPDATED_BLEND=8,e.COMPUPDATED_CAMERAS=4,e.COMPUPDATED_INSTANCES=1,e.COMPUPDATED_LIGHTS=2,e.CUBEFACE_NEGX=1,e.CUBEFACE_NEGY=3,e.CUBEFACE_NEGZ=5,e.CUBEFACE_POSX=0,e.CUBEFACE_POSY=2,e.CUBEFACE_POSZ=4,e.CUBEPROJ_BOX=1,e.CUBEPROJ_NONE=0,e.CULLFACE_BACK=1,e.CULLFACE_FRONT=2,e.CULLFACE_FRONTANDBACK=3,e.CULLFACE_NONE=0,e.CURVE_CARDINAL=3,e.CURVE_CATMULL=2,e.CURVE_LINEAR=0,e.CURVE_SMOOTHSTEP=1,e.CURVE_SPLINE=4,e.CURVE_STEP=5,e.Camera=En,e.CameraComponent=_x,e.CameraComponentSystem=yx,e.CanvasFont=md,e.CollisionComponent=tg,e.CollisionComponentSystem=Sg,e.Color=me,e.Command=Da,e.Component=Cl,e.ComponentSystem=h_,e.ComponentSystemRegistry=kl,e.ContactPoint=ly,e.ContactResult=cy,e.ContainerHandler=Xf,e.ContainerResource=Hf,e.ContextCreationError=yb,e.Controller=bm,e.CssHandler=qf,e.CubemapHandler=jf,e.Curve=ge,e.CurveSet=ve,e.DETAILMODE_ADD="add",e.DETAILMODE_MAX="max",e.DETAILMODE_MIN="min",e.DETAILMODE_MUL="mul",e.DETAILMODE_OVERLAY="overlay",e.DETAILMODE_SCREEN="screen",e.DEVICETYPE_WEBGL=li,e.DEVICETYPE_WEBGPU=ci,e.DISTANCE_EXPONENTIAL=vd,e.DISTANCE_INVERSE=gd,e.DISTANCE_LINEAR=_d,e.DefaultAnimBinder=ed,e.ELEMENTTYPE_FLOAT32=6,e.ELEMENTTYPE_GROUP=k_,e.ELEMENTTYPE_IMAGE=O_,e.ELEMENTTYPE_INT16=2,e.ELEMENTTYPE_INT32=4,e.ELEMENTTYPE_INT8=0,e.ELEMENTTYPE_TEXT=F_,e.ELEMENTTYPE_UINT16=3,e.ELEMENTTYPE_UINT32=5,e.ELEMENTTYPE_UINT8=1,e.EMITTERSHAPE_BOX=0,e.EMITTERSHAPE_SPHERE=1,e.EVENT_KEYDOWN="keydown",e.EVENT_KEYUP="keyup",e.EVENT_MOUSEDOWN=am,e.EVENT_MOUSEMOVE=om,e.EVENT_MOUSEUP=hm,e.EVENT_MOUSEWHEEL=lm,e.EVENT_SELECT="select",e.EVENT_SELECTEND="selectend",e.EVENT_SELECTSTART="selectstart",e.EVENT_TOUCHCANCEL="touchcancel",e.EVENT_TOUCHEND="touchend",e.EVENT_TOUCHMOVE="touchmove",e.EVENT_TOUCHSTART="touchstart",e.ElementComponent=Jg,e.ElementComponentSystem=nv,e.ElementDragHelper=Fy,e.ElementInput=Jm,e.ElementInputEvent=Km,e.ElementMouseEvent=Zm,e.ElementSelectEvent=Qm,e.ElementTouchEvent=$m,e.Entity=$l,e.EntityReference=D_,e.EnvLighting=Ls,e.EventHandler=m,e.FILLMODE_FILL_WINDOW=Gl,e.FILLMODE_KEEP_ASPECT=Wl,e.FILLMODE_NONE=Vl,e.FILTER_LINEAR=1,e.FILTER_LINEAR_MIPMAP_LINEAR=5,e.FILTER_LINEAR_MIPMAP_NEAREST=4,e.FILTER_NEAREST=0,e.FILTER_NEAREST_MIPMAP_LINEAR=3,e.FILTER_NEAREST_MIPMAP_NEAREST=2,e.FITMODE_CONTAIN=N_,e.FITMODE_COVER=U_,e.FITMODE_STRETCH=B_,e.FITTING_BOTH=3,e.FITTING_NONE=0,e.FITTING_SHRINK=2,e.FITTING_STRETCH=1,e.FOG_EXP="exp",e.FOG_EXP2="exp2",e.FOG_LINEAR=ze,e.FOG_NONE=Ue,e.FONT_BITMAP=dd,e.FONT_MSDF=ud,e.FRESNEL_NONE=0,e.FRESNEL_SCHLICK=2,e.FUNC_ALWAYS=7,e.FUNC_EQUAL=2,e.FUNC_GREATER=4,e.FUNC_GREATEREQUAL=6,e.FUNC_LESS=1,e.FUNC_LESSEQUAL=3,e.FUNC_NEVER=0,e.FUNC_NOTEQUAL=5,e.FolderHandler=Yf,e.Font=fd,e.FontHandler=Zf,e.ForwardRenderer=ah,e.Frustum=Je,e.GAMMA_NONE=0,e.GAMMA_SRGB=1,e.GAMMA_SRGBFAST=2,e.GAMMA_SRGBHDR=3,e.GamePads=i_,e.GraphNode=Hn,e.GraphicsDevice=or,e.HierarchyHandler=np,e.HtmlHandler=sp,e.Http=fe,e.I18n=Dl,e.INDEXFORMAT_UINT16=1,e.INDEXFORMAT_UINT32=2,e.INDEXFORMAT_UINT8=0,e.INTERPOLATION_CUBIC=2,e.INTERPOLATION_LINEAR=1,e.INTERPOLATION_STEP=0,e.ImageElement=Tg,e.IndexBuffer=mr,e.IndexedList=j,e.JointComponent=hv,e.JointComponentSystem=dv,e.JsonHandler=rp,e.JsonStandardMaterialParser=op,e.KEY_0=48,e.KEY_1=49,e.KEY_2=50,e.KEY_3=51,e.KEY_4=52,e.KEY_5=53,e.KEY_6=54,e.KEY_7=55,e.KEY_8=56,e.KEY_9=57,e.KEY_A=65,e.KEY_ADD=107,e.KEY_ALT=18,e.KEY_B=66,e.KEY_BACKSPACE=8,e.KEY_BACK_SLASH=220,e.KEY_C=67,e.KEY_CAPS_LOCK=20,e.KEY_CLOSE_BRACKET=221,e.KEY_COMMA=188,e.KEY_CONTEXT_MENU=93,e.KEY_CONTROL=17,e.KEY_D=68,e.KEY_DECIMAL=110,e.KEY_DELETE=46,e.KEY_DIVIDE=111,e.KEY_DOWN=40,e.KEY_E=69,e.KEY_END=35,e.KEY_ENTER=13,e.KEY_EQUAL=61,e.KEY_ESCAPE=27,e.KEY_F=70,e.KEY_F1=112,e.KEY_F10=121,e.KEY_F11=122,e.KEY_F12=123,e.KEY_F2=113,e.KEY_F3=114,e.KEY_F4=115,e.KEY_F5=116,e.KEY_F6=117,e.KEY_F7=118,e.KEY_F8=119,e.KEY_F9=120,e.KEY_G=71,e.KEY_H=72,e.KEY_HOME=36,e.KEY_I=73,e.KEY_INSERT=45,e.KEY_J=74,e.KEY_K=75,e.KEY_L=76,e.KEY_LEFT=37,e.KEY_M=77,e.KEY_META=224,e.KEY_MULTIPLY=106,e.KEY_N=78,e.KEY_NUMPAD_0=96,e.KEY_NUMPAD_1=97,e.KEY_NUMPAD_2=98,e.KEY_NUMPAD_3=99,e.KEY_NUMPAD_4=100,e.KEY_NUMPAD_5=101,e.KEY_NUMPAD_6=102,e.KEY_NUMPAD_7=103,e.KEY_NUMPAD_8=104,e.KEY_NUMPAD_9=105,e.KEY_O=79,e.KEY_OPEN_BRACKET=219,e.KEY_P=80,e.KEY_PAGE_DOWN=34,e.KEY_PAGE_UP=33,e.KEY_PAUSE=19,e.KEY_PERIOD=190,e.KEY_PRINT_SCREEN=44,e.KEY_Q=81,e.KEY_R=82,e.KEY_RETURN=13,e.KEY_RIGHT=39,e.KEY_S=83,e.KEY_SEMICOLON=59,e.KEY_SEPARATOR=108,e.KEY_SHIFT=16,e.KEY_SLASH=191,e.KEY_SPACE=32,e.KEY_SUBTRACT=109,e.KEY_T=84,e.KEY_TAB=9,e.KEY_U=85,e.KEY_UP=38,e.KEY_V=86,e.KEY_W=87,e.KEY_WINDOWS=91,e.KEY_X=88,e.KEY_Y=89,e.KEY_Z=90,e.Key=pu,e.Keyboard=mm,e.KeyboardEvent=cm,e.LAYERID_DEPTH=1,e.LAYERID_IMMEDIATE=3,e.LAYERID_SKYBOX=2,e.LAYERID_UI=4,e.LAYERID_WORLD=0,e.LAYER_FX=2,e.LAYER_GIZMO=1,e.LAYER_HUD=0,e.LAYER_WORLD=15,e.LIGHTFALLOFF_INVERSESQUARED=1,e.LIGHTFALLOFF_LINEAR=0,e.LIGHTSHAPE_DISK=2,e.LIGHTSHAPE_PUNCTUAL=0,e.LIGHTSHAPE_RECT=1,e.LIGHTSHAPE_SPHERE=3,e.LIGHTTYPE_COUNT=3,e.LIGHTTYPE_DIRECTIONAL=0,e.LIGHTTYPE_OMNI=1,e.LIGHTTYPE_POINT=1,e.LIGHTTYPE_SPOT=2,e.LINEBATCH_GIZMO=2,e.LINEBATCH_OVERLAY=1,e.LINEBATCH_WORLD=0,e.Layer=fh,e.LayerComposition=bh,e.LayoutCalculator=Mv,e.LayoutChildComponent=fv,e.LayoutChildComponentSystem=_v,e.LayoutGroupComponent=Pv,e.LayoutGroupComponentSystem=Lv,e.Light=Ih,e.LightComponent=Sx,e.LightComponentSystem=Ax,e.LightingParams=Lh,e.Lightmapper=sc,e.LocalizedAsset=Qp,e.MASK_AFFECT_DYNAMIC=1,e.MASK_AFFECT_LIGHTMAPPED=2,e.MASK_BAKE=4,e.MOTION_FREE=sv,e.MOTION_LIMITED=rv,e.MOTION_LOCKED=av,e.MOUSEBUTTON_LEFT=0,e.MOUSEBUTTON_MIDDLE=1,e.MOUSEBUTTON_NONE=-1,e.MOUSEBUTTON_RIGHT=2,e.Mat3=xe,e.Mat4=Ee,e.Material=Bs,e.MaterialHandler=cp,e.Mesh=ea,e.MeshInstance=ka,e.Model=hc,e.ModelComponent=Dv,e.ModelComponentSystem=Fv,e.ModelHandler=vp,e.Morph=rc,e.MorphInstance=oc,e.MorphTarget=lc,e.Mouse=xm,e.MouseEvent=ym,e.Node=mu,e.ORIENTATION_HORIZONTAL=0,e.ORIENTATION_VERTICAL=1,e.OrientedBox=rt,e.PAD_1=0,e.PAD_2=1,e.PAD_3=2,e.PAD_4=3,e.PAD_DOWN=13,e.PAD_FACE_1=0,e.PAD_FACE_2=1,e.PAD_FACE_3=2,e.PAD_FACE_4=3,e.PAD_LEFT=14,e.PAD_L_SHOULDER_1=4,e.PAD_L_SHOULDER_2=6,e.PAD_L_STICK_BUTTON=10,e.PAD_L_STICK_X=0,e.PAD_L_STICK_Y=1,e.PAD_RIGHT=15,e.PAD_R_SHOULDER_1=5,e.PAD_R_SHOULDER_2=7,e.PAD_R_STICK_BUTTON=11,e.PAD_R_STICK_X=2,e.PAD_R_STICK_Y=3,e.PAD_SELECT=8,e.PAD_START=9,e.PAD_UP=12,e.PAD_VENDOR=16,e.PARTICLEMODE_CPU=1,e.PARTICLEMODE_GPU=0,e.PARTICLEORIENTATION_EMITTER=2,e.PARTICLEORIENTATION_SCREEN=0,e.PARTICLEORIENTATION_WORLD=1,e.PARTICLESORT_DISTANCE=1,e.PARTICLESORT_NEWER_FIRST=2,e.PARTICLESORT_NONE=0,e.PARTICLESORT_OLDER_FIRST=3,e.PIXELFORMAT_111110F=18,e.PIXELFORMAT_A8=0,e.PIXELFORMAT_ASTC_4x4=28,e.PIXELFORMAT_ATC_RGB=29,e.PIXELFORMAT_ATC_RGBA=30,e.PIXELFORMAT_DEPTH=ft,e.PIXELFORMAT_DEPTHSTENCIL=pt,e.PIXELFORMAT_DXT1=8,e.PIXELFORMAT_DXT3=9,e.PIXELFORMAT_DXT5=ht,e.PIXELFORMAT_ETC1=mt,e.PIXELFORMAT_ETC2_RGB=22,e.PIXELFORMAT_ETC2_RGBA=23,e.PIXELFORMAT_L8=1,e.PIXELFORMAT_L8_A8=2,e.PIXELFORMAT_PVRTC_2BPP_RGBA_1=gt,e.PIXELFORMAT_PVRTC_2BPP_RGB_1=_t,e.PIXELFORMAT_PVRTC_4BPP_RGBA_1=27,e.PIXELFORMAT_PVRTC_4BPP_RGB_1=26,e.PIXELFORMAT_R32F=15,e.PIXELFORMAT_R4_G4_B4_A4=5,e.PIXELFORMAT_R5_G5_B5_A1=4,e.PIXELFORMAT_R5_G6_B5=3,e.PIXELFORMAT_R8_G8_B8=6,e.PIXELFORMAT_R8_G8_B8_A8=7,e.PIXELFORMAT_RGB16F=lt,e.PIXELFORMAT_RGB32F=ut,e.PIXELFORMAT_RGBA16F=ct,e.PIXELFORMAT_RGBA32F=dt,e.PIXELFORMAT_SRGB=19,e.PIXELFORMAT_SRGBA=20,e.PRIMITIVE_LINELOOP=2,e.PRIMITIVE_LINES=1,e.PRIMITIVE_LINESTRIP=3,e.PRIMITIVE_POINTS=0,e.PRIMITIVE_TRIANGLES=4,e.PRIMITIVE_TRIFAN=6,e.PRIMITIVE_TRISTRIP=5,e.PROJECTION_ORTHOGRAPHIC=1,e.PROJECTION_PERSPECTIVE=0,e.ParticleEmitter=su,e.ParticleSystemComponent=Gv,e.ParticleSystemComponentSystem=Xv,e.PhongMaterial=Tb,e.Picker=ou,e.Plane=ot,e.PostEffect=Ir,e.PostEffectQueue=px,e.ProgramLibrary=rr,e.Quat=Pe,e.RENDERSTYLE_POINTS=2,e.RENDERSTYLE_SOLID=0,e.RENDERSTYLE_WIREFRAME=1,e.RESOLUTION_AUTO=Hl,e.RESOLUTION_FIXED=Xl,e.RIGIDBODY_ACTIVE_TAG=1,e.RIGIDBODY_CF_KINEMATIC_OBJECT=2,e.RIGIDBODY_CF_NORESPONSE_OBJECT=4,e.RIGIDBODY_CF_STATIC_OBJECT=1,e.RIGIDBODY_DISABLE_DEACTIVATION=4,e.RIGIDBODY_DISABLE_SIMULATION=5,e.RIGIDBODY_ISLAND_SLEEPING=2,e.RIGIDBODY_TYPE_DYNAMIC="dynamic",e.RIGIDBODY_TYPE_KINEMATIC="kinematic",e.RIGIDBODY_TYPE_STATIC="static",e.RIGIDBODY_WANTS_DEACTIVATION=3,e.Ray=et,e.RaycastResult=oy,e.ReadStream=se,e.RenderComponent=qv,e.RenderComponentSystem=Zv,e.RenderHandler=Sp,e.RenderTarget=cr,e.ResourceHandler=wp,e.ResourceLoader=tl,e.RigidBodyComponent=ry,e.RigidBodyComponentSystem=dy,e.SAMPLETYPE_DEPTH="depth",e.SAMPLETYPE_FLOAT=ii,e.SAMPLETYPE_UNFILTERABLE_FLOAT=ni,e.SCALEMODE_BLEND=py,e.SCALEMODE_NONE=fy,e.SCROLLBAR_VISIBILITY_SHOW_ALWAYS=0,e.SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED=1,e.SCROLL_MODE_BOUNCE=1,e.SCROLL_MODE_CLAMP=0,e.SCROLL_MODE_INFINITE=2,e.SEMANTIC_ATTR=Dt,e.SEMANTIC_ATTR0=kt,e.SEMANTIC_ATTR1=Ot,e.SEMANTIC_ATTR10=Ht,e.SEMANTIC_ATTR11=Xt,e.SEMANTIC_ATTR12=qt,e.SEMANTIC_ATTR13=jt,e.SEMANTIC_ATTR14=Yt,e.SEMANTIC_ATTR15=Kt,e.SEMANTIC_ATTR2=Ft,e.SEMANTIC_ATTR3=Bt,e.SEMANTIC_ATTR4=Nt,e.SEMANTIC_ATTR5=Ut,e.SEMANTIC_ATTR6=zt,e.SEMANTIC_ATTR7=Vt,e.SEMANTIC_ATTR8=Gt,e.SEMANTIC_ATTR9=Wt,e.SEMANTIC_BLENDINDICES=St,e.SEMANTIC_BLENDWEIGHT=bt,e.SEMANTIC_COLOR=wt,e.SEMANTIC_NORMAL=yt,e.SEMANTIC_POSITION=vt,e.SEMANTIC_TANGENT=xt,e.SEMANTIC_TEXCOORD=Tt,e.SEMANTIC_TEXCOORD0=At,e.SEMANTIC_TEXCOORD1=Mt,e.SEMANTIC_TEXCOORD2=Ct,e.SEMANTIC_TEXCOORD3=Et,e.SEMANTIC_TEXCOORD4=Pt,e.SEMANTIC_TEXCOORD5=Rt,e.SEMANTIC_TEXCOORD6=It,e.SEMANTIC_TEXCOORD7=Lt,e.SHADERDEF_DIRLM=Ge,e.SHADERDEF_INSTANCING=32,e.SHADERDEF_LM=64,e.SHADERDEF_LMAMBIENT=je,e.SHADERDEF_MORPH_NORMAL=Xe,e.SHADERDEF_MORPH_POSITION=He,e.SHADERDEF_MORPH_TEXTURE_BASED=qe,e.SHADERDEF_NOSHADOW=1,e.SHADERDEF_SCREENSPACE=We,e.SHADERDEF_SKIN=2,e.SHADERDEF_TANGENTS=512,e.SHADERDEF_UV0=4,e.SHADERDEF_UV1=8,e.SHADERDEF_VCOLOR=16,e.SHADERSTAGE_COMPUTE=4,e.SHADERSTAGE_FRAGMENT=2,e.SHADERSTAGE_VERTEX=1,e.SHADERTAG_MATERIAL=1,e.SHADERTYPE_DEPTH=Ke,e.SHADERTYPE_FORWARD=Ye,e.SHADERTYPE_PICK=Ze,e.SHADERTYPE_SHADOW=$e,e.SHADER_DEPTH=2,e.SHADER_FORWARD=0,e.SHADER_FORWARDHDR=1,e.SHADER_PICK=3,e.SHADER_SHADOW=4,e.SHADOWUPDATE_NONE=0,e.SHADOWUPDATE_REALTIME=2,e.SHADOWUPDATE_THISFRAME=1,e.SHADOW_COUNT=6,e.SHADOW_DEPTH=0,e.SHADOW_PCF1=5,e.SHADOW_PCF3=0,e.SHADOW_PCF5=4,e.SHADOW_VSM16=2,e.SHADOW_VSM32=3,e.SHADOW_VSM8=1,e.SORTKEY_DEPTH=1,e.SORTKEY_FORWARD=0,e.SORTMODE_BACK2FRONT=3,e.SORTMODE_CUSTOM=5,e.SORTMODE_FRONT2BACK=4,e.SORTMODE_MANUAL=1,e.SORTMODE_MATERIALMESH=2,e.SORTMODE_NONE=0,e.SPECOCC_AO=1,e.SPECOCC_GLOSSDEPENDENT=2,e.SPECOCC_NONE=0,e.SPECULAR_BLINN=1,e.SPECULAR_PHONG=0,e.SPRITETYPE_ANIMATED=Jy,e.SPRITETYPE_SIMPLE=Qy,e.SPRITE_RENDERMODE_SIMPLE=0,e.SPRITE_RENDERMODE_SLICED=1,e.SPRITE_RENDERMODE_TILED=2,e.STENCILOP_DECREMENT=5,e.STENCILOP_DECREMENTWRAP=6,e.STENCILOP_INCREMENT=3,e.STENCILOP_INCREMENTWRAP=4,e.STENCILOP_INVERT=7,e.STENCILOP_KEEP=0,e.STENCILOP_REPLACE=2,e.STENCILOP_ZERO=1,e.Scene=Kh,e.SceneHandler=Tp,e.SceneRegistry=Bl,e.SceneRegistryItem=Fl,e.SceneSettingsHandler=Ap,e.ScopeId=un,e.ScopeSpace=dn,e.ScreenComponent=_y,e.ScreenComponentSystem=yy,e.ScriptAttributes=Ml,e.ScriptComponent=El,e.ScriptComponentSystem=Ex,e.ScriptHandler=gl,e.ScriptLegacyComponent=xy,e.ScriptLegacyComponentSystem=Py,e.ScriptRegistry=Il,e.ScriptType=Rl,e.ScrollViewComponent=Ny,e.ScrollViewComponentSystem=Vy,e.ScrollbarComponent=Gy,e.ScrollbarComponentSystem=Xy,e.Shader=zi,e.ShaderHandler=Mp,e.SingleContactResult=hy,e.Skeleton=vu,e.Skin=hu,e.SkinBatchInstance=Sa,e.SkinInstance=ba,e.SortedLoopArray=re,e.Sound=Cd,e.SoundComponent=Yy,e.SoundComponentSystem=$y,e.SoundInstance=Pd,e.SoundInstance3d=Rd,e.SoundManager=Md,e.SoundSlot=jy,e.Sprite=uu,e.SpriteAnimationClip=ex,e.SpriteComponent=rx,e.SpriteComponentSystem=hx,e.SpriteHandler=Pp,e.StandardMaterial=Zs,e.StencilParameters=du,e.TEXHINT_ASSET=2,e.TEXHINT_LIGHTMAP=3,e.TEXHINT_NONE=0,e.TEXHINT_SHADOWMAP=1,e.TEXTUREDIMENSION_1D="1d",e.TEXTUREDIMENSION_2D=ti,e.TEXTUREDIMENSION_2D_ARRAY="2d-array",e.TEXTUREDIMENSION_3D="3d",e.TEXTUREDIMENSION_CUBE="cube",e.TEXTUREDIMENSION_CUBE_ARRAY="cube-array",e.TEXTURELOCK_READ=1,e.TEXTURELOCK_WRITE=2,e.TEXTUREPROJECTION_CUBE=ri,e.TEXTUREPROJECTION_EQUIRECT=ai,e.TEXTUREPROJECTION_NONE=si,e.TEXTUREPROJECTION_OCTAHEDRAL=oi,e.TEXTURETYPE_DEFAULT=Zt,e.TEXTURETYPE_RGBE=Qt,e.TEXTURETYPE_RGBM=$t;e.TEXTURETYPE_RGBP=Jt,e.TEXTURETYPE_SWIZZLEGGGR=ei,e.TONEMAP_ACES=3,e.TONEMAP_ACES2=4,e.TONEMAP_FILMIC=1,e.TONEMAP_HEJL=2,e.TONEMAP_LINEAR=0,e.TRACEID_RENDER_ACTION="RenderAction",e.TRACEID_RENDER_FRAME="RenderFrame",e.TRACEID_RENDER_PASS="RenderPass",e.TRACEID_RENDER_PASS_DETAIL="RenderPassDetail",e.TRACEID_RENDER_TARGET_ALLOC="RenderTargetAlloc",e.TRACEID_SHADER_ALLOC="ShaderAlloc",e.TRACEID_TEXTURE_ALLOC="TextureAlloc",e.TRACEID_VRAM_IB="VRAM.Ib",e.TRACEID_VRAM_TEXTURE="VRAM.Texture",e.TRACEID_VRAM_VB="VRAM.Vb",e.TYPE_FLOAT32=6,e.TYPE_INT16=2,e.TYPE_INT32=4,e.TYPE_INT8=0,e.TYPE_UINT16=3,e.TYPE_UINT32=5,e.TYPE_UINT8=1,e.Tags=ae,e.Template=Rp,e.TemplateHandler=Ip,e.TextElement=Hg,e.TextHandler=Lp,e.Texture=wn,e.TextureAtlas=fu,e.TextureAtlasHandler=Zp,e.TextureHandler=qp,e.TextureParser=Xp,e.Timer=he,e.Touch=s_,e.TouchDevice=a_,e.TouchEvent=r_,e.Tracing=ue,e.TransformFeedback=kr,e.UNIFORMTYPE_BOOL=0,e.UNIFORMTYPE_BVEC2=9,e.UNIFORMTYPE_BVEC3=10,e.UNIFORMTYPE_BVEC4=11,e.UNIFORMTYPE_FLOAT=2,e.UNIFORMTYPE_FLOATARRAY=17,e.UNIFORMTYPE_INT=1,e.UNIFORMTYPE_IVEC2=6,e.UNIFORMTYPE_IVEC3=7,e.UNIFORMTYPE_IVEC4=8,e.UNIFORMTYPE_MAT2=12,e.UNIFORMTYPE_MAT3=13,e.UNIFORMTYPE_MAT4=14,e.UNIFORMTYPE_TEXTURE2D=15,e.UNIFORMTYPE_TEXTURE2D_SHADOW=18,e.UNIFORMTYPE_TEXTURE3D=20,e.UNIFORMTYPE_TEXTURECUBE=16,e.UNIFORMTYPE_TEXTURECUBE_SHADOW=19,e.UNIFORMTYPE_VEC2=3,e.UNIFORMTYPE_VEC2ARRAY=21,e.UNIFORMTYPE_VEC3=4,e.UNIFORMTYPE_VEC3ARRAY=22,e.UNIFORMTYPE_VEC4=5,e.UNIFORMTYPE_VEC4ARRAY=23,e.UNIFORM_BUFFER_DEFAULT_SLOT_NAME=ui,e.URI=ce,e.UnsupportedBrowserError=vb,e.VIEW_CENTER=0,e.VIEW_LEFT=1,e.VIEW_RIGHT=2,e.Vec2=be,e.Vec3=ye,e.Vec4=Se,e.VertexBuffer=Si,e.VertexFormat=Ti,e.VertexIterator=Pr,e.WasmModule=K,e.WebglGraphicsDevice=jr,e.WorldClusters=$a,e.XRDEPTHSENSINGFORMAT_F32="float32",e.XRDEPTHSENSINGFORMAT_L8A8=Fx,e.XRDEPTHSENSINGUSAGE_CPU=kx,e.XRDEPTHSENSINGUSAGE_GPU=Ox,e.XRHAND_LEFT=Dx,e.XRHAND_NONE="none",e.XRHAND_RIGHT="right",e.XRSPACE_BOUNDEDFLOOR="bounded-floor",e.XRSPACE_LOCAL="local",e.XRSPACE_LOCALFLOOR="local-floor",e.XRSPACE_UNBOUNDED="unbounded",e.XRSPACE_VIEWER=Lx,e.XRTARGETRAY_GAZE="gaze",e.XRTARGETRAY_POINTER="tracked-pointer",e.XRTARGETRAY_SCREEN="screen",e.XRTRACKABLE_MESH="mesh",e.XRTRACKABLE_PLANE="plane",e.XRTRACKABLE_POINT="point",e.XRTYPE_AR=Ix,e.XRTYPE_INLINE=Px,e.XRTYPE_VR=Rx,e.XrDepthSensing=lb,e.XrDomOverlay=hb,e.XrHitTest=zx,e.XrHitTestSource=Ux,e.XrImageTracking=ob,e.XrInput=eb,e.XrInputSource=Jx,e.XrLightEstimation=rb,e.XrManager=fb,e.XrPlane=ub,e.XrPlaneDetection=db,e.XrTrackedImage=ab,e.ZoneComponent=lx,e.ZoneComponentSystem=dx,e.anim=Cb,e.apps={},e.asset={ASSET_ANIMATION:"animation",ASSET_AUDIO:"audio",ASSET_IMAGE:"image",ASSET_JSON:"json",ASSET_MODEL:"model",ASSET_MATERIAL:"material",ASSET_TEXT:"text",ASSET_TEXTURE:"texture",ASSET_CUBEMAP:"cubemap",ASSET_SCRIPT:"script"},e.audio=Eb,e.basisInitialize=Vd,e.basisSetDownloadConfig=function(e,t,i){Vd({glueUrl:e,wasmUrl:t,fallbackUrl:i,lazyInit:!0})},e.basisTranscode=Wd,e.bindGroupNames=di,e.calculateNormals=sa,e.calculateTangents=ra,e.common={},e.config={},e.createBox=pa,e.createCapsule=ca,e.createCone=ua,e.createCylinder=la,e.createMesh=aa,e.createPlane=fa,e.createScript=em,e.createShader=an,e.createShaderFromCode=on,e.createSphere=da,e.createStyle=function(e){var t=document.createElement("style");return t.type="text/css",t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e)),t},e.createTorus=oa,e.createURI=function(e){var t="";if((e.authority||e.scheme)&&(e.host||e.hostpath))throw new Error("Can't have 'scheme' or 'authority' and 'host' or 'hostpath' option");if(e.host&&e.hostpath)throw new Error("Can't have 'host' and 'hostpath' option");if(e.path&&e.hostpath)throw new Error("Can't have 'path' and 'hostpath' option");return e.scheme&&(t+=e.scheme+":"),e.authority&&(t+="//"+e.authority),e.host&&(t+=e.host),e.path&&(t+=e.path),e.hostpath&&(t+=e.hostpath),e.query&&(t+="?"+e.query),e.fragment&&(t+="#"+e.fragment),t},e.data={},e.drawFullscreenQuad=Dr,e.drawQuadWithShader=Ei,e.drawTexture=function(e,t,i,n,s,r,a){void 0===a&&(a=!1),n=n||e.getCopyShader(),e.constantTexSource.setValue(t),Ei(e,i,n,s,r,a)},e.events=_,e.extend=f,e.fw=Rb,e.getTouchTargetCoords=n_,e.gfx=bb,e.guid=g,e.http=pe,e.inherits=function(e,t){var i=function(){},n=function(i,n,s,r,a,o,h,l){t.call(this,i,n,s,r,a,o,h,l),e.call(this,i,n,s,r,a,o,h,l)};return n._super=t.prototype,i.prototype=t.prototype,n.prototype=new i,n},e.input=Pb,e.isDefined=p,e.log=mb,e.makeArray=function(e){return Array.prototype.slice.call(e)},e.math=de,e.now=oe,e.path=v,e.platform=L,e.posteffect=Sb,e.prefilterCubemap=function(e){},e.programlib=xb,e.registerScript=im,e.reprojectTexture=Ps,e.revision=c,e.scene=Ab,e.script=xl,e.semanticToLocation=vi,e.shFromCubemap=function(e,t,i){if(7!==t.format)return null;if(!t._levels[0]||!t._levels[0][0])return null;var n=t.width;if(!t._levels[0][0].length){if(!(t._levels[0][0]instanceof HTMLImageElement))return null;for(var s=on(e,Wi.fullscreenQuadVS,Wi.fullscreenQuadPS,"fsQuadSimple"),r=e.scope.resolve("source"),a=0;a<6;a++){var o=t._levels[0][a],h=new wn(e,{name:"prefiltered-cube",cubemap:!1,type:Zt,format:t.format,width:n,height:n,mipmaps:!1});h._levels[0]=o,h.upload();var l=new wn(e,{name:"prefiltered-cube",cubemap:!1,type:Zt,format:t.format,width:n,height:n,mipmaps:!1}),c=new cr({colorBuffer:l,depth:!1});r.setValue(h),Ei(e,c,s);var u=e.gl;u.bindFramebuffer(u.FRAMEBUFFER,c.impl._glFrameBuffer);var d=new Uint8Array(n*n*4);u.readPixels(0,0,h.width,h.height,u.RGBA,u.UNSIGNED_BYTE,d),t._levels[0][a]=d}}for(var f=[],p=0;p<n;p++)for(var m=0;m<n;m++){var _=m/(n-1)*2-1,g=p/(n-1)*2-1;f[p*n+m]=new ye(_,g,1).normalize()}for(var v=new Float32Array(27),y=0,x=0;x<6;x++)for(var b=0;b<n;b++)for(var S=0;S<n;S++){var w=b*n+S,T=dr(S,b,n),A=4*T/17,M=8*T/17,C=15*T/17,E=5*T/68,P=15*T/68,R=f[w],I=void 0,L=void 0,D=void 0;0===x?(I=R.z,L=-R.y,D=-R.x):1===x?(I=-R.z,L=-R.y,D=R.x):2===x?(I=R.x,L=R.z,D=R.y):3===x?(I=R.x,L=-R.z,D=-R.y):4===x?(I=R.x,L=-R.y,D=R.z):5===x&&(I=-R.x,L=-R.y,D=-R.z),i||(I=-I);for(var k=t._levels[0][x][4*w+3]/255,O=0;O<3;O++){var F=t._levels[0][x][4*w+O]/255;t.type===$t?(F*=8*k,F*=F):F=Math.pow(F,2.2),v[0+O]+=F*A,v[3+O]+=F*M*I,v[6+O]+=F*M*L,v[9+O]+=F*M*D,v[12+O]+=F*C*I*D,v[15+O]+=F*C*D*L,v[18+O]+=F*C*L*I,v[21+O]+=F*E*(3*D*D-1),v[24+O]+=F*P*(I*I-L*L),y+=T}}for(var B=0;B<v.length;B++)v[B]*=4*Math.PI/y;return v},e.shaderChunks=Wi,e.shaderChunksLightmapper=fr,e.shadowTypeToString=Ve,e.shape=gb,e.string=q,e.time=_b,e.type=d,e.typedArrayIndexFormats=_i,e.typedArrayIndexFormatsByteSize=gi,e.typedArrayToType=mi,e.typedArrayTypes=fi,e.typedArrayTypesByteSize=pi,e.uniformTypeToName=hi,e.version=l,Object.defineProperty(e,"__esModule",{value:!0})}));