/** * @license * PlayCanvas Engine v1.66.3 revision bf0b7c6e9 (RELEASE) * Copyright 2011-2023 PlayCanvas Ltd. All rights reserved. */ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).pc={})}(this,(function(t){"use strict";function e(t,e,i){t.prototype[e]||Object.defineProperty(t.prototype,e,{value:i,configurable:!0,enumerable:!1,writable:!0})}e(Array,"fill",(function(t){if(null==this)throw new TypeError("this is null or not defined");for(var e=Object(this),i=e.length>>>0,n=arguments[1]>>0,s=n<0?Math.max(i+n,0):Math.min(n,i),r=arguments[2],a=void 0===r?i:r>>0,o=a<0?Math.max(i+a,0):Math.min(a,i);s>>0;if("function"!=typeof t)throw TypeError("predicate must be a function");for(var n=arguments[1],s=0;s>>0;if("function"!=typeof t)throw new TypeError("predicate must be a function");for(var n=arguments[1],s=0;s0)-(t<0)||+t}),void 0===Number.isFinite&&(Number.isFinite=function(t){return"number"==typeof t&&isFinite(t)}),"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(t,e){if(null==t)throw new TypeError("Cannot convert undefined or null to object");for(var i=Object(t),n=1;nthis.length)&&(e=this.length),this.substring(e-t.length,e)===t})),e(String,"includes",(function(t,e){return"number"!=typeof e&&(e=0),!(e+t.length>this.length)&&-1!==this.indexOf(t,e)})),e(String,"startsWith",(function(t,e){var i=e>0?0|e:0;return this.substring(i,i+t.length)===t})),e(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=0;--r){var a=this.tryEntries[r],o=a.completion;if("root"===a.tryLoc)return s("end");if(a.tryLoc<=this.prev){var h=n.call(a,"catchLoc"),l=n.call(a,"finallyLoc");if(h&&l){if(this.prev=0;--i){var s=this.tryEntries[i];if(s.tryLoc<=this.prev&&n.call(s,"finallyLoc")&&this.prev=0;--e){var i=this.tryEntries[e];if(i.finallyLoc===t)return this.complete(i.completion,i.afterLoc),R(i),v}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var i=this.tryEntries[e];if(i.tryLoc===t){var n=i.completion;if("throw"===n.type){var s=n.arg;R(i)}return s}}throw new Error("illegal catch attempt")},delegateYield:function(e,i,n){return this.delegate={iterator:L(e),resultName:i,nextLoc:n},"next"===this.method&&(this.arg=t),v}},e}function _(t,e,i,n,s,r,a){try{var o=t[r](a),h=o.value}catch(t){return void i(t)}o.done?e(h):Promise.resolve(h).then(n,s)}function v(t){return function(){var e=this,i=arguments;return new Promise((function(n,s){var r=t.apply(e,i);function a(t){_(r,n,s,a,o,"next",t)}function o(t){_(r,n,s,a,o,"throw",t)}a(void 0)}))}}function g(t,e){for(var i=0;it.length)&&(e=t.length);for(var i=0,n=new Array(e);i=t.length?{done:!0}:{done:!1,value:t[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.")}function C(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}var E=function(){function t(){}return t.set=function(t,e){},t.get=function(e){return t._traceChannels.has(e)},t}();E._traceChannels=new Set,E.stack=!1;var M=function(){function t(t,e,i,n,s){void 0===s&&(s=!1),this.handler=void 0,this.name=void 0,this.callback=void 0,this.scope=void 0,this._once=void 0,this._removed=!1,this.handler=t,this.name=e,this.callback=i,this.scope=n,this._once=s}var e=t.prototype;return e.off=function(){this._removed||this.handler.off(this.name,this.callback,this.scope)},e.on=function(t,e,i){return void 0===i&&(i=this),this.handler._addCallback(t,e,i,!1)},e.once=function(t,e,i){return void 0===i&&(i=this),this.handler._addCallback(t,e,i,!0)},y(t,[{key:"removed",get:function(){return this._removed},set:function(t){t&&(this._removed=!0)}}]),t}(),P=function(){function t(){this._callbacks=new Map,this._callbackActive=new Map}var e=t.prototype;return e.initEventHandler=function(){this._callbacks=new Map,this._callbackActive=new Map},e._addCallback=function(t,e,i,n){if(this._callbacks.has(t)||this._callbacks.set(t,[]),this._callbackActive.has(t)){var s=this._callbackActive.get(t);s&&s===this._callbacks.get(t)&&this._callbackActive.set(t,s.slice())}var r=new M(this,t,e,i,n);return this._callbacks.get(t).push(r),r},e.on=function(t,e,i){return void 0===i&&(i=this),this._addCallback(t,e,i,!1)},e.once=function(t,e,i){return void 0===i&&(i=this),this._addCallback(t,e,i,!0)},e.off=function(t,e,i){if(t)this._callbackActive.has(t)&&this._callbackActive.get(t)===this._callbacks.get(t)&&this._callbackActive.set(t,this._callbackActive.get(t).slice());else for(var n,s=A(this._callbackActive);!(n=s()).done;){var r=n.value,a=r[0],o=r[1];this._callbacks.has(a)&&(this._callbacks.get(a)===o&&this._callbackActive.set(a,o.slice()))}if(t)if(e){var h=this._callbacks.get(t);if(!h)return this;for(var l=0;l0?r=r.slice(0,r.length-2):(a>0&&r.push(L.delimiter),r.push(n[a])));return s=r.join(""),e||s[0]!==L.delimiter||(s=s.slice(1)),i&&s[s.length-1]!==L.delimiter&&(s+=L.delimiter),s},split:function(t){var e=t.lastIndexOf(L.delimiter);return-1!==e?[t.substring(0,e),t.substring(e+1)]:["",t]},getBasename:function(t){return L.split(t)[1]},getDirectory:function(t){return L.split(t)[0]},getExtension:function(t){var e=t.split("?")[0].split(".").pop();return e!==t?"."+e:""},isRelativePath:function(t){return"/"!==t.charAt(0)&&null===t.match(/:\/\//)},extractPath:function(t){var e="",i=t.split("/"),n=0;if(i.length>1)if(L.isRelativePath(t))if("."===i[0])for(n=0;n0),N=!("browser"!==O||!navigator.getGamepads&&!navigator.webkitGetGamepads),z="undefined"!=typeof Worker,V=function(){var t=!1;try{var e=Object.defineProperty({},"passive",{get:function(){return t=!0,!1}});window.addEventListener("testpassive",null,e),window.removeEventListener("testpassive",null,e)}catch(t){}return t}(),G={environment:O,global:"browser"===O?window:global,browser:"browser"===O,desktop:["windows","osx","linux","cros"].includes(k),mobile:["android","ios"].includes(k),ios:"ios"===k,android:"android"===k,xbox:B,gamepads:N,touch:U,workers:z,passiveEvents:V,browserName:F},H="abcdefghijklmnopqrstuvwxyz",W="ABCDEFGHIJKLMNOPQRSTUVWXYZ",X=55296,j=56319,q=56320,Y=57343,K=127462,Z=127487,Q=65024,$=65039;function J(t,e){void 0===e&&(e=0);var i=t.length;if(e<0||e>=i)return null;var n=t.charCodeAt(e);if(i>1&&n>=X&&n<=j){var s=t.charCodeAt(e+1);if(s>=q&&s<=Y)return{code:1024*(n-X)+s-q+65536,long:!0}}return{code:n,long:!1}}function tt(t,e,i){if(!t)return!1;var n=J(t);if(n){var s=n.code;return s>=e&&s<=i}return!1}function et(t,e){if(e===t.length-1)return 1;if(tt(t[e],X,j)){var i=t.substring(e,e+2),n=t.substring(e+2,e+4);return tt(n,127995,127999)||tt(i,K,Z)&&tt(n,K,Z)?4:tt(n,Q,$)?3:2}return tt(t[e+1],Q,$)?2:1}var it,nt,st,rt={ASCII_LOWERCASE:H,ASCII_UPPERCASE:W,ASCII_LETTERS:H+W,format:function(t){for(var e=0;e<(arguments.length<=1?0:arguments.length-1);e++)t=t.replace("{"+e+"}",e+1<1||arguments.length<=e+1?void 0:arguments[e+1]);return t},getCodePoint:function(t,e){var i=J(t,e);return i&&i.code},getCodePoints:function(t){if("string"!=typeof t)throw new TypeError("Not a string");for(var e,i=0,n=[];e=J(t,i);)n.push(e.code),i+=e.long?2:1;return n},getSymbols:function(t){if("string"!=typeof t)throw new TypeError("Not a string");for(var e,i=0,n=t.length,s=[],r=0;i65535?[55296+(e>>10),e%1024+56320]:[t],n.push(String.fromCharCode.apply(null,i));return n.join("")}},at=function(){function t(){this._list=[],this._index={}}var e=t.prototype;return e.push=function(t,e){if(this._index[t])throw Error("Key already in index "+t);var i=this._list.push(e)-1;this._index[t]=i},e.has=function(t){return void 0!==this._index[t]},e.get=function(t){var e=this._index[t];return void 0!==e?this._list[e]:null},e.remove=function(t){var e=this._index[t];if(void 0!==e){for(t in this._list.splice(e,1),delete this._index[t],this._index){var i=this._index[t];i>e&&(this._index[t]=i-1)}return!0}return!1},e.list=function(){return this._list},e.clear=function(){for(var t in this._list.length=0,this._index)delete this._index[t]},t}(),ot=function(){function t(){}return t.loadScript=function(t,e){var i=document.createElement("script");i.setAttribute("src",t),i.onload=function(){e(null)},i.onerror=function(){e("Failed to load script='"+t+"'")},document.body.appendChild(i)},t.loadWasm=function(e,i,n){var s=t.wasmSupported()&&i.glueUrl&&i.wasmUrl?i.glueUrl:i.fallbackUrl;s?t.loadScript(s,(function(t){if(t)n(t,null);else{var s=window[e];window[e]=void 0,s({locateFile:function(){return i.wasmUrl},onAbort:function(){n("wasm module aborted.")}}).then((function(t){n(null,t)}))}})):n("No supported wasm modules found.",null)},t.getModule=function(e){return t.modules.hasOwnProperty(e)||(t.modules[e]={config:null,initializing:!1,instance:null,callbacks:[]}),t.modules[e]},t.initialize=function(e,i){if(!i.initializing){var n=i.config;(n.glueUrl||n.wasmUrl||n.fallbackUrl)&&(i.initializing=!0,t.loadWasm(e,n,(function(t,s){t?n.errorHandler?n.errorHandler(t):console.error("failed to initialize module="+e+" error="+t):(i.instance=s,i.callbacks.forEach((function(t){t(s)})))})))}},t}();ot.modules={},ot.wasmSupported=(it=function(){try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){var t=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(t instanceof WebAssembly.Module)return new WebAssembly.Instance(t)instanceof WebAssembly.Instance}}catch(t){}return!1},st=nt={},function(){return st===nt&&(st=it()),st});var ht=function(){function t(){}return t.setConfig=function(t,e){var i=ot.getModule(t);i.config=e,i.callbacks.length>0&&ot.initialize(t,i)},t.getConfig=function(t){var e;return null==(e=ot.modules)||null==(e=e[t])?void 0:e.config},t.getInstance=function(t,e){var i=ot.getModule(t);i.instance?e(i.instance):(i.callbacks.push(e),i.config&&ot.initialize(t,i))},t}(),lt=function(){function t(t){this.arraybuffer=t,this.dataView=new DataView(t),this.offset=0,this.stack=[]}var e=t.prototype;return e.reset=function(t){void 0===t&&(t=0),this.offset=t},e.skip=function(t){this.offset+=t},e.align=function(t){this.offset=this.offset+t-1&~(t-1)},e._inc=function(t){return this.offset+=t,this.offset-t},e.readChar=function(){return String.fromCharCode(this.dataView.getUint8(this.offset++))},e.readChars=function(t){for(var e="",i=0;i=t.byteLength);){var i=String.fromCharCode(this.readU8());if("\n"===i)break;e+=i}return e},y(t,[{key:"remainingBytes",get:function(){return this.dataView.byteLength-this.offset}}]),t}(),ct=function(){function t(t){this.items=[],this.length=0,this.loopIndex=-1,this._sortBy=void 0,this._sortHandler=void 0,this._sortBy=t.sortBy,this._sortHandler=this._doSort.bind(this)}var e=t.prototype;return e._binarySearch=function(t){for(var e,i,n=0,s=this.items.length-1,r=t[this._sortBy];n<=s;)e=Math.floor((n+s)/2),(i=this.items[e][this._sortBy])<=r?n=e+1:i>r&&(s=e-1);return n},e._doSort=function(t,e){var i=this._sortBy;return t[i]-e[i]},e.insert=function(t){var e=this._binarySearch(t);this.items.splice(e,0,t),this.length++,this.loopIndex>=e&&this.loopIndex++},e.append=function(t){this.items.push(t),this.length++},e.remove=function(t){var e=this.items.indexOf(t);e<0||(this.items.splice(e,1),this.length--,this.loopIndex>=e&&this.loopIndex--)},e.sort=function(){var t=this.loopIndex>=0?this.items[this.loopIndex]:null;this.items.sort(this._sortHandler),null!==t&&(this.loopIndex=this.items.indexOf(t))},t}(),ut=function(t){function e(e){var i;return(i=t.call(this)||this)._index={},i._list=[],i._parent=e,i}S(e,t);var i=e.prototype;return i.add=function(){var t=!1,e=this._processArguments(arguments,!0);if(!e.length)return t;for(var i=0;i=i?i:t<=e?e:t},intToBytes24:function(t){return[t>>16&255,t>>8&255,255&t]},intToBytes32:function(t){return[t>>24&255,t>>16&255,t>>8&255,255&t]},bytesToInt24:function(t,e,i){return t.length&&(i=t[2],e=t[1],t=t[0]),t<<16|e<<8|i},bytesToInt32:function(t,e,i,n){return t.length&&(n=t[3],i=t[2],e=t[1],t=t[0]),(t<<24|e<<16|i<<8|n)>>>0},lerp:function(t,e,i){return t+(e-t)*_t.clamp(i,0,1)},lerpAngle:function(t,e,i){return e-t>180&&(e-=360),e-t<-180&&(e+=360),_t.lerp(t,e,_t.clamp(i,0,1))},powerOfTwo:function(t){return 0!==t&&!(t&t-1)},nextPowerOfTwo:function(t){return t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,++t},nearestPowerOfTwo:function(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))},random:function(t,e){var i=e-t;return Math.random()*i+t},smoothstep:function(t,e,i){return i<=t?0:i>=e?1:(i=(i-t)/(e-t))*i*(3-2*i)},smootherstep:function(t,e,i){return i<=t?0:i>=e?1:(i=(i-t)/(e-t))*i*i*(i*(6*i-15)+10)},roundUp:function(t,e){return 0===e?t:Math.ceil(t/e)*e},between:function(t,e,i,n){var s=Math.min(e,i),r=Math.max(e,i);return n?t>=s&&t<=r:t>s&&t7?e=_t.intToBytes32(i):(e=_t.intToBytes24(i))[3]=255,this.set(e[0]/255,e[1]/255,e[2]/255,e[3]/255),this},e.toString=function(t){var e="#"+((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===t){var i=Math.round(255*this.a).toString(16);this.a<16/255?e+="0"+i:e+=i}return e},t}();ft=vt,vt.BLACK=Object.freeze(new ft(0,0,0,1)),vt.BLUE=Object.freeze(new ft(0,0,1,1)),vt.CYAN=Object.freeze(new ft(0,1,1,1)),vt.GRAY=Object.freeze(new ft(.5,.5,.5,1)),vt.GREEN=Object.freeze(new ft(0,1,0,1)),vt.MAGENTA=Object.freeze(new ft(1,0,1,1)),vt.RED=Object.freeze(new ft(1,0,0,1)),vt.WHITE=Object.freeze(new ft(1,1,1,1)),vt.YELLOW=Object.freeze(new ft(1,1,0,1));var gt,yt,xt=function(){function t(t,e){void 0===e&&(e=0),this._curve=void 0,this._left=-1/0,this._right=1/0,this._recip=0,this._p0=0,this._p1=0,this._m0=0,this._m1=0,this._curve=t,this._reset(e)}var e=t.prototype;return e.evaluate=function(t,e){var i;void 0===e&&(e=!1),(e||t=this._right)&&this._reset(t);var n=this._curve.type;if(5===n)i=this._p0;else{var s=0===this._recip?0:(t-this._left)*this._recip;i=0===n?_t.lerp(this._p0,this._p1,s):1===n?_t.lerp(this._p0,this._p1,s*s*(3-2*s)):this._evaluateHermite(this._p0,this._p1,this._m0,this._m1,s)}return i},e._reset=function(t){var e=this._curve.keys,i=e.length;if(i)if(t=e[i-1][0])this._left=e[i-1][0],this._right=1/0,this._recip=0,this._p0=this._p1=e[i-1][1],this._m0=this._m1=0;else{for(var n=0;t>=e[n+1][0];)n++;this._left=e[n][0],this._right=e[n+1][0];var s=1/(this._right-this._left);this._recip=isFinite(s)?s:0,this._p0=e[n][1],this._p1=e[n+1][1],this._isHermite()&&this._calcTangents(e,n)}else this._left=-1/0,this._right=1/0,this._recip=0,this._p0=this._p1=this._m0=this._m1=0},e._isHermite=function(){return 2===this._curve.type||3===this._curve.type||4===this._curve.type},e._calcTangents=function(t,e){var i,n,s=t[e],r=t[e+1];if(i=0===e?[t[0][0]+(t[0][0]-t[1][0]),t[0][1]+(t[0][1]-t[1][1])]:t[e-1],n=e===t.length-2?[t[e+1][0]+(t[e+1][0]-t[e][0]),t[e+1][1]+(t[e+1][1]-t[e][1])]:t[e+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])}},e._evaluateHermite=function(t,e,i,n,s){var r=s*s,a=s+s,o=1-s,h=o*o;return t*((1+a)*h)+i*(s*h)+e*(r*(3-a))+n*(r*(s-1))},t}(),St=function(){function t(t){if(this.keys=[],this.type=1,this.tension=.5,this._eval=new xt(this),t)for(var e=0;et);s++);var r=[t,e];return this.keys.splice(s,0,r),r},e.get=function(t){return this.keys[t]},e.sort=function(){this.keys.sort((function(t,e){return t[0]-e[0]}))},e.value=function(t){return this._eval.evaluate(t,!0)},e.closest=function(t){for(var e=this.keys,i=e.length,n=2,s=null,r=0;r=a))break;n=a,s=e[r]}return s},e.clone=function(){var t=new this.constructor;return t.keys=p(t.keys,this.keys),t.type=this.type,t.tension=this.tension,t},e.quantize=function(t){t=Math.max(t,2);var e=new Float32Array(t),i=1/(t-1);e[0]=this._eval.evaluate(0,!0);for(var n=1;n1)for(var t=0;t0){var i=1/Math.sqrt(e);this.x=t.x*i,this.y=t.y*i,this.z=t.z*i}return this},e.floor=function(t){return void 0===t&&(t=this),this.x=Math.floor(t.x),this.y=Math.floor(t.y),this.z=Math.floor(t.z),this},e.ceil=function(t){return void 0===t&&(t=this),this.x=Math.ceil(t.x),this.y=Math.ceil(t.y),this.z=Math.ceil(t.z),this},e.round=function(t){return void 0===t&&(t=this),this.x=Math.round(t.x),this.y=Math.round(t.y),this.z=Math.round(t.z),this},e.min=function(t){return t.xthis.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},e.project=function(t){var e=(this.x*t.x+this.y*t.y+this.z*t.z)/(t.x*t.x+t.y*t.y+t.z*t.z);return this.x=t.x*e,this.y=t.y*e,this.z=t.z*e,this},e.set=function(t,e,i){return this.x=t,this.y=e,this.z=i,this},e.sub=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},e.sub2=function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this},e.subScalar=function(t){return this.x-=t,this.y-=t,this.z-=t,this},e.toString=function(){return"["+this.x+", "+this.y+", "+this.z+"]"},t}();gt=wt,wt.ZERO=Object.freeze(new gt(0,0,0)),wt.ONE=Object.freeze(new gt(1,1,1)),wt.UP=Object.freeze(new gt(0,1,0)),wt.DOWN=Object.freeze(new gt(0,-1,0)),wt.RIGHT=Object.freeze(new gt(1,0,0)),wt.LEFT=Object.freeze(new gt(-1,0,0)),wt.FORWARD=Object.freeze(new gt(0,0,-1)),wt.BACK=Object.freeze(new gt(0,0,1));var Tt,At=function(){function t(){this.data=new Float32Array(9),this.data[0]=this.data[4]=this.data[8]=1}var e=t.prototype;return e.clone=function(){return(new(0,this.constructor)).copy(this)},e.copy=function(t){var e=t.data,i=this.data;return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],this},e.set=function(t){var e=this.data;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],this},e.equals=function(t){var e=this.data,i=t.data;return e[0]===i[0]&&e[1]===i[1]&&e[2]===i[2]&&e[3]===i[3]&&e[4]===i[4]&&e[5]===i[5]&&e[6]===i[6]&&e[7]===i[7]&&e[8]===i[8]},e.isIdentity=function(){var t=this.data;return 1===t[0]&&0===t[1]&&0===t[2]&&0===t[3]&&1===t[4]&&0===t[5]&&0===t[6]&&0===t[7]&&1===t[8]},e.setIdentity=function(){var t=this.data;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,this},e.toString=function(){return"["+this.data.join(", ")+"]"},e.transpose=function(t){void 0===t&&(t=this);var e,i=t.data,n=this.data;i===n?(e=i[1],n[1]=i[3],n[3]=e,e=i[2],n[2]=i[6],n[6]=e,e=i[5],n[5]=i[7],n[7]=e):(n[0]=i[0],n[1]=i[3],n[2]=i[6],n[3]=i[1],n[4]=i[4],n[5]=i[7],n[6]=i[2],n[7]=i[5],n[8]=i[8]);return this},e.setFromMat4=function(t){var e=t.data,i=this.data;return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[4],i[4]=e[5],i[5]=e[6],i[6]=e[8],i[7]=e[9],i[8]=e[10],this},e.invertMat4=function(t){var e=t.data,i=e[0],n=e[1],s=e[2],r=e[4],a=e[5],o=e[6],h=e[8],l=e[9],c=e[10],u=c*a-o*l,d=-c*n+s*l,f=o*n-s*a,p=-c*r+o*h,m=c*i-s*h,_=-o*i+s*r,v=l*r-a*h,g=-l*i+n*h,y=a*i-n*r,x=i*u+n*p+s*v;if(0===x)this.setIdentity();else{var S=1/x,b=this.data;b[0]=u*S,b[1]=d*S,b[2]=f*S,b[3]=p*S,b[4]=m*S,b[5]=_*S,b[6]=v*S,b[7]=g*S,b[8]=y*S}return this},e.transformVector=function(t,e){void 0===e&&(e=new wt);var i=this.data,n=t.x,s=t.y,r=t.z;return e.x=n*i[0]+s*i[3]+r*i[6],e.y=n*i[1]+s*i[4]+r*i[7],e.z=n*i[2]+s*i[5]+r*i[8],e},t}();yt=At,At.IDENTITY=Object.freeze(new yt),At.ZERO=Object.freeze((new yt).set([0,0,0,0,0,0,0,0,0]));var Ct,Et=function(){function t(t,e){void 0===t&&(t=0),void 0===e&&(e=0),this.x=void 0,this.y=void 0,2===t.length?(this.x=t[0],this.y=t[1]):(this.x=t,this.y=e)}var e=t.prototype;return e.add=function(t){return this.x+=t.x,this.y+=t.y,this},e.add2=function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this},e.addScalar=function(t){return this.x+=t,this.y+=t,this},e.addScaled=function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this},e.clone=function(){return new(0,this.constructor)(this.x,this.y)},e.copy=function(t){return this.x=t.x,this.y=t.y,this},e.cross=function(t){return this.x*t.y-this.y*t.x},e.distance=function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},e.div=function(t){return this.x/=t.x,this.y/=t.y,this},e.div2=function(t,e){return this.x=t.x/e.x,this.y=t.y/e.y,this},e.divScalar=function(t){return this.x/=t,this.y/=t,this},e.dot=function(t){return this.x*t.x+this.y*t.y},e.equals=function(t){return this.x===t.x&&this.y===t.y},e.equalsApprox=function(t,e){return void 0===e&&(e=1e-6),Math.abs(this.x-t.x)0){var i=1/Math.sqrt(e);this.x=t.x*i,this.y=t.y*i}return this},e.rotate=function(t){var e=Math.atan2(this.x,this.y)+t*_t.DEG_TO_RAD,i=Math.sqrt(this.x*this.x+this.y*this.y);return this.x=Math.sin(e)*i,this.y=Math.cos(e)*i,this},e.angle=function(){return Math.atan2(this.x,this.y)*_t.RAD_TO_DEG},e.angleTo=function(t){return Math.atan2(this.x*t.y+this.y*t.x,this.x*t.x+this.y*t.y)*_t.RAD_TO_DEG},e.floor=function(t){return void 0===t&&(t=this),this.x=Math.floor(t.x),this.y=Math.floor(t.y),this},e.ceil=function(t){return void 0===t&&(t=this),this.x=Math.ceil(t.x),this.y=Math.ceil(t.y),this},e.round=function(t){return void 0===t&&(t=this),this.x=Math.round(t.x),this.y=Math.round(t.y),this},e.min=function(t){return t.xthis.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),this},e.set=function(t,e){return this.x=t,this.y=e,this},e.sub=function(t){return this.x-=t.x,this.y-=t.y,this},e.sub2=function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this},e.subScalar=function(t){return this.x-=t,this.y-=t,this},e.toString=function(){return"["+this.x+", "+this.y+"]"},t.angleRad=function(t,e){return Math.atan2(t.x*e.y-t.y*e.x,t.x*e.x+t.y*e.y)},t}();Tt=Et,Et.ZERO=Object.freeze(new Tt(0,0)),Et.ONE=Object.freeze(new Tt(1,1)),Et.UP=Object.freeze(new Tt(0,1)),Et.DOWN=Object.freeze(new Tt(0,-1)),Et.RIGHT=Object.freeze(new Tt(1,0)),Et.LEFT=Object.freeze(new Tt(-1,0));var Mt,Pt=function(){function t(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=0),this.x=void 0,this.y=void 0,this.z=void 0,this.w=void 0,4===t.length?(this.x=t[0],this.y=t[1],this.z=t[2],this.w=t[3]):(this.x=t,this.y=e,this.z=i,this.w=n)}var e=t.prototype;return e.add=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},e.add2=function(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this},e.addScalar=function(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this},e.addScaled=function(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this},e.clone=function(){return new(0,this.constructor)(this.x,this.y,this.z,this.w)},e.copy=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},e.div=function(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this},e.div2=function(t,e){return this.x=t.x/e.x,this.y=t.y/e.y,this.z=t.z/e.z,this.w=t.w/e.w,this},e.divScalar=function(t){return this.x/=t,this.y/=t,this.z/=t,this.w/=t,this},e.dot=function(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w},e.equals=function(t){return this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},e.equalsApprox=function(t,e){return void 0===e&&(e=1e-6),Math.abs(this.x-t.x)0){var i=1/Math.sqrt(e);this.x=t.x*i,this.y=t.y*i,this.z=t.z*i,this.w=t.w*i}return this},e.floor=function(t){return void 0===t&&(t=this),this.x=Math.floor(t.x),this.y=Math.floor(t.y),this.z=Math.floor(t.z),this.w=Math.floor(t.w),this},e.ceil=function(t){return void 0===t&&(t=this),this.x=Math.ceil(t.x),this.y=Math.ceil(t.y),this.z=Math.ceil(t.z),this.w=Math.ceil(t.w),this},e.round=function(t){return void 0===t&&(t=this),this.x=Math.round(t.x),this.y=Math.round(t.y),this.z=Math.round(t.z),this.w=Math.round(t.w),this},e.min=function(t){return t.xthis.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},e.set=function(t,e,i,n){return this.x=t,this.y=e,this.z=i,this.w=n,this},e.sub=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},e.sub2=function(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this},e.subScalar=function(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this},e.toString=function(){return"["+this.x+", "+this.y+", "+this.z+", "+this.w+"]"},t}();Ct=Pt,Pt.ZERO=Object.freeze(new Ct(0,0,0,0)),Pt.ONE=Object.freeze(new Ct(1,1,1,1));var Rt,It=new Et,Lt=new wt,Dt=new wt,Ot=new wt,kt=new wt,Ft=function(){function t(){this.data=new Float32Array(16),this.data[0]=this.data[5]=this.data[10]=this.data[15]=1}t._getPerspectiveHalfSize=function(t,e,i,n,s){s?(t.x=n*Math.tan(e*Math.PI/360),t.y=t.x/i):(t.y=n*Math.tan(e*Math.PI/360),t.x=t.y*i)};var e=t.prototype;return e.add2=function(t,e){var i=t.data,n=e.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},e.add=function(t){return this.add2(this,t)},e.clone=function(){return(new(0,this.constructor)).copy(this)},e.copy=function(t){var e=t.data,i=this.data;return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15],this},e.equals=function(t){var e=this.data,i=t.data;return e[0]===i[0]&&e[1]===i[1]&&e[2]===i[2]&&e[3]===i[3]&&e[4]===i[4]&&e[5]===i[5]&&e[6]===i[6]&&e[7]===i[7]&&e[8]===i[8]&&e[9]===i[9]&&e[10]===i[10]&&e[11]===i[11]&&e[12]===i[12]&&e[13]===i[13]&&e[14]===i[14]&&e[15]===i[15]},e.isIdentity=function(){var t=this.data;return 1===t[0]&&0===t[1]&&0===t[2]&&0===t[3]&&0===t[4]&&1===t[5]&&0===t[6]&&0===t[7]&&0===t[8]&&0===t[9]&&1===t[10]&&0===t[11]&&0===t[12]&&0===t[13]&&0===t[14]&&1===t[15]},e.mul2=function(t,e){var i,n,s,r,a=t.data,o=e.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],v=a[8],g=a[9],y=a[10],x=a[11],S=a[12],b=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+v*s+S*r,h[1]=c*i+p*n+g*s+b*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+v*s+S*r,h[5]=c*i+p*n+g*s+b*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+v*s+S*r,h[9]=c*i+p*n+g*s+b*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+v*s+S*r,h[13]=c*i+p*n+g*s+b*r,h[14]=u*i+m*n+y*s+w*r,h[15]=d*i+_*n+x*s+T*r,this},e.mulAffine2=function(t,e){var i,n,s,r=t.data,a=e.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],v=r[12],g=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+v,o[13]=l*i+d*n+m*s+g,o[14]=c*i+f*n+_*s+y,o[15]=1,this},e.mul=function(t){return this.mul2(this,t)},e.transformPoint=function(t,e){void 0===e&&(e=new wt);var i=this.data,n=t.x,s=t.y,r=t.z;return e.x=n*i[0]+s*i[4]+r*i[8]+i[12],e.y=n*i[1]+s*i[5]+r*i[9]+i[13],e.z=n*i[2]+s*i[6]+r*i[10]+i[14],e},e.transformVector=function(t,e){void 0===e&&(e=new wt);var i=this.data,n=t.x,s=t.y,r=t.z;return e.x=n*i[0]+s*i[4]+r*i[8],e.y=n*i[1]+s*i[5]+r*i[9],e.z=n*i[2]+s*i[6]+r*i[10],e},e.transformVec4=function(t,e){void 0===e&&(e=new Pt);var i=this.data,n=t.x,s=t.y,r=t.z,a=t.w;return e.x=n*i[0]+s*i[4]+r*i[8]+a*i[12],e.y=n*i[1]+s*i[5]+r*i[9]+a*i[13],e.z=n*i[2]+s*i[6]+r*i[10]+a*i[14],e.w=n*i[3]+s*i[7]+r*i[11]+a*i[15],e},e.setLookAt=function(t,e,i){Ot.sub2(t,e).normalize(),Dt.copy(i).normalize(),Lt.cross(Dt,Ot).normalize(),Dt.cross(Ot,Lt);var n=this.data;return n[0]=Lt.x,n[1]=Lt.y,n[2]=Lt.z,n[3]=0,n[4]=Dt.x,n[5]=Dt.y,n[6]=Dt.z,n[7]=0,n[8]=Ot.x,n[9]=Ot.y,n[10]=Ot.z,n[11]=0,n[12]=t.x,n[13]=t.y,n[14]=t.z,n[15]=1,this},e.setFrustum=function(t,e,i,n,s,r){var a=2*s,o=e-t,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]=(e+t)/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},e.setPerspective=function(e,i,n,s,r){return t._getPerspectiveHalfSize(It,e,i,n,r),this.setFrustum(-It.x,It.x,-It.y,It.y,n,s)},e.setOrtho=function(t,e,i,n,s,r){var a=this.data;return a[0]=2/(e-t),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]=-(e+t)/(e-t),a[13]=-(n+i)/(n-i),a[14]=-(r+s)/(r-s),a[15]=1,this},e.setFromAxisAngle=function(t,e){e*=_t.DEG_TO_RAD;var i=t.x,n=t.y,s=t.z,r=Math.cos(e),a=Math.sin(e),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},e.setTranslate=function(t,e,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]=t,n[13]=e,n[14]=i,n[15]=1,this},e.setScale=function(t,e,i){var n=this.data;return n[0]=t,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=e,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},e.setViewport=function(t,e,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]=t+.5*i,s[13]=e+.5*n,s[14]=.5,s[15]=1,this},e.setReflection=function(t,e){var i=t.x,n=t.y,s=t.z,r=this.data;return r[0]=1-2*i*i,r[1]=-2*i*n,r[2]=-2*i*s,r[3]=0,r[4]=-2*i*n,r[5]=1-2*n*n,r[6]=-2*n*s,r[7]=0,r[8]=-2*i*s,r[9]=-2*n*s,r[10]=1-2*s*s,r[11]=0,r[12]=-2*i*e,r[13]=-2*n*e,r[14]=-2*s*e,r[15]=1,this},e.invert=function(t){void 0===t&&(t=this);var e=t.data,i=e[0],n=e[1],s=e[2],r=e[3],a=e[4],o=e[5],h=e[6],l=e[7],c=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],_=e[14],v=e[15],g=i*o-n*a,y=i*h-s*a,x=i*l-r*a,S=n*h-s*o,b=n*l-r*o,w=s*l-r*h,T=c*m-u*p,A=c*_-d*p,C=c*v-f*p,E=u*_-d*m,M=u*v-f*m,P=d*v-f*_,R=g*P-y*M+x*E+S*C-b*A+w*T;if(0===R)this.setIdentity();else{var I=1/R,L=this.data;L[0]=(o*P-h*M+l*E)*I,L[1]=(-n*P+s*M-r*E)*I,L[2]=(m*w-_*b+v*S)*I,L[3]=(-u*w+d*b-f*S)*I,L[4]=(-a*P+h*C-l*A)*I,L[5]=(i*P-s*C+r*A)*I,L[6]=(-p*w+_*x-v*y)*I,L[7]=(c*w-d*x+f*y)*I,L[8]=(a*M-o*C+l*T)*I,L[9]=(-i*M+n*C-r*T)*I,L[10]=(p*b-m*x+v*g)*I,L[11]=(-c*b+u*x-f*g)*I,L[12]=(-a*E+o*A-h*T)*I,L[13]=(i*E-n*A+s*T)*I,L[14]=(-p*S+m*y-_*g)*I,L[15]=(c*S-u*y+d*g)*I}return this},e.set=function(t){var e=this.data;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],this},e.setIdentity=function(){var t=this.data;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this},e.setTRS=function(t,e,i){var n=e.x,s=e.y,r=e.z,a=e.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,v=s*d,g=r*d,y=a*c,x=a*u,S=a*d,b=this.data;return b[0]=(1-(_+g))*o,b[1]=(p+S)*o,b[2]=(m-x)*o,b[3]=0,b[4]=(p-S)*h,b[5]=(1-(f+g))*h,b[6]=(v+y)*h,b[7]=0,b[8]=(m+x)*l,b[9]=(v-y)*l,b[10]=(1-(f+_))*l,b[11]=0,b[12]=t.x,b[13]=t.y,b[14]=t.z,b[15]=1,this},e.transpose=function(t){void 0===t&&(t=this);var e,i=t.data,n=this.data;i===n?(e=i[1],n[1]=i[4],n[4]=e,e=i[2],n[2]=i[8],n[8]=e,e=i[3],n[3]=i[12],n[12]=e,e=i[6],n[6]=i[9],n[9]=e,e=i[7],n[7]=i[13],n[13]=e,e=i[11],n[11]=i[14],n[14]=e):(n[0]=i[0],n[1]=i[4],n[2]=i[8],n[3]=i[12],n[4]=i[1],n[5]=i[5],n[6]=i[9],n[7]=i[13],n[8]=i[2],n[9]=i[6],n[10]=i[10],n[11]=i[14],n[12]=i[3],n[13]=i[7],n[14]=i[11],n[15]=i[15]);return this},e.getTranslation=function(t){return void 0===t&&(t=new wt),t.set(this.data[12],this.data[13],this.data[14])},e.getX=function(t){return void 0===t&&(t=new wt),t.set(this.data[0],this.data[1],this.data[2])},e.getY=function(t){return void 0===t&&(t=new wt),t.set(this.data[4],this.data[5],this.data[6])},e.getZ=function(t){return void 0===t&&(t=new wt),t.set(this.data[8],this.data[9],this.data[10])},e.getScale=function(t){return void 0===t&&(t=new wt),this.getX(Lt),this.getY(Dt),this.getZ(Ot),t.set(Lt.length(),Dt.length(),Ot.length()),t},e.setFromEulerAngles=function(t,e,i){t*=_t.DEG_TO_RAD,e*=_t.DEG_TO_RAD,i*=_t.DEG_TO_RAD;var n=Math.sin(-t),s=Math.cos(-t),r=Math.sin(-e),a=Math.cos(-e),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},e.getEulerAngles=function(t){void 0===t&&(t=new wt),this.getScale(kt);var e=kt.x,i=kt.y,n=kt.z;if(0===e||0===i||0===n)return t.set(0,0,0);var s,r,a=this.data,o=Math.asin(-a[2]/e),h=.5*Math.PI;return o-h?(s=Math.atan2(a[6]/i,a[10]/n),r=Math.atan2(a[1]/e,a[0]/e)):(r=0,s=-Math.atan2(a[4]/i,a[5]/i)):(r=0,s=Math.atan2(a[4]/i,a[5]/i)),t.set(s,o,r).mulScalar(_t.RAD_TO_DEG)},e.toString=function(){return"["+this.data.join(", ")+"]"},y(t,[{key:"scaleSign",get:function(){return this.getX(Lt),this.getY(Dt),this.getZ(Ot),Lt.cross(Lt,Dt),Lt.dot(Ot)<0?-1:1}}]),t}();Mt=Ft,Ft.IDENTITY=Object.freeze(new Mt),Ft.ZERO=Object.freeze((new Mt).set([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]));var Bt=function(){function t(t,e,i,n){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===n&&(n=1),this.x=void 0,this.y=void 0,this.z=void 0,this.w=void 0,4===t.length?(this.x=t[0],this.y=t[1],this.z=t[2],this.w=t[3]):(this.x=t,this.y=e,this.z=i,this.w=n)}var e=t.prototype;return e.clone=function(){return new(0,this.constructor)(this.x,this.y,this.z,this.w)},e.conjugate=function(t){return void 0===t&&(t=this),this.x=-1*t.x,this.y=-1*t.y,this.z=-1*t.z,this.w=t.w,this},e.copy=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},e.equals=function(t){return this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},e.equalsApprox=function(t,e){return void 0===e&&(e=1e-6),Math.abs(this.x-t.x)=.99999?(e=2*Math.atan2(s,o),i=Math.PI/2,n=0):(e=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))),t.set(e,i,n).mulScalar(_t.RAD_TO_DEG)},e.invert=function(t){return void 0===t&&(t=this),this.conjugate(t).normalize()},e.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},e.lengthSq=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},e.mul=function(t){var e=this.x,i=this.y,n=this.z,s=this.w,r=t.x,a=t.y,o=t.z,h=t.w;return this.x=s*r+e*h+i*o-n*a,this.y=s*a+i*h+n*r-e*o,this.z=s*o+n*h+e*a-i*r,this.w=s*h-e*r-i*a-n*o,this},e.mul2=function(t,e){var i=t.x,n=t.y,s=t.z,r=t.w,a=e.x,o=e.y,h=e.z,l=e.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},e.normalize=function(t){void 0===t&&(t=this);var e=t.length();return 0===e?(this.x=this.y=this.z=0,this.w=1):(e=1/e,this.x=t.x*e,this.y=t.y*e,this.z=t.z*e,this.w=t.w*e),this},e.set=function(t,e,i,n){return this.x=t,this.y=e,this.z=i,this.w=n,this},e.setFromAxisAngle=function(t,e){e*=.5*_t.DEG_TO_RAD;var i=Math.sin(e),n=Math.cos(e);return this.x=i*t.x,this.y=i*t.y,this.z=i*t.z,this.w=n,this},e.setFromEulerAngles=function(t,e,i){if(t instanceof wt){var n=t;t=n.x,e=n.y,i=n.z}var s=.5*_t.DEG_TO_RAD;t*=s,e*=s,i*=s;var r=Math.sin(t),a=Math.cos(t),o=Math.sin(e),h=Math.cos(e),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},e.setFromMat4=function(t){var e,i,n,s,r,a,o,h,l,c,u,d,f,p;if(e=(t=t.data)[0],i=t[1],n=t[2],s=t[4],r=t[5],a=t[6],o=t[8],h=t[9],l=t[10],0===(d=e*e+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=(e*=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):e>r?e>l?(u=e-(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-(e+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+e)+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-(e+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},e.setFromDirections=function(t,e){var i=1+t.dot(e);return iMath.abs(t.y)?(this.x=-t.z,this.y=0,this.z=t.x,this.w=0):(this.x=0,this.y=-t.z,this.z=t.y,this.w=0):(this.x=t.y*e.z-t.z*e.y,this.y=t.z*e.x-t.x*e.z,this.z=t.x*e.y-t.y*e.x,this.w=i),this.normalize()},e.slerp=function(t,e,i){var n=t.x,s=t.y,r=t.z,a=t.w,o=e.x,h=e.y,l=e.z,c=e.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},e.transformVector=function(t,e){void 0===e&&(e=new wt);var i=t.x,n=t.y,s=t.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 e.x=l*h+d*-r+c*-o-u*-a,e.y=c*h+d*-a+u*-r-l*-o,e.z=u*h+d*-o+l*-a-c*-r,e},e.toString=function(){return"["+this.x+", "+this.y+", "+this.z+", "+this.w+"]"},t}();Rt=Bt,Bt.IDENTITY=Object.freeze(new Rt(0,0,0,1)),Bt.ZERO=Object.freeze(new Rt(0,0,0,0));var Ut=new wt,Nt=new wt,zt=new wt,Vt=new wt,Gt=new wt,Ht=function(){function t(t,e){void 0===t&&(t=new wt),void 0===e&&(e=new wt(.5,.5,.5)),this.center=void 0,this.halfExtents=void 0,this._min=new wt,this._max=new wt,this.center=t,this.halfExtents=e}var e=t.prototype;return e.add=function(t){var e=this.center,i=e.x,n=e.y,s=e.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=t.center,_=m.x,v=m.y,g=m.z,y=t.halfExtents,x=y.x,S=y.y,b=y.z,w=_-x,T=_+x,A=v-S,C=v+S,E=g-b,M=g+b;wc&&(c=T),Ad&&(d=C),Ep&&(p=M),e.x=.5*(l+c),e.y=.5*(u+d),e.z=.5*(f+p),r.x=.5*(c-l),r.y=.5*(d-u),r.z=.5*(p-f)},e.copy=function(t){this.center.copy(t.center),this.halfExtents.copy(t.halfExtents)},e.clone=function(){return new t(this.center.clone(),this.halfExtents.clone())},e.intersects=function(t){var e=this.getMax(),i=this.getMin(),n=t.getMax(),s=t.getMin();return i.x<=n.x&&e.x>=s.x&&i.y<=n.y&&e.y>=s.y&&i.z<=n.z&&e.z>=s.z},e._intersectsRay=function(t,e){var i=Ut.copy(this.getMin()).sub(t.origin),n=Nt.copy(this.getMax()).sub(t.origin),s=t.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=zt.set(Math.min(i.x,n.x),Math.min(i.y,n.y),Math.min(i.z,n.z)),a=Vt.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&&e.copy(t.direction).mulScalar(h).add(t.origin),l},e._fastIntersectsRay=function(t){var e=Ut,i=Nt,n=zt,s=Vt,r=Gt,a=t.direction;return e.sub2(t.origin,this.center),s.set(Math.abs(e.x),Math.abs(e.y),Math.abs(e.z)),n.mul2(e,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,e),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)))))},e.intersectsRay=function(t,e){return e?this._intersectsRay(t,e):this._fastIntersectsRay(t)},e.setMinMax=function(t,e){this.center.add2(e,t).mulScalar(.5),this.halfExtents.sub2(e,t).mulScalar(.5)},e.getMin=function(){return this._min.copy(this.center).sub(this.halfExtents)},e.getMax=function(){return this._max.copy(this.center).add(this.halfExtents)},e.containsPoint=function(t){var e=this.getMin(),i=this.getMax();return!(t.xi.x||t.yi.y||t.zi.z)},e.setFromTransformedAabb=function(t,e,i){void 0===i&&(i=!1);var n=t.center,s=t.halfExtents,r=e.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 v=1/Math.sqrt(m);l*=v,c*=v,u*=v}if((m=d*d+f*f+p*p)>0){var g=1/Math.sqrt(m);d*=g,f*=g,p*=g}}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)},t.computeMinMax=function(t,e,i,n){if(void 0===n&&(n=t.length/3),n>0){for(var s=t[0],r=t[1],a=t[2],o=s,h=r,l=a,c=3*n,u=3;uo&&(o=d),f>h&&(h=f),p>l&&(l=p)}e.set(s,r,a),i.set(o,h,l)}},e.compute=function(e,i){t.computeMinMax(e,Ut,Nt,i),this.setMinMax(Ut,Nt)},e.intersectsBoundingSphere=function(t){return this._distanceToBoundingSphereSq(t)<=t.radius*t.radius},e._distanceToBoundingSphereSq=function(t){for(var e=this.getMin(),i=this.getMax(),n=0,s=["x","y","z"],r=0;r<3;++r){var a=0,o=t.center[s[r]],h=e[s[r]],l=i[s[r]],c=0;ol&&(a+=(c=o-l)*c),n+=a}return n},e._expand=function(t,e){Ut.add2(this.getMin(),t),Nt.add2(this.getMax(),e),this.setMinMax(Ut,Nt)},t}(),Wt=new wt,Xt=new wt,jt=function(){function t(t,e){void 0===t&&(t=new wt),void 0===e&&(e=.5),this.center=void 0,this.radius=void 0,this.center=t,this.radius=e}var e=t.prototype;return e.containsPoint=function(t){var e=Wt.sub2(t,this.center).lengthSq(),i=this.radius;return e0&&n>0)return!1;var r=n*n-s;if(r<0)return!1;var a=Math.abs(-n-Math.sqrt(r));return e&&e.copy(t.direction).mulScalar(a).add(t.origin),!0},e.intersectsBoundingSphere=function(t){Wt.sub2(t.center,this.center);var e=t.radius+this.radius;return Wt.lengthSq()<=e*e},t}(),qt=function(){function t(){this.planes=[];for(var t=0;t<6;t++)this.planes[t]=[]}var e=t.prototype;return e.setFromMat4=function(t){var e,i=t.data,n=this.planes;(e=n[0])[0]=i[3]-i[0],e[1]=i[7]-i[4],e[2]=i[11]-i[8],e[3]=i[15]-i[12];var s=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=s,e[1]/=s,e[2]/=s,e[3]/=s,(e=n[1])[0]=i[3]+i[0],e[1]=i[7]+i[4],e[2]=i[11]+i[8],e[3]=i[15]+i[12],s=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]),e[0]/=s,e[1]/=s,e[2]/=s,e[3]/=s,(e=n[2])[0]=i[3]+i[1],e[1]=i[7]+i[5],e[2]=i[11]+i[9],e[3]=i[15]+i[13],s=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]),e[0]/=s,e[1]/=s,e[2]/=s,e[3]/=s,(e=n[3])[0]=i[3]-i[1],e[1]=i[7]-i[5],e[2]=i[11]-i[9],e[3]=i[15]-i[13],s=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]),e[0]/=s,e[1]/=s,e[2]/=s,e[3]/=s,(e=n[4])[0]=i[3]-i[2],e[1]=i[7]-i[6],e[2]=i[11]-i[10],e[3]=i[15]-i[14],s=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]),e[0]/=s,e[1]/=s,e[2]/=s,e[3]/=s,(e=n[5])[0]=i[3]+i[2],e[1]=i[7]+i[6],e[2]=i[11]+i[10],e[3]=i[15]+i[14],s=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]),e[0]/=s,e[1]/=s,e[2]/=s,e[3]/=s},e.containsPoint=function(t){var e,i;for(e=0;e<6;e++)if((i=this.planes[e])[0]*t.x+i[1]*t.y+i[2]*t.z+i[3]<=0)return!1;return!0},e.containsSphere=function(t){var e,i,n,s=0,r=t.radius,a=t.center,o=a.x,h=a.y,l=a.z,c=this.planes;for(i=0;i<6;i++){if((e=(n=c[i])[0]*o+n[1]*h+n[2]*l+n[3])<=-r)return 0;e>r&&s++}return 6===s?2:1},t}(),Yt=function(){function t(t,e){this.origin=new wt,this.direction=wt.FORWARD.clone(),t&&this.origin.copy(t),e&&this.direction.copy(e)}var e=t.prototype;return e.set=function(t,e){return this.origin.copy(t),this.direction.copy(e),this},e.copy=function(t){return this.set(t.origin,t.direction)},e.clone=function(){return new this.constructor(this.origin,this.direction)},t}(),Kt=new Yt,Zt=new wt,Qt=new jt,$t=new Ft,Jt=function(){function t(t,e){void 0===t&&(t=new Ft),void 0===e&&(e=new wt(.5,.5,.5)),this.halfExtents=void 0,this._modelTransform=void 0,this._worldTransform=void 0,this._aabb=void 0,this.halfExtents=e,this._modelTransform=t.clone().invert(),this._worldTransform=t.clone(),this._aabb=new Ht(new wt,this.halfExtents)}var e=t.prototype;return e.intersectsRay=function(t,e){if(this._modelTransform.transformPoint(t.origin,Kt.origin),this._modelTransform.transformVector(t.direction,Kt.direction),e){var i=this._aabb._intersectsRay(Kt,e);return $t.copy(this._modelTransform).invert().transformPoint(e,e),i}return this._aabb._fastIntersectsRay(Kt)},e.containsPoint=function(t){return this._modelTransform.transformPoint(t,Zt),this._aabb.containsPoint(Zt)},e.intersectsBoundingSphere=function(t){return this._modelTransform.transformPoint(t.center,Qt.center),Qt.radius=t.radius,!!this._aabb.intersectsBoundingSphere(Qt)},y(t,[{key:"worldTransform",get:function(){return this._worldTransform},set:function(t){this._worldTransform.copy(t),this._modelTransform.copy(t).invert()}}]),t}(),te=function(){function t(t,e){void 0===t&&(t=wt.UP),void 0===e&&(e=0),this.normal=new wt,this.distance=void 0,this.normal.copy(t),this.distance=e}var e=t.prototype;return e.setFromPointNormal=function(t,e){return this.normal.copy(e),this.distance=-this.normal.dot(t),this},e.intersectsLine=function(t,e,i){var n=this.distance,s=this.normal.dot(t)+n,r=s/(s-(this.normal.dot(e)+n)),a=r>=0&&r<=1;return a&&i&&i.lerp(t,e,r),a},e.intersectsRay=function(t,e){var i=this.normal.dot(t.direction);if(0===i)return!1;var n=-(this.normal.dot(t.origin)+this.distance)/i;return n>=0&&e&&e.copy(t.direction).mulScalar(n).add(t.origin),n>=0},e.copy=function(t){return this.normal.copy(t.normal),this.distance=t.distance,this},e.clone=function(){return(new(0,this.constructor)).copy(this)},t}(),ee="linear",ie="inverse",ne="exponential",se=0,re=10,ae=11,oe=12,he=13,le=14,ce=15,ue=16,de=17,fe=18,pe=21,me=24,_e=25,ve=26,ge=27,ye=new Map([[0,{name:"A8",size:1}],[1,{name:"L8",size:1}],[2,{name:"LA8",size:2}],[3,{name:"RGB565",size:2}],[4,{name:"RGBA5551",size:2}],[5,{name:"RGBA4",size:2}],[6,{name:"RGB8",size:4}],[7,{name:"RGBA8",size:4}],[ae,{name:"RGB16F",size:8}],[oe,{name:"RGBA16F",size:8}],[he,{name:"RGB32F",size:16}],[le,{name:"RGBA32F",size:16}],[ce,{name:"R32F",size:4}],[ue,{name:"DEPTH",size:4}],[de,{name:"DEPTHSTENCIL",size:4}],[fe,{name:"111110F",size:4}],[19,{name:"SRGB",size:4}],[20,{name:"SRGBA",size:4}],[31,{name:"BGRA8",size:4}],[8,{name:"DXT1",blockSize:8}],[9,{name:"DXT3",blockSize:16}],[re,{name:"DXT5",blockSize:16}],[pe,{name:"ETC1",blockSize:8}],[22,{name:"ETC2_RGB",blockSize:8}],[23,{name:"ETC2_RGBA",blockSize:16}],[me,{name:"PVRTC_2BPP_RGB_1",blockSize:8}],[_e,{name:"PVRTC_2BPP_RGBA_1",blockSize:8}],[ve,{name:"PVRTC_4BPP_RGB_1",blockSize:8}],[ge,{name:"PVRTC_4BPP_RGBA_1",blockSize:8}],[28,{name:"ASTC_4x4",blockSize:16}],[29,{name:"ATC_RGB",blockSize:8}],[30,{name:"ATC_RGBA",blockSize:16}]]),xe=function(t){return void 0!==ye.get(t).blockSize},Se=function(t){switch(t){case he:case le:return Float32Array;case 3:case 4:case 5:case ae:case oe:return Uint16Array;default:return Uint8Array}},be=5,we="POSITION",Te="NORMAL",Ae="TANGENT",Ce="BLENDWEIGHT",Ee="BLENDINDICES",Me="COLOR",Pe="TEXCOORD",Re="TEXCOORD0",Ie="TEXCOORD1",Le="TEXCOORD2",De="TEXCOORD3",Oe="TEXCOORD4",ke="TEXCOORD5",Fe="TEXCOORD6",Be="TEXCOORD7",Ue="ATTR",Ne="ATTR0",ze="ATTR1",Ve="ATTR2",Ge="ATTR3",He="ATTR4",We="ATTR5",Xe="ATTR6",je="ATTR7",qe="ATTR8",Ye="ATTR9",Ke="ATTR10",Ze="ATTR11",Qe="ATTR12",$e="ATTR13",Je="ATTR14",ti="ATTR15",ei="default",ii="rgbm",ni="rgbe",si="rgbp",ri="swizzleGGGR",ai="2d",oi="2d-array",hi="cube",li="3d",ci="none",ui="cube",di="equirect",fi="octahedral",pi="wgsl",mi=1,_i=13,vi=14,gi=["bool","int","float","vec2","vec3","vec4","ivec2","ivec3","ivec4","bec2","bec3","bec4","mat2","mat3","mat4","sampler2D","samplerCube","","sampler2DShadow","samplerCubeShadow","sampler3D","","",""],yi="webgl1",xi="webgl2",Si="webgpu",bi="null",wi=["mesh","view"],Ti="default",Ai=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array],Ci=[1,1,2,2,4,4,4],Ei={Int8Array:0,Uint8Array:mi,Int16Array:2,Uint16Array:3,Int32Array:4,Uint32Array:5,Float32Array:6},Mi=[Uint8Array,Uint16Array,Uint32Array],Pi=[1,2,4],Ri={};Ri[we]=0,Ri[Te]=1,Ri[Ce]=2,Ri[Ee]=3,Ri[Me]=4,Ri[Re]=5,Ri[Ie]=6,Ri[Le]=7,Ri[De]=8,Ri[Oe]=9,Ri[ke]=10,Ri[Fe]=11,Ri[Be]=12,Ri[Ae]=13,Ri[Ne]=0,Ri[ze]=1,Ri[Ve]=2,Ri[Ge]=3,Ri[He]=4,Ri[We]=5,Ri[Xe]=6,Ri[je]=7,Ri[qe]=8,Ri[Ye]=9,Ri[Ke]=10,Ri[Ze]=11,Ri[Qe]=12,Ri[$e]=13,Ri[Je]=14,Ri[ti]=15;var Ii,Li,Di="1.65",Oi=function(t,e,i,n){return void 0===n&&(n=1),t&~(n<>e&i},Fi=function(t,e,i){void 0===i&&(i=1);var n=i<>>0}var Ki,Zi=function(){function t(){this.map=new Map,this.id=0}return t.prototype.get=function(t){var e=this.map.get(t);return void 0===e&&(e=this.id++,this.map.set(t,e)),e},t}(),Qi=new Zi,$i=[2,4,8,12,16],Ji=function(){function t(t,e,i){this.device=t,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.instancing=!1,this.size=e.reduce((function(t,e){return t+4*Math.ceil(e.components*Ci[e.type]/4)}),0);for(var n,s=0,r=0,a=e.length;r1?_:1),this.autoResolve=null==(a=t.autoResolve)||a,this.name=t.name,this.name)||(this.name=null==(p=this._colorBuffer)?void 0:p.name);this.name||(this.name=null==(m=this._depthBuffer)?void 0:m.name);this.name||(this.name="Untitled"),this.flipY=null!=(o=t.flipY)&&o,this.validateMrt(),this.impl=f.createRenderTargetImpl(this)}var e=t.prototype;return e.destroy=function(){var t=this._device;t&&(t.targets.delete(this),t.renderTarget===this&&t.setRenderTarget(null),this.destroyFrameBuffers())},e.destroyFrameBuffers=function(){var t=this._device;t&&this.impl.destroy(t)},e.destroyTextureBuffers=function(){var t,e;null==(t=this._depthBuffer)||t.destroy(),this._depthBuffer=null,null==(e=this._colorBuffers)||e.forEach((function(t){t.destroy()})),this._colorBuffers=null,this._colorBuffer=null},e.resize=function(t,e){var i,n,s=this._device;this.destroyFrameBuffers(),s.renderTarget===this&&s.setRenderTarget(null),null==(i=this._depthBuffer)||i.resize(t,e),null==(n=this._colorBuffers)||n.forEach((function(i){i.resize(t,e)})),this.validateMrt(),this.impl=s.createRenderTargetImpl(this)},e.validateMrt=function(){},e.init=function(){this.impl.init(this._device,this)},e.loseContext=function(){this.impl.loseContext()},e.resolve=function(t,e){void 0===t&&(t=!0),void 0===e&&(e=!!this._depthBuffer),this._device&&this._samples>1&&this.impl.resolve(this._device,this,t,e)},e.copy=function(t,e,i){if(!this._device){if(!t._device)return!1;this._device=t._device}return this._device.copyRenderTarget(t,this,e,i)},e.getColorBuffer=function(t){var e;return null==(e=this._colorBuffers)?void 0:e[t]},y(t,[{key:"initialized",get:function(){return this.impl.initialized}},{key:"device",get:function(){return this._device}},{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 t,e;return(null==(t=this._colorBuffer)?void 0:t.width)||(null==(e=this._depthBuffer)?void 0:e.width)||this._device.width}},{key:"height",get:function(){var t,e;return(null==(t=this._colorBuffer)?void 0:t.height)||(null==(e=this._depthBuffer)?void 0:e.height)||this._device.height}}]),t}(),an=function(){function t(){this.bindGroup=void 0}var e=t.prototype;return e.update=function(t){this.destroy();var e=t.device,i=this.createDescriptor(e,t);this.bindGroup=e.wgpu.createBindGroup(i)},e.destroy=function(){this.bindGroup=null},e.createDescriptor=function(t,e){var i=[],n=e.format,s=0;return e.uniformBuffers.forEach((function(t){var e=t.persistent?t.impl.buffer:t.allocation.gpuBuffer.buffer;i.push({binding:s++,resource:{buffer:e,offset:0,size:t.format.byteSize}})})),e.textures.forEach((function(e,r){var a=e.impl,o=n.textureFormats[r],h=a.getView(t);i.push({binding:s++,resource:h});var l=a.getSampler(t,o.sampleType);i.push({binding:s++,resource:l})})),{layout:e.format.impl.bindGroupLayout,entries:i}},t}(),on=function(){function t(){}return t.shaderStage=function(t){var e=0;return 1&t&&(e|=GPUShaderStage.VERTEX),2&t&&(e|=GPUShaderStage.FRAGMENT),4&t&&(e|=GPUShaderStage.COMPUTE),e},t}(),hn=[];hn[0]="filtering",hn[1]="non-filtering",hn[2]="comparison";var ln=[];ln[0]="float",ln[1]="unfilterable-float",ln[2]="depth";var cn=new Zi,un=function(){function t(t){var e=t.device,i=this.createDescriptor(t),n=i.key,s=i.descr;this.key=cn.get(n),this.bindGroupLayout=e.wgpu.createBindGroupLayout(s)}var e=t.prototype;return e.destroy=function(){this.bindGroupLayout=null},e.loseContext=function(){},e.getTextureSlot=function(t,e){return t.bufferFormats.length+2*e},e.createDescriptor=function(t){var e=[],i="",n=0;return t.bufferFormats.forEach((function(t){var s=on.shaderStage(t.visibility);i+="#"+n+"U:"+s,e.push({binding:n++,visibility:s,buffer:{type:"uniform",hasDynamicOffset:!0}})})),t.textureFormats.forEach((function(t){var s=on.shaderStage(t.visibility),r=t.sampleType,a=t.textureDimension,o=ln[r];i+="#"+n+"T:"+s+"-"+o+"-"+a+"-false",e.push({binding:n++,visibility:s,texture:{sampleType:o,viewDimension:a,multisampled:false}});var h=hn[r];i+="#"+n+"S:"+s+"-"+h,e.push({binding:n++,visibility:s,sampler:{type:h}})})),{key:i,descr:{entries:e}}},t}(),dn=function(){function t(){this.buffer=null}var e=t.prototype;return e.destroy=function(t){this.buffer&&(this.buffer.destroy(),this.buffer=null)},e.loseContext=function(){},e.unlock=function(t,e,i,n){var s,r,a=t.wgpu;if(!this.buffer){var o=n.byteLength+3&-4;this.buffer=t.wgpu.createBuffer({size:o,usage:i|GPUBufferUsage.COPY_DST})}var h=null!=(s=n.byteOffset)?s:0,l=new Uint8Array(null!=(r=n.buffer)?r:n,h,n.byteLength),c=new Uint8Array(this.buffer.size);c.set(l),a.queue.writeBuffer(this.buffer,0,c,0,c.length)},y(t,[{key:"initialized",get:function(){return!!this.buffer}}]),t}(),fn=function(t){function e(e){var i;return(i=t.call(this)||this).format=null,i.format=1===e.format?"uint16":"uint32",i}return S(e,t),e.prototype.unlock=function(e){var i=e.device;t.prototype.unlock.call(this,i,e.usage,GPUBufferUsage.INDEX,e.storage)},e}(dn),pn=function(t,e){if(t.size!==e.size)return!1;for(var i=0;i1?"x"+o.numComponents:"")}),e&&a!==r-1||(i.push({attributes:s,arrayStride:o.stride,stepMode:n}),s=[])}};return t&&n(t),e&&n(e),i},t}(),gn=["point-list","line-list",void 0,"line-strip","triangle-list","triangle-strip",void 0],yn=["add","subtract","reverse-subtract","min","max"],xn=["zero","one","src","one-minus-src","dst","one-minus-dst","src-alpha","src-alpha-saturated","one-minus-src-alpha","dst-alpha","one-minus-dst-alpha","constant","one-minus-constant"],Sn=["never","less","equal","less-equal","greater","not-equal","greater-equal","always"],bn=["none","back","front"],wn=["keep","zero","replace","increment-clamp","increment-wrap","decrement-clamp","decrement-wrap","invert"],Tn=[],An=function(){this.pipeline=void 0,this.hashes=void 0},Cn=function(){function t(t){this.lookupHashes=new Uint32Array(13),this.device=t,this.vertexBufferLayout=new vn,this.cache=new Map}var e=t.prototype;return e.get=function(t,e,i,n,s,r,a,o,h,l,c,u){var d,f,p,m,_,v,g,y,x=this.lookupHashes;x[0]=t.type,x[1]=n.id,x[2]=h,x[3]=o.key,x[4]=a.key,x[5]=null!=(d=null==e?void 0:e.renderingHash)?d:0,x[6]=null!=(f=null==i?void 0:i.renderingHash)?f:0,x[7]=s.impl.key,x[8]=null!=(p=null==(m=r[0])?void 0:m.key)?p:0,x[9]=null!=(_=null==(v=r[1])?void 0:v.key)?_:0,x[10]=null!=(g=null==(y=r[2])?void 0:y.key)?g:0,x[11]=l?c.key:0,x[12]=l?u.key:0;var S=Yi(x),b=this.cache.get(S);if(b)for(var w=0;w0){f.fragment={module:d.getFragmentShaderModule(),entryPoint:d.fragmentEntryPoint,targets:[]};var m=0;s.redWrite&&(m|=GPUColorWrite.RED),s.greenWrite&&(m|=GPUColorWrite.GREEN),s.blueWrite&&(m|=GPUColorWrite.BLUE),s.alphaWrite&&(m|=GPUColorWrite.ALPHA);var _=this.getBlend(s);p.forEach((function(t){f.fragment.targets.push({format:t.format,writeMask:m,blend:_})}))}return u.createRenderPipeline(f)},t}(),En=new Zi,Mn=function(){function t(){this.format=void 0,this.multisampledBuffer=void 0}return t.prototype.destroy=function(){var t;null==(t=this.multisampledBuffer)||t.destroy(),this.multisampledBuffer=null},t}(),Pn=function(){function t(t){var e=this;this.initialized=!1,this.key=void 0,this.colorAttachments=[],this.depthFormat=void 0,this.hasStencil=void 0,this.depthTexture=null,this.depthTextureInternal=!1,this.assignedColorTexture=null,this.renderPassDescriptor={},this.renderTarget=t,t._colorBuffers&&t._colorBuffers.forEach((function(t,i){e.setColorAttachment(i,void 0,t.impl.format)})),this.updateKey()}var e=t.prototype;return e.destroy=function(t){var e;(this.initialized=!1,this.depthTextureInternal)&&(null==(e=this.depthTexture)||e.destroy(),this.depthTexture=null);this.assignedColorTexture=null,this.colorAttachments.forEach((function(t){t.destroy()})),this.colorAttachments.length=0},e.updateKey=function(){var t=this.renderTarget,e=t.samples+":"+(t.depth?this.depthFormat:"nodepth");this.colorAttachments.forEach((function(t){e+=":"+t.format})),this.key=En.get(e)},e.setDepthFormat=function(t){this.depthFormat=t,this.hasStencil="depth24plus-stencil8"===t},e.assignColorTexture=function(t){this.assignedColorTexture=t;var e=t.createView(),i=this.renderPassDescriptor.colorAttachments[0];this.renderTarget.samples>1?i.resolveTarget=e:i.view=e,this.setColorAttachment(0,void 0,t.format),this.updateKey()},e.setColorAttachment=function(t,e,i){this.colorAttachments[t]||(this.colorAttachments[t]=new Mn),e&&(this.colorAttachments[t].multisampledBuffer=e),i&&(this.colorAttachments[t].format=i)},e.init=function(t,e){var i,n,s=t.wgpu;this.initDepthStencil(s,e),this.renderPassDescriptor.colorAttachments=[];for(var r=null!=(i=null==(n=e._colorBuffers)?void 0:n.length)?i:1,a=0;a1?GPUTextureUsage.TEXTURE_BINDING:GPUTextureUsage.COPY_SRC,this.depthTexture=t.createTexture(o),this.depthTextureInternal=!0}this.renderPassDescriptor.depthStencilAttachment={view:this.depthTexture.createView()}}},e.initColor=function(t,e,i){var n={},s=e.samples,r=e.width,a=e.height,o=e.getColorBuffer(i),h=null;if(o){h=o.cubemap?o.impl.createView({dimension:"2d",baseArrayLayer:e.face,arrayLayerCount:1,mipLevelCount:1}):o.impl.createView({mipLevelCount:1})}if(s>1){var l,c,u={size:[r,a,1],dimension:"2d",sampleCount:s,format:null!=(l=null==(c=this.colorAttachments[i])?void 0:c.format)?l:o.impl.format,usage:GPUTextureUsage.RENDER_ATTACHMENT},d=t.createTexture(u);this.setColorAttachment(i,d,u.format),n.view=d.createView(),n.resolveTarget=h}else n.view=h;return n},e.setupForRenderPass=function(t){for(var e,i,n=null!=(e=null==(i=this.renderPassDescriptor.colorAttachments)?void 0:i.length)?e:0,s=0;s>e,1)},t.calcLevelGpuSize=function(t,e,i,n){var s,r,a,o=ye.get(n),h=null!=(s=null==(r=ye.get(n))?void 0:r.size)?s:0;if(h>0)return t*e*i*h;var l=null!=(a=o.blockSize)?a:0,c=Math.floor((t+3)/4),u=Math.floor((e+3)/4),d=Math.floor((i+3)/4);return n!==me&&n!==_e||(c=Math.max(Math.floor(c/2),1)),c*u*d*l},t.calcGpuSize=function(e,i,n,s,r,a){for(var o=0;o+=t.calcLevelGpuSize(e,i,n,s),r&&(1!==e||1!==i||1!==n);)e=Math.max(e>>1,1),i=Math.max(i>>1,1),n=Math.max(n>>1,1);return o*(a?6:1)},t}(),Zn=[];Zn[0]="",Zn[1]="r8unorm",Zn[2]="rg8unorm",Zn[3]="",Zn[4]="",Zn[5]="",Zn[6]="rgba8unorm",Zn[7]="rgba8unorm",Zn[8]="bc1-rgba-unorm",Zn[9]="bc2-rgba-unorm",Zn[10]="bc3-rgba-unorm",Zn[11]="",Zn[12]="rgba16float",Zn[13]="",Zn[14]="rgba32float",Zn[15]="r32float",Zn[16]="depth32float",Zn[17]="depth24plus-stencil8",Zn[18]="rg11b10ufloat",Zn[19]="",Zn[20]="",Zn[21]="",Zn[22]="etc2-rgb8unorm",Zn[23]="etc2-rgba8unorm",Zn[24]="",Zn[25]="",Zn[26]="",Zn[27]="",Zn[28]="astc-4x4-unorm",Zn[29]="",Zn[30]="",Zn[31]="bgra8unorm";var Qn=[];Qn[0]="repeat",Qn[1]="clamp-to-edge",Qn[2]="mirror-repeat";var $n=[];$n[0]={level:"nearest",mip:"nearest"},$n[1]={level:"linear",mip:"nearest"},$n[2]={level:"nearest",mip:"nearest"},$n[3]={level:"nearest",mip:"linear"},$n[4]={level:"linear",mip:"nearest"},$n[5]={level:"linear",mip:"linear"};var Jn=function(){function t(t){this.gpuTexture=void 0,this.view=void 0,this.samplers=[],this.descr=void 0,this.format=void 0,this.texture=t,this.format=Zn[t.format],this.create(t.device)}var e=t.prototype;return e.create=function(t){var e,i=this.texture,n=t.wgpu,s=i.requiredMipLevels;this.descr={size:{width:i.width,height:i.height,depthOrArrayLayers:i.cubemap?6:1},format:this.format,mipLevelCount:s,sampleCount:1,dimension:i.volume?"3d":"2d",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|(xe(i.format)?0:GPUTextureUsage.RENDER_ATTACHMENT)|GPUTextureUsage.COPY_SRC},this.gpuTexture=n.createTexture(this.descr),this.texture.format===de&&(e={format:"depth24plus",aspect:"depth-only"}),this.view=this.createView(e)},e.destroy=function(t){},e.propertyChanged=function(t){this.samplers.length=0},e.getView=function(t){return this.uploadImmediate(t,this.texture),this.view},e.createView=function(t){var e,i,n,s,r,a,o,h=null!=t?t:{},l=this.descr,c=this.texture,u={format:null!=(e=h.format)?e:l.format,dimension:null!=(i=h.dimension)?i:c.cubemap?"cube":c.volume?"3d":"2d",aspect:null!=(n=h.aspect)?n:"all",baseMipLevel:null!=(s=h.baseMipLevel)?s:0,mipLevelCount:null!=(r=h.mipLevelCount)?r:l.mipLevelCount,baseArrayLayer:null!=(a=h.baseArrayLayer)?a:0,arrayLayerCount:null!=(o=h.arrayLayerCount)?o:l.depthOrArrayLayers};return this.gpuTexture.createView(u)},e.getSampler=function(t,e){var i=this.samplers[e];if(!i){var n=this.texture,s={addressModeU:Qn[n.addressU],addressModeV:Qn[n.addressV],addressModeW:Qn[n.addressW]};!e&&n.compareOnRead&&(e=2),2===e?(s.compare="less",s.magFilter="linear",s.minFilter="linear"):1===e||this.texture.format===le||this.texture.format===de||this.texture.format===oe?(s.magFilter="nearest",s.minFilter="nearest",s.mipmapFilter="nearest"):(s.magFilter=$n[n.magFilter].level,s.minFilter=$n[n.minFilter].level,s.mipmapFilter=$n[n.minFilter].mip);var r="linear"===s.minFilter&&"linear"===s.magFilter&&"linear"===s.mipmapFilter;s.maxAnisotropy=r?_t.clamp(Math.round(n._anisotropy),1,t.maxTextureAnisotropy):1,i=t.wgpu.createSampler(s),this.samplers[e]=i}return i},e.loseContext=function(){},e.uploadImmediate=function(t,e){(e._needsUpload||e._needsMipmapsUpload)&&(this.uploadData(t),e._needsUpload=!1,e._needsMipmapsUpload=!1)},e.uploadData=function(t){var e=this.texture;if(e._levels){for(var i=!1,n=e.requiredMipLevels,s=0;s<=|&+-]/g,us=function(){function t(){}return t.run=function(t,e){void 0===e&&(e=!1),t=(t=t.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm,"$1")).split(/\r?\n/).map((function(t){return t.trimEnd()})).join("\n");var i=new Map;if(e){var n=new Map,s=t.match(/(pcFragColor[1-8])\b/g);null==s||s.forEach((function(t){var e,i=parseInt(t.charAt(t.length-1),10);n.set(i,(null!=(e=n.get(i))?e:0)+1)})),n.forEach((function(t,e){1===t&&i.set("REMOVE_COLOR_ATTACHMENT_"+e,"")}))}t=this._preprocess(t,i);var r=new Map;return i.forEach((function(t,e){Number.isInteger(parseFloat(t))&&!t.includes(".")&&r.set(e,t)})),null!==t&&(t=t.split(/\r?\n/).map((function(t){return""===t.trim()?"":t})).map((function(t){return r.forEach((function(e,i){t=t.replace(new RegExp("\\["+i+"\\]","g"),"["+e+"]")})),t})).join("\n"),t=t.replace(/(\n\n){3,}/gm,"\n\n")),t},t._preprocess=function(e,i){void 0===i&&(i=new Map);for(var n,s=e,r=[],a=!1;null!==(n=is.exec(e));){var o=n[1];switch(o){case"define":ns.lastIndex=n.index;var h=ns.exec(e);a||(a=null===h);var l=h[1];hs.lastIndex=h.index;var c=hs.exec(l)[1],u=l.substring(c.length).trim();""===u&&(u="true"),t._keep(r)&&i.set(c,u),is.lastIndex=h.index+h[0].length;break;case"undef":rs.lastIndex=n.index;var d=rs.exec(e),f=d[1].trim();t._keep(r)&&i.delete(f),is.lastIndex=d.index+d[0].length;break;case"extension":ss.lastIndex=n.index;var p=ss.exec(e);if(a||(a=null===p),p){var m=p[1];t._keep(r)&&i.set(m,"true")}is.lastIndex=p.index+p[0].length;break;case"ifdef":case"ifndef":case"if":as.lastIndex=n.index;var _=as.exec(e),v=_[2],g=t.evaluate(v,i);a||(a=g.error);var y=g.result;"ifndef"===o&&(y=!y),r.push({anyKeep:y,keep:y,start:n.index,end:as.lastIndex}),is.lastIndex=_.index+_[0].length;break;case"endif":case"else":case"elif":os.lastIndex=n.index;var x=os.exec(e),S=r.pop(),b=S.keep?e.substring(S.end,n.index):"";e=e.substring(0,S.start)+b+e.substring(os.lastIndex),is.lastIndex=S.start+b.length;var w=x[1];if("else"===w||"elif"===w){var T=!1;if(!S.anyKeep)if("else"===w)T=!S.keep;else{var A=t.evaluate(x[2],i);T=A.result,a||(a=A.error)}r.push({anyKeep:S.anyKeep||T,keep:T,start:is.lastIndex,end:is.lastIndex})}}}return a?(console.warn("Failed to preprocess shader: ",{source:s}),s):e},t._keep=function(t){for(var e=0;e=0;r--){var a=this.usedBuffers[r],o=a.stagingBuffer,h=a.gpuBuffer,l=a.offset,c=a.size,u=o.buffer;u.unmap(),s.copyBufferToBuffer(u,l,h.buffer,l,c),n.push(h)}var d=s.finish();i.addCommandBuffer(d,!0);for(var f=0;f0&&(this._frameTime=e[0]),E.get(l))for(var n=0;n0&&(this.dynamicBuffers.submit(),this.wgpu.queue.submit(this.commandBuffers),this.commandBuffers.length=0,this.dynamicBuffers.onCommandBuffersSubmitted())},n.clear=function(t){t.flags&&this.clearRenderer.clear(this,this.renderTarget,t,this.defaultClearOptions)},n.setDepthBias=function(t){},n.setDepthBiasValues=function(t,e){},n.setViewport=function(t,e,i,n){this.passEncoder&&(this.renderTarget.flipY||(e=this.renderTarget.height-e-n),this.vx=t,this.vy=e,this.vw=i,this.vh=n,this.passEncoder.setViewport(t,e,i,n,0,1))},n.setScissor=function(t,e,i,n){this.passEncoder&&(this.renderTarget.flipY||(e=this.renderTarget.height-e-n),this.sx=t,this.sy=e,this.sw=i,this.sh=n,this.passEncoder.setScissorRect(t,e,i,n))},n.copyRenderTarget=function(t,e,i,n){var s,r={width:t?t.width:e.width,height:t?t.height:e.height,depthOrArrayLayers:1},a=null!=(s=this.commandEncoder)?s:this.wgpu.createCommandEncoder();if(i){var o={texture:t?t.colorBuffer.impl.gpuTexture:this.renderTarget.impl.assignedColorTexture,mipLevel:0},h={texture:e?e.colorBuffer.impl.gpuTexture:this.renderTarget.impl.assignedColorTexture,mipLevel:0};a.copyTextureToTexture(o,h,r)}if(n){var l=(t||this.renderTarget).impl.depthTexture;if(t.samples>1){var c=e.colorBuffer.impl.gpuTexture;this.resolver.resolveDepth(a,l,c)}else{var u={texture:l,mipLevel:0},d={texture:e?e.depthBuffer.impl.gpuTexture:this.renderTarget.impl.depthTexture,mipLevel:0};a.copyTextureToTexture(u,d,r)}}if(!this.commandEncoder){var f=a.finish();this.addCommandBuffer(f)}return!0},e}(nn),Is=0,Ls=function(){function t(t,e){var i,n,s,r,a,o,h,l,c,u,d,f,p,m,_,v,g,y,x,S;(void 0===e&&(e={}),this.name=void 0,this._isRenderTarget=!1,this._gpuSize=0,this.id=Is++,this._invalid=!1,this._lockedLevel=-1,this.renderVersionDirty=0,this.device=t,this.name=null!=(i=e.name)?i:"",this._width=Math.floor(null!=(n=e.width)?n:4),this._height=Math.floor(null!=(s=e.height)?s:4),this._format=null!=(r=e.format)?r:7,this._compressed=xe(this._format),t.supportsVolumeTextures)?(this._volume=null!=(x=e.volume)&&x,this._depth=Math.floor(null!=(S=e.depth)?S:1)):(this._volume=!1,this._depth=1);this._cubemap=null!=(a=e.cubemap)&&a,this.fixCubemapSeams=null!=(o=e.fixCubemapSeams)&&o,this._flipY=null!=(h=e.flipY)&&h,this._premultiplyAlpha=null!=(l=e.premultiplyAlpha)&&l,this._mipmaps=null==(c=null!=(u=e.mipmaps)?u:e.autoMipmap)||c,this._minFilter=null!=(d=e.minFilter)?d:5,this._magFilter=null!=(f=e.magFilter)?f:1,this._anisotropy=null!=(p=e.anisotropy)?p:1,this._addressU=null!=(m=e.addressU)?m:0,this._addressV=null!=(_=e.addressV)?_:0,this._addressW=null!=(v=e.addressW)?v:0,this._compareOnRead=null!=(g=e.compareOnRead)&&g,this._compareFunc=null!=(y=e.compareFunc)?y:1,this.type=ei,e.hasOwnProperty("type")?this.type=e.type:e.hasOwnProperty("rgbm")?this.type=e.rgbm?ii:ei:e.hasOwnProperty("swizzleGGGR")&&(this.type=e.swizzleGGGR?ri:ei),this.projection=ci,this._cubemap?this.projection=ui:e.projection&&e.projection!==ui&&(this.projection=e.projection),this.impl=t.createTextureImpl(this),this.dirtyAll(),this._levels=e.levels,this._levels?this.upload():this._levels=this._cubemap?[[null,null,null,null,null,null]]:[null],t.textures.push(this)}var e,i=t.prototype;return i.destroy=function(){var t=this.device;if(t){var e=t.textures.indexOf(this);-1!==e&&t.textures.splice(e,1),t.scope.removeValue(this),this.impl.destroy(t),this.adjustVramSizeTracking(t._vram,-this._gpuSize),this._levels=null,this.device=null}},i.resize=function(t,e,i){void 0===i&&(i=1);var n=this.device;this.adjustVramSizeTracking(n._vram,-this._gpuSize),this.impl.destroy(n),this._width=t,this._height=e,this._depth=i,this.impl=n.createTextureImpl(this),this.dirtyAll()},i.loseContext=function(){this.impl.loseContext(),this.dirtyAll()},i.adjustVramSizeTracking=function(t,e){t.tex+=e},i.propertyChanged=function(t){this.impl.propertyChanged(t),this.renderVersionDirty=this.device.renderVersion},i.dirtyAll=function(){this._levelsUpdated=this._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0],this._needsUpload=!0,this._needsMipmapsUpload=this._mipmaps,this._mipmapsUploaded=!1,this.propertyChanged(255)},i.lock=function(t){void 0===t&&(t={}),void 0===t.level&&(t.level=0),void 0===t.face&&(t.face=0),void 0===t.mode&&(t.mode=2),this._lockedLevel=t.level;var e=this.cubemap?this._levels[t.face]:this._levels;if(null===e[t.level]){var i=Math.max(1,this._width>>t.level),n=Math.max(1,this._height>>t.level),s=Math.max(1,this._depth>>t.level),r=new ArrayBuffer(Kn.calcLevelGpuSize(i,n,s,this._format));e[t.level]=new(Se(this._format))(r)}return e[t.level]},i.setSource=function(t,e){void 0===e&&(e=0);var i,n,s=!1;if(this._cubemap){if(t[0]){i=t[0].width||0,n=t[0].height||0;for(var r=0;r<6;r++){var a=t[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[e][o]!==t[o]&&(this._levelsUpdated[e][o]=!0)}else this.device._isBrowserInterface(t)||(s=!0),s||(t!==this._levels[e]&&(this._levelsUpdated[e]=!0),i=t.width,n=t.height);if(s)if(this._width=4,this._height=4,this._cubemap)for(var h=0;h<6;h++)this._levels[e][h]=null,this._levelsUpdated[e][h]=!0;else this._levels[e]=null,this._levelsUpdated[e]=!0;else 0===e&&(this._width=i,this._height=n),this._levels[e]=t;this._invalid===s&&s||(this._invalid=s,this.upload())},i.getSource=function(t){return void 0===t&&(t=0),this._levels[t]},i.unlock=function(){this._lockedLevel,this.upload(),this._lockedLevel=-1},i.upload=function(){var t,e;this._needsUpload=!0,this._needsMipmapsUpload=this._mipmaps,null==(t=(e=this.impl).uploadImmediate)||t.call(e,this.device,this)},i.downloadAsync=(e=v(m().mark((function t(){var e,i,n,s=this;return m().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:e=[],i=m().mark((function t(){var i,r,a,o;return m().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:i=new rn({colorBuffer:s,depth:!1,face:n}),s.device.setRenderTarget(i),s.device.initRenderTarget(i),(r=s.cubemap?s._levels[n]:s._levels)[0],r[0]&&s.device._isBrowserInterface(r[0])&&(r[0]=null),a=s.lock({face:n}),o=null==s.device.readPixelsAsync?void 0:s.device.readPixelsAsync(0,0,s.width,s.height,a).then((function(){return i.destroy()})),e.push(o);case 9:case"end":return t.stop()}}),t)})),n=0;case 3:if(!(n<(this.cubemap?6:1))){t.next=8;break}return t.delegateYield(i(),"t0",5);case 5:n++,t.next=3;break;case 8:return t.next=10,Promise.all(e);case 10:case"end":return t.stop()}}),t,this)}))),function(){return e.apply(this,arguments)}),y(t,[{key:"requiredMipLevels",get:function(){return this.mipmaps?Math.floor(Math.log2(Math.max(this.width,this.height)))+1:1}},{key:"minFilter",get:function(){return this._minFilter},set:function(t){this._minFilter!==t&&(this._minFilter=t,this.propertyChanged(1))}},{key:"magFilter",get:function(){return this._magFilter},set:function(t){this._magFilter!==t&&(this._magFilter=t,this.propertyChanged(2))}},{key:"addressU",get:function(){return this._addressU},set:function(t){this._addressU!==t&&(this._addressU=t,this.propertyChanged(4))}},{key:"addressV",get:function(){return this._addressV},set:function(t){this._addressV!==t&&(this._addressV=t,this.propertyChanged(8))}},{key:"addressW",get:function(){return this._addressW},set:function(t){this.device.supportsVolumeTextures&&this._volume&&t!==this._addressW&&(this._addressW=t,this.propertyChanged(16))}},{key:"compareOnRead",get:function(){return this._compareOnRead},set:function(t){this._compareOnRead!==t&&(this._compareOnRead=t,this.propertyChanged(32))}},{key:"compareFunc",get:function(){return this._compareFunc},set:function(t){this._compareFunc!==t&&(this._compareFunc=t,this.propertyChanged(64))}},{key:"anisotropy",get:function(){return this._anisotropy},set:function(t){this._anisotropy!==t&&(this._anisotropy=t,this.propertyChanged(128))}},{key:"mipmaps",get:function(){return this._mipmaps},set:function(t){this._mipmaps!==t&&(this._mipmaps=t,this.device.isWebGPU,t&&(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 Kn.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(t){this._flipY!==t&&(this._flipY=t,this._needsUpload=!0)}},{key:"premultiplyAlpha",get:function(){return this._premultiplyAlpha},set:function(t){this._premultiplyAlpha!==t&&(this._premultiplyAlpha=t,this._needsUpload=!0)}},{key:"pot",get:function(){return _t.powerOfTwo(this._width)&&_t.powerOfTwo(this._height)}},{key:"encoding",get:function(){switch(this.type){case ii:return"rgbm";case ni:return"rgbe";case si:return"rgbp";default:return this.format===ae||this.format===he||this.format===oe||this.format===le?"linear":"srgb"}}}]),t}(),Ds=function(){function t(){this.bufferId=null}var e=t.prototype;return e.destroy=function(t){this.bufferId&&(t.gl.deleteBuffer(this.bufferId),this.bufferId=null)},e.loseContext=function(){this.bufferId=null},e.unlock=function(t,e,i,n){var s,r=t.gl;switch(this.bufferId||(this.bufferId=r.createBuffer()),e){case 0:s=r.STATIC_DRAW;break;case 1:s=r.DYNAMIC_DRAW;break;case 2:s=r.STREAM_DRAW;break;case 3:s=t.isWebGL2?r.DYNAMIC_COPY:r.STATIC_DRAW}r.bindBuffer(i,this.bufferId),r.bufferData(i,n,s)},y(t,[{key:"initialized",get:function(){return!!this.bufferId}}]),t}(),Os=function(t){function e(){for(var e,i=arguments.length,n=new Array(i),s=0;se||n>e){var s=e/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(t,0,0,i,n,0,0,r,a),o}return t}var js=function(){function t(){this._glTexture=null,this._glTarget=void 0,this._glFormat=void 0,this._glInternalFormat=void 0,this._glPixelType=void 0,this.dirtyParameterFlags=0}var e=t.prototype;return e.destroy=function(t){if(this._glTexture){for(var e=0;et.maxCubeMapSize||h.height>t.maxCubeMapSize)&&(h=Xs(h,t.maxCubeMapSize),0===r&&(e._width=h.width,e._height=h.height)),t.setUnpackFlipY(!1),t.setUnpackPremultiplyAlpha(e._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(e._levelsUpdated[0][o]){var l=n[o];e._compressed?i.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+o,r,this._glInternalFormat,Math.max(e._width*s,1),Math.max(e._height*s,1),0,l):(t.setUnpackFlipY(!1),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+o,r,this._glInternalFormat,Math.max(e._width*s,1),Math.max(e._height*s,1),0,this._glFormat,this._glPixelType,l))}}else e._volume?(s=1/Math.pow(2,r),e._compressed?i.compressedTexImage3D(i.TEXTURE_3D,r,this._glInternalFormat,Math.max(e._width*s,1),Math.max(e._height*s,1),Math.max(e._depth*s,1),0,n):(t.setUnpackFlipY(!1),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),i.texImage3D(i.TEXTURE_3D,r,this._glInternalFormat,Math.max(e._width*s,1),Math.max(e._height*s,1),Math.max(e._depth*s,1),0,this._glFormat,this._glPixelType,n))):(t._isBrowserInterface(n)?(t._isImageBrowserInterface(n)&&(n.width>t.maxTextureSize||n.height>t.maxTextureSize)&&(n=Xs(n,t.maxTextureSize),0===r&&(e._width=n.width,e._height=n.height)),t.setUnpackFlipY(e._flipY),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),i.texImage2D(i.TEXTURE_2D,r,this._glInternalFormat,this._glFormat,this._glPixelType,n)):(s=1/Math.pow(2,r),e._compressed?i.compressedTexImage2D(i.TEXTURE_2D,r,this._glInternalFormat,Math.max(Math.floor(e._width*s),1),Math.max(Math.floor(e._height*s),1),0,n):(t.setUnpackFlipY(!1),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),i.texImage2D(i.TEXTURE_2D,r,this._glInternalFormat,Math.max(e._width*s,1),Math.max(e._height*s,1),0,this._glFormat,this._glPixelType,n))),e._mipmapsUploaded=0!==r);r++}else r++;if(e._needsUpload)if(e._cubemap)for(var c=0;c<6;c++)e._levelsUpdated[0][c]=!1;else e._levelsUpdated[0]=!1;!e._compressed&&e._mipmaps&&e._needsMipmapsUpload&&(e.pot||t.isWebGL2)&&1===e._levels.length&&(i.generateMipmap(this._glTarget),e._mipmapsUploaded=!0),e._gpuSize&&e.adjustVramSizeTracking(t._vram,-e._gpuSize),e._gpuSize=e.gpuSize,e.adjustVramSizeTracking(t._vram,e._gpuSize)}},t}(),qs=function(){function t(t,e){this.msaaFB=void 0,this.resolveFB=void 0,this.msaaFB=t,this.resolveFB=e}return t.prototype.destroy=function(t){this.msaaFB&&(t.deleteRenderbuffer(this.msaaFB),this.msaaFB=null),this.resolveFB&&(t.deleteRenderbuffer(this.resolveFB),this.resolveFB=null)},t}(),Ys=function(){function t(){this._glFrameBuffer=null,this._glDepthBuffer=null,this._glResolveFrameBuffer=null,this.colorMrtFramebuffers=null,this._glMsaaColorBuffers=[],this._glMsaaDepthBuffer=null,this.suppliedColorFramebuffer=void 0,this._isInitialized=!1}var e=t.prototype;return e.destroy=function(t){var e,i=t.gl;this._isInitialized=!1,this._glFrameBuffer&&(this._glFrameBuffer!==this.suppliedColorFramebuffer&&i.deleteFramebuffer(this._glFrameBuffer),this._glFrameBuffer=null),this._glDepthBuffer&&(i.deleteRenderbuffer(this._glDepthBuffer),this._glDepthBuffer=null),this._glResolveFrameBuffer&&(this._glResolveFrameBuffer!==this.suppliedColorFramebuffer&&i.deleteFramebuffer(this._glResolveFrameBuffer),this._glResolveFrameBuffer=null),this._glMsaaColorBuffers.forEach((function(t){i.deleteRenderbuffer(t)})),this._glMsaaColorBuffers.length=0,null==(e=this.colorMrtFramebuffers)||e.forEach((function(t){t.destroy(i)})),this.colorMrtFramebuffers=null,this._glMsaaDepthBuffer&&(i.deleteRenderbuffer(this._glMsaaDepthBuffer),this._glMsaaDepthBuffer=null),this.suppliedColorFramebuffer=void 0},e.init=function(t,e){var i=t.gl;this._isInitialized=!0;var n=[];if(void 0!==this.suppliedColorFramebuffer)this._glFrameBuffer=this.suppliedColorFramebuffer;else{var s,r,a,o;this._glFrameBuffer=i.createFramebuffer(),t.setFramebuffer(this._glFrameBuffer);for(var h=null!=(s=null==(r=e._colorBuffers)?void 0:r.length)?s:0,l=t.isWebGL2?i.COLOR_ATTACHMENT0:null!=(a=null==(o=t.extDrawBuffers)?void 0:o.COLOR_ATTACHMENT0_WEBGL)?a:i.COLOR_ATTACHMENT0,c=0;c1&&t.isWebGL2)){if(this._glDepthBuffer||(this._glDepthBuffer=i.createRenderbuffer()),i.bindRenderbuffer(i.RENDERBUFFER,this._glDepthBuffer),e._stencil)i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,this._glDepthBuffer);else{var f=t.isWebGL2?i.DEPTH_COMPONENT32F:i.DEPTH_COMPONENT16;i.renderbufferStorage(i.RENDERBUFFER,f,e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,this._glDepthBuffer)}i.bindRenderbuffer(i.RENDERBUFFER,null)}}}if(t.isWebGL2&&e._samples>1){var p,m;this._glResolveFrameBuffer=this._glFrameBuffer,this._glFrameBuffer=i.createFramebuffer(),t.setFramebuffer(this._glFrameBuffer);var _=null!=(p=null==(m=e._colorBuffers)?void 0:m.length)?p:0;if(void 0!==this.suppliedColorFramebuffer){var v=i.createRenderbuffer();this._glMsaaColorBuffers.push(v);var g=7===t.backBufferFormat?i.RGBA8:i.RGB8;i.bindRenderbuffer(i.RENDERBUFFER,v),i.renderbufferStorageMultisample(i.RENDERBUFFER,e._samples,g,e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,v)}else for(var y=0;y<_;++y){var x=e.getColorBuffer(y);if(x){var S=i.createRenderbuffer();this._glMsaaColorBuffers.push(S),i.bindRenderbuffer(i.RENDERBUFFER,S),i.renderbufferStorageMultisample(i.RENDERBUFFER,e._samples,x.impl._glInternalFormat,e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+y,i.RENDERBUFFER,S)}}e._depth&&(this._glMsaaDepthBuffer||(this._glMsaaDepthBuffer=i.createRenderbuffer()),i.bindRenderbuffer(i.RENDERBUFFER,this._glMsaaDepthBuffer),e._stencil?(i.renderbufferStorageMultisample(i.RENDERBUFFER,e._samples,i.DEPTH24_STENCIL8,e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,this._glMsaaDepthBuffer)):(i.renderbufferStorageMultisample(i.RENDERBUFFER,e._samples,i.DEPTH_COMPONENT32F,e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,this._glMsaaDepthBuffer))),_>1&&(this._createMsaaMrtFramebuffers(t,e,_),t.setFramebuffer(this._glFrameBuffer),t.drawBuffers(n))}},e._createMsaaMrtFramebuffers=function(t,e,i){var n=t.gl;this.colorMrtFramebuffers=[];for(var s=0;s=0&&!(n>0&&"/"===t[n-1]);){var s=t.indexOf(";",n),r=t.lastIndexOf(" ",s),a=t.substring(r+1,s),o=er[a];void 0!==o?e[a]=o:(e[a]="ATTR"+i,i++),n=t.indexOf("attribute",n+1)}return e},t}(),nr=function(){function t(){this.renderVersion=void 0,this.queries=[]}return t.prototype.destroy=function(t){this.queries.forEach((function(e){return t.deleteQuery(e)})),this.queries=null},t}(),sr=function(t){function e(e){var i;return(i=t.call(this)||this).device=void 0,i.freeQueries=[],i.frameQueries=[],i.previousFrameQueries=[],i.timings=[],i.device=e,i.ext=e.extDisjointTimerQuery,i}S(e,t);var i=e.prototype;return i.destroy=function(){var t=this;this.freeQueries.forEach((function(e){return t.device.gl.deleteQuery(e)})),this.frameQueries.forEach((function(e){return t.device.gl.deleteQuery(e)})),this.previousFrameQueries.forEach((function(e){return e.destroy(t.device.gl)})),this.freeQueries=null,this.frameQueries=null,this.previousFrameQueries=null},i.loseContext=function(){t.prototype.loseContext.call(this),this.freeQueries=[],this.frameQueries=[],this.previousFrameQueries=[]},i.restoreContext=function(){this.ext=this.device.extDisjointTimerQuery},i.getQuery=function(){var t;return null!=(t=this.freeQueries.pop())?t:this.device.gl.createQuery()},i.start=function(t){if(this.ext){var e=this.getSlot(t),i=this.getQuery();return this.frameQueries[e]=i,this.device.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,i),e}},i.end=function(t){void 0!==t&&this.device.gl.endQuery(this.ext.TIME_ELAPSED_EXT)},i.frameStart=function(){this.processEnableRequest(),this._enabled&&(this.frameGPUMarkerSlot=this.start("GpuFrame"))},i.frameEnd=function(){this._enabled&&this.end(this.frameGPUMarkerSlot)},i.request=function(){var e=this;if(this._enabled){var i=this.ext,n=this.device.gl,s=this.device.renderVersion,r=this.frameQueries;if(r.length>0){this.frameQueries=[];var a=new nr;a.queries=r,a.renderVersion=s,this.previousFrameQueries.push(a)}if(this.previousFrameQueries.length>0){var o=this.previousFrameQueries[0],h=o.queries,l=h[h.length-1],c=n.getQueryParameter(l,n.QUERY_RESULT_AVAILABLE),u=n.getParameter(i.GPU_DISJOINT_EXT);if(c&&!u){this.previousFrameQueries.shift();var d=this.timings;d.length=0;for(var f=0;f0;var g=s.vertexUniformsCount;return g-=16,g-=8,g-=1,g-=16,s.boneLimit=Math.floor(g/3),s.boneLimit=Math.min(s.boneLimit,128),"Mali-450 MP"===s.unmaskedRenderer&&(s.boneLimit=34),s.constantTexSource=s.scope.resolve("source"),s.extTextureFloat?s.isWebGL2?s.textureFloatRenderable=!!s.extColorBufferFloat:s.textureFloatRenderable=hr(a,a.FLOAT):s.textureFloatRenderable=!1,s.extColorBufferHalfFloat?s.textureHalfFloatRenderable=!!s.extColorBufferHalfFloat:s.extTextureHalfFloat?s.isWebGL2?s.textureHalfFloatRenderable=!!s.extColorBufferFloat:s.textureHalfFloatRenderable=hr(a,s.extTextureHalfFloat.HALF_FLOAT_OES):s.textureHalfFloatRenderable=!1,s.supportsMorphTargetTexturesCore="highp"===s.maxPrecision&&s.maxVertexTextures>=2,s.supportsDepthShadow=s.isWebGL2,s._textureFloatHighPrecision=void 0,s._textureHalfFloatUpdatable=void 0,s.areaLightLutFormat=7,s.extTextureHalfFloat&&s.textureHalfFloatUpdatable&&s.extTextureHalfFloatLinear?s.areaLightLutFormat=oe:s.extTextureFloat&&s.extTextureFloatLinear&&(s.areaLightLutFormat=le),s.postInit(),s}S(e,t);var i,n=e.prototype;return n.postInit=function(){t.prototype.postInit.call(this),this.gpuProfiler=new sr(this)},n.destroy=function(){t.prototype.destroy.call(this);var e=this.gl;this.isWebGL2&&this.feedback&&e.deleteTransformFeedback(this.feedback),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,t.prototype.postDestroy.call(this)},n.createBackbuffer=function(t){this.supportsStencil=this.initOptions.stencil,this.backBuffer=new rn({name:"WebglFramebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.backBuffer.impl.suppliedColorFramebuffer=t},n.updateBackbufferFormat=function(t){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,t);var i=this.gl.getParameter(this.gl.ALPHA_BITS);this.backBufferFormat=i?7:6},n.updateBackbuffer=function(){var t=this.canvas.width!==this.backBufferSize.x||this.canvas.height!==this.backBufferSize.y;(this._defaultFramebufferChanged||t)&&(this._defaultFramebufferChanged&&this.updateBackbufferFormat(this._defaultFramebuffer),this._defaultFramebufferChanged=!1,this.backBufferSize.set(this.canvas.width,this.canvas.height),this.backBuffer.destroy(),this.createBackbuffer(this._defaultFramebuffer))},n.createVertexBufferImpl=function(t,e){return new Os},n.createIndexBufferImpl=function(t){return new ks(t)},n.createShaderImpl=function(t){return new Ws(t)},n.createTextureImpl=function(t){return new js},n.createRenderTargetImpl=function(t){return new Ys},n.getPrecision=function(){var t=this.gl,e="highp";if(t.getShaderPrecisionFormat){var i=t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.HIGH_FLOAT),n=t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT),s=t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT),r=t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT);if(i&&n&&s&&r){var a=i.precision>0&&s.precision>0,o=n.precision>0&&r.precision>0;a||(e=o?"mediump":"lowp")}}return e},n.getExtension=function(){for(var t=0;t0&&t.fullSizeClearRect&&s.invalidateFramebuffer(s.DRAW_FRAMEBUFFER,rr)}null!=(n=t.colorOps)&&n.resolve&&this.isWebGL2&&t.samples>1&&e.autoResolve&&e.resolve(!0,!1);for(var o=0;o1&&t.autoResolve&&t.resolve();var e=t._colorBuffer;e&&e.impl._glTexture&&e.mipmaps&&(e.pot||this.isWebGL2)&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(e),this.gl.generateMipmap(e.impl._glTarget))}},n.setUnpackFlipY=function(t){if(this.unpackFlipY!==t){this.unpackFlipY=t;var e=this.gl;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,t)}},n.setUnpackPremultiplyAlpha=function(t){if(this.unpackPremultiplyAlpha!==t){this.unpackPremultiplyAlpha=t;var e=this.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t)}},n.activeTexture=function(t){this.textureUnit!==t&&(this.gl.activeTexture(this.gl.TEXTURE0+t),this.textureUnit=t)},n.bindTexture=function(t){var e=t.impl,i=e._glTarget,n=e._glTexture,s=this.textureUnit,r=this.targetToSlot[i];this.textureUnits[s][r]!==n&&(this.gl.bindTexture(i,n),this.textureUnits[s][r]=n)},n.bindTextureOnUnit=function(t,e){var i=t.impl,n=i._glTarget,s=i._glTexture,r=this.targetToSlot[n];this.textureUnits[e][r]!==s&&(this.activeTexture(e),this.gl.bindTexture(n,s),this.textureUnits[e][r]=s)},n.setTextureParameters=function(t){var e=this.gl,i=t.impl.dirtyParameterFlags,n=t.impl._glTarget;if(1&i){var s=t._minFilter;(!t.pot&&!this.isWebGL2||!t._mipmaps||t._compressed&&1===t._levels.length)&&(2===s||3===s?s=0:4!==s&&5!==s||(s=1)),e.texParameteri(n,e.TEXTURE_MIN_FILTER,this.glFilter[s])}if(2&i&&e.texParameteri(n,e.TEXTURE_MAG_FILTER,this.glFilter[t._magFilter]),4&i&&(this.isWebGL2?e.texParameteri(n,e.TEXTURE_WRAP_S,this.glAddress[t._addressU]):e.texParameteri(n,e.TEXTURE_WRAP_S,this.glAddress[t.pot?t._addressU:1])),8&i&&(this.isWebGL2?e.texParameteri(n,e.TEXTURE_WRAP_T,this.glAddress[t._addressV]):e.texParameteri(n,e.TEXTURE_WRAP_T,this.glAddress[t.pot?t._addressV:1])),16&i&&this.isWebGL2&&e.texParameteri(n,e.TEXTURE_WRAP_R,this.glAddress[t._addressW]),32&i&&this.isWebGL2&&e.texParameteri(n,e.TEXTURE_COMPARE_MODE,t._compareOnRead?e.COMPARE_REF_TO_TEXTURE:e.NONE),64&i&&this.isWebGL2&&e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,this.glComparison[t._compareFunc]),128&i){var r=this.extTextureFilterAnisotropic;r&&e.texParameterf(n,r.TEXTURE_MAX_ANISOTROPY_EXT,_t.clamp(Math.round(t._anisotropy),1,this.maxAnisotropy))}},n.setTexture=function(t,e){var i=t.impl;i._glTexture||i.initialize(this,t),i.dirtyParameterFlags>0||t._needsUpload||t._needsMipmapsUpload?(this.activeTexture(e),this.bindTexture(t),i.dirtyParameterFlags&&(this.setTextureParameters(t),i.dirtyParameterFlags=0),(t._needsUpload||t._needsMipmapsUpload)&&(i.upload(this,t),t._needsUpload=!1,t._needsMipmapsUpload=!1)):this.bindTextureOnUnit(t,e)},n.createVertexArray=function(t){var e,i,n=t.length>1;if(n){e="";for(var s=0;s0?u.drawElementsInstanced(S,b,T,A,e):u.drawElements(S,b,T,A)}else{var C=t.base;e>0?u.drawArraysInstanced(S,C,b,e):u.drawArrays(S,C,b)}this.isWebGL2&&this.transformFeedbackBuffer&&(u.endTransformFeedback(),u.bindBufferBase(u.TRANSFORM_FEEDBACK_BUFFER,0,null)),this._drawCallsPerFrame++}},n.clear=function(t){var e,i=this.defaultClearOptions,n=null!=(e=(t=t||i).flags)?e:i.flags;if(0!==n){var s=this.gl;if(1&n){var r,a=null!=(r=t.color)?r:i.color,o=a[0],h=a[1],l=a[2],c=a[3],u=this.clearColor;o===u.r&&h===u.g&&l===u.b&&c===u.a||(this.gl.clearColor(o,h,l,c),this.clearColor.set(o,h,l,c)),this.setBlendState(Ui.NOBLEND)}if(2&n){var d,f=null!=(d=t.depth)?d:i.depth;f!==this.clearDepth&&(this.gl.clearDepth(f),this.clearDepth=f),this.setDepthState(Ni.WRITEDEPTH)}if(4&n){var p,m=null!=(p=t.stencil)?p:i.stencil;m!==this.clearStencil&&(this.gl.clearStencil(m),this.clearStencil=m)}s.clear(this.glClearFlag[n])}},n.submit=function(){this.gl.flush()},n.readPixels=function(t,e,i,n,s){var r=this.gl;r.readPixels(t,e,i,n,r.RGBA,r.UNSIGNED_BYTE,s)},n.readPixelsAsync=(i=v(m().mark((function t(e,i,n,s,r){var a,o,h,l,c,u,d,f,p,_=this;return m().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(l=this.gl,this.isWebGL2){t.next=4;break}return this.readPixels(e,i,n,s,r),t.abrupt("return");case 4:return c=function(t,e){var i=l.fenceSync(l.SYNC_GPU_COMMANDS_COMPLETE,0);return _.submit(),new Promise((function(n,s){!function r(){var a=l.clientWaitSync(i,t,0);a===l.WAIT_FAILED?(l.deleteSync(i),s(new Error("webgl clientWaitSync sync failed"))):a===l.TIMEOUT_EXPIRED?setTimeout(r,e):(l.deleteSync(i),n())}()}))},u=null==(a=this.renderTarget.colorBuffer)?void 0:a.impl,d=null!=(o=null==u?void 0:u._glFormat)?o:l.RGBA,f=null!=(h=null==u?void 0:u._glPixelType)?h:l.UNSIGNED_BYTE,p=l.createBuffer(),l.bindBuffer(l.PIXEL_PACK_BUFFER,p),l.bufferData(l.PIXEL_PACK_BUFFER,r.byteLength,l.STREAM_READ),l.readPixels(e,i,n,s,d,f,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),t.next=15,c(0,20);case 15:l.bindBuffer(l.PIXEL_PACK_BUFFER,p),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,r),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteBuffer(p);case 19:case"end":return t.stop()}}),t,this)}))),function(t,e,n,s,r){return i.apply(this,arguments)}),n.setAlphaToCoverage=function(t){this.isWebGL1||this.alphaToCoverage!==t&&(this.alphaToCoverage=t,t?this.gl.enable(this.gl.SAMPLE_ALPHA_TO_COVERAGE):this.gl.disable(this.gl.SAMPLE_ALPHA_TO_COVERAGE))},n.setTransformFeedbackBuffer=function(t){if(this.transformFeedbackBuffer!==t&&(this.transformFeedbackBuffer=t,this.isWebGL2)){var e=this.gl;t?(this.feedback||(this.feedback=e.createTransformFeedback()),e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,this.feedback)):e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,null)}},n.setRaster=function(t){this.raster!==t&&(this.raster=t,this.isWebGL2&&(t?this.gl.disable(this.gl.RASTERIZER_DISCARD):this.gl.enable(this.gl.RASTERIZER_DISCARD)))},n.setDepthBias=function(t){this.depthBiasEnabled!==t&&(this.depthBiasEnabled=t,t?this.gl.enable(this.gl.POLYGON_OFFSET_FILL):this.gl.disable(this.gl.POLYGON_OFFSET_FILL))},n.setDepthBiasValues=function(t,e){this.gl.polygonOffset(e,t)},n.setStencilTest=function(t){if(this.stencil!==t){var e=this.gl;t?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this.stencil=t}},n.setStencilFunc=function(t,e,i){this.stencilFuncFront===t&&this.stencilRefFront===e&&this.stencilMaskFront===i&&this.stencilFuncBack===t&&this.stencilRefBack===e&&this.stencilMaskBack===i||(this.gl.stencilFunc(this.glComparison[t],e,i),this.stencilFuncFront=this.stencilFuncBack=t,this.stencilRefFront=this.stencilRefBack=e,this.stencilMaskFront=this.stencilMaskBack=i)},n.setStencilFuncFront=function(t,e,i){if(this.stencilFuncFront!==t||this.stencilRefFront!==e||this.stencilMaskFront!==i){var n=this.gl;n.stencilFuncSeparate(n.FRONT,this.glComparison[t],e,i),this.stencilFuncFront=t,this.stencilRefFront=e,this.stencilMaskFront=i}},n.setStencilFuncBack=function(t,e,i){if(this.stencilFuncBack!==t||this.stencilRefBack!==e||this.stencilMaskBack!==i){var n=this.gl;n.stencilFuncSeparate(n.BACK,this.glComparison[t],e,i),this.stencilFuncBack=t,this.stencilRefBack=e,this.stencilMaskBack=i}},n.setStencilOperation=function(t,e,i,n){this.stencilFailFront===t&&this.stencilZfailFront===e&&this.stencilZpassFront===i&&this.stencilFailBack===t&&this.stencilZfailBack===e&&this.stencilZpassBack===i||(this.gl.stencilOp(this.glStencilOp[t],this.glStencilOp[e],this.glStencilOp[i]),this.stencilFailFront=this.stencilFailBack=t,this.stencilZfailFront=this.stencilZfailBack=e,this.stencilZpassFront=this.stencilZpassBack=i),this.stencilWriteMaskFront===n&&this.stencilWriteMaskBack===n||(this.gl.stencilMask(n),this.stencilWriteMaskFront=n,this.stencilWriteMaskBack=n)},n.setStencilOperationFront=function(t,e,i,n){this.stencilFailFront===t&&this.stencilZfailFront===e&&this.stencilZpassFront===i||(this.gl.stencilOpSeparate(this.gl.FRONT,this.glStencilOp[t],this.glStencilOp[e],this.glStencilOp[i]),this.stencilFailFront=t,this.stencilZfailFront=e,this.stencilZpassFront=i),this.stencilWriteMaskFront!==n&&(this.gl.stencilMaskSeparate(this.gl.FRONT,n),this.stencilWriteMaskFront=n)},n.setStencilOperationBack=function(t,e,i,n){this.stencilFailBack===t&&this.stencilZfailBack===e&&this.stencilZpassBack===i||(this.gl.stencilOpSeparate(this.gl.BACK,this.glStencilOp[t],this.glStencilOp[e],this.glStencilOp[i]),this.stencilFailBack=t,this.stencilZfailBack=e,this.stencilZpassBack=i),this.stencilWriteMaskBack!==n&&(this.gl.stencilMaskSeparate(this.gl.BACK,n),this.stencilWriteMaskBack=n)},n.setBlendState=function(t){var e=this.blendState;if(!e.equals(t)){var i=this.gl,n=t.blend,s=t.colorOp,r=t.alphaOp,a=t.colorSrcFactor,o=t.colorDstFactor,h=t.alphaSrcFactor,l=t.alphaDstFactor;if(e.blend!==n&&(n?i.enable(i.BLEND):i.disable(i.BLEND)),e.colorOp!==s||e.alphaOp!==r){var c=this.glBlendEquation;i.blendEquationSeparate(c[s],c[r])}e.colorSrcFactor===a&&e.colorDstFactor===o&&e.alphaSrcFactor===h&&e.alphaDstFactor===l||i.blendFuncSeparate(this.glBlendFunctionColor[a],this.glBlendFunctionColor[o],this.glBlendFunctionAlpha[h],this.glBlendFunctionAlpha[l]),e.allWrite!==t.allWrite&&this.gl.colorMask(t.redWrite,t.greenWrite,t.blueWrite,t.alphaWrite),e.copy(t)}},n.setBlendColor=function(t,e,i,n){var s=this.blendColor;t===s.r&&e===s.g&&i===s.b&&n===s.a||(this.gl.blendColor(t,e,i,n),s.set(t,e,i,n))},n.setStencilState=function(t,e){t||e?(this.setStencilTest(!0),t===e?(this.setStencilFunc(t.func,t.ref,t.readMask),this.setStencilOperation(t.fail,t.zfail,t.zpass,t.writeMask)):(null!=t||(t=en.DEFAULT),this.setStencilFuncFront(t.func,t.ref,t.readMask),this.setStencilOperationFront(t.fail,t.zfail,t.zpass,t.writeMask),null!=e||(e=en.DEFAULT),this.setStencilFuncBack(e.func,e.ref,e.readMask),this.setStencilOperationBack(e.fail,e.zfail,e.zpass,e.writeMask))):this.setStencilTest(!1)},n.setDepthState=function(t){var e=this.depthState;if(!e.equals(t)){var i=this.gl,n=t.write;e.write!==n&&i.depthMask(n);var s=t.func,r=t.test;!r&&n&&(r=!0,s=7),e.func!==s&&i.depthFunc(this.glComparison[s]),e.test!==r&&(r?i.enable(i.DEPTH_TEST):i.disable(i.DEPTH_TEST)),e.copy(t)}},n.setCullMode=function(t){if(this.cullMode!==t){if(t===se)this.gl.disable(this.gl.CULL_FACE);else{this.cullMode===se&&this.gl.enable(this.gl.CULL_FACE);var e=this.glCull[t];this.cullFace!==e&&(this.gl.cullFace(e),this.cullFace=e)}this.cullMode=t}},n.setShader=function(t){if(t!==this.shader){if(t.failed)return!1;if(!t.ready&&!t.impl.finalize(this,t))return t.failed=!0,!1;this.shader=t,this.gl.useProgram(t.impl.glProgram),this.attributesInvalidated=!0}return!0},n.getHdrFormat=function(t,e,i,n){var s=this.extTextureHalfFloat&&(!e||this.textureHalfFloatRenderable)&&(!i||this.textureHalfFloatUpdatable)&&(!n||this.extTextureHalfFloatLinear),r=this.extTextureFloat&&(!e||this.textureFloatRenderable)&&(!n||this.extTextureFloatLinear);return s&&r?t?le:oe:s?oe:r?le:null},n.clearVertexArrayObjectCache=function(){var t=this.gl;this._vaoMap.forEach((function(e,i,n){t.deleteVertexArray(e)})),this._vaoMap.clear()},y(e,[{key:"extDisjointTimerQuery",get:function(){return this._extDisjointTimerQuery||this.isWebGL2&&(this._extDisjointTimerQuery=this.getExtension("EXT_disjoint_timer_query_webgl2","EXT_disjoint_timer_query")),this._extDisjointTimerQuery}},{key:"defaultFramebuffer",get:function(){return this._defaultFramebuffer},set:function(t){this._defaultFramebuffer!==t&&(this._defaultFramebuffer=t,this._defaultFramebufferChanged=!0)}},{key:"fullscreen",get:function(){return!!document.fullscreenElement},set:function(t){t?this.gl.canvas.requestFullscreen():document.exitFullscreen()}},{key:"textureFloatHighPrecision",get:function(){return void 0===this._textureFloatHighPrecision&&(this._textureFloatHighPrecision=function(t){if(!t.textureFloatRenderable)return!1;var e=new fs(t,ir.createDefinition(t,{name:"ptest1",vertexCode:ar,fragmentCode:"\nvoid main(void) { \n\tgl_FragColor = vec4(2147483648.0);\n}\n"})),i=new fs(t,ir.createDefinition(t,{name:"ptest2",vertexCode:ar,fragmentCode:"\nuniform sampler2D source;\nvec4 packFloat(float depth) {\n\tconst vec4 bit_shift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);\n\tvec4 res = mod(depth * bit_shift * vec4(255), vec4(256) ) / vec4(255);\n\tres -= res.xxyz * bit_mask;\n\treturn res;\n}\nvoid main(void) {\n\tfloat c = texture2D(source, vec2(0.0)).r;\n\tfloat diff = abs(c - 2147483648.0) / 2147483648.0;\n\tgl_FragColor = packFloat(diff);\n}\n"})),n={format:le,width:1,height:1,mipmaps:!1,minFilter:0,magFilter:0,name:"testFHP"},s=new Ls(t,n),r=new rn({colorBuffer:s,depth:!1});or(t,r,e),n.format=7;var a=new Ls(t,n),o=new rn({colorBuffer:a,depth:!1});t.constantTexSource.setValue(s),or(t,o,i);var h=t.activeFramebuffer;t.setFramebuffer(o.impl._glFrameBuffer);var l=new Uint8Array(4);t.readPixels(0,0,1,1,l),t.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(),e.destroy(),i.destroy(),0===c}(this)),this._textureFloatHighPrecision}},{key:"textureHalfFloatUpdatable",get:function(){return void 0===this._textureHalfFloatUpdatable&&(this.isWebGL2?this._textureHalfFloatUpdatable=!0:this._textureHalfFloatUpdatable=function(t,e){var i=!0,n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE);var s=new Uint16Array(16);return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,2,2,0,t.RGBA,e,s),t.getError()!==t.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")),t.bindTexture(t.TEXTURE_2D,null),t.deleteTexture(n),i}(this.gl,this.extTextureHalfFloat.HALF_FLOAT_OES)),this._textureHalfFloatUpdatable}}]),e}(nn),cr=function(){function t(){}return t.prototype.unlock=function(t){},t}(),ur=function(){function t(){}var e=t.prototype;return e.destroy=function(t){},e.init=function(t,e){},e.loseContext=function(){},e.resolve=function(t,e,i,n){},t}(),dr=function(){function t(){}var e=t.prototype;return e.destroy=function(t){},e.loseContext=function(){},e.restoreContext=function(t,e){},t}(),fr=function(){function t(){}var e=t.prototype;return e.destroy=function(t){},e.propertyChanged=function(t){},e.loseContext=function(){},t}(),pr=function(){function t(){}var e=t.prototype;return e.destroy=function(t){},e.unlock=function(t){},t}(),mr=function(t){function e(e,i){var n;return void 0===i&&(i={}),i=(n=t.call(this,e,i)||this).initOptions,n.isNull=!0,n._deviceType=bi,n.samples=1,n}S(e,t);var i=e.prototype;return i.destroy=function(){t.prototype.destroy.call(this)},i.initDeviceCaps=function(){this.disableParticleSystem=!0,this.precision="highp",this.maxPrecision="highp",this.maxSamples=4,this.maxTextures=16,this.maxTextureSize=4096,this.maxCubeMapSize=4096,this.maxVolumeSize=4096,this.maxColorAttachments=8,this.maxPixelRatio=1,this.maxAnisotropy=16,this.supportsInstancing=!0,this.supportsUniformBuffers=!1,this.supportsVolumeTextures=!0,this.supportsBoneTextures=!0,this.supportsMorphTargetTexturesCore=!0,this.supportsAreaLights=!0,this.supportsDepthShadow=!0,this.supportsGpuParticles=!1,this.supportsMrt=!0,this.extUintElement=!0,this.extTextureFloat=!0,this.textureFloatRenderable=!0,this.extTextureHalfFloat=!0,this.textureHalfFloatRenderable=!0,this.textureHalfFloatUpdatable=!0,this.boneLimit=1024,this.supportsImageBitmap=!0,this.extStandardDerivatives=!0,this.extBlendMinmax=!0,this.areaLightLutFormat=7,this.supportsTextureFetch=!0},i.postInit=function(){t.prototype.postInit.call(this)},i.frameStart=function(){t.prototype.frameStart.call(this)},i.frameEnd=function(){t.prototype.frameEnd.call(this)},i.createVertexBufferImpl=function(t,e){return new pr(t,e)},i.createIndexBufferImpl=function(t){return new cr(t)},i.createShaderImpl=function(t){return new dr(t)},i.createTextureImpl=function(t){return new fr(t)},i.createRenderTargetImpl=function(t){return new ur(t)},i.draw=function(t,e,i){},i.setShader=function(t){return!0},i.setBlendState=function(t){},i.setDepthState=function(t){},i.setStencilState=function(t,e){},i.setBlendColor=function(t,e,i,n){},i.setCullMode=function(t){},i.setAlphaToCoverage=function(t){},i.initializeContextCaches=function(){t.prototype.initializeContextCaches.call(this)},i.startPass=function(t){},i.endPass=function(t){},i.clear=function(t){},i.setDepthBias=function(t){},i.setDepthBiasValues=function(t,e){},i.setViewport=function(t,e,i,n){},i.setScissor=function(t,e,i,n){},i.copyRenderTarget=function(t,e,i,n){return!0},e}(nn);var _r=0,vr=function(){function t(t,e,i,n,s){void 0===n&&(n=0),this.device=t,this.format=e,this.numIndices=i,this.usage=n,this.id=_r++,this.impl=t.createIndexBufferImpl(this);var r=Pi[e];this.bytesPerIndex=r,this.numBytes=this.numIndices*r,s?this.setData(s):this.storage=new ArrayBuffer(this.numBytes),this.adjustVramSizeTracking(t._vram,this.numBytes),this.device.buffers.push(this)}var e=t.prototype;return e.destroy=function(){var t=this.device,e=t.buffers.indexOf(this);-1!==e&&t.buffers.splice(e,1),this.device.indexBuffer===this&&(this.device.indexBuffer=null),this.impl.initialized&&(this.impl.destroy(t),this.adjustVramSizeTracking(t._vram,-this.storage.byteLength))},e.adjustVramSizeTracking=function(t,e){t.ib+=e},e.loseContext=function(){this.impl.loseContext()},e.getFormat=function(){return this.format},e.getNumIndices=function(){return this.numIndices},e.lock=function(){return this.storage},e.unlock=function(){this.impl.unlock(this)},e.setData=function(t){return t.byteLength===this.numBytes&&(this.storage=t,this.unlock(),!0)},e._lockTypedArray=function(){var t=this.lock();return 2===this.format?new Uint32Array(t):1===this.format?new Uint16Array(t):new Uint8Array(t)},e.writeData=function(t,e){var i=this._lockTypedArray();if(t.length>e)if(ArrayBuffer.isView(t))t=t.subarray(0,e),i.set(t);else for(var n=0;nthis.vertexBuffer.numVertices&&(i=this.vertexBuffer.numVertices);var s=n.numComponents;if(this.vertexBuffer.getFormat().interleaved)for(var r=0,a=0;ai*s){var o=i*s;if(ArrayBuffer.isView(e))e=e.subarray(0,o),n.array.set(e);else for(var h=0;h0?this.wheelDelta=1:i.deltaY<0&&(this.wheelDelta=-1)),Yr()?(this.dx=i.movementX||i.webkitMovementX||i.mozMovementX||0,this.dy=i.movementY||i.webkitMovementY||i.mozMovementY||0):(this.dx=this.x-e._lastX,this.dy=this.y-e._lastY),"mousedown"===i.type||"mouseup"===i.type?this.button=i.button:this.button=-1,this.buttons=e._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},Zr=function(t){function e(e){var i;return(i=t.call(this)||this)._lastX=0,i._lastY=0,i._buttons=[!1,!1,!1],i._lastbuttons=[!1,!1,!1],i._upHandler=i._handleUp.bind(w(i)),i._downHandler=i._handleDown.bind(w(i)),i._moveHandler=i._handleMove.bind(w(i)),i._wheelHandler=i._handleWheel.bind(w(i)),i._contextMenuHandler=function(t){t.preventDefault()},i._target=null,i._attached=!1,i.attach(e),i}S(e,t),e.isPointerLocked=function(){return Yr()};var i=e.prototype;return i.attach=function(t){if(this._target=t,!this._attached){this._attached=!0;var e=!!G.passiveEvents&&{passive:!1};window.addEventListener("mouseup",this._upHandler,e),window.addEventListener("mousedown",this._downHandler,e),window.addEventListener("mousemove",this._moveHandler,e),window.addEventListener("wheel",this._wheelHandler,e)}},i.detach=function(){if(this._attached){this._attached=!1,this._target=null;var t=!!G.passiveEvents&&{passive:!1};window.removeEventListener("mouseup",this._upHandler,t),window.removeEventListener("mousedown",this._downHandler,t),window.removeEventListener("mousemove",this._moveHandler,t),window.removeEventListener("wheel",this._wheelHandler,t)}},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(t,e){if(document.body.requestPointerLock){t&&document.addEventListener("pointerlockchange",(function e(){t(),document.removeEventListener("pointerlockchange",e)}),!1),e&&document.addEventListener("pointerlockerror",(function t(){e(),document.removeEventListener("pointerlockerror",t)}),!1),document.body.requestPointerLock()}else e&&e()},i.disablePointerLock=function(t){if(document.exitPointerLock){t&&document.addEventListener("pointerlockchange",(function e(){t(),document.removeEventListener("pointerlockchange",e)}),!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(t){return this._buttons[t]},i.wasPressed=function(t){return this._buttons[t]&&!this._lastbuttons[t]},i.wasReleased=function(t){return!this._buttons[t]&&this._lastbuttons[t]},i._handleUp=function(t){this._buttons[t.button]=!1;var e=new Kr(this,t);e.event&&this.fire(Ur,e)},i._handleDown=function(t){this._buttons[t.button]=!0;var e=new Kr(this,t);e.event&&this.fire(Fr,e)},i._handleMove=function(t){var e=new Kr(this,t);e.event&&(this.fire(Br,e),this._lastX=e.x,this._lastY=e.y)},i._handleWheel=function(t){var e=new Kr(this,t);e.event&&this.fire(Nr,e)},i._getTargetCoords=function(t){var e=this._target.getBoundingClientRect(),i=Math.floor(e.left),n=Math.floor(e.top);return t.clientX=i+this._target.clientWidth||t.clientY=n+this._target.clientHeight?null:{x:t.clientX-i,y:t.clientY-n}},e}(P),Qr=function(){function t(t,e){void 0===e&&(e={}),this._keyboard=e.keyboard||null,this._mouse=e.mouse||null,this._gamepads=e.gamepads||null,this._element=null,this._actions={},this._axes={},this._axesValues={},t&&this.attach(t)}var e=t.prototype;return e.attach=function(t){this._element=t,this._keyboard&&this._keyboard.attach(t),this._mouse&&this._mouse.attach(t)},e.detach=function(){this._keyboard&&this._keyboard.detach(),this._mouse&&this._mouse.detach(),this._element=null},e.disableContextMenu=function(){this._mouse||this._enableMouse(),this._mouse.disableContextMenu()},e.enableContextMenu=function(){this._mouse||this._enableMouse(),this._mouse.enableContextMenu()},e.update=function(t){for(var e in this._keyboard&&this._keyboard.update(),this._mouse&&this._mouse.update(),this._gamepads&&this._gamepads.update(),this._axesValues={},this._axes)this._axesValues[e]=[]},e.appendAction=function(t,e){this._actions[t]=this._actions[t]||[],this._actions[t].push(e)},e.registerKeys=function(t,e){if(this._keyboard||this._enableKeyboard(),this._actions[t])throw new Error("Action: "+t+" already registered");if(void 0===e)throw new Error("Invalid button");e.length||(e=[e]),this.appendAction(t,{type:Or,keys:e})},e.registerMouse=function(t,e){if(this._mouse||this._enableMouse(),void 0===e)throw new Error("Invalid button");this.appendAction(t,{type:Dr,button:e})},e.registerPadButton=function(t,e,i){if(void 0===i)throw new Error("Invalid button");this.appendAction(t,{type:kr,button:i,pad:e})},e.registerAxis=function(t){var e=t.name;this._axes[e]||(this._axes[e]=[]);var i=this._axes[e].push(e);(t=t||{}).pad=t.pad||0;var n=function(n,s,r,a){switch(s){case"mousex":n._mouse.on(Br,(function(t){n._axesValues[e][i]=t.dx/10}));break;case"mousey":n._mouse.on(Br,(function(t){n._axesValues[e][i]=t.dy/10}));break;case"key":n._axes[e].push((function(){return n._keyboard.isPressed(a)?r:0}));break;case"padrx":n._axes[e].push((function(){return n._gamepads.getAxis(t.pad,2)}));break;case"padry":n._axes[e].push((function(){return n._gamepads.getAxis(t.pad,3)}));break;case"padlx":n._axes[e].push((function(){return n._gamepads.getAxis(t.pad,0)}));break;case"padly":n._axes[e].push((function(){return n._gamepads.getAxis(t.pad,1)}));break;default:throw new Error("Unknown axis")}};n(this,t.positive,1,t.positiveKey),(t.negativeKey||t.negative!==t.positive)&&n(this,t.negative,-1,t.negativeKey)},e.isPressed=function(t){if(!this._actions[t])return!1;for(var e=this._actions[t].length,i=0;iMath.abs(e)&&(e=s)}else this._axesValues[t]&&Math.abs(this._axesValues[t][n])>Math.abs(e)&&(e=this._axesValues[t][n]);return e},e._enableMouse=function(){if(this._mouse=new Zr,!this._element)throw new Error("Controller must be attached to an Element");this._mouse.attach(this._element)},e._enableKeyboard=function(){if(this._keyboard=new qr,!this._element)throw new Error("Controller must be attached to an Element");this._keyboard.attach(this._element)},t}(),$r=Object.freeze([]),Jr=function(){return $r};"undefined"!=typeof navigator&&(Jr=(navigator.getGamepads||navigator.webkitGetGamepads||Jr).bind(navigator));var ta={buttons:{PAD_FACE_1:0,PAD_FACE_2:1,PAD_FACE_3:2,PAD_FACE_4:3,PAD_L_SHOULDER_1:4,PAD_R_SHOULDER_1:5,PAD_L_SHOULDER_2:6,PAD_R_SHOULDER_2:7,PAD_SELECT:8,PAD_START:9,PAD_L_STICK_BUTTON:10,PAD_R_STICK_BUTTON:11,PAD_UP:12,PAD_DOWN:13,PAD_LEFT:14,PAD_RIGHT:15,PAD_VENDOR:16,XRPAD_TRIGGER:0,XRPAD_SQUEEZE:1,XRPAD_TOUCHPAD_BUTTON:2,XRPAD_STICK_BUTTON:3,XRPAD_A:4,XRPAD_B:5},axes:{PAD_L_STICK_X:0,PAD_L_STICK_Y:1,PAD_R_STICK_X:2,PAD_R_STICK_Y:3,XRPAD_TOUCHPAD_X:0,XRPAD_TOUCHPAD_Y:1,XRPAD_STICK_X:2,XRPAD_STICK_Y:3}},ea={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"]},DEFAULT_DUAL:{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_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"],synthesizedButtons:{PAD_UP:{axis:0,min:0,max:1},PAD_DOWN:{axis:0,min:-1,max:0},PAD_LEFT:{axis:0,min:-1,max:0},PAD_RIGHT:{axis:0,min:0,max:1}}},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"],mapping:"standard"},DEFAULT_XR:{buttons:["XRPAD_TRIGGER","XRPAD_SQUEEZE","XRPAD_TOUCHPAD_BUTTON","XRPAD_STICK_BUTTON","XRPAD_A","XRPAD_B"],axes:["XRPAD_TOUCHPAD_X","XRPAD_TOUCHPAD_Y","XRPAD_STICK_X","XRPAD_STICK_Y"],mapping:"xr-standard"}},ia={"Product: 0268":"PS3"},na={};function sa(t){var e=na[t.id];if(e)return e;for(var i in ia)if(-1!==t.id.indexOf(i)){var n=ia[i];if(!t.mapping){var s=ea["RAW_"+n];if(s)return s}return ea[n]}if("xr-standard"===t.mapping)return ea.DEFAULT_XR;var r=ea.DEFAULT,a=t.buttons.length0):(this.value=t.value,this.pressed=t.pressed,this.touched=null!=(i=t.touched)?i:t.value>0);e&&("number"==typeof e?(this.wasPressed=1!==e&&this.pressed,this.wasReleased=1===e&&!this.pressed,this.wasTouched=0===e&&this.touched):(this.wasPressed=!e.pressed&&this.pressed,this.wasReleased=e.pressed&&!this.pressed,this.wasTouched=!(null!=(n=e.touched)?n:e.value>0)&&this.touched))}return t.prototype.update=function(t){var e,i=t.value,n=t.pressed,s=null!=(e=t.touched)?e:i>0;this.wasPressed=!this.pressed&&n,this.wasReleased=this.pressed&&!n,this.wasTouched=!this.touched&&s,this.value=i,this.pressed=n,this.touched=s},t}(),ha=Object.freeze(new oa(0)),la=function(){function t(t,e){this._compiledMapping={buttons:[],axes:[]},this.id=t.id,this.index=t.index,this._buttons=t.buttons.map((function(t){return new oa(t)})),this._axes=[].concat(t.axes),this._previousAxes=[].concat(t.axes),this.mapping=e.mapping,this.map=e,this.hand=t.hand||"none",this.pad=t,this._compileMapping()}var e,i=t.prototype;return i._compileMapping=function(){var t=this,e=this._compiledMapping,i=e.axes,n=e.buttons,s=ta.axes,r=ta.buttons;i.length=0,n.length=0,this.map.axes&&this.map.axes.forEach((function(e,n){i[s[e]]=function(){return t.pad.axes[n]||0}}));for(var a=0,o=i.length;ara?e:0},y(t,[{key:"connected",get:function(){return this.pad.connected}},{key:"axes",get:function(){return this._compiledMapping.axes.map((function(t){return t()}))}},{key:"buttons",get:function(){return this._compiledMapping.buttons.map((function(t){return t()}))}}]),t}(),ca=function(t){function e(){var e;return(e=t.call(this)||this).gamepadsSupported=G.gamepads,e.current=[],e._previous=[],e._ongamepadconnectedHandler=e._ongamepadconnected.bind(w(e)),e._ongamepaddisconnectedHandler=e._ongamepaddisconnected.bind(w(e)),window.addEventListener("gamepadconnected",e._ongamepadconnectedHandler,!1),window.addEventListener("gamepaddisconnected",e._ongamepaddisconnectedHandler,!1),e.poll(),e}S(e,t);var i=e.prototype;return i._ongamepadconnected=function(t){for(var e=new la(t.gamepad,this.getMap(t.gamepad)),i=this.current,n=i.findIndex((function(t){return t.index===e.index}));-1!==n;)i.splice(n,1),n=i.findIndex((function(t){return t.index===e.index}));i.push(e),this.fire(zr,e)},i._ongamepaddisconnected=function(t){var e=this.current,i=e.findIndex((function(e){return e.index===t.gamepad.index}));-1!==i&&(this.fire(Vr,e[i]),e.splice(i,1))},i.update=function(){this.poll()},i.poll=function(t){void 0===t&&(t=[]),t.length>0&&(t.length=0);for(var e=Jr(),i=0,n=e.length;i=0?t.ResponseType.ARRAY_BUFFER:".json"===n?t.ResponseType.JSON:".xml"===n?t.ResponseType.DOCUMENT:t.ResponseType.TEXT},e._isBinaryContentType=function(e){return[t.ContentType.BASIS,t.ContentType.BIN,t.ContentType.DDS,t.ContentType.GLB,t.ContentType.MP3,t.ContentType.MP4,t.ContentType.OGG,t.ContentType.OPUS,t.ContentType.WAV].indexOf(e)>=0},e._isBinaryResponseType=function(e){return e===t.ResponseType.ARRAY_BUFFER||e===t.ResponseType.BLOB||e===t.ResponseType.JSON},e._onReadyStateChange=function(t,e,i,n){if(4===n.readyState)switch(n.status){case 0:n.responseURL&&n.responseURL.startsWith("file:///")?this._onSuccess(t,e,i,n):this._onError(t,e,i,n);break;case 200:case 201:case 206:case 304:this._onSuccess(t,e,i,n);break;default:this._onError(t,e,i,n)}},e._onSuccess=function(e,i,n,s){var r,a,o=s.getResponseHeader("Content-Type");o&&(a=o.split(";")[0].trim());try{r=this._isBinaryContentType(a)||this._isBinaryResponseType(s.responseType)?s.response:a===t.ContentType.JSON||i.split("?")[0].endsWith(".json")?JSON.parse(s.responseText):s.responseType===t.ResponseType.DOCUMENT||a===t.ContentType.XML?s.responseXML:s.responseText,n.callback(null,r)}catch(t){n.callback(t)}},e._onError=function(e,i,n,s){var r=this;if(!n.retrying)if(n.retry&&n.retriesn)return 0;var o=0;return r===ee?o=1-s*(a-i)/(n-i):r===ie?o=i/(i+s*(a-i)):r===ne&&(o=Math.pow(a/i,-s)),_t.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*e}},getMaxDistance:function(){return this.maxDistance},setMaxDistance:function(t){this.maxDistance=t},getMinDistance:function(){return this.minDistance},setMinDistance:function(t){this.minDistance=t},getRollOffFactor:function(){return this.rollOffFactor},setRollOffFactor:function(t){this.rollOffFactor=t},getDistanceModel:function(){return this.distanceModel},setDistanceModel:function(t){this.distanceModel=t}})}var Sa=function(){function t(t){this._manager=t,this.position=new wt,this.velocity=new wt,this.orientation=new Ft}var e=t.prototype;return e.getPosition=function(){return this.position},e.setPosition=function(t){this.position.copy(t);var e=this.listener;e&&("positionX"in e?(e.positionX.value=t.x,e.positionY.value=t.y,e.positionZ.value=t.z):e.setPosition&&e.setPosition(t.x,t.y,t.z))},e.getVelocity=function(){return this.velocity},e.setVelocity=function(t){},e.setOrientation=function(t){this.orientation.copy(t);var e=this.listener;if(e){var i=t.data;"forwardX"in e?(e.forwardX.value=-i[8],e.forwardY.value=-i[9],e.forwardZ.value=-i[10],e.upX.value=i[4],e.upY.value=i[5],e.upZ.value=i[6]):e.setOrientation&&e.setOrientation(-i[8],-i[9],-i[10],i[4],i[5],i[6])}},e.getOrientation=function(){return this.orientation},y(t,[{key:"listener",get:function(){var t=this._manager.context;return t?t.listener:null}}]),t}(),ba="running",wa=["click","touchstart","mousedown"],Ta=function(t){function e(){var e;return(e=t.call(this)||this)._context=null,e.AudioContext="undefined"!=typeof AudioContext&&AudioContext||"undefined"!=typeof webkitAudioContext&&webkitAudioContext,e.AudioContext,e._unlockHandlerFunc=e._unlockHandler.bind(w(e)),e._userSuspended=!1,e.listener=new Sa(w(e)),e._volume=1,e}S(e,t);var i=e.prototype;return i.suspend=function(){this._userSuspended||(this._userSuspended=!0,this._context&&this._context.state===ba&&this._suspend())},i.resume=function(){this._userSuspended&&(this._userSuspended=!1,this._context&&this._context.state!==ba&&this._resume())},i.destroy=function(){var t;(this.fire("destroy"),this._context)&&(this._removeUnlockListeners(),null==(t=this._context)||t.close(),this._context=null)},i.playSound=function(t,e){void 0===e&&(e={});var i=null;return ga&&(i=new ga(this,t,e)).play(),i},i.playSound3d=function(t,e,i){void 0===i&&(i={});var n=null;return ya&&((n=new ya(this,t,i)).setPosition(e),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._resume=function(){var t=this;this._context.resume().then((function(){var e=t._context.createBufferSource();e.buffer=t._context.createBuffer(1,1,t._context.sampleRate),e.connect(t._context.destination),e.start(0),e.onended=function(i){e.disconnect(0),t.fire("resume")}}),(function(t){})).catch((function(t){}))},i._suspend=function(){var t=this;this._context.suspend().then((function(){t.fire("suspend")}),(function(t){})).catch((function(t){}))},i._unlockHandler=function(){this._removeUnlockListeners(),this._userSuspended||this._context.state===ba||this._resume()},i._registerUnlockListeners=function(){var t=this;wa.forEach((function(e){window.addEventListener(e,t._unlockHandlerFunc,!1)}))},i._removeUnlockListeners=function(){var t=this;wa.forEach((function(e){window.removeEventListener(e,t._unlockHandlerFunc,!1)}))},y(e,[{key:"volume",get:function(){return this._volume},set:function(t){t=_t.clamp(t,0,1),this._volume=t,this.fire("volumechange",t)}},{key:"suspended",get:function(){return this._userSuspended}},{key:"context",get:function(){return!this._context&&this.AudioContext&&(this._context=new this.AudioContext,this._context.state!==ba&&this._registerUnlockListeners()),this._context}}]),e}(P),Aa=function(){function t(t){this.audio=void 0,this.buffer=void 0,t instanceof Audio?this.audio=t:this.buffer=t}return y(t,[{key:"duration",get:function(){var t=0;return this.buffer?t=this.buffer.duration:this.audio&&(t=this.audio.duration),t||0}}]),t}();function Ca(t,e){return t%e||0}var Ea=function(t){function e(e,i,n){var s;return(s=t.call(this)||this).source=null,s._manager=e,s._volume=void 0!==n.volume?_t.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,va()?(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(w(s))):(s._isReady=!1,s._loadedMetadataHandler=s._onLoadedMetadata.bind(w(s)),s._timeUpdateHandler=s._onTimeUpdate.bind(w(s)),s._endedHandler=s._onEnded.bind(w(s)),s._createSource()),s}S(e,t);var i=e.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 t=Ca(this._startOffset,this.duration);t=Ca(this._startTime+t,this._sound.duration),this._startOffset=null,this._duration?this.source.start(0,t,this._duration):this.source.start(0,t),this._startedAt=this._manager.context.currentTime,this._currentTime=0,this._currentOffset=t,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;var t=this.currentTime;return this._state=0,this._waitingContextSuspension||(this.source||this._createSource(),null!==this._startOffset&&(t=Ca(this._startOffset,this.duration),t=Ca(this._startTime+t,this._sound.duration),this._startOffset=null),this._duration?this.source.start(0,t,this._duration):this.source.start(0,t),this._startedAt=this._manager.context.currentTime,this._currentOffset=t,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 t=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++,t&&this.source&&this.source.stop(0),this.source=null,this._suspendInstanceEvents||this._onStop()),!0},i.setExternalNodes=function(t,e){if(t){e||(e=t);var i=this._manager.context.destination;this._firstNode!==t&&(this._firstNode?this._connectorNode.disconnect(this._firstNode):this._connectorNode.disconnect(i),this._firstNode=t,this._connectorNode.connect(t)),this._lastNode!==e&&(this._lastNode&&this._lastNode.disconnect(i),this._lastNode=e,this._lastNode.connect(i))}else console.error("The firstNode must be a valid Audio Node")},i.clearExternalNodes=function(){var t=this._manager.context.destination;this._firstNode&&(this._connectorNode.disconnect(this._firstNode),this._firstNode=null),this._lastNode&&(this._lastNode.disconnect(t),this._lastNode=null),this._connectorNode.connect(t)},i.getExternalNodes=function(){return[this._firstNode,this._lastNode]},i._createSource=function(){if(!this._sound)return null;var t=this._manager.context;return this._sound.buffer&&(this.source=t.createBufferSource(),this.source.buffer=this._sound.buffer,this.source.connect(this._inputNode),this.source.onended=this._endedHandler,this.source.loopStart=Ca(this._startTime,this.source.buffer.duration),this._duration&&(this.source.loopEnd=Math.max(this.source.loopStart,Ca(this._startTime+this._duration,this.source.buffer.duration)))),this.source},i._updateCurrentTime=function(){this._currentTime=Ca((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)},y(e,[{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(t){if(!(t<0))if(0===this._state){var e=this._suspendInstanceEvents;this._suspendInstanceEvents=!0,this.stop(),this._startOffset=t,this.play(),this._suspendInstanceEvents=e}else this._startOffset=t,this._currentTime=t}},{key:"duration",get:function(){return this._sound?this._duration?Ca(this._duration,this._sound.duration):this._sound.duration:0},set:function(t){this._duration=Math.max(0,Number(t)||0);var e=0===this._state;this.stop(),e&&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(t){this._loop=!!t,this.source&&(this.source.loop=this._loop)}},{key:"pitch",get:function(){return this._pitch},set:function(t){this._currentOffset=this.currentTime,this._startedAt=this._manager.context.currentTime,this._pitch=Math.max(Number(t)||0,.01),this.source&&(this.source.playbackRate.value=this._pitch)}},{key:"sound",get:function(){return this._sound},set:function(t){this._sound=t,2!==this._state?this.stop():this._createSource()}},{key:"startTime",get:function(){return this._startTime},set:function(t){this._startTime=Math.max(0,Number(t)||0);var e=0===this._state;this.stop(),e&&this.play()}},{key:"volume",get:function(){return this._volume},set:function(t){t=_t.clamp(t,0,1),this._volume=t,this.gain&&(this.gain.gain.value=t*this._manager.volume)}}]),e}(P);va()||(Object.assign(Ea.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 t=Ca(this._startOffset,this.duration);t=Ca(this._startTime+t,this._sound.duration),this._startOffset=null,this.source.currentTime=t},_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>Ca(this._startTime+this._duration,this.source.duration)&&(this.loop?this.source.currentTime=Ca(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(Ea.prototype,"volume",{get:function(){return this._volume},set:function(t){t=_t.clamp(t,0,1),this._volume=t,this.source&&(this.source.volume=t*this._manager.volume)}}),Object.defineProperty(Ea.prototype,"pitch",{get:function(){return this._pitch},set:function(t){this._pitch=Math.max(Number(t)||0,.01),this.source&&(this.source.playbackRate=this._pitch)}}),Object.defineProperty(Ea.prototype,"sound",{get:function(){return this._sound},set:function(t){this.stop(),this._sound=t}}),Object.defineProperty(Ea.prototype,"currentTime",{get:function(){return null!==this._startOffset?this._startOffset:2!==this._state&&this.source?this.source.currentTime-this._startTime:0},set:function(t){t<0||(this._startOffset=t,this.source&&this._isReady&&(this.source.currentTime=Ca(this._startTime+Ca(t,this.duration),this._sound.duration),this._startOffset=null))}}));var Ma=function(t){function e(e,i,n){var s;return void 0===n&&(n={}),(s=t.call(this,e,i,n)||this)._position=new wt,s._velocity=new wt,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:ee,s}return S(e,t),e.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)},y(e,[{key:"position",get:function(){return this._position},set:function(t){this._position.copy(t);var e=this.panner;"positionX"in e?(e.positionX.value=t.x,e.positionY.value=t.y,e.positionZ.value=t.z):e.setPosition&&e.setPosition(t.x,t.y,t.z)}},{key:"velocity",get:function(){return this._velocity},set:function(t){this._velocity.copy(t)}},{key:"maxDistance",get:function(){return this.panner.maxDistance},set:function(t){this.panner.maxDistance=t}},{key:"refDistance",get:function(){return this.panner.refDistance},set:function(t){this.panner.refDistance=t}},{key:"rollOffFactor",get:function(){return this.panner.rolloffFactor},set:function(t){this.panner.rolloffFactor=t}},{key:"distanceModel",get:function(){return this.panner.distanceModel},set:function(t){this.panner.distanceModel=t}}]),e}(Ea);if(!va()){var Pa=new wt;Object.defineProperty(Ma.prototype,"position",{get:function(){return this._position},set:function(t){if(this._position.copy(t),this.source){var e=function(t,e,i,n,s,r){var a=(Pa=Pa.sub2(t,e)).length();if(an)return 0;var o=0;return r===ee?o=1-s*(a-i)/(n-i):r===ie?o=i/(i+s*(a-i)):r===ne&&(o=Math.pow(a/i,-s)),_t.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*e*this._manager.volume}}}),Object.defineProperty(Ma.prototype,"maxDistance",{get:function(){return this._maxDistance},set:function(t){this._maxDistance=t}}),Object.defineProperty(Ma.prototype,"refDistance",{get:function(){return this._refDistance},set:function(t){this._refDistance=t}}),Object.defineProperty(Ma.prototype,"rollOffFactor",{get:function(){return this._rollOffFactor},set:function(t){this._rollOffFactor=t}}),Object.defineProperty(Ma.prototype,"distanceModel",{get:function(){return this._distanceModel},set:function(t){this._distanceModel=t}})}var Ra="none",Ia="linear",La={0:"PCF3",1:"VSM8",2:"VSM16",3:"VSM32",4:"PCF5",5:"PCF1",6:"PCSS"},Da="mul",Oa=32,ka=128,Fa=256,Ba=512,Ua=1024,Na=2048,za=4096,Va=8192,Ga=function(){function t(){this._refCount=0}var e=t.prototype;return e.incRefCount=function(){this._refCount++},e.decRefCount=function(){this._refCount--},y(t,[{key:"refCount",get:function(){return this._refCount}}]),t}(),Ha=function(){function t(){}return t.set=function(e){t._graphicsDevice=e},t.get=function(){return t._graphicsDevice},t}();Ha._graphicsDevice=null;var Wa=0,Xa=function(){function t(){this.initDefaults()}var e=t.prototype;return e.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},e._changeVertexCount=function(t,e){this.vertexCount||(this.vertexCount=t)},t}();Xa.DEFAULT_COMPONENTS_POSITION=3,Xa.DEFAULT_COMPONENTS_NORMAL=3,Xa.DEFAULT_COMPONENTS_UV=2,Xa.DEFAULT_COMPONENTS_COLORS=4;var ja=function(t,e,i,n){this.data=t,this.componentCount=e,this.dataType=i,this.dataTypeNormalize=n},qa=function(t){function e(e){var i;return(i=t.call(this)||this)._aabbVer=0,i.id=Wa++,i.device=e||Ha.get(),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 Ht,i.boneAabb=null,i}S(e,t);var i=e.prototype;return i.destroy=function(){var t=this.morph;t&&(this.morph=null,t.refCount<1&&t.destroy()),this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);for(var e=0;e0){var S=v.array[v.index+x];if(u[S]=!0,e=m.array[m.index],i=m.array[m.index+1],n=m.array[m.index+2],s=c[S],(r=l[S]).x>e&&(r.x=e),r.y>i&&(r.y=i),r.z>n&&(r.z=n),s.xb&&(r.x=b),r.y>w&&(r.y=w),r.z>T&&(r.z=T),s.x0&&this.indexBuffer[0]&&(this._geometryData.indexCount=this.indexBuffer[0].numIndices,this._geometryData.maxIndices=this.indexBuffer[0].numIndices))},i.clear=function(t,e,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=t?0:1,this._geometryData.indicesUsage=e?0:1},i.setVertexStream=function(t,e,i,n,s,r){void 0===s&&(s=6),void 0===r&&(r=!1),this._initGeometryData();var a=n||e.length/i;this._geometryData._changeVertexCount(a,t),this._geometryData.vertexStreamsUpdated=!0,this._geometryData.vertexStreamDictionary[t]=new ja(e,i,s,r)},i.getVertexStream=function(t,e){var i=0,n=!1;if(this._geometryData){var s=this._geometryData.vertexStreamDictionary[t];s&&(n=!0,i=this._geometryData.vertexCount,ArrayBuffer.isView(e)?e.set(s.data):(e.length=0,e.push(s.data)))}n||this.vertexBuffer&&(i=new Lr(this.vertexBuffer).readData(t,e));return i},i.setPositions=function(t,e,i){void 0===e&&(e=Xa.DEFAULT_COMPONENTS_POSITION),this.setVertexStream(we,t,e,i,6,!1)},i.setNormals=function(t,e,i){void 0===e&&(e=Xa.DEFAULT_COMPONENTS_NORMAL),this.setVertexStream(Te,t,e,i,6,!1)},i.setUvs=function(t,e,i,n){void 0===i&&(i=Xa.DEFAULT_COMPONENTS_UV),this.setVertexStream(Pe+t,e,i,n,6,!1)},i.setColors=function(t,e,i){void 0===e&&(e=Xa.DEFAULT_COMPONENTS_COLORS),this.setVertexStream(Me,t,e,i,6,!1)},i.setColors32=function(t,e){this.setVertexStream(Me,t,Xa.DEFAULT_COMPONENTS_COLORS,e,mi,!0)},i.setIndices=function(t,e){this._initGeometryData(),this._geometryData.indexStreamUpdated=!0,this._geometryData.indices=t,this._geometryData.indexCount=e||t.length},i.getPositions=function(t){return this.getVertexStream(we,t)},i.getNormals=function(t){return this.getVertexStream(Te,t)},i.getUvs=function(t,e){return this.getVertexStream(Pe+t,e)},i.getColors=function(t){return this.getVertexStream(Me,t)},i.getIndices=function(t){var e=0;if(this._geometryData&&this._geometryData.indices){var i=this._geometryData.indices;if(e=this._geometryData.indexCount,ArrayBuffer.isView(t))t.set(i);else{t.length=0;for(var n=0,s=i.length;n0&&this.indexBuffer[0])e=this.indexBuffer[0].readData(t)}return e},i.update=function(t,e){if(void 0===t&&(t=4),void 0===e&&(e=!0),this._geometryData){if(e){var i=this._geometryData.vertexStreamDictionary[we];i&&3===i.componentCount&&(this._aabb.compute(i.data,this._geometryData.vertexCount),this._aabbVer++)}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=t,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(t){var e=[];for(var i in this._geometryData.vertexStreamDictionary){var n=this._geometryData.vertexStreamDictionary[i];e.push({semantic:i,components:n.componentCount,type:n.dataType,normalize:n.dataTypeNormalize})}return new Ji(this.device,e,t)},i._updateVertexBuffer=function(){if(!this.vertexBuffer){var t=this._geometryData.maxVertices,e=this._buildVertexFormat(t);this.vertexBuffer=new ji(this.device,e,t,this._geometryData.verticesUsage)}var i=new Lr(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 t=this._geometryData.maxVertices>65535?2:1;this.indexBuffer[0]=new vr(this.device,t,this._geometryData.maxIndices,this._geometryData.indicesUsage)}var e=this._geometryData.indices;e&&(this.indexBuffer[0].writeData(e,this._geometryData.indexCount),this._geometryData.indices=null)},i.prepareRenderState=function(t){1===t?this.generateWireframe():2===t&&(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 t,e=this.vertexBuffer.numVertices,i=[];if(this.indexBuffer.length>0&&this.indexBuffer[0]){for(var n=[[0,1],[1,2],[2,0]],s=this.primitive[0].base,r=this.primitive[0].count,a=this.indexBuffer[0],o=new Mi[a.format](a.storage),h=new Set,l=s;ld?d*e+u:u*e+d;h.has(f)||(h.add(f),i.push(u,d))}t=a.format}else{for(var p=0;p65535?2:1}var m=new vr(this.vertexBuffer.device,t,i.length);new Mi[m.format](m.storage).set(i),m.unlock(),this.primitive[1]={type:1,base:0,count:i.length,indexed:!0},this.indexBuffer[1]=m},y(e,[{key:"morph",get:function(){return this._morph},set:function(t){t!==this._morph&&(this._morph&&this._morph.decRefCount(),this._morph=t,t&&t.incRefCount())}},{key:"aabb",get:function(){return this._aabb},set:function(t){this._aabb=t,this._aabbVer++}}]),e}(Ga),Ya=4/64,Ka=1-2*Ya,Za=[];function Qa(t,e){for(var i=e.length/3,n=t.length/3,s=new wt,r=new wt,a=new wt,o=new wt,h=new wt,l=new wt,c=[],u=0;u0)for(var g=0;g<=n;g++)for(var y=0;y<=s;y++){var x=y/s*2*Math.PI-Math.PI,S=Math.sin(x),b=Math.cos(x);u.set(S*t,-i/2,b*t),c.set(S*e,i/2,b*e),o.lerp(u,c,g/n),h.sub2(c,u).normalize(),d.set(b,0,-S),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=g/n;m.push(w,1-T);var A=T;if(T=w,w=(w=A)*Ka+Ya,T=T*Ka+Ya,w/=3,_.push(w,1-T),g0)for(var ut=0;ut1&&v.push(a,a+ut,a+ut-1)}if(a+=s,e>0)for(var gt=0;gt1&&v.push(a,a+gt-1,a+gt)}}return{positions:f,normals:p,uvs:m,uvs1:_,indices:v}}function io(t,e){var i,n,s,r,a;void 0===e&&(e={});var o=null!=(i=e.radius)?i:.5,h=null!=(n=e.height)?n:1,l=null!=(s=e.heightSegments)?s:5,c=null!=(r=e.capSegments)?r:20,u=null!=(a=e.calculateTangents)&&a,d=eo(o,o,h,l,c,!1);return u&&(d.tangents=$a(d.positions,d.normals,d.uvs,d.indices)),Ja(t,d.positions,d)}function no(t,e){var i,n,s,r,a;void 0===e&&(e={});var o=null!=(i=e.radius)?i:.3,h=null!=(n=e.height)?n:1,l=null!=(s=e.heightSegments)?s:1,c=null!=(r=e.sides)?r:20,u=null!=(a=e.calculateTangents)&&a,d=eo(o,o,h-2*o,l,c,!0);return u&&(d.tangents=$a(d.positions,d.normals,d.uvs,d.indices)),Ja(t,d.positions,d)}function so(t,e){var i,n,s,r,a,o;void 0===e&&(e={});var h=null!=(i=e.baseRadius)?i:.5,l=null!=(n=e.peakRadius)?n:0,c=null!=(s=e.height)?s:1,u=null!=(r=e.heightSegments)?r:5,d=null!=(a=e.capSegments)?a:18,f=null!=(o=e.calculateTangents)&&o,p=eo(h,l,c,u,d,!1);return f&&(p.tangents=$a(p.positions,p.normals,p.uvs,p.indices)),Ja(t,p.positions,p)}function ro(t,e){var i,n,s,r;void 0===e&&(e={});for(var a=null!=(i=e.radius)?i:.5,o=null!=(n=e.latitudeBands)?n:16,h=null!=(s=e.longitudeBands)?s:16,l=null!=(r=e.calculateTangents)&&r,c=[],u=[],d=[],f=[],p=0;p<=o;p++)for(var m=p*Math.PI/o,_=Math.sin(m),v=Math.cos(m),g=0;g<=h;g++){var y=2*g*Math.PI/h-Math.PI/2,x=Math.sin(y),S=Math.cos(y)*_,b=v,w=x*_,T=1-g/h,A=1-p/o;c.push(S*a,b*a,w*a),u.push(S,b,w),d.push(T,1-A)}for(var C=0;C shadowZ ? 1.0 : 0.0;\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\tfloat getShadowOmniClusteredPCF3(sampler2D shadowMap, vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {\n\t\tfloat shadowTextureResolution = shadowParams.x;\n\t\tvec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n\t\tfloat shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;\n\t\tvec3 shadowCoord = vec3(uv, shadowZ);\n\t\treturn getShadowPCF3x3(shadowMap, shadowCoord, shadowParams);\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\tfloat getShadowOmniClusteredPCF5(sampler2D shadowMap, vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {\n\t\tfloat shadowTextureResolution = shadowParams.x;\n\t\tvec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n\t\tfloat shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;\n\t\tvec3 shadowCoord = vec3(uv, shadowZ);\n\t\treturn getShadowPCF3x3(shadowMap, shadowCoord, shadowParams);\n\t}\n\t#endif\n#endif\n#ifdef GL2\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\tfloat getShadowSpotClusteredPCF1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\t\treturn textureShadow(shadowMap, shadowCoord);\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\tfloat getShadowSpotClusteredPCF3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\t\treturn getShadowSpotPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\tfloat getShadowSpotClusteredPCF5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\t\treturn getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);\n\t}\n\t#endif\n#else\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\tfloat getShadowSpotClusteredPCF1(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n\t\tfloat depth = unpackFloat(textureShadow(shadowMap, shadowCoord.xy));\n\t\treturn depth > shadowCoord.z ? 1.0 : 0.0;\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\tfloat getShadowSpotClusteredPCF3(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n\t\treturn getShadowSpotPCF3x3(shadowMap, shadowCoord, shadowParams);\n\t}\n\t#endif\n\t#if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\tfloat getShadowSpotClusteredPCF5(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n\t\treturn getShadowSpotPCF3x3(shadowMap, shadowCoord, shadowParams);\n\t}\n\t#endif\n#endif\n",clusteredLightUtilsPS:"\nvec2 getCubemapFaceCoordinates(const vec3 dir, out float faceIndex, out vec2 tileOffset)\n{\n\tvec3 vAbs = abs(dir);\n\tfloat ma;\n\tvec2 uv;\n\tif (vAbs.z >= vAbs.x && vAbs.z >= vAbs.y) {\n\t\tfaceIndex = dir.z < 0.0 ? 5.0 : 4.0;\n\t\tma = 0.5 / vAbs.z;\n\t\tuv = vec2(dir.z < 0.0 ? -dir.x : dir.x, -dir.y);\n\t\ttileOffset.x = 2.0;\n\t\ttileOffset.y = dir.z < 0.0 ? 1.0 : 0.0;\n\t} else if(vAbs.y >= vAbs.x) {\n\t\tfaceIndex = dir.y < 0.0 ? 3.0 : 2.0;\n\t\tma = 0.5 / vAbs.y;\n\t\tuv = vec2(dir.x, dir.y < 0.0 ? -dir.z : dir.z);\n\t\ttileOffset.x = 1.0;\n\t\ttileOffset.y = dir.y < 0.0 ? 1.0 : 0.0;\n\t} else {\n\t\tfaceIndex = dir.x < 0.0 ? 1.0 : 0.0;\n\t\tma = 0.5 / vAbs.x;\n\t\tuv = vec2(dir.x < 0.0 ? dir.z : -dir.z, -dir.y);\n\t\ttileOffset.x = 0.0;\n\t\ttileOffset.y = dir.x < 0.0 ? 1.0 : 0.0;\n\t}\n\treturn uv * ma + 0.5;\n}\nvec2 getCubemapAtlasCoordinates(const vec3 omniAtlasViewport, float shadowEdgePixels, float shadowTextureResolution, const vec3 dir) {\n\tfloat faceIndex;\n\tvec2 tileOffset;\n\tvec2 uv = getCubemapFaceCoordinates(dir, faceIndex, tileOffset);\n\tfloat atlasFaceSize = omniAtlasViewport.z;\n\tfloat tileSize = shadowTextureResolution * atlasFaceSize;\n\tfloat offset = shadowEdgePixels / tileSize;\n\tuv = uv * vec2(1.0 - offset * 2.0) + vec2(offset * 1.0);\n\tuv *= atlasFaceSize;\n\tuv += tileOffset * atlasFaceSize;\n\tuv += omniAtlasViewport.xy;\n\treturn uv;\n}\n",clusteredLightPS:"\nuniform highp sampler2D clusterWorldTexture;\nuniform highp sampler2D lightsTexture8;\nuniform highp sampler2D lightsTextureFloat;\n#if defined(CLUSTER_COOKIES)\n\t#define CLUSTER_COOKIES_OR_SHADOWS\n#endif\n#if defined(CLUSTER_SHADOWS)\n\t#define CLUSTER_COOKIES_OR_SHADOWS\n#endif\n#ifdef CLUSTER_SHADOWS\n\t#ifdef GL2\n\t\tuniform sampler2DShadow shadowAtlasTexture;\n\t#else\n\t\tuniform sampler2D shadowAtlasTexture;\n\t#endif\n#endif\n#ifdef CLUSTER_COOKIES\n\tuniform sampler2D cookieAtlasTexture;\n#endif\n#ifdef GL2\n\tuniform int clusterMaxCells;\n#else\n\tuniform float clusterMaxCells;\n\tuniform vec4 lightsTextureInvSize;\n#endif\nuniform float clusterSkip;\nuniform vec3 clusterCellsCountByBoundsSize;\nuniform vec3 clusterTextureSize;\nuniform vec3 clusterBoundsMin;\nuniform vec3 clusterBoundsDelta;\nuniform vec3 clusterCellsDot;\nuniform vec3 clusterCellsMax;\nuniform vec2 clusterCompressionLimit0;\nuniform vec2 shadowAtlasParams;\nstruct ClusterLightData {\n\tvec3 halfWidth;\n\tfloat lightType;\n\tvec3 halfHeight;\n\t#ifdef GL2\n\t\tint lightIndex;\n\t#else\n\t\tfloat lightV;\n\t#endif\n\tvec3 position;\n\tfloat shape;\n\tvec3 direction;\n\tfloat falloffMode;\n\tvec3 color;\n\tfloat shadowIntensity;\n\tvec3 omniAtlasViewport;\n\tfloat range;\n\tvec4 cookieChannelMask;\n\tfloat shadowBias;\n\tfloat shadowNormalBias;\n\tfloat innerConeAngleCos;\n\tfloat outerConeAngleCos;\n\tfloat cookie;\n\tfloat cookieRgb;\n\tfloat cookieIntensity;\n\tfloat mask;\n};\nmat4 lightProjectionMatrix;\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.lightType > 0.5 )\n#define isClusteredLightFalloffLinear(light) ( light.falloffMode < 0.5 )\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#ifdef CLUSTER_MESH_DYNAMIC_LIGHTS\n\t#define acceptLightMask(light) ( light.mask < 0.75)\n#else\n\t#define acceptLightMask(light) ( light.mask > 0.25)\n#endif\nvec4 decodeClusterLowRange4Vec4(vec4 d0, vec4 d1, vec4 d2, vec4 d3) {\n\treturn vec4(\n\t\tbytes2floatRange4(d0, -2.0, 2.0),\n\t\tbytes2floatRange4(d1, -2.0, 2.0),\n\t\tbytes2floatRange4(d2, -2.0, 2.0),\n\t\tbytes2floatRange4(d3, -2.0, 2.0)\n\t);\n}\n#ifdef GL2\n\tvec4 sampleLightsTexture8(const ClusterLightData clusterLightData, int index) {\n\t\treturn texelFetch(lightsTexture8, ivec2(index, clusterLightData.lightIndex), 0);\n\t}\n\tvec4 sampleLightTextureF(const ClusterLightData clusterLightData, int index) {\n\t\treturn texelFetch(lightsTextureFloat, ivec2(index, clusterLightData.lightIndex), 0);\n\t}\n#else\n\tvec4 sampleLightsTexture8(const ClusterLightData clusterLightData, float index) {\n\t\treturn texture2DLodEXT(lightsTexture8, vec2(index * lightsTextureInvSize.z, clusterLightData.lightV), 0.0);\n\t}\n\tvec4 sampleLightTextureF(const ClusterLightData clusterLightData, float index) {\n\t\treturn texture2DLodEXT(lightsTextureFloat, vec2(index * lightsTextureInvSize.x, clusterLightData.lightV), 0.0);\n\t}\n#endif\nvoid decodeClusterLightCore(inout ClusterLightData clusterLightData, float lightIndex) {\n\t#ifdef GL2\n\t\tclusterLightData.lightIndex = int(lightIndex);\n\t#else\n\t\tclusterLightData.lightV = (lightIndex + 0.5) * lightsTextureInvSize.w;\n\t#endif\n\tvec4 lightInfo = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_FLAGS);\n\tclusterLightData.lightType = lightInfo.x;\n\tclusterLightData.shape = lightInfo.y;\n\tclusterLightData.falloffMode = lightInfo.z;\n\tclusterLightData.shadowIntensity = lightInfo.w;\n\tvec4 colorA = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COLOR_A);\n\tvec4 colorB = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COLOR_B);\n\tclusterLightData.color = vec3(bytes2float2(colorA.xy), bytes2float2(colorA.zw), bytes2float2(colorB.xy)) * clusterCompressionLimit0.y;\n\tclusterLightData.cookie = colorB.z;\n\tclusterLightData.mask = colorB.w;\n\t#ifdef CLUSTER_TEXTURE_FLOAT\n\t\tvec4 lightPosRange = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_POSITION_RANGE);\n\t\tclusterLightData.position = lightPosRange.xyz;\n\t\tclusterLightData.range = lightPosRange.w;\n\t\tvec4 lightDir_Unused = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_SPOT_DIRECTION);\n\t\tclusterLightData.direction = lightDir_Unused.xyz;\n\t#else\n\t\tvec4 encPosX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_POSITION_X);\n\t\tvec4 encPosY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_POSITION_Y);\n\t\tvec4 encPosZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_POSITION_Z);\n\t\tclusterLightData.position = vec3(bytes2float4(encPosX), bytes2float4(encPosY), bytes2float4(encPosZ)) * clusterBoundsDelta + clusterBoundsMin;\n\t\tvec4 encRange = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_RANGE);\n\t\tclusterLightData.range = bytes2float4(encRange) * clusterCompressionLimit0.x;\n\t\tvec4 encDirX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_DIRECTION_X);\n\t\tvec4 encDirY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_DIRECTION_Y);\n\t\tvec4 encDirZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_DIRECTION_Z);\n\t\tclusterLightData.direction = vec3(bytes2float4(encDirX), bytes2float4(encDirY), bytes2float4(encDirZ)) * 2.0 - 1.0;\n\t#endif\n}\nvoid decodeClusterLightSpot(inout ClusterLightData clusterLightData) {\n\tvec4 coneAngle = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_ANGLES);\n\tclusterLightData.innerConeAngleCos = bytes2float2(coneAngle.xy) * 2.0 - 1.0;\n\tclusterLightData.outerConeAngleCos = bytes2float2(coneAngle.zw) * 2.0 - 1.0;\n}\nvoid decodeClusterLightOmniAtlasViewport(inout ClusterLightData clusterLightData) {\n\t#ifdef CLUSTER_TEXTURE_FLOAT\n\t\tclusterLightData.omniAtlasViewport = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_0).xyz;\n\t#else\n\t\tvec4 viewportA = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_ATLAS_VIEWPORT_A);\n\t\tvec4 viewportB = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_ATLAS_VIEWPORT_B);\n\t\tclusterLightData.omniAtlasViewport = vec3(bytes2float2(viewportA.xy), bytes2float2(viewportA.zw), bytes2float2(viewportB.xy));\n\t#endif\n}\nvoid decodeClusterLightAreaData(inout ClusterLightData clusterLightData) {\n\t#ifdef CLUSTER_TEXTURE_FLOAT\n\t\tclusterLightData.halfWidth = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_AREA_DATA_WIDTH).xyz;\n\t\tclusterLightData.halfHeight = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_AREA_DATA_HEIGHT).xyz;\n\t#else\n\t\tvec4 areaWidthX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_WIDTH_X);\n\t\tvec4 areaWidthY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_WIDTH_Y);\n\t\tvec4 areaWidthZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_WIDTH_Z);\n\t\tclusterLightData.halfWidth = vec3(mantissaExponent2Float(areaWidthX), mantissaExponent2Float(areaWidthY), mantissaExponent2Float(areaWidthZ));\n\t\tvec4 areaHeightX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_HEIGHT_X);\n\t\tvec4 areaHeightY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_HEIGHT_Y);\n\t\tvec4 areaHeightZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_HEIGHT_Z);\n\t\tclusterLightData.halfHeight = vec3(mantissaExponent2Float(areaHeightX), mantissaExponent2Float(areaHeightY), mantissaExponent2Float(areaHeightZ));\n\t#endif\n}\nvoid decodeClusterLightProjectionMatrixData(inout ClusterLightData clusterLightData) {\n\t\n\t#ifdef CLUSTER_TEXTURE_FLOAT\n\t\tvec4 m0 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_0);\n\t\tvec4 m1 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_1);\n\t\tvec4 m2 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_2);\n\t\tvec4 m3 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_3);\n\t#else\n\t\tvec4 m00 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_00);\n\t\tvec4 m01 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_01);\n\t\tvec4 m02 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_02);\n\t\tvec4 m03 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_03);\n\t\tvec4 m0 = decodeClusterLowRange4Vec4(m00, m01, m02, m03);\n\t\tvec4 m10 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_10);\n\t\tvec4 m11 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_11);\n\t\tvec4 m12 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_12);\n\t\tvec4 m13 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_13);\n\t\tvec4 m1 = decodeClusterLowRange4Vec4(m10, m11, m12, m13);\n\t\tvec4 m20 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_20);\n\t\tvec4 m21 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_21);\n\t\tvec4 m22 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_22);\n\t\tvec4 m23 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_23);\n\t\tvec4 m2 = decodeClusterLowRange4Vec4(m20, m21, m22, m23);\n\t\tvec4 m30 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_30);\n\t\tvec4 m31 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_31);\n\t\tvec4 m32 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_32);\n\t\tvec4 m33 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_33);\n\t\tvec4 m3 = vec4(mantissaExponent2Float(m30), mantissaExponent2Float(m31), mantissaExponent2Float(m32), mantissaExponent2Float(m33));\n\t#endif\n\t\n\tlightProjectionMatrix = mat4(m0, m1, m2, m3);\n}\nvoid decodeClusterLightShadowData(inout ClusterLightData clusterLightData) {\n\t\n\tvec4 biases = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SHADOW_BIAS);\n\tclusterLightData.shadowBias = bytes2floatRange2(biases.xy, -1.0, 20.0),\n\tclusterLightData.shadowNormalBias = bytes2float2(biases.zw);\n}\nvoid decodeClusterLightCookieData(inout ClusterLightData clusterLightData) {\n\tvec4 cookieA = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COOKIE_A);\n\tclusterLightData.cookieIntensity = cookieA.x;\n\tclusterLightData.cookieRgb = cookieA.y;\n\tclusterLightData.cookieChannelMask = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COOKIE_B);\n}\nvoid evaluateLight(\n\tClusterLightData light, \n\tvec3 worldNormal, \n\tvec3 viewDir, \n\tvec3 reflectionDir,\n#if defined(LIT_CLEARCOAT)\n\tvec3 clearcoatReflectionDir,\n#endif\n\tfloat gloss, \n\tvec3 specularity, \n\tvec3 geometricNormal, \n\tmat3 tbn, \n#if defined(LIT_IRIDESCENCE)\n\tvec3 iridescenceFresnel,\n#endif\n\tvec3 clearcoat_worldNormal,\n\tfloat clearcoat_gloss,\n\tfloat sheen_gloss,\n\tfloat iridescence_intensity\n) {\n\tvec3 cookieAttenuation = vec3(1.0);\n\tfloat diffuseAttenuation = 1.0;\n\tfloat falloffAttenuation = 1.0;\n\tgetLightDirPoint(light.position);\n\t#ifdef CLUSTER_AREALIGHTS\n\tif (isClusteredLightArea(light)) {\n\t\tdecodeClusterLightAreaData(light);\n\t\tif (isClusteredLightRect(light)) {\n\t\t\tcalcRectLightValues(light.position, light.halfWidth, light.halfHeight);\n\t\t} else if (isClusteredLightDisk(light)) {\n\t\t\tcalcDiskLightValues(light.position, light.halfWidth, light.halfHeight);\n\t\t} else {\n\t\t\tcalcSphereLightValues(light.position, light.halfWidth, light.halfHeight);\n\t\t}\n\t\tfalloffAttenuation = getFalloffWindow(light.range, dLightDirW);\n\t} else\n\t#endif\n\t{\n\t\tif (isClusteredLightFalloffLinear(light))\n\t\t\tfalloffAttenuation = getFalloffLinear(light.range, dLightDirW);\n\t\telse\n\t\t\tfalloffAttenuation = getFalloffInvSquared(light.range, dLightDirW);\n\t}\n\tif (falloffAttenuation > 0.00001) {\n\t\t#ifdef CLUSTER_AREALIGHTS\n\t\tif (isClusteredLightArea(light)) {\n\t\t\tif (isClusteredLightRect(light)) {\n\t\t\t\tdiffuseAttenuation = getRectLightDiffuse(worldNormal, viewDir, dLightDirW, dLightDirNormW) * 16.0;\n\t\t\t} else if (isClusteredLightDisk(light)) {\n\t\t\t\tdiffuseAttenuation = getDiskLightDiffuse(worldNormal, viewDir, dLightDirW, dLightDirNormW) * 16.0;\n\t\t\t} else {\n\t\t\t\tdiffuseAttenuation = getSphereLightDiffuse(worldNormal, viewDir, dLightDirW, dLightDirNormW) * 16.0;\n\t\t\t}\n\t\t} else\n\t\t#endif\n\t\t{\n\t\t\tfalloffAttenuation *= getLightDiffuse(worldNormal, viewDir, dLightDirW, dLightDirNormW); \n\t\t}\n\t\tif (isClusteredLightSpot(light)) {\n\t\t\tdecodeClusterLightSpot(light);\n\t\t\tfalloffAttenuation *= getSpotEffect(light.direction, light.innerConeAngleCos, light.outerConeAngleCos, dLightDirNormW);\n\t\t}\n\t\t#if defined(CLUSTER_COOKIES_OR_SHADOWS)\n\t\tif (falloffAttenuation > 0.00001) {\n\t\t\tif (isClusteredLightCastShadow(light) || isClusteredLightCookie(light)) {\n\t\t\t\tif (isClusteredLightSpot(light)) {\n\t\t\t\t\tdecodeClusterLightProjectionMatrixData(light);\n\t\t\t\t} else {\n\t\t\t\t\tdecodeClusterLightOmniAtlasViewport(light);\n\t\t\t\t}\n\t\t\t\tfloat shadowTextureResolution = shadowAtlasParams.x;\n\t\t\t\tfloat shadowEdgePixels = shadowAtlasParams.y;\n\t\t\t\t#ifdef CLUSTER_COOKIES\n\t\t\t\tif (isClusteredLightCookie(light)) {\n\t\t\t\t\tdecodeClusterLightCookieData(light);\n\t\t\t\t\tif (isClusteredLightSpot(light)) {\n\t\t\t\t\t\tcookieAttenuation = getCookie2DClustered(TEXTURE_PASS(cookieAtlasTexture), lightProjectionMatrix, vPositionW, light.cookieIntensity, isClusteredLightCookieRgb(light), light.cookieChannelMask);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcookieAttenuation = getCookieCubeClustered(TEXTURE_PASS(cookieAtlasTexture), dLightDirW, light.cookieIntensity, isClusteredLightCookieRgb(light), light.cookieChannelMask, shadowTextureResolution, shadowEdgePixels, light.omniAtlasViewport);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t#endif\n\t\t\t\t#ifdef CLUSTER_SHADOWS\n\t\t\t\tif (isClusteredLightCastShadow(light)) {\n\t\t\t\t\tdecodeClusterLightShadowData(light);\n\t\t\t\t\tvec4 shadowParams = vec4(shadowTextureResolution, light.shadowNormalBias, light.shadowBias, 1.0 / light.range);\n\t\t\t\t\tif (isClusteredLightSpot(light)) {\n\t\t\t\t\t\tgetShadowCoordPerspZbufferNormalOffset(lightProjectionMatrix, shadowParams, geometricNormal);\n\t\t\t\t\t\t\n\t\t\t\t\t\t#if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\t\t\t\t\t\t\tfloat shadow = getShadowSpotClusteredPCF1(SHADOWMAP_PASS(shadowAtlasTexture), dShadowCoord, shadowParams);\n\t\t\t\t\t\t#elif defined(CLUSTER_SHADOW_TYPE_PCF3)\n\t\t\t\t\t\t\tfloat shadow = getShadowSpotClusteredPCF3(SHADOWMAP_PASS(shadowAtlasTexture), dShadowCoord, shadowParams);\n\t\t\t\t\t\t#elif defined(CLUSTER_SHADOW_TYPE_PCF5)\n\t\t\t\t\t\t\tfloat shadow = getShadowSpotClusteredPCF5(SHADOWMAP_PASS(shadowAtlasTexture), dShadowCoord, shadowParams);\n\t\t\t\t\t\t#elif defined(CLUSTER_SHADOW_TYPE_PCSS)\n\t\t\t\t\t\t\tfloat shadow = getShadowSpotClusteredPCSS(SHADOWMAP_PASS(shadowAtlasTexture), dShadowCoord, shadowParams);\n\t\t\t\t\t\t#endif\n\t\t\t\t\t\tfalloffAttenuation *= mix(1.0, shadow, light.shadowIntensity);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvec3 dir = normalOffsetPointShadow(shadowParams, dLightPosW, dLightDirW, dLightDirNormW, geometricNormal);\n\t\t\t\t\t\t#if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\t\t\t\t\t\t\tfloat shadow = getShadowOmniClusteredPCF1(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);\n\t\t\t\t\t\t#elif defined(CLUSTER_SHADOW_TYPE_PCF3)\n\t\t\t\t\t\t\tfloat shadow = getShadowOmniClusteredPCF3(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);\n\t\t\t\t\t\t#elif defined(CLUSTER_SHADOW_TYPE_PCF5)\n\t\t\t\t\t\t\tfloat shadow = getShadowOmniClusteredPCF5(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);\n\t\t\t\t\t\t#endif\n\t\t\t\t\t\tfalloffAttenuation *= mix(1.0, shadow, light.shadowIntensity);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t#endif\n\t\t\t}\n\t\t}\n\t\t#endif\n\t\t#ifdef CLUSTER_AREALIGHTS\n\t\tif (isClusteredLightArea(light)) {\n\t\t\t{\n\t\t\t\tvec3 areaDiffuse = (diffuseAttenuation * falloffAttenuation) * light.color * cookieAttenuation;\n\t\t\t\t#if defined(LIT_SPECULAR)\n\t\t\t\t\t#if defined(LIT_CONSERVE_ENERGY)\n\t\t\t\t\t\tareaDiffuse = mix(areaDiffuse, vec3(0), dLTCSpecFres);\n\t\t\t\t\t#endif\n\t\t\t\t#endif\n\t\t\t\tdDiffuseLight += areaDiffuse;\n\t\t\t}\n\t\t\t#ifdef LIT_SPECULAR\n\t\t\t\tfloat areaLightSpecular;\n\t\t\t\tif (isClusteredLightRect(light)) {\n\t\t\t\t\tareaLightSpecular = getRectLightSpecular(worldNormal, viewDir);\n\t\t\t\t} else if (isClusteredLightDisk(light)) {\n\t\t\t\t\tareaLightSpecular = getDiskLightSpecular(worldNormal, viewDir);\n\t\t\t\t} else {\n\t\t\t\t\tareaLightSpecular = getSphereLightSpecular(worldNormal, viewDir);\n\t\t\t\t}\n\t\t\t\tdSpecularLight += dLTCSpecFres * areaLightSpecular * falloffAttenuation * light.color * cookieAttenuation;\n\t\t\t\t#ifdef LIT_CLEARCOAT\n\t\t\t\t\tfloat areaLightSpecularCC;\n\t\t\t\t\tif (isClusteredLightRect(light)) {\n\t\t\t\t\t\tareaLightSpecularCC = getRectLightSpecular(clearcoat_worldNormal, viewDir);\n\t\t\t\t\t} else if (isClusteredLightDisk(light)) {\n\t\t\t\t\t\tareaLightSpecularCC = getDiskLightSpecular(clearcoat_worldNormal, viewDir);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tareaLightSpecularCC = getSphereLightSpecular(clearcoat_worldNormal, viewDir);\n\t\t\t\t\t}\n\t\t\t\t\tccSpecularLight += ccLTCSpecFres * areaLightSpecularCC * falloffAttenuation * light.color * cookieAttenuation;\n\t\t\t\t#endif\n\t\t\t#endif\n\t\t} else\n\t\t#endif\n\t\t{\n\t\t\t{\n\t\t\t\tvec3 punctualDiffuse = falloffAttenuation * light.color * cookieAttenuation;\n\t\t\t\t#if defined(CLUSTER_AREALIGHTS)\n\t\t\t\t#if defined(LIT_SPECULAR)\n\t\t\t\t#if defined(LIT_CONSERVE_ENERGY)\n\t\t\t\t\tpunctualDiffuse = mix(punctualDiffuse, vec3(0), specularity);\n\t\t\t\t#endif\n\t\t\t\t#endif\n\t\t\t\t#endif\n\t\t\t\tdDiffuseLight += punctualDiffuse;\n\t\t\t}\n \n\t\t\t#ifdef LIT_SPECULAR\n\t\t\t\tvec3 halfDir = normalize(-dLightDirNormW + viewDir);\n\t\t\t\t\n\t\t\t\t#ifdef LIT_SPECULAR_FRESNEL\n\t\t\t\t\tdSpecularLight += \n\t\t\t\t\t\tgetLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, dLightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * \n\t\t\t\t\t\tgetFresnel(\n\t\t\t\t\t\t\tdot(viewDir, halfDir), \n\t\t\t\t\t\t\tgloss, \n\t\t\t\t\t\t\tspecularity\n\t\t\t\t\t\t#if defined(LIT_IRIDESCENCE)\n\t\t\t\t\t\t\t, iridescenceFresnel,\n\t\t\t\t\t\t\tiridescence_intensity\n\t\t\t\t\t\t#endif\n\t\t\t\t\t\t\t);\n\t\t\t\t#else\n\t\t\t\t\tdSpecularLight += getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, dLightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * specularity;\n\t\t\t\t#endif\n\t\t\t\t#ifdef LIT_CLEARCOAT\n\t\t\t\t\t#ifdef LIT_SPECULAR_FRESNEL\n\t\t\t\t\t\tccSpecularLight += getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, dLightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * getFresnelCC(dot(viewDir, halfDir));\n\t\t\t\t\t#else\n\t\t\t\t\t\tccSpecularLight += getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, dLightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation; \n\t\t\t\t\t#endif\n\t\t\t\t#endif\n\t\t\t\t#ifdef LIT_SHEEN\n\t\t\t\t\tsSpecularLight += getLightSpecularSheen(halfDir, worldNormal, viewDir, dLightDirNormW, sheen_gloss) * falloffAttenuation * light.color * cookieAttenuation;\n\t\t\t\t#endif\n\t\t\t#endif\n\t\t}\n\t}\n\tdAtten = falloffAttenuation;\n\tdAttenD = diffuseAttenuation;\n\tdAtten3 = cookieAttenuation;\n}\nvoid evaluateClusterLight(\n\tfloat lightIndex, \n\tvec3 worldNormal, \n\tvec3 viewDir, \n\tvec3 reflectionDir, \n#if defined(LIT_CLEARCOAT)\n\tvec3 clearcoatReflectionDir,\n#endif\n\tfloat gloss, \n\tvec3 specularity, \n\tvec3 geometricNormal, \n\tmat3 tbn, \n#if defined(LIT_IRIDESCENCE)\n\tvec3 iridescenceFresnel,\n#endif\n\tvec3 clearcoat_worldNormal,\n\tfloat clearcoat_gloss,\n\tfloat sheen_gloss,\n\tfloat iridescence_intensity\n) {\n\tClusterLightData clusterLightData;\n\tdecodeClusterLightCore(clusterLightData, lightIndex);\n\tif (acceptLightMask(clusterLightData))\n\t\tevaluateLight(\n\t\t\tclusterLightData, \n\t\t\tworldNormal, \n\t\t\tviewDir, \n\t\t\treflectionDir, \n#if defined(LIT_CLEARCOAT)\n\t\t\tclearcoatReflectionDir, \n#endif\n\t\t\tgloss, \n\t\t\tspecularity, \n\t\t\tgeometricNormal, \n\t\t\ttbn, \n#if defined(LIT_IRIDESCENCE)\n\t\t\tiridescenceFresnel,\n#endif\n\t\t\tclearcoat_worldNormal,\n\t\t\tclearcoat_gloss,\n\t\t\tsheen_gloss,\n\t\t\tiridescence_intensity\n\t\t);\n}\nvoid addClusteredLights(\n\tvec3 worldNormal, \n\tvec3 viewDir, \n\tvec3 reflectionDir, \n#if defined(LIT_CLEARCOAT)\n\tvec3 clearcoatReflectionDir,\n#endif\n\tfloat gloss, \n\tvec3 specularity, \n\tvec3 geometricNormal, \n\tmat3 tbn, \n#if defined(LIT_IRIDESCENCE)\n\tvec3 iridescenceFresnel,\n#endif\n\tvec3 clearcoat_worldNormal,\n\tfloat clearcoat_gloss,\n\tfloat sheen_gloss,\n\tfloat iridescence_intensity\n) {\n\tif (clusterSkip > 0.5)\n\t\treturn;\n\tvec3 cellCoords = floor((vPositionW - clusterBoundsMin) * clusterCellsCountByBoundsSize);\n\tif (!(any(lessThan(cellCoords, vec3(0.0))) || any(greaterThanEqual(cellCoords, clusterCellsMax)))) {\n\t\tfloat cellIndex = dot(clusterCellsDot, cellCoords);\n\t\tfloat clusterV = floor(cellIndex * clusterTextureSize.y);\n\t\tfloat clusterU = cellIndex - (clusterV * clusterTextureSize.x);\n\t\t#ifdef GL2\n\t\t\tfor (int lightCellIndex = 0; lightCellIndex < clusterMaxCells; lightCellIndex++) {\n\t\t\t\tfloat lightIndex = texelFetch(clusterWorldTexture, ivec2(int(clusterU) + lightCellIndex, clusterV), 0).x;\n\t\t\t\tif (lightIndex <= 0.0)\n\t\t\t\t\t\treturn;\n\t\t\t\tevaluateClusterLight(\n\t\t\t\t\tlightIndex * 255.0, \n\t\t\t\t\tworldNormal, \n\t\t\t\t\tviewDir, \n\t\t\t\t\treflectionDir,\n#if defined(LIT_CLEARCOAT)\n\t\t\t\t\tclearcoatReflectionDir,\n#endif\n\t\t\t\t\tgloss, \n\t\t\t\t\tspecularity, \n\t\t\t\t\tgeometricNormal, \n\t\t\t\t\ttbn, \n#if defined(LIT_IRIDESCENCE)\n\t\t\t\t\tiridescenceFresnel,\n#endif\n\t\t\t\t\tclearcoat_worldNormal,\n\t\t\t\t\tclearcoat_gloss,\n\t\t\t\t\tsheen_gloss,\n\t\t\t\t\tiridescence_intensity\n\t\t\t\t); \n\t\t\t}\n\t\t#else\n\t\t\tclusterV = (clusterV + 0.5) * clusterTextureSize.z;\n\t\t\tconst float maxLightCells = 256.0;\n\t\t\tfor (float lightCellIndex = 0.5; lightCellIndex < maxLightCells; lightCellIndex++) {\n\t\t\t\tfloat lightIndex = texture2DLodEXT(clusterWorldTexture, vec2(clusterTextureSize.y * (clusterU + lightCellIndex), clusterV), 0.0).x;\n\t\t\t\tif (lightIndex <= 0.0)\n\t\t\t\t\treturn;\n\t\t\t\t\n\t\t\t\tevaluateClusterLight(\n\t\t\t\t\tlightIndex * 255.0, \n\t\t\t\t\tworldNormal, \n\t\t\t\t\tviewDir, \n\t\t\t\t\treflectionDir,\n#if defined(LIT_CLEARCOAT)\n\t\t\t\t\tclearcoatReflectionDir,\n#endif\n\t\t\t\t\tgloss, \n\t\t\t\t\tspecularity, \n\t\t\t\t\tgeometricNormal, \n\t\t\t\t\ttbn, \n#if defined(LIT_IRIDESCENCE)\n\t\t\t\t\tiridescenceFresnel,\n#endif\n\t\t\t\t\tclearcoat_worldNormal,\n\t\t\t\t\tclearcoat_gloss,\n\t\t\t\t\tsheen_gloss,\n\t\t\t\t\tiridescence_intensity\n\t\t\t\t); \n\t\t\t\tif (lightCellIndex >= clusterMaxCells) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t#endif\n\t}\n}\n",combinePS:"\nvec3 combineColor(vec3 albedo, vec3 sheenSpecularity, float clearcoatSpecularity) {\n\tvec3 ret = vec3(0);\n#ifdef LIT_OLD_AMBIENT\n\tret += (dDiffuseLight - light_globalAmbient) * albedo + material_ambient * light_globalAmbient;\n#else\n\tret += albedo * dDiffuseLight;\n#endif\n#ifdef LIT_SPECULAR\n\tret += dSpecularLight;\n#endif\n#ifdef LIT_REFLECTIONS\n\tret += dReflection.rgb * dReflection.a;\n#endif\n#ifdef LIT_SHEEN\n\tfloat sheenScaling = 1.0 - max(max(sheenSpecularity.r, sheenSpecularity.g), sheenSpecularity.b) * 0.157;\n\tret = ret * sheenScaling + (sSpecularLight + sReflection.rgb) * sheenSpecularity;\n#endif\n#ifdef LIT_CLEARCOAT\n\tfloat clearCoatScaling = 1.0 - ccFresnel * clearcoatSpecularity;\n\tret = ret * clearCoatScaling + (ccSpecularLight + ccReflection.rgb) * clearcoatSpecularity;\n#endif\n\treturn ret;\n}\n",cookiePS:"\nvec4 getCookie2D(sampler2D tex, mat4 transform, float intensity) {\n\tvec4 projPos = transform * vec4(vPositionW, 1.0);\n\tprojPos.xy /= projPos.w;\n\treturn mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);\n}\nvec4 getCookie2DClip(sampler2D tex, mat4 transform, float intensity) {\n\tvec4 projPos = transform * vec4(vPositionW, 1.0);\n\tprojPos.xy /= projPos.w;\n\tif (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\treturn mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);\n}\nvec4 getCookie2DXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {\n\tvec4 projPos = transform * vec4(vPositionW, 1.0);\n\tprojPos.xy /= projPos.w;\n\tprojPos.xy += cookieOffset;\n\tvec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);\n\treturn mix(vec4(1.0), texture2D(tex, uv), intensity);\n}\nvec4 getCookie2DClipXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {\n\tvec4 projPos = transform * vec4(vPositionW, 1.0);\n\tprojPos.xy /= projPos.w;\n\tprojPos.xy += cookieOffset;\n\tif (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\tvec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);\n\treturn mix(vec4(1.0), texture2D(tex, uv), intensity);\n}\nvec4 getCookieCube(samplerCube tex, mat4 transform, float intensity) {\n\treturn mix(vec4(1.0), textureCube(tex, dLightDirNormW * mat3(transform)), intensity);\n}\n",cubeMapProjectBoxPS:"\nuniform vec3 envBoxMin;\nuniform vec3 envBoxMax;\nvec3 cubeMapProject(vec3 nrdir) {\n\tnrdir = cubeMapRotate(nrdir);\n\tvec3 rbmax = (envBoxMax - vPositionW) / nrdir;\n\tvec3 rbmin = (envBoxMin - vPositionW) / nrdir;\n\tvec3 rbminmax;\n\trbminmax.x = nrdir.x>0.0? rbmax.x : rbmin.x;\n\trbminmax.y = nrdir.y>0.0? rbmax.y : rbmin.y;\n\trbminmax.z = nrdir.z>0.0? rbmax.z : rbmin.z;\n\tfloat fa = min(min(rbminmax.x, rbminmax.y), rbminmax.z);\n\tvec3 posonbox = vPositionW + nrdir * fa;\n\tvec3 envBoxPos = (envBoxMin + envBoxMax) * 0.5;\n\treturn normalize(posonbox - envBoxPos);\n}\n",cubeMapProjectNonePS:"\nvec3 cubeMapProject(vec3 dir) {\n\treturn cubeMapRotate(dir);\n}\n",cubeMapRotatePS:"\n#ifdef CUBEMAP_ROTATION\nuniform mat3 cubeMapRotationMatrix;\n#endif\nvec3 cubeMapRotate(vec3 refDir) {\n#ifdef CUBEMAP_ROTATION\n\treturn refDir * cubeMapRotationMatrix;\n#else\n\treturn refDir;\n#endif\n}\n",debugOutputPS:"\n#ifdef DEBUG_ALBEDO_PASS\ngl_FragColor = vec4(gammaCorrectOutput(litArgs_albedo), 1.0);\n#endif\n#ifdef DEBUG_UV0_PASS\ngl_FragColor = vec4(litArgs_albedo , 1.0);\n#endif\n#ifdef DEBUG_WORLD_NORMAL_PASS\ngl_FragColor = vec4(litArgs_worldNormal * 0.5 + 0.5, 1.0);\n#endif\n#ifdef DEBUG_OPACITY_PASS\ngl_FragColor = vec4(vec3(litArgs_opacity) , 1.0);\n#endif\n#ifdef DEBUG_SPECULARITY_PASS\ngl_FragColor = vec4(litArgs_specularity, 1.0);\n#endif\n#ifdef DEBUG_GLOSS_PASS\ngl_FragColor = vec4(vec3(litArgs_gloss) , 1.0);\n#endif\n#ifdef DEBUG_METALNESS_PASS\ngl_FragColor = vec4(vec3(litArgs_metalness) , 1.0);\n#endif\n#ifdef DEBUG_AO_PASS\ngl_FragColor = vec4(vec3(litArgs_ao) , 1.0);\n#endif\n#ifdef DEBUG_EMISSION_PASS\ngl_FragColor = vec4(gammaCorrectOutput(litArgs_emission), 1.0);\n#endif\n",debugProcessFrontendPS:"\n#ifdef DEBUG_LIGHTING_PASS\nlitArgs_albedo = vec3(0.5);\n#endif\n#ifdef DEBUG_UV0_PASS\n#ifdef VARYING_VUV0\nlitArgs_albedo = vec3(vUv0, 0);\n#else\nlitArgs_albedo = vec3(0);\n#endif\n#endif\n",detailModesPS:"\nvec3 detailMode_mul(vec3 c1, vec3 c2) {\n\treturn c1 * c2;\n}\nvec3 detailMode_add(vec3 c1, vec3 c2) {\n\treturn c1 + c2;\n}\nvec3 detailMode_screen(vec3 c1, vec3 c2) {\n\treturn 1.0 - (1.0 - c1)*(1.0 - c2);\n}\nvec3 detailMode_overlay(vec3 c1, vec3 c2) {\n\treturn mix(1.0 - 2.0*(1.0 - c1)*(1.0 - c2), 2.0*c1*c2, step(c1, vec3(0.5)));\n}\nvec3 detailMode_min(vec3 c1, vec3 c2) {\n\treturn min(c1, c2);\n}\nvec3 detailMode_max(vec3 c1, vec3 c2) {\n\treturn max(c1, c2);\n}\n",diffusePS:"\n#ifdef MAPCOLOR\nuniform vec3 material_diffuse;\n#endif\nvoid getAlbedo() {\n\tdAlbedo = vec3(1.0);\n#ifdef MAPCOLOR\n\tdAlbedo *= material_diffuse.rgb;\n#endif\n#ifdef MAPTEXTURE\n\tvec3 albedoBase = $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n\tdAlbedo *= addAlbedoDetail(albedoBase);\n#endif\n#ifdef MAPVERTEX\n\tdAlbedo *= gammaCorrectInput(saturate(vVertexColor.$VC));\n#endif\n}\n",diffuseDetailMapPS:"\nvec3 addAlbedoDetail(vec3 albedo) {\n#ifdef MAPTEXTURE\n\tvec3 albedoDetail = $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n\treturn detailMode_$DETAILMODE(albedo, albedoDetail);\n#else\n\treturn albedo;\n#endif\n}\n",decodePS:po,emissivePS:"\n#ifdef MAPCOLOR\nuniform vec3 material_emissive;\n#endif\n#ifdef MAPFLOAT\nuniform float material_emissiveIntensity;\n#endif\nvoid getEmission() {\n\tdEmission = vec3(1.0);\n\t#ifdef MAPFLOAT\n\tdEmission *= material_emissiveIntensity;\n\t#endif\n\t#ifdef MAPCOLOR\n\tdEmission *= material_emissive;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tdEmission *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tdEmission *= gammaCorrectInput(saturate(vVertexColor.$VC));\n\t#endif\n}\n",encodePS:mo,endPS:"\n\tgl_FragColor.rgb = combineColor(litArgs_albedo, litArgs_sheen_specularity, litArgs_clearcoat_specularity);\n\tgl_FragColor.rgb += litArgs_emission;\n\tgl_FragColor.rgb = addFog(gl_FragColor.rgb);\n\t#ifndef HDR\n\tgl_FragColor.rgb = toneMap(gl_FragColor.rgb);\n\tgl_FragColor.rgb = gammaCorrectOutput(gl_FragColor.rgb);\n\t#endif\n",endVS:"\n",envAtlasPS:"\nconst float atlasSize = 512.0;\nconst float seamSize = 1.0 / atlasSize;\nvec2 mapUv(vec2 uv, vec4 rect) {\n\treturn vec2(mix(rect.x + seamSize, rect.x + rect.z - seamSize, uv.x),\n\t\t\t\tmix(rect.y + seamSize, rect.y + rect.w - seamSize, uv.y));\n}\nvec2 mapRoughnessUv(vec2 uv, float level) {\n\tfloat t = 1.0 / exp2(level);\n\treturn mapUv(uv, vec4(0, 1.0 - t, t, t * 0.5));\n}\nvec2 mapShinyUv(vec2 uv, float level) {\n\tfloat t = 1.0 / exp2(level);\n\treturn mapUv(uv, vec4(1.0 - t, 1.0 - t, t, t * 0.5));\n}\n",envConstPS:"\nvec3 processEnvironment(vec3 color) {\n\treturn color;\n}\n",envMultiplyPS:"\nuniform float skyboxIntensity;\nvec3 processEnvironment(vec3 color) {\n\treturn color * skyboxIntensity;\n}\n",extensionPS:"\n",extensionVS:"\n",falloffInvSquaredPS:"\nfloat getFalloffWindow(float lightRadius, vec3 lightDir) {\n\tfloat sqrDist = dot(lightDir, lightDir);\n\tfloat invRadius = 1.0 / lightRadius;\n\treturn square( saturate( 1.0 - square( sqrDist * square(invRadius) ) ) );\n}\nfloat getFalloffInvSquared(float lightRadius, vec3 lightDir) {\n\tfloat sqrDist = dot(lightDir, lightDir);\n\tfloat falloff = 1.0 / (sqrDist + 1.0);\n\tfloat invRadius = 1.0 / lightRadius;\n\tfalloff *= 16.0;\n\tfalloff *= square( saturate( 1.0 - square( sqrDist * square(invRadius) ) ) );\n\treturn falloff;\n}\n",falloffLinearPS:"\nfloat getFalloffLinear(float lightRadius, vec3 lightDir) {\n\tfloat d = length(lightDir);\n\treturn max(((lightRadius - d) / lightRadius), 0.0);\n}\n",fixCubemapSeamsNonePS:"\nvec3 fixSeams(vec3 vec, float mipmapIndex) {\n\treturn vec;\n}\nvec3 fixSeams(vec3 vec) {\n\treturn vec;\n}\nvec3 fixSeamsStatic(vec3 vec, float invRecMipSize) {\n\treturn vec;\n}\nvec3 calcSeam(vec3 vec) {\n\treturn vec3(0);\n}\nvec3 applySeam(vec3 vec, vec3 seam, float scale) {\n\treturn vec;\n}\n",fixCubemapSeamsStretchPS:"\nvec3 fixSeams(vec3 vec, float mipmapIndex) {\n\tvec3 avec = abs(vec);\n\tfloat scale = 1.0 - exp2(mipmapIndex) / 128.0;\n\tfloat M = max(max(avec.x, avec.y), avec.z);\n\tif (avec.x != M) vec.x *= scale;\n\tif (avec.y != M) vec.y *= scale;\n\tif (avec.z != M) vec.z *= scale;\n\treturn vec;\n}\nvec3 fixSeams(vec3 vec) {\n\tvec3 avec = abs(vec);\n\tfloat scale = 1.0 - 1.0 / 128.0;\n\tfloat M = max(max(avec.x, avec.y), avec.z);\n\tif (avec.x != M) vec.x *= scale;\n\tif (avec.y != M) vec.y *= scale;\n\tif (avec.z != M) vec.z *= scale;\n\treturn vec;\n}\nvec3 fixSeamsStatic(vec3 vec, float invRecMipSize) {\n\tvec3 avec = abs(vec);\n\tfloat scale = invRecMipSize;\n\tfloat M = max(max(avec.x, avec.y), avec.z);\n\tif (avec.x != M) vec.x *= scale;\n\tif (avec.y != M) vec.y *= scale;\n\tif (avec.z != M) vec.z *= scale;\n\treturn vec;\n}\nvec3 calcSeam(vec3 vec) {\n\tvec3 avec = abs(vec);\n\tfloat M = max(avec.x, max(avec.y, avec.z));\n\treturn vec3(avec.x != M ? 1.0 : 0.0,\n\t\t\t\tavec.y != M ? 1.0 : 0.0,\n\t\t\t\tavec.z != M ? 1.0 : 0.0);\n}\nvec3 applySeam(vec3 vec, vec3 seam, float scale) {\n\treturn vec * (seam * -scale + vec3(1.0));\n}\n",floatUnpackingPS:"\nfloat bytes2float2(vec2 data) {\n\treturn dot(data, vec2(1.0, 1.0 / 255.0));\n}\nfloat bytes2float3(vec3 data) {\n\treturn dot(data, vec3(1.0, 1.0 / 255.0, 1.0 / 65025.0));\n}\nfloat bytes2float4(vec4 data) {\n\treturn dot(data, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n}\nfloat bytes2floatRange2(vec2 data, float min, float max) {\n\treturn mix(min, max, bytes2float2(data));\n}\nfloat bytes2floatRange3(vec3 data, float min, float max) {\n\treturn mix(min, max, bytes2float3(data));\n}\nfloat bytes2floatRange4(vec4 data, float min, float max) {\n\treturn mix(min, max, bytes2float4(data));\n}\nfloat mantissaExponent2Float(vec4 pack)\n{\n\tfloat value = bytes2floatRange3(pack.xyz, -1.0, 1.0);\n\tfloat exponent = floor(pack.w * 255.0 - 127.0);\n\treturn value * exp2(exponent);\n}\n",fogExpPS:"\nuniform vec3 fog_color;\nuniform float fog_density;\nfloat dBlendModeFogFactor = 1.0;\nvec3 addFog(vec3 color) {\n\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\tfloat fogFactor = exp(-depth * fog_density);\n\tfogFactor = clamp(fogFactor, 0.0, 1.0);\n\treturn mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogExp2PS:"\nuniform vec3 fog_color;\nuniform float fog_density;\nfloat dBlendModeFogFactor = 1.0;\nvec3 addFog(vec3 color) {\n\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\tfloat fogFactor = exp(-depth * depth * fog_density * fog_density);\n\tfogFactor = clamp(fogFactor, 0.0, 1.0);\n\treturn 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;\nvec3 addFog(vec3 color) {\n\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\tfloat fogFactor = (fog_end - depth) / (fog_end - fog_start);\n\tfogFactor = clamp(fogFactor, 0.0, 1.0);\n\treturn mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogNonePS:"\nfloat dBlendModeFogFactor = 1.0;\nvec3 addFog(vec3 color) {\n\treturn color;\n}\n",fresnelSchlickPS:"\nvec3 getFresnel(\n\t\tfloat cosTheta, \n\t\tfloat gloss, \n\t\tvec3 specularity\n#if defined(LIT_IRIDESCENCE)\n\t\t, vec3 iridescenceFresnel, \n\t\tfloat iridescenceIntensity\n#endif\n\t) {\n\tfloat fresnel = pow(1.0 - max(cosTheta, 0.0), 5.0);\n\tfloat glossSq = gloss * gloss;\n\tvec3 ret = specularity + (max(vec3(glossSq), specularity) - specularity) * fresnel;\n#if defined(LIT_IRIDESCENCE)\n\treturn mix(ret, iridescenceFresnel, iridescenceIntensity);\n#else\n\treturn ret;\n#endif\t\n}\nfloat getFresnelCC(float cosTheta) {\n\tfloat fresnel = pow(1.0 - max(cosTheta, 0.0), 5.0);\n\treturn 0.04 + (1.0 - 0.04) * fresnel;\n}\n",fullscreenQuadPS:"\nvarying vec2 vUv0;\nuniform sampler2D source;\nvoid main(void) {\n\tgl_FragColor = texture2D(source, vUv0);\n}\n",fullscreenQuadVS:"\nattribute vec2 vertex_position;\nvarying vec2 vUv0;\nvoid main(void)\n{\n\tgl_Position = vec4(vertex_position, 0.5, 1.0);\n\tvUv0 = vertex_position.xy*0.5+0.5;\n}\n",gamma1_0PS:"\nfloat gammaCorrectInput(float color) {\n\treturn color;\n}\nvec3 gammaCorrectInput(vec3 color) {\n\treturn color;\n}\nvec4 gammaCorrectInput(vec4 color) {\n\treturn color;\n}\nvec3 gammaCorrectOutput(vec3 color) {\n\treturn color;\n}\n",gamma2_2PS:"\nfloat gammaCorrectInput(float color) {\n\treturn decodeGamma(color);\n}\nvec3 gammaCorrectInput(vec3 color) {\n\treturn decodeGamma(color);\n}\nvec4 gammaCorrectInput(vec4 color) {\n\treturn vec4(decodeGamma(color.xyz), color.w);\n}\nvec3 gammaCorrectOutput(vec3 color) {\n#ifdef HDR\n\treturn color;\n#else\n\treturn pow(color + 0.0000001, vec3(1.0 / 2.2));\n#endif\n}\n",gles2PS:Ks,gles3PS:Zs,gles3VS:Qs,glossPS:"\n#ifdef MAPFLOAT\nuniform float material_gloss;\n#endif\nvoid getGlossiness() {\n\tdGlossiness = 1.0;\n\t#ifdef MAPFLOAT\n\tdGlossiness *= material_gloss;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tdGlossiness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tdGlossiness *= saturate(vVertexColor.$VC);\n\t#endif\n\t#ifdef MAPINVERT\n\tdGlossiness = 1.0 - dGlossiness;\n\t#endif\n\tdGlossiness += 0.0000001;\n}\n",iridescenceDiffractionPS:"\nuniform float material_iridescenceRefractionIndex;\n#ifndef PI\n#define PI 3.14159265\n#endif\nfloat iridescence_iorToFresnel(float transmittedIor, float incidentIor) {\n\treturn pow((transmittedIor - incidentIor) / (transmittedIor + incidentIor), 2.0);\n}\nvec3 iridescence_iorToFresnel(vec3 transmittedIor, float incidentIor) {\n\treturn pow((transmittedIor - vec3(incidentIor)) / (transmittedIor + vec3(incidentIor)), vec3(2.0));\n}\nvec3 iridescence_fresnelToIor(vec3 f0) {\n\tvec3 sqrtF0 = sqrt(f0);\n\treturn (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0);\n}\nvec3 iridescence_sensitivity(float opd, vec3 shift) {\n\tfloat phase = 2.0 * PI * opd * 1.0e-9;\n\tconst vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13);\n\tconst vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06);\n\tconst vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09);\n\tvec3 xyz = val * sqrt(2.0 * PI * var) * cos(pos * phase + shift) * exp(-pow(phase, 2.0) * var);\n\txyz.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\txyz /= vec3(1.0685e-07);\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t3.2404542, -0.9692660, 0.0556434,\n\t -1.5371385, 1.8760108, -0.2040259,\n\t -0.4985314, 0.0415560, 1.0572252\n\t);\n\treturn XYZ_TO_REC709 * xyz;\n}\nfloat iridescence_fresnel(float cosTheta, float f0) {\n\tfloat x = clamp(1.0 - cosTheta, 0.0, 1.0);\n\tfloat x2 = x * x;\n\tfloat x5 = x * x2 * x2;\n\treturn f0 + (1.0 - f0) * x5;\n} \nvec3 iridescence_fresnel(float cosTheta, vec3 f0) {\n\tfloat x = clamp(1.0 - cosTheta, 0.0, 1.0);\n\tfloat x2 = x * x;\n\tfloat x5 = x * x2 * x2; \n\treturn f0 + (vec3(1.0) - f0) * x5;\n}\nvec3 calcIridescence(float outsideIor, float cosTheta, vec3 base_f0, float iridescenceThickness) {\n\tfloat iridescenceIor = mix(outsideIor, material_iridescenceRefractionIndex, smoothstep(0.0, 0.03, iridescenceThickness));\n\tfloat sinTheta2Sq = pow(outsideIor / iridescenceIor, 2.0) * (1.0 - pow(cosTheta, 2.0));\n\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\tif (cosTheta2Sq < 0.0) {\n\t\treturn vec3(1.0);\n\t}\n\tfloat cosTheta2 = sqrt(cosTheta2Sq);\n\tfloat r0 = iridescence_iorToFresnel(iridescenceIor, outsideIor);\n\tfloat r12 = iridescence_fresnel(cosTheta, r0);\n\tfloat r21 = r12;\n\tfloat t121 = 1.0 - r12;\n\tfloat phi12 = iridescenceIor < outsideIor ? PI : 0.0;\n\tfloat phi21 = PI - phi12;\n\tvec3 baseIor = iridescence_fresnelToIor(base_f0 + vec3(0.0001));\n\tvec3 r1 = iridescence_iorToFresnel(baseIor, iridescenceIor);\n\tvec3 r23 = iridescence_fresnel(cosTheta2, r1);\n\tvec3 phi23 = vec3(0.0);\n\tif (baseIor[0] < iridescenceIor) phi23[0] = PI;\n\tif (baseIor[1] < iridescenceIor) phi23[1] = PI;\n\tif (baseIor[2] < iridescenceIor) phi23[2] = PI;\n\tfloat opd = 2.0 * iridescenceIor * iridescenceThickness * cosTheta2;\n\tvec3 phi = vec3(phi21) + phi23; \n\tvec3 r123Sq = clamp(r12 * r23, 1e-5, 0.9999);\n\tvec3 r123 = sqrt(r123Sq);\n\tvec3 rs = pow(t121, 2.0) * r23 / (1.0 - r123Sq);\n\tvec3 c0 = r12 + rs;\n\tvec3 i = c0;\n\tvec3 cm = rs - t121;\n\tfor (int m = 1; m <= 2; m++) {\n\t\tcm *= r123;\n\t\tvec3 sm = 2.0 * iridescence_sensitivity(float(m) * opd, float(m) * phi);\n\t\ti += cm * sm;\n\t}\n\treturn max(i, vec3(0.0));\n}\nvec3 getIridescence(float cosTheta, vec3 specularity, float iridescenceThickness) {\n\treturn calcIridescence(1.0, cosTheta, specularity, iridescenceThickness);\n}\n",iridescencePS:"\n#ifdef MAPFLOAT\nuniform float material_iridescence;\n#endif\nvoid getIridescence() {\n\tfloat iridescence = 1.0;\n\t#ifdef MAPFLOAT\n\tiridescence *= material_iridescence;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tiridescence *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\tdIridescence = iridescence; \n}\n",iridescenceThicknessPS:"\nuniform float material_iridescenceThicknessMax;\n#ifdef MAPTEXTURE\nuniform float material_iridescenceThicknessMin;\n#endif\nvoid getIridescenceThickness() {\n\t#ifdef MAPTEXTURE\n\tfloat blend = texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\tfloat iridescenceThickness = mix(material_iridescenceThicknessMin, material_iridescenceThicknessMax, blend);\n\t#else\n\tfloat iridescenceThickness = material_iridescenceThicknessMax;\n\t#endif\n\tdIridescenceThickness = iridescenceThickness; \n}\n",instancingVS:"\nattribute vec4 instance_line1;\nattribute vec4 instance_line2;\nattribute vec4 instance_line3;\nattribute vec4 instance_line4;\n",iorPS:"\n#ifdef MAPFLOAT\nuniform float material_refractionIndex;\n#endif\nvoid getIor() {\n#ifdef MAPFLOAT\n\tdIor = material_refractionIndex;\n#else\n\tdIor = 1.0 / 1.5;\n#endif\n}\n",lightDiffuseLambertPS:"\nfloat getLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {\n\treturn max(dot(worldNormal, -lightDirNorm), 0.0);\n}\n",lightDirPointPS:"\nvoid getLightDirPoint(vec3 lightPosW) {\n\tdLightDirW = vPositionW - lightPosW;\n\tdLightDirNormW = normalize(dLightDirW);\n\tdLightPosW = lightPosW;\n}\n",lightmapAddPS:"\nvoid addLightMap(\n\tvec3 lightmap, \n\tvec3 dir, \n\tvec3 worldNormal, \n\tvec3 viewDir, \n\tvec3 reflectionDir, \n\tfloat gloss, \n\tvec3 specularity, \n\tvec3 vertexNormal, \n\tmat3 tbn\n#if defined(LIT_IRIDESCENCE)\n\tvec3 iridescenceFresnel, \n\tfloat iridescenceIntensity\n#endif\n) {\n\tdDiffuseLight += lightmap;\n}\n",lightmapDirAddPS:"\nvoid addLightMap(\n\tvec3 lightmap, \n\tvec3 dir, \n\tvec3 worldNormal, \n\tvec3 viewDir, \n\tvec3 reflectionDir, \n\tfloat gloss, \n\tvec3 specularity, \n\tvec3 vertexNormal, \n\tmat3 tbn\n#if defined(LIT_IRIDESCENCE)\n\tvec3 iridescenceFresnel, \n\tfloat iridescenceIntensity\n#endif\n) {\n\tif (dot(dir, dir) < 0.0001) {\n\t\tdDiffuseLight += lightmap;\n\t} else {\n\t\tfloat vlight = saturate(dot(dir, -vertexNormal));\n\t\tfloat flight = saturate(dot(dir, -worldNormal));\n\t\tfloat nlight = (flight / max(vlight, 0.01)) * 0.5;\n\t\tdDiffuseLight += lightmap * nlight * 2.0;\n\t\tvec3 halfDir = normalize(-dir + viewDir);\n\t\tvec3 specularLight = lightmap * getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, dir, gloss, tbn);\n#ifdef LIT_SPECULAR_FRESNEL\n\t\tspecularLight *= \n\t\t\tgetFresnel(dot(viewDir, halfDir), \n\t\t\tgloss, \n\t\t\tspecularity\n\t\t#if defined(LIT_IRIDESCENCE)\n\t\t\t, iridescenceFresnel,\n\t\t\tiridescenceIntensity\n\t\t#endif\n\t\t\t);\n#endif\n\t\tdSpecularLight += specularLight;\n\t}\n}\n",lightmapDirPS:"\nuniform sampler2D texture_lightMap;\nuniform sampler2D texture_dirLightMap;\nvoid getLightMap() {\n\tdLightmap = $DECODE(texture2DBias(texture_lightMap, $UV, textureBias)).$CH;\n\tvec3 dir = texture2DBias(texture_dirLightMap, $UV, textureBias).xyz * 2.0 - 1.0;\n\tfloat dirDot = dot(dir, dir);\n\tdLightmapDir = (dirDot > 0.001) ? dir / sqrt(dirDot) : vec3(0.0);\n}\n",lightmapSinglePS:"\nvoid getLightMap() {\n\tdLightmap = vec3(1.0);\n\t#ifdef MAPTEXTURE\n\tdLightmap *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tdLightmap *= saturate(vVertexColor.$VC);\n\t#endif\n}\n",lightSpecularAnisoGGXPS:"\nfloat calcLightSpecular(float gloss, vec3 worldNormal, vec3 viewDir, vec3 h, vec3 lightDirNorm, mat3 tbn) {\n\tfloat PI = 3.141592653589793;\n\tfloat roughness = max((1.0 - gloss) * (1.0 - gloss), 0.001);\n\tfloat anisotropy = material_anisotropy * roughness;\n \n\tfloat at = max((roughness + anisotropy), roughness / 4.0);\n\tfloat ab = max((roughness - anisotropy), roughness / 4.0);\n\tfloat NoH = dot(worldNormal, h);\n\tfloat ToH = dot(tbn[0], h);\n\tfloat BoH = dot(tbn[1], h);\n\tfloat a2 = at * ab;\n\tvec3 v = vec3(ab * ToH, at * BoH, a2 * NoH);\n\tfloat v2 = dot(v, v);\n\tfloat w2 = a2 / v2;\n\tfloat D = a2 * w2 * w2 * (1.0 / PI);\n\tfloat ToV = dot(tbn[0], viewDir);\n\tfloat BoV = dot(tbn[1], viewDir);\n\tfloat ToL = dot(tbn[0], -lightDirNorm);\n\tfloat BoL = dot(tbn[1], -lightDirNorm);\n\tfloat NoV = dot(worldNormal, viewDir);\n\tfloat NoL = dot(worldNormal, -lightDirNorm);\n\tfloat lambdaV = NoL * length(vec3(at * ToV, ab * BoV, NoV));\n\tfloat lambdaL = NoV * length(vec3(at * ToL, ab * BoL, NoL));\n\tfloat G = 0.5 / (lambdaV + lambdaL);\n\treturn D * G;\n}\nfloat getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) {\n\treturn calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm, tbn);\n}\n",lightSpecularBlinnPS:"\nfloat calcLightSpecular(float gloss, vec3 worldNormal, vec3 h) {\n\tfloat nh = max( dot( h, worldNormal ), 0.0 );\n\tfloat specPow = exp2(gloss * 11.0);\n\tspecPow = max(specPow, 0.0001);\n\treturn pow(nh, specPow) * (specPow + 2.0) / 8.0;\n}\nfloat getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) {\n\treturn calcLightSpecular(gloss, worldNormal, h);\n}\n",lightSpecularPhongPS:"\nfloat calcLightSpecular(float gloss, vec3 reflDir, vec3 lightDirNorm) {\n\tfloat specPow = gloss;\n\treturn pow(max(dot(reflDir, -lightDirNorm), 0.0), specPow + 0.0001);\n}\nfloat getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) {\n\treturn calcLightSpecular(gloss, reflDir, lightDirNorm);\n}\n",lightSheenPS:"\nfloat sheenD(vec3 normal, vec3 h, float roughness) {\n\tfloat invR = 1.0 / (roughness * roughness);\n\tfloat cos2h = max(dot(normal, h), 0.0);\n\tcos2h *= cos2h;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\n\treturn (2.0 + invR) * pow(sin2h, invR * 0.5) / (2.0 * PI);\n}\nfloat sheenV(vec3 normal, vec3 viewDir, vec3 light) {\n\tfloat NoV = max(dot(normal, viewDir), 0.000001);\n\tfloat NoL = max(dot(normal, light), 0.000001);\n\treturn 1.0 / (4.0 * (NoL + NoV - NoL * NoV));\n}\nfloat getLightSpecularSheen(vec3 h, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float sheenGloss) {\n\tfloat D = sheenD(worldNormal, h, sheenGloss);\n\tfloat V = sheenV(worldNormal, viewDir, -lightDirNorm);\n\treturn D * V;\n}\n",linearizeDepthPS:"\n#ifndef LINEARIZE_DEPTH\n#define LINEARIZE_DEPTH\nfloat linearizeDepth(float z, vec4 cameraParams) {\n\tif (cameraParams.w == 0.0)\n\t\treturn (cameraParams.z * cameraParams.y) / (cameraParams.y + z * (cameraParams.z - cameraParams.y));\n\telse\n\t\treturn cameraParams.z + z * (cameraParams.y - cameraParams.z);\n}\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n#endif\n#ifdef GL2\nfloat linearizeDepth(float z) {\n\treturn linearizeDepth(z, camera_params);\n}\n#else\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n\tconst vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n\treturn dot(rgbaDepth, bitShift);\n}\n#endif\n#endif\n#endif\n",litShaderArgsPS:"\nvec3 litArgs_albedo;\nfloat litArgs_opacity;\nvec3 litArgs_emission;\nvec3 litArgs_worldNormal;\nfloat litArgs_ao;\nvec3 litArgs_lightmap;\nvec3 litArgs_lightmapDir;\nfloat litArgs_metalness;\nvec3 litArgs_specularity;\nfloat litArgs_specularityFactor;\nfloat litArgs_gloss;\nfloat litArgs_sheen_gloss;\nvec3 litArgs_sheen_specularity;\nfloat litArgs_transmission;\nfloat litArgs_thickness;\nfloat litArgs_ior;\nfloat litArgs_iridescence_intensity;\nfloat litArgs_iridescence_thickness;\nvec3 litArgs_clearcoat_worldNormal;\nfloat litArgs_clearcoat_specularity;\nfloat litArgs_clearcoat_gloss;\n",ltcPS:"\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nstruct Coords {\n\tvec3 coord0;\n\tvec3 coord1;\n\tvec3 coord2;\n\tvec3 coord3;\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\tvec3 v1 = rectCoords.coord1 - rectCoords.coord0;\n\tvec3 v2 = rectCoords.coord3 - rectCoords.coord0;\n\t\n\tvec3 lightNormal = cross( v1, v2 );\n\tfloat factor = sign(-dot( lightNormal, P - rectCoords.coord0 ));\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = factor * cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords.coord0 - P );\n\tcoords[ 1 ] = mat * ( rectCoords.coord1 - P );\n\tcoords[ 2 ] = mat * ( rectCoords.coord2 - P );\n\tcoords[ 3 ] = mat * ( rectCoords.coord3 - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn result;\n}\nCoords dLTCCoords;\nCoords getLTCLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){\n\tCoords coords;\n\tcoords.coord0 = lightPos + halfWidth - halfHeight;\n\tcoords.coord1 = lightPos - halfWidth - halfHeight;\n\tcoords.coord2 = lightPos - halfWidth + halfHeight;\n\tcoords.coord3 = lightPos + halfWidth + halfHeight;\n\treturn coords;\n}\nfloat dSphereRadius;\nCoords getSphereLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){\n\tdSphereRadius = max(length(halfWidth), length(halfHeight));\n\tvec3 f = reflect(normalize(lightPos - view_position), vNormalW);\n\tvec3 w = normalize(cross(f, halfHeight));\n\tvec3 h = normalize(cross(f, w));\n\treturn getLTCLightCoords(lightPos, w * dSphereRadius, h * dSphereRadius);\n}\nvec2 dLTCUV;\n#ifdef LIT_CLEARCOAT\nvec2 ccLTCUV;\n#endif\nvec2 getLTCLightUV(float gloss, vec3 worldNormal, vec3 viewDir)\n{\n\tfloat roughness = max((1.0 - gloss) * (1.0 - gloss), 0.001);\n\treturn LTC_Uv( worldNormal, viewDir, roughness );\n}\nvec3 dLTCSpecFres;\n#ifdef LIT_CLEARCOAT\nvec3 ccLTCSpecFres;\n#endif\nvec3 getLTCLightSpecFres(vec2 uv, vec3 specularity)\n{\n\tvec4 t2 = texture2DLodEXT(areaLightsLutTex2, uv, 0.0);\n\t#ifdef AREA_R8_G8_B8_A8_LUTS\n\tt2 *= vec4(0.693103,1,1,1);\n\tt2 += vec4(0.306897,0,0,0);\n\t#endif\n\treturn specularity * t2.x + ( vec3( 1.0 ) - specularity) * t2.y;\n}\nvoid calcLTCLightValues(float gloss, vec3 worldNormal, vec3 viewDir, vec3 specularity, float clearcoatGloss, vec3 clearcoatWorldNormal, float clearcoatSpecularity)\n{\n\tdLTCUV = getLTCLightUV(gloss, worldNormal, viewDir);\n\tdLTCSpecFres = getLTCLightSpecFres(dLTCUV, specularity); \n#ifdef LIT_CLEARCOAT\n\tccLTCUV = getLTCLightUV(clearcoatGloss, clearcoatWorldNormal, viewDir);\n\tccLTCSpecFres = getLTCLightSpecFres(ccLTCUV, vec3(clearcoatSpecularity));\n#endif\n}\nvoid calcRectLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n\tdLTCCoords = getLTCLightCoords(lightPos, halfWidth, halfHeight);\n}\nvoid calcDiskLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n\tcalcRectLightValues(lightPos, halfWidth, halfHeight);\n}\nvoid calcSphereLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n\tdLTCCoords = getSphereLightCoords(lightPos, halfWidth, halfHeight);\n}\nvec3 SolveCubic(vec4 Coefficient)\n{\n\tfloat pi = 3.14159;\n\tCoefficient.xyz /= Coefficient.w;\n\tCoefficient.yz /= 3.0;\n\tfloat A = Coefficient.w;\n\tfloat B = Coefficient.z;\n\tfloat C = Coefficient.y;\n\tfloat D = Coefficient.x;\n\tvec3 Delta = vec3(\n\t\t-Coefficient.z * Coefficient.z + Coefficient.y,\n\t\t-Coefficient.y * Coefficient.z + Coefficient.x,\n\t\tdot(vec2(Coefficient.z, -Coefficient.y), Coefficient.xy)\n\t);\n\tfloat Discriminant = dot(vec2(4.0 * Delta.x, -Delta.y), Delta.zy);\n\tvec3 RootsA, RootsD;\n\tvec2 xlc, xsc;\n\t{\n\t\tfloat A_a = 1.0;\n\t\tfloat C_a = Delta.x;\n\t\tfloat D_a = -2.0 * B * Delta.x + Delta.y;\n\t\tfloat Theta = atan(sqrt(Discriminant), -D_a) / 3.0;\n\t\tfloat x_1a = 2.0 * sqrt(-C_a) * cos(Theta);\n\t\tfloat x_3a = 2.0 * sqrt(-C_a) * cos(Theta + (2.0 / 3.0) * pi);\n\t\tfloat xl;\n\t\tif ((x_1a + x_3a) > 2.0 * B)\n\t\t\txl = x_1a;\n\t\telse\n\t\t\txl = x_3a;\n\t\txlc = vec2(xl - B, A);\n\t}\n\t{\n\t\tfloat A_d = D;\n\t\tfloat C_d = Delta.z;\n\t\tfloat D_d = -D * Delta.y + 2.0 * C * Delta.z;\n\t\tfloat Theta = atan(D * sqrt(Discriminant), -D_d) / 3.0;\n\t\tfloat x_1d = 2.0 * sqrt(-C_d) * cos(Theta);\n\t\tfloat x_3d = 2.0 * sqrt(-C_d) * cos(Theta + (2.0 / 3.0) * pi);\n\t\tfloat xs;\n\t\tif (x_1d + x_3d < 2.0 * C)\n\t\t\txs = x_1d;\n\t\telse\n\t\t\txs = x_3d;\n\t\txsc = vec2(-D, xs + C);\n\t}\n\tfloat E = xlc.y * xsc.y;\n\tfloat F = -xlc.x * xsc.y - xlc.y * xsc.x;\n\tfloat G = xlc.x * xsc.x;\n\tvec2 xmc = vec2(C * F - B * G, -B * F + C * E);\n\tvec3 Root = vec3(xsc.x / xsc.y, xmc.x / xmc.y, xlc.x / xlc.y);\n\tif (Root.x < Root.y && Root.x < Root.z)\n\t\tRoot.xyz = Root.yxz;\n\telse if (Root.z < Root.x && Root.z < Root.y)\n\t\tRoot.xyz = Root.xzy;\n\treturn Root;\n}\nfloat LTC_EvaluateDisk(vec3 N, vec3 V, vec3 P, mat3 Minv, Coords points)\n{\n\tvec3 T1, T2;\n\tT1 = normalize(V - N * dot(V, N));\n\tT2 = cross(N, T1);\n\tmat3 R = transposeMat3( mat3( T1, T2, N ) );\n\tvec3 L_[ 3 ];\n\tL_[ 0 ] = R * ( points.coord0 - P );\n\tL_[ 1 ] = R * ( points.coord1 - P );\n\tL_[ 2 ] = R * ( points.coord2 - P );\n\tvec3 Lo_i = vec3(0);\n\tvec3 C = 0.5 * (L_[0] + L_[2]);\n\tvec3 V1 = 0.5 * (L_[1] - L_[2]);\n\tvec3 V2 = 0.5 * (L_[1] - L_[0]);\n\tC = Minv * C;\n\tV1 = Minv * V1;\n\tV2 = Minv * V2;\n\tfloat a, b;\n\tfloat d11 = dot(V1, V1);\n\tfloat d22 = dot(V2, V2);\n\tfloat d12 = dot(V1, V2);\n\tif (abs(d12) / sqrt(d11 * d22) > 0.0001)\n\t{\n\t\tfloat tr = d11 + d22;\n\t\tfloat det = -d12 * d12 + d11 * d22;\n\t\tdet = sqrt(det);\n\t\tfloat u = 0.5 * sqrt(tr - 2.0 * det);\n\t\tfloat v = 0.5 * sqrt(tr + 2.0 * det);\n\t\tfloat e_max = (u + v) * (u + v);\n\t\tfloat e_min = (u - v) * (u - v);\n\t\tvec3 V1_, V2_;\n\t\tif (d11 > d22)\n\t\t{\n\t\t\tV1_ = d12 * V1 + (e_max - d11) * V2;\n\t\t\tV2_ = d12 * V1 + (e_min - d11) * V2;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tV1_ = d12*V2 + (e_max - d22)*V1;\n\t\t\tV2_ = d12*V2 + (e_min - d22)*V1;\n\t\t}\n\t\ta = 1.0 / e_max;\n\t\tb = 1.0 / e_min;\n\t\tV1 = normalize(V1_);\n\t\tV2 = normalize(V2_);\n\t}\n\telse\n\t{\n\t\ta = 1.0 / dot(V1, V1);\n\t\tb = 1.0 / dot(V2, V2);\n\t\tV1 *= sqrt(a);\n\t\tV2 *= sqrt(b);\n\t}\n\tvec3 V3 = cross(V1, V2);\n\tif (dot(C, V3) < 0.0)\n\t\tV3 *= -1.0;\n\tfloat L = dot(V3, C);\n\tfloat x0 = dot(V1, C) / L;\n\tfloat y0 = dot(V2, C) / L;\n\tfloat E1 = inversesqrt(a);\n\tfloat E2 = inversesqrt(b);\n\ta *= L * L;\n\tb *= L * L;\n\tfloat c0 = a * b;\n\tfloat c1 = a * b * (1.0 + x0 * x0 + y0 * y0) - a - b;\n\tfloat c2 = 1.0 - a * (1.0 + x0 * x0) - b * (1.0 + y0 * y0);\n\tfloat c3 = 1.0;\n\tvec3 roots = SolveCubic(vec4(c0, c1, c2, c3));\n\tfloat e1 = roots.x;\n\tfloat e2 = roots.y;\n\tfloat e3 = roots.z;\n\tvec3 avgDir = vec3(a * x0 / (a - e2), b * y0 / (b - e2), 1.0);\n\tmat3 rotate = mat3(V1, V2, V3);\n\tavgDir = rotate * avgDir;\n\tavgDir = normalize(avgDir);\n\tfloat L1 = sqrt(-e2 / e3);\n\tfloat L2 = sqrt(-e2 / e1);\n\tfloat formFactor = L1 * L2 * inversesqrt((1.0 + L1 * L1) * (1.0 + L2 * L2));\n\t\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tvec2 uv = vec2(avgDir.z * 0.5 + 0.5, formFactor);\n\tuv = uv*LUT_SCALE + LUT_BIAS;\n\tfloat scale = texture2DLodEXT(areaLightsLutTex2, uv, 0.0).w;\n\treturn formFactor*scale;\n}\nfloat getRectLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {\n\treturn LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mat3( 1.0 ), dLTCCoords );\n}\nfloat getDiskLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {\n\treturn LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mat3( 1.0 ), dLTCCoords );\n}\nfloat getSphereLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {\n\tfloat falloff = dSphereRadius / (dot(lightDir, lightDir) + dSphereRadius);\n\treturn getLightDiffuse(worldNormal, viewDir, lightDir, lightDirNorm) * falloff;\n}\nmat3 getLTCLightInvMat(vec2 uv)\n{\n\tvec4 t1 = texture2DLodEXT(areaLightsLutTex1, uv, 0.0);\n\t#ifdef AREA_R8_G8_B8_A8_LUTS\n\tt1 *= vec4(1.001, 0.3239, 0.60437568, 1.0);\n\tt1 += vec4(0.0, -0.2976, -0.01381, 0.0);\n\t#endif\n\treturn mat3(\n\t\tvec3( t1.x, 0, t1.y ),\n\t\tvec3(\t0, 1,\t0 ),\n\t\tvec3( t1.z, 0, t1.w )\n\t);\n}\nfloat calcRectLightSpecular(vec3 worldNormal, vec3 viewDir, vec2 uv) {\n\tmat3 mInv = getLTCLightInvMat(uv);\n\treturn LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );\n}\nfloat getRectLightSpecular(vec3 worldNormal, vec3 viewDir) {\n\treturn calcRectLightSpecular(worldNormal, viewDir, dLTCUV);\n}\nfloat calcDiskLightSpecular(vec3 worldNormal, vec3 viewDir, vec2 uv) {\n\tmat3 mInv = getLTCLightInvMat(uv);\n\treturn LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );\n}\nfloat getDiskLightSpecular(vec3 worldNormal, vec3 viewDir) {\n\treturn calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);\n}\nfloat getSphereLightSpecular(vec3 worldNormal, vec3 viewDir) {\n\treturn calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);\n}\n",metalnessPS:"\n#ifdef MAPFLOAT\nuniform float material_metalness;\n#endif\nvoid getMetalness() {\n\tfloat metalness = 1.0;\n\t#ifdef MAPFLOAT\n\tmetalness *= material_metalness;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tmetalness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tmetalness *= saturate(vVertexColor.$VC);\n\t#endif\n\tdMetalness = metalness;\n}\n",metalnessModulatePS:"\nvec3 getSpecularModulate(in vec3 specularity, in vec3 albedo, in float metalness, in float f0) {\n\tvec3 dielectricF0 = f0 * specularity;\n\treturn mix(dielectricF0, albedo, metalness);\n}\nvec3 getAlbedoModulate(in vec3 albedo, in float metalness) {\n\treturn albedo * (1.0 - metalness);\n}\n",msdfPS:"\nuniform sampler2D texture_msdfMap;\n#ifdef GL_OES_standard_derivatives\n#define USE_FWIDTH\n#endif\n#ifdef GL2\n#define USE_FWIDTH\n#endif\nfloat median(float r, float g, float b) {\n\treturn max(min(r, g), min(max(r, g), b));\n}\nfloat map (float min, float max, float v) {\n\treturn (v - min) / (max - min);\n}\nuniform float font_sdfIntensity;\nuniform float font_pxrange;\nuniform float font_textureWidth;\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\nvec4 applyMsdf(vec4 color) {\n\tvec3 tsample = texture2D(texture_msdfMap, vUv0).rgb;\n\tvec2 uvShdw = vUv0 - shadow_offset;\n\tvec3 ssample = texture2D(texture_msdfMap, uvShdw).rgb;\n\tfloat sigDist = median(tsample.r, tsample.g, tsample.b);\n\tfloat sigDistShdw = median(ssample.r, ssample.g, ssample.b);\n\tfloat smoothingMax = 0.2;\n\t#ifdef USE_FWIDTH\n\tvec2 w = fwidth(vUv0);\n\tfloat smoothing = clamp(w.x * font_textureWidth / font_pxrange, 0.0, smoothingMax);\n\t#else\n\tfloat font_size = 16.0;\n\tfloat smoothing = clamp(font_pxrange / font_size, 0.0, smoothingMax);\n\t#endif\n\tfloat mapMin = 0.05;\n\tfloat mapMax = clamp(1.0 - font_sdfIntensity, mapMin, 1.0);\n\tfloat sigDistInner = map(mapMin, mapMax, sigDist);\n\tfloat sigDistOutline = map(mapMin, mapMax, sigDist + outline_thickness);\n\tsigDistShdw = map(mapMin, mapMax, sigDistShdw + outline_thickness);\n\tfloat center = 0.5;\n\tfloat inside = smoothstep(center-smoothing, center+smoothing, sigDistInner);\n\tfloat outline = smoothstep(center-smoothing, center+smoothing, sigDistOutline);\n\tfloat shadow = smoothstep(center-smoothing, center+smoothing, sigDistShdw);\n\tvec4 tcolor = (outline > inside) ? outline * vec4(outline_color.a * outline_color.rgb, outline_color.a) : vec4(0.0);\n\ttcolor = mix(tcolor, color, inside);\n\tvec4 scolor = (shadow > outline) ? shadow * vec4(shadow_color.a * shadow_color.rgb, shadow_color.a) : tcolor;\n\ttcolor = mix(scolor, tcolor, outline);\n\t\n\treturn tcolor;\n}\n",msdfVS:"\nattribute vec3 vertex_outlineParameters;\nattribute vec3 vertex_shadowParameters;\nvarying vec4 outline_color;\nvarying float outline_thickness;\nvarying vec4 shadow_color;\nvarying vec2 shadow_offset;\nvoid unpackMsdfParams() {\n\tvec3 little = mod(vertex_outlineParameters, 256.);\n\tvec3 big = (vertex_outlineParameters - little) / 256.;\n\toutline_color.rb = little.xy / 255.;\n\toutline_color.ga = big.xy / 255.;\n\toutline_thickness = little.z / 255. * 0.2;\n\tlittle = mod(vertex_shadowParameters, 256.);\n\tbig = (vertex_shadowParameters - little) / 256.;\n\tshadow_color.rb = little.xy / 255.;\n\tshadow_color.ga = big.xy / 255.;\n\tshadow_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\nvec3 getNormal() {\n\t#ifdef SKIN\n\tdNormalMatrix = mat3(dModelMatrix[0].xyz, dModelMatrix[1].xyz, dModelMatrix[2].xyz);\n\t#elif defined(INSTANCING)\n\tdNormalMatrix = mat3(instance_line1.xyz, instance_line2.xyz, instance_line3.xyz);\n\t#else\n\tdNormalMatrix = matrix_normal;\n\t#endif\n\tvec3 tempNormal = vertex_normal;\n\t#ifdef MORPHING\n\t#ifdef MORPHING_NRM03\n\ttempNormal += morph_weights_a[0] * morph_nrm0;\n\ttempNormal += morph_weights_a[1] * morph_nrm1;\n\ttempNormal += morph_weights_a[2] * morph_nrm2;\n\ttempNormal += morph_weights_a[3] * morph_nrm3;\n\t#endif\n\t#ifdef MORPHING_NRM47\n\ttempNormal += morph_weights_b[0] * morph_nrm4;\n\ttempNormal += morph_weights_b[1] * morph_nrm5;\n\ttempNormal += morph_weights_b[2] * morph_nrm6;\n\ttempNormal += morph_weights_b[3] * morph_nrm7;\n\t#endif\n\t#endif\n\t#ifdef MORPHING_TEXTURE_BASED_NORMAL\n\t\t#ifdef WEBGPU\n\t\t\tivec2 morphUV = getTextureMorphCoords();\n\t\t\tvec3 morphNormal = texelFetch(morphNormalTex, ivec2(morphUV), 0).xyz;\n\t\t#else\n\t\t\tvec2 morphUV = getTextureMorphCoords();\n\t\t\tvec3 morphNormal = texture2D(morphNormalTex, morphUV).xyz;\n\t\t#endif\n\ttempNormal += morphNormal;\n\t#endif\n\treturn normalize(dNormalMatrix * tempNormal);\n}\n",normalDetailMapPS:"\n#ifdef MAPTEXTURE\nuniform float material_normalDetailMapBumpiness;\nvec3 blendNormals(vec3 n1, vec3 n2) {\n\tn1 += vec3(0, 0, 1);\n\tn2 *= vec3(-1, -1, 1);\n\treturn n1 * dot(n1, n2) / n1.z - n2;\n}\n#endif\nvec3 addNormalDetail(vec3 normalMap) {\n#ifdef MAPTEXTURE\n\tvec3 normalDetailMap = unpackNormal(texture2DBias($SAMPLER, $UV, textureBias));\n\tnormalDetailMap = mix(vec3(0.0, 0.0, 1.0), normalDetailMap, material_normalDetailMapBumpiness);\n\treturn blendNormals(normalMap, normalDetailMap);\n#else\n\treturn normalMap;\n#endif\n}\n",normalInstancedVS:"\nvec3 getNormal() {\n\tdNormalMatrix = mat3(instance_line1.xyz, instance_line2.xyz, instance_line3.xyz);\n\treturn normalize(dNormalMatrix * vertex_normal);\n}\n",normalMapPS:"\n#ifdef MAPTEXTURE\nuniform float material_bumpiness;\n#endif\nvoid getNormal() {\n#ifdef MAPTEXTURE\n\tvec3 normalMap = unpackNormal(texture2DBias($SAMPLER, $UV, textureBias));\n\tnormalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, material_bumpiness);\n\tdNormalW = normalize(dTBN * addNormalDetail(normalMap));\n#else\n\tdNormalW = dVertexNormalW;\n#endif\n}\n",normalSkinnedVS:"\nvec3 getNormal() {\n\tdNormalMatrix = mat3(dModelMatrix[0].xyz, dModelMatrix[1].xyz, dModelMatrix[2].xyz);\n\treturn normalize(dNormalMatrix * vertex_normal);\n}\n",normalXYPS:"\nvec3 unpackNormal(vec4 nmap) {\n\tvec3 normal;\n\tnormal.xy = nmap.wy * 2.0 - 1.0;\n\tnormal.z = sqrt(1.0 - saturate(dot(normal.xy, normal.xy)));\n\treturn normal;\n}\n",normalXYZPS:"\nvec3 unpackNormal(vec4 nmap) {\n\treturn nmap.xyz * 2.0 - 1.0;\n}\n",opacityPS:"\n#ifdef MAPFLOAT\nuniform float material_opacity;\n#endif\nvoid getOpacity() {\n\tdAlpha = 1.0;\n\t#ifdef MAPFLOAT\n\tdAlpha *= material_opacity;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tdAlpha *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tdAlpha *= clamp(vVertexColor.$VC, 0.0, 1.0);\n\t#endif\n}\n",outputPS:"\n",outputAlphaPS:"\ngl_FragColor.a = litArgs_opacity;\n",outputAlphaOpaquePS:"\n\tgl_FragColor.a = 1.0;\n",outputAlphaPremulPS:"\ngl_FragColor.rgb *= litArgs_opacity;\ngl_FragColor.a = litArgs_opacity;\n",outputTex2DPS:"\nvarying vec2 vUv0;\nuniform sampler2D source;\nvoid main(void) {\n\tgl_FragColor = texture2D(source, vUv0);\n}\n",packDepthPS:"\nvec4 packFloat(float depth) {\n\tconst vec4 bit_shift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);\n\tvec4 res = mod(depth * bit_shift * vec4(255), vec4(256) ) / vec4(255);\n\tres -= res.xxyz * bit_mask;\n\treturn res;\n}\n",sheenPS:"\n#ifdef MAPCOLOR\nuniform vec3 material_sheen;\n#endif\nvoid getSheen() {\n\tvec3 sheenColor = vec3(1, 1, 1);\n\t#ifdef MAPCOLOR\n\tsheenColor *= material_sheen;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tsheenColor *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tsheenColor *= saturate(vVertexColor.$VC);\n\t#endif\n\tsSpecularity = sheenColor;\n}\n",sheenGlossPS:"\n#ifdef MAPFLOAT\nuniform float material_sheenGloss;\n#endif\nvoid getSheenGlossiness() {\n\tfloat sheenGlossiness = 1.0;\n\t#ifdef MAPFLOAT\n\tsheenGlossiness *= material_sheenGloss;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tsheenGlossiness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tsheenGlossiness *= saturate(vVertexColor.$VC);\n\t#endif\n\t#ifdef MAPINVERT\n\tsheenGlossiness = 1.0 - sheenGlossiness;\n\t#endif\n\tsheenGlossiness += 0.0000001;\n\tsGlossiness = sheenGlossiness;\n}\n",parallaxPS:"\nuniform float material_heightMapFactor;\nvoid getParallax() {\n\tfloat parallaxScale = material_heightMapFactor;\n\tfloat height = texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\theight = height * parallaxScale - parallaxScale*0.5;\n\tvec3 viewDirT = dViewDirW * dTBN;\n\tviewDirT.z += 0.42;\n\tdUvOffset = height * (viewDirT.xy / viewDirT.z);\n}\n",particlePS:"\nvarying vec4 texCoordsAlphaLife;\nuniform sampler2D colorMap;\nuniform sampler2D colorParam;\nuniform float graphSampleSize;\nuniform float graphNumSamples;\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n#endif\nuniform float softening;\nuniform float colorMult;\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n\tconst vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n\tfloat depth = dot(rgbaDepth, bitShift);\n\treturn depth;\n}\n#endif\nvoid main(void) {\n\tvec4 tex = gammaCorrectInput(texture2D(colorMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y)));\n\tvec4 ramp = gammaCorrectInput(texture2D(colorParam, vec2(texCoordsAlphaLife.w, 0.0)));\n\tramp.rgb *= colorMult;\n\tramp.a += texCoordsAlphaLife.z;\n\tvec3 rgb = tex.rgb * ramp.rgb;\n\tfloat a = tex.a * ramp.a;\n",particleVS:"\nvec3 unpack3NFloats(float src) {\n\tfloat r = fract(src);\n\tfloat g = fract(src * 256.0);\n\tfloat b = fract(src * 65536.0);\n\treturn vec3(r, g, b);\n}\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\nvec4 tex1Dlod_lerp(highp sampler2D tex, vec2 tc) {\n\treturn mix( texture2D(tex,tc), texture2D(tex,tc + graphSampleSize), fract(tc.x*graphNumSamples) );\n}\nvec4 tex1Dlod_lerp(highp sampler2D tex, vec2 tc, out vec3 w) {\n\tvec4 a = texture2D(tex,tc);\n\tvec4 b = texture2D(tex,tc + graphSampleSize);\n\tfloat c = fract(tc.x*graphNumSamples);\n\tvec3 unpackedA = unpack3NFloats(a.w);\n\tvec3 unpackedB = unpack3NFloats(b.w);\n\tw = mix(unpackedA, unpackedB, c);\n\treturn mix(a, b, c);\n}\nvec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix) {\n\tfloat c = cos(pRotation);\n\tfloat s = sin(pRotation);\n\tmat2 m = mat2(c, -s, s, c);\n\trotMatrix = m;\n\treturn m * quadXY;\n}\nvec3 billboard(vec3 InstanceCoords, vec2 quadXY) {\n\t#ifdef SCREEN_SPACE\n\t\tvec3 pos = vec3(-1, 0, 0) * quadXY.x + vec3(0, -1, 0) * quadXY.y;\n\t#else\n\t\tvec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;\n\t#endif\n\treturn pos;\n}\nvec3 customFace(vec3 InstanceCoords, vec2 quadXY) {\n\tvec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;\n\treturn pos;\n}\nvec2 safeNormalize(vec2 v) {\n\tfloat l = length(v);\n\treturn (l > 1e-06) ? v / l : v;\n}\nvoid main(void) {\n\tvec3 meshLocalPos = particle_vertexData.xyz;\n\tfloat id = floor(particle_vertexData.w);\n\tfloat rndFactor = fract(sin(id + 1.0 + seed));\n\tvec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));\n\tfloat uv = id / numParticlesPot;\n\treadInput(uv);\n#ifdef LOCAL_SPACE\n\tinVel = mat3(matrix_model) * inVel;\n#endif\n\tvec2 velocityV = safeNormalize((mat3(matrix_view) * inVel).xy);\n\tfloat particleLifetime = lifetime;\n\tif (inLife <= 0.0 || inLife > particleLifetime || !inShow) meshLocalPos = vec3(0.0);\n\tvec2 quadXY = meshLocalPos.xy;\n\tfloat nlife = clamp(inLife / particleLifetime, 0.0, 1.0);\n\tvec3 paramDiv;\n\tvec4 params = tex1Dlod_lerp(internalTex2, vec2(nlife, 0), paramDiv);\n\tfloat scale = params.y;\n\tfloat scaleDiv = paramDiv.x;\n\tfloat alphaDiv = paramDiv.z;\n\tscale += (scaleDiv * 2.0 - 1.0) * scaleDivMult * fract(rndFactor*10000.0);\n#ifndef USE_MESH\n\ttexCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);\n#else\n\ttexCoordsAlphaLife = vec4(particle_uv, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);\n#endif\n\tvec3 particlePos = inPos;\n\tvec3 particlePosMoved = vec3(0.0);\n\tmat2 rotMatrix;\n",particleAnimFrameClampVS:"\n\tfloat animFrame = min(floor(texCoordsAlphaLife.w * animTexParams.y) + animTexParams.x, animTexParams.z);\n",particleAnimFrameLoopVS:"\n\tfloat animFrame = floor(mod(texCoordsAlphaLife.w * animTexParams.y + animTexParams.x, animTexParams.z + 1.0));\n",particleAnimTexVS:"\n\tfloat animationIndex;\n\tif (animTexIndexParams.y == 1.0) {\n\t\tanimationIndex = floor((animTexParams.w + 1.0) * rndFactor3.z) * (animTexParams.z + 1.0);\n\t} else {\n\t\tanimationIndex = animTexIndexParams.x * (animTexParams.z + 1.0);\n\t}\n\tfloat atlasX = (animationIndex + animFrame) * animTexTilesParams.x;\n\tfloat atlasY = 1.0 - floor(atlasX + 1.0) * animTexTilesParams.y;\n\tatlasX = fract(atlasX);\n\ttexCoordsAlphaLife.xy *= animTexTilesParams.xy;\n\ttexCoordsAlphaLife.xy += vec2(atlasX, atlasY);\n",particleInputFloatPS:"\nvoid readInput(float uv) {\n\tvec4 tex = texture2D(particleTexIN, vec2(uv, 0.25));\n\tvec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.75));\n\tinPos = tex.xyz;\n\tinVel = tex2.xyz;\n\tinAngle = (tex.w < 0.0? -tex.w : tex.w) - 1000.0;\n\tinShow = tex.w >= 0.0;\n\tinLife = tex2.w;\n}\n",particleInputRgba8PS:"\n#define PI2 6.283185307179586\nuniform vec3 inBoundsSize;\nuniform vec3 inBoundsCenter;\nuniform float maxVel;\nfloat decodeFloatRG(vec2 rg) {\n\treturn rg.y*(1.0/255.0) + rg.x;\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}\nvoid readInput(float uv) {\n\tvec4 tex0 = texture2D(particleTexIN, vec2(uv, 0.125));\n\tvec4 tex1 = texture2D(particleTexIN, vec2(uv, 0.375));\n\tvec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.625));\n\tvec4 tex3 = texture2D(particleTexIN, vec2(uv, 0.875));\n\tinPos = vec3(decodeFloatRG(tex0.rg), decodeFloatRG(tex0.ba), decodeFloatRG(tex1.rg));\n\tinPos = (inPos - vec3(0.5)) * inBoundsSize + inBoundsCenter;\n\tinVel = tex2.xyz;\n\tinVel = (inVel - vec3(0.5)) * maxVel;\n\tinAngle = decodeFloatRG(tex1.ba) * PI2;\n\tinShow = tex2.a > 0.5;\n\tinLife = decodeFloatRGBA(tex3);\n\tfloat maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));\n\tfloat maxPosLife = lifetime+1.0;\n\tinLife = inLife * (maxNegLife + maxPosLife) - maxNegLife;\n}\n",particleOutputFloatPS:"\nvoid writeOutput() {\n\tif (gl_FragCoord.y<1.0) {\n\t\tgl_FragColor = vec4(outPos, (outAngle + 1000.0) * visMode);\n\t} else {\n\t\tgl_FragColor = vec4(outVel, outLife);\n\t}\n}\n",particleOutputRgba8PS:"\nuniform vec3 outBoundsMul;\nuniform vec3 outBoundsAdd;\nvec2 encodeFloatRG( float v ) {\n\tvec2 enc = vec2(1.0, 255.0) * v;\n\tenc = fract(enc);\n\tenc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n\treturn enc;\n}\nvec4 encodeFloatRGBA( float v ) {\n\tvec4 enc = vec4(1.0, 255.0, 65025.0, 160581375.0) * v;\n\tenc = fract(enc);\n\tenc -= enc.yzww * vec4(1.0/255.0,1.0/255.0,1.0/255.0,0.0);\n\treturn enc;\n}\nvoid writeOutput() {\n\toutPos = outPos * outBoundsMul + outBoundsAdd;\n\toutAngle = fract(outAngle / PI2);\n\toutVel = (outVel / maxVel) + vec3(0.5);\n\tfloat maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));\n\tfloat maxPosLife = lifetime+1.0;\n\toutLife = (outLife + maxNegLife) / (maxNegLife + maxPosLife);\n\tif (gl_FragCoord.y < 1.0) {\n\t\tgl_FragColor = vec4(encodeFloatRG(outPos.x), encodeFloatRG(outPos.y));\n\t} else if (gl_FragCoord.y < 2.0) {\n\t\tgl_FragColor = vec4(encodeFloatRG(outPos.z), encodeFloatRG(outAngle));\n\t} else if (gl_FragCoord.y < 3.0) {\n\t\tgl_FragColor = vec4(outVel, visMode*0.5+0.5);\n\t} else {\n\t\tgl_FragColor = encodeFloatRGBA(outLife);\n\t}\n}\n",particleUpdaterAABBPS:"\nuniform mat3 spawnBounds;\nuniform vec3 spawnPosInnerRatio;\nvec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {\n\tvec3 pos = inBounds - vec3(0.5);\n\tvec3 posAbs = abs(pos);\n\tvec3 maxPos = vec3(max(posAbs.x, max(posAbs.y, posAbs.z)));\n\tvec3 edge = maxPos + (vec3(0.5) - maxPos) * spawnPosInnerRatio;\n\tpos.x = edge.x * (maxPos.x == posAbs.x ? sign(pos.x) : 2.0 * pos.x);\n\tpos.y = edge.y * (maxPos.y == posAbs.y ? sign(pos.y) : 2.0 * pos.y);\n\tpos.z = edge.z * (maxPos.z == posAbs.z ? sign(pos.z) : 2.0 * pos.z);\n#ifndef LOCAL_SPACE\n\treturn emitterPos + spawnBounds * pos;\n#else\n\treturn spawnBounds * pos;\n#endif\n}\nvoid addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {\n\tlocalVelocity -= vec3(0, 0, initialVelocity);\n}\n",particleUpdaterEndPS:"\n\twriteOutput();\n}\n",particleUpdaterInitPS:"\nvarying vec2 vUv0;\nuniform highp sampler2D particleTexIN;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\nuniform highp sampler2D internalTex3;\nuniform mat3 emitterMatrix, emitterMatrixInv;\nuniform vec3 emitterScale;\nuniform vec3 emitterPos, frameRandom, localVelocityDivMult, velocityDivMult;\nuniform float delta, rate, rateDiv, lifetime, numParticles, rotSpeedDivMult, radialSpeedDivMult, seed;\nuniform float startAngle, startAngle2;\nuniform float initialVelocity;\nuniform float graphSampleSize;\nuniform float graphNumSamples;\nvec3 inPos;\nvec3 inVel;\nfloat inAngle;\nbool inShow;\nfloat inLife;\nfloat visMode;\nvec3 outPos;\nvec3 outVel;\nfloat outAngle;\nbool outShow;\nfloat outLife;\n",particleUpdaterNoRespawnPS:"\n\tif (outLife >= lifetime) {\n\t\toutLife -= max(lifetime, (numParticles - 1.0) * particleRate);\n\t\tvisMode = -1.0;\n\t}\n",particleUpdaterOnStopPS:"\n\tvisMode = outLife < 0.0? -1.0: visMode;\n",particleUpdaterRespawnPS:"\n\tif (outLife >= lifetime) {\n\t\toutLife -= max(lifetime, (numParticles - 1.0) * particleRate);\n\t\tvisMode = 1.0;\n\t}\n\tvisMode = outLife < 0.0? 1.0: visMode;\n",particleUpdaterSpherePS:"\nuniform float spawnBoundsSphere;\nuniform float spawnBoundsSphereInnerRatio;\nvec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {\n\tfloat rnd4 = fract(rndFactor * 1000.0);\n\tvec3 norm = normalize(inBounds.xyz - vec3(0.5));\n\tfloat r = rnd4 * (1.0 - spawnBoundsSphereInnerRatio) + spawnBoundsSphereInnerRatio;\n#ifndef LOCAL_SPACE\n\treturn emitterPos + norm * r * spawnBoundsSphere;\n#else\n\treturn norm * r * spawnBoundsSphere;\n#endif\n}\nvoid addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {\n\tlocalVelocity += normalize(inBounds - vec3(0.5)) * initialVelocity;\n}\n",particleUpdaterStartPS:"\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\nvec3 unpack3NFloats(float src) {\n\tfloat r = fract(src);\n\tfloat g = fract(src * 256.0);\n\tfloat b = fract(src * 65536.0);\n\treturn vec3(r, g, b);\n}\nvec3 tex1Dlod_lerp(highp sampler2D tex, vec2 tc, out vec3 w) {\n\tvec4 a = texture2D(tex, tc);\n\tvec4 b = texture2D(tex, tc + graphSampleSize);\n\tfloat c = fract(tc.x * graphNumSamples);\n\tvec3 unpackedA = unpack3NFloats(a.w);\n\tvec3 unpackedB = unpack3NFloats(b.w);\n\tw = mix(unpackedA, unpackedB, c);\n\treturn mix(a.xyz, b.xyz, c);\n}\n#define HASHSCALE4 vec4(1031, .1030, .0973, .1099)\nvec4 hash41(float p) {\n\tvec4 p4 = fract(vec4(p) * HASHSCALE4);\n\tp4 += dot(p4, p4.wzxy+19.19);\n\treturn 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}\nvoid main(void) {\n\tif (gl_FragCoord.x > numParticles) discard;\n\treadInput(vUv0.x);\n\tvisMode = inShow? 1.0 : -1.0;\n\tvec4 rndFactor = hash41(gl_FragCoord.x + seed);\n\tfloat particleRate = rate + rateDiv * rndFactor.x;\n\toutLife = inLife + delta;\n\tfloat nlife = clamp(outLife / lifetime, 0.0, 1.0);\n\tvec3 localVelocityDiv;\n\tvec3 velocityDiv;\n\tvec3 paramDiv;\n\tvec3 localVelocity = tex1Dlod_lerp(internalTex0, vec2(nlife, 0), localVelocityDiv);\n\tvec3 velocity =\t tex1Dlod_lerp(internalTex1, vec2(nlife, 0), velocityDiv);\n\tvec3 params =\t\ttex1Dlod_lerp(internalTex2, vec2(nlife, 0), paramDiv);\n\tfloat rotSpeed = params.x;\n\tfloat rotSpeedDiv = paramDiv.y;\n\tvec3 radialParams = tex1Dlod_lerp(internalTex3, vec2(nlife, 0), paramDiv);\n\tfloat radialSpeed = radialParams.x;\n\tfloat radialSpeedDiv = radialParams.y;\n\tbool respawn = inLife <= 0.0 || outLife >= lifetime;\n\tinPos = respawn ? calcSpawnPosition(rndFactor.xyz, rndFactor.x) : inPos;\n\tinAngle = respawn ? mix(startAngle, startAngle2, rndFactor.x) : inAngle;\n#ifndef LOCAL_SPACE\n\tvec3 radialVel = inPos - emitterPos;\n#else\n\tvec3 radialVel = inPos;\n#endif\n\tradialVel = (dot(radialVel, radialVel) > 1.0E-8) ? radialSpeed * normalize(radialVel) : vec3(0.0);\n\tradialVel += (radialSpeedDiv * vec3(2.0) - vec3(1.0)) * radialSpeedDivMult * rndFactor.xyz;\n\tlocalVelocity +=\t(localVelocityDiv * vec3(2.0) - vec3(1.0)) * localVelocityDivMult * rndFactor.xyz;\n\tvelocity +=\t\t (velocityDiv * vec3(2.0) - vec3(1.0)) * velocityDivMult * rndFactor.xyz;\n\trotSpeed +=\t\t (rotSpeedDiv * 2.0 - 1.0) * rotSpeedDivMult * rndFactor.y;\n\taddInitialVelocity(localVelocity, rndFactor.xyz);\n#ifndef LOCAL_SPACE\n\toutVel = emitterMatrix * localVelocity + (radialVel + velocity) * emitterScale;\n#else\n\toutVel = (localVelocity + radialVel) / emitterScale + emitterMatrixInv * velocity;\n#endif\n\toutPos = inPos + outVel * delta;\n\toutAngle = inAngle + rotSpeed * delta;\n",particle_billboardVS:"\n\tquadXY = rotate(quadXY, inAngle, rotMatrix);\n\tvec3 localPos = billboard(particlePos, quadXY);\n",particle_blendAddPS:"\n\tdBlendModeFogFactor = 0.0;\n\trgb *= saturate(gammaCorrectInput(max(a, 0.0)));\n\tif ((rgb.r + rgb.g + rgb.b) < 0.000001) discard;\n",particle_blendMultiplyPS:"\n\trgb = mix(vec3(1.0), rgb, vec3(a));\n\tif (rgb.r + rgb.g + rgb.b > 2.99) discard;\n",particle_blendNormalPS:"\n\tif (a < 0.01) discard;\n",particle_cpuVS:"\nattribute vec4 particle_vertexData;\nattribute vec4 particle_vertexData2;\nattribute vec4 particle_vertexData3;\nattribute float particle_vertexData4;\n#ifndef USE_MESH\nattribute vec2 particle_vertexData5;\n#else\nattribute vec4 particle_vertexData5;\n#endif\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nuniform mat3 matrix_normal;\nuniform mat4 matrix_viewInverse;\nuniform float numParticles;\nuniform float lifetime;\nuniform float stretch;\nuniform float seed;\nuniform vec3 wrapBounds;\nuniform vec3 emitterScale;\nuniform vec3 faceTangent;\nuniform vec3 faceBinorm;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\nuniform vec3 emitterPos;\nvarying vec4 texCoordsAlphaLife;\nvec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix)\n{\n\tfloat c = cos(pRotation);\n\tfloat s = sin(pRotation);\n\tmat2 m = mat2(c, -s, s, c);\n\trotMatrix = m;\n\treturn m * quadXY;\n}\nvec3 billboard(vec3 InstanceCoords, vec2 quadXY)\n{\n\tvec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;\n\treturn pos;\n}\nvec3 customFace(vec3 InstanceCoords, vec2 quadXY)\n{\n\tvec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;\n\treturn pos;\n}\nvoid main(void)\n{\n\tvec3 particlePos = particle_vertexData.xyz;\n\tvec3 inPos = particlePos;\n\tvec3 vertPos = particle_vertexData3.xyz;\n\tvec3 inVel = vec3(particle_vertexData2.w, particle_vertexData3.w, particle_vertexData5.x);\n\tfloat id = floor(particle_vertexData4);\n\tfloat rndFactor = fract(sin(id + 1.0 + seed));\n\tvec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));\n#ifdef LOCAL_SPACE\n\tinVel = mat3(matrix_model) * inVel;\n#endif\n\tvec2 velocityV = normalize((mat3(matrix_view) * inVel).xy);\n\tvec2 quadXY = vertPos.xy;\n#ifdef USE_MESH\n\ttexCoordsAlphaLife = vec4(particle_vertexData5.zw, particle_vertexData2.z, particle_vertexData.w);\n#else\n\ttexCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, particle_vertexData2.z, particle_vertexData.w);\n#endif\n\tmat2 rotMatrix;\n\tfloat inAngle = particle_vertexData2.x;\n\tvec3 particlePosMoved = vec3(0.0);\n\tvec3 meshLocalPos = particle_vertexData3.xyz;\n",particle_cpu_endVS:"\n\tlocalPos *= particle_vertexData2.y * emitterScale;\n\tlocalPos += particlePos;\n\tgl_Position = matrix_viewProjection * vec4(localPos, 1.0);\n",particle_customFaceVS:"\n\tquadXY = rotate(quadXY, inAngle, rotMatrix);\n\tvec3 localPos = customFace(particlePos, quadXY);\n",particle_endPS:"\n\trgb = addFog(rgb);\n\trgb = toneMap(rgb);\n\trgb = gammaCorrectOutput(rgb);\n\tgl_FragColor = vec4(rgb, a);\n}\n",particle_endVS:"\n\tlocalPos *= scale * emitterScale;\n\tlocalPos += particlePos;\n\t#ifdef SCREEN_SPACE\n\tgl_Position = vec4(localPos.x, localPos.y, 0.0, 1.0);\n\t#else\n\tgl_Position = matrix_viewProjection * vec4(localPos.xyz, 1.0);\n\t#endif\n",particle_halflambertPS:"\n\tvec3 negNormal = normal*0.5+0.5;\n\tvec3 posNormal = -normal*0.5+0.5;\n\tnegNormal *= negNormal;\n\tposNormal *= posNormal;\n",particle_initVS:"\nattribute vec4 particle_vertexData;\n#ifdef USE_MESH\nattribute vec2 particle_uv;\n#endif\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\nuniform mat3 matrix_normal;\nuniform mat4 matrix_viewInverse;\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\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#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n#endif\nvarying vec4 texCoordsAlphaLife;\nvec3 inPos;\nvec3 inVel;\nfloat inAngle;\nbool inShow;\nfloat inLife;\n",particle_lambertPS:"\n\tvec3 negNormal = max(normal, vec3(0.0));\n\tvec3 posNormal = max(-normal, vec3(0.0));\n",particle_lightingPS:"\n\tvec3 light = negNormal.x*lightCube[0] + posNormal.x*lightCube[1] +\n\t\t\t\t\t\tnegNormal.y*lightCube[2] + posNormal.y*lightCube[3] +\n\t\t\t\t\t\tnegNormal.z*lightCube[4] + posNormal.z*lightCube[5];\n\trgb *= light;\n",particle_localShiftVS:"\n\tparticlePos = (matrix_model * vec4(particlePos, 1.0)).xyz;\n",particle_meshVS:"\n\tvec3 localPos = meshLocalPos;\n\tlocalPos.xy = rotate(localPos.xy, inAngle, rotMatrix);\n\tlocalPos.yz = rotate(localPos.yz, inAngle, rotMatrix);\n\tbillboard(particlePos, quadXY);\n",particle_normalVS:"\n\tNormal = normalize(localPos + matrix_viewInverse[2].xyz);\n",particle_normalMapPS:"\n\tvec3 normalMap = normalize(texture2D(normalMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y)).xyz * 2.0 - 1.0);\n\tvec3 normal = ParticleMat * normalMap;\n",particle_pointAlongVS:"\n\tinAngle = atan(velocityV.x, velocityV.y);\n",particle_softPS:"\n\tfloat depth = getLinearScreenDepth();\n\tfloat particleDepth = vDepth;\n\tfloat depthDiff = saturate(abs(particleDepth - depth) * softening);\n\ta *= depthDiff;\n",particle_softVS:"\n\tvDepth = getLinearDepth(localPos);\n",particle_stretchVS:"\n\tvec3 moveDir = inVel * stretch;\n\tvec3 posPrev = particlePos - moveDir;\n\tposPrev += particlePosMoved;\n\tvec2 centerToVertexV = normalize((mat3(matrix_view) * localPos).xy);\n\tfloat interpolation = dot(-velocityV, centerToVertexV) * 0.5 + 0.5;\n\tparticlePos = mix(particlePos, posPrev, interpolation);\n",particle_TBNVS:"\n\tmat3 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\tParticleMat = mat3(-matrix_viewInverse[0].xyz, -matrix_viewInverse[1].xyz, matrix_viewInverse[2].xyz) * rot3;\n",particle_wrapVS:"\n\tvec3 origParticlePos = particlePos;\n\tparticlePos -= matrix_model[3].xyz;\n\tparticlePos = mod(particlePos, wrapBounds) - wrapBounds * 0.5;\n\tparticlePos += matrix_model[3].xyz;\n\tparticlePosMoved = particlePos - origParticlePos;\n",reflDirPS:"\nvoid getReflDir(vec3 worldNormal, vec3 viewDir, float gloss, mat3 tbn) {\n\tdReflDirW = normalize(-reflect(viewDir, worldNormal));\n}\n",reflDirAnisoPS:"\nvoid getReflDir(vec3 worldNormal, vec3 viewDir, float gloss, mat3 tbn) {\n\tfloat roughness = sqrt(1.0 - min(gloss, 1.0));\n\tfloat anisotropy = material_anisotropy * roughness;\n\tvec3 anisotropicDirection = anisotropy >= 0.0 ? tbn[1] : tbn[0];\n\tvec3 anisotropicTangent = cross(anisotropicDirection, viewDir);\n\tvec3 anisotropicNormal = cross(anisotropicTangent, anisotropicDirection);\n\tvec3 bentNormal = normalize(mix(normalize(worldNormal), normalize(anisotropicNormal), anisotropy));\n\tdReflDirW = reflect(-viewDir, bentNormal);\n}\n",reflectionCCPS:"\n#ifdef LIT_CLEARCOAT\nvoid addReflectionCC(vec3 reflDir, float gloss) {\n\tccReflection += calcReflection(reflDir, gloss);\n}\n#endif\n",reflectionCubePS:"\nuniform samplerCube texture_cubeMap;\nuniform float material_reflectivity;\nvec3 calcReflection(vec3 reflDir, float gloss) {\n\tvec3 lookupVec = fixSeams(cubeMapProject(reflDir));\n\tlookupVec.x *= -1.0;\n\treturn $DECODE(textureCube(texture_cubeMap, lookupVec));\n}\nvoid addReflection(vec3 reflDir, float gloss) { \n\tdReflection += vec4(calcReflection(reflDir, gloss), 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;\nvec3 calcReflection(vec3 reflDir, float gloss) {\n\tvec3 dir = cubeMapProject(reflDir) * vec3(-1.0, 1.0, 1.0);\n\tvec2 uv = toSphericalUv(dir);\n\tfloat level = saturate(1.0 - gloss) * 5.0;\n\tfloat ilevel = floor(level);\n\tfloat flevel = level - ilevel;\n\tvec3 sharp = $DECODE_CUBEMAP(textureCube(texture_cubeMap, fixSeams(dir)));\n\tvec3 roughA = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel)));\n\tvec3 roughB = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0)));\n\treturn processEnvironment(mix(sharp, mix(roughA, roughB, flevel), min(level, 1.0)));\n}\nvoid addReflection(vec3 reflDir, float gloss) { \n\tdReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);\n}\n",reflectionEnvPS:"\n#ifndef ENV_ATLAS\n#define ENV_ATLAS\nuniform sampler2D texture_envAtlas;\n#endif\nuniform float material_reflectivity;\nfloat shinyMipLevel(vec2 uv) {\n\tvec2 dx = dFdx(uv);\n\tvec2 dy = dFdy(uv);\n\tvec2 uv2 = vec2(fract(uv.x + 0.5), uv.y);\n\tvec2 dx2 = dFdx(uv2);\n\tvec2 dy2 = dFdy(uv2);\n\tfloat maxd = min(max(dot(dx, dx), dot(dy, dy)), max(dot(dx2, dx2), dot(dy2, dy2)));\n\treturn clamp(0.5 * log2(maxd) - 1.0 + textureBias, 0.0, 5.0);\n}\nvec3 calcReflection(vec3 reflDir, float gloss) {\n\tvec3 dir = cubeMapProject(reflDir) * vec3(-1.0, 1.0, 1.0);\n\tvec2 uv = toSphericalUv(dir);\n\tfloat level = saturate(1.0 - gloss) * 5.0;\n\tfloat ilevel = floor(level);\n\tfloat level2 = shinyMipLevel(uv * atlasSize);\n\tfloat ilevel2 = floor(level2);\n\tvec2 uv0, uv1;\n\tfloat weight;\n\tif (ilevel == 0.0) {\n\t\tuv0 = mapShinyUv(uv, ilevel2);\n\t\tuv1 = mapShinyUv(uv, ilevel2 + 1.0);\n\t\tweight = level2 - ilevel2;\n\t} else {\n\t\tuv0 = uv1 = mapRoughnessUv(uv, ilevel);\n\t\tweight = 0.0;\n\t}\n\tvec3 linearA = $DECODE(texture2D(texture_envAtlas, uv0));\n\tvec3 linearB = $DECODE(texture2D(texture_envAtlas, uv1));\n\tvec3 linear0 = mix(linearA, linearB, weight);\n\tvec3 linear1 = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0)));\n\treturn processEnvironment(mix(linear0, linear1, level - ilevel));\n}\nvoid addReflection(vec3 reflDir, float gloss) { \n\tdReflection += vec4(calcReflection(reflDir, gloss), 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;\nvec3 calcReflection(vec3 reflDir, float gloss) {\n\tvec3 reflDirV = (mat3(matrix_view) * reflDir).xyz;\n\tfloat m = 2.0 * sqrt( dot(reflDirV.xy, reflDirV.xy) + (reflDirV.z+1.0)*(reflDirV.z+1.0) );\n\tvec2 sphereMapUv = reflDirV.xy / m + 0.5;\n\treturn $DECODE(texture2D(texture_sphereMap, sphereMapUv));\n}\nvoid addReflection(vec3 reflDir, float gloss) { \n\tdReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);\n}\n",reflectionSphereLowPS:"\nuniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\nvec3 calcReflection(vec3 reflDir, float gloss) {\n\tvec3 reflDirV = vNormalV;\n\tvec2 sphereMapUv = reflDirV.xy * 0.5 + 0.5;\n\treturn $DECODE(texture2D(texture_sphereMap, sphereMapUv));\n}\nvoid addReflection(vec3 reflDir, float gloss) { \n\tdReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);\n}\n",reflectionSheenPS:"\nvoid addReflectionSheen(vec3 worldNormal, vec3 viewDir, float gloss) {\n\tfloat NoV = dot(worldNormal, viewDir);\n\tfloat alphaG = gloss * gloss;\n\tfloat a = gloss < 0.25 ? -339.2 * alphaG + 161.4 * gloss - 25.9 : -8.48 * alphaG + 14.3 * gloss - 9.95;\n\tfloat b = gloss < 0.25 ? 44.0 * alphaG - 23.7 * gloss + 3.26 : 1.97 * alphaG - 3.27 * gloss + 0.72;\n\tfloat DG = exp( a * NoV + b ) + ( gloss < 0.25 ? 0.0 : 0.1 * ( gloss - 0.25 ) );\n\tsReflection += calcReflection(worldNormal, 0.0) * saturate(DG);\n}\n",refractionCubePS:"\nvec3 refract2(vec3 viewVec, vec3 normal, float IOR) {\n\tfloat vn = dot(viewVec, normal);\n\tfloat k = 1.0 - IOR * IOR * (1.0 - vn * vn);\n\tvec3 refrVec = IOR * viewVec - (IOR * vn + sqrt(k)) * normal;\n\treturn refrVec;\n}\nvoid addRefraction(\n\tvec3 worldNormal, \n\tvec3 viewDir, \n\tfloat thickness, \n\tfloat gloss, \n\tvec3 specularity, \n\tvec3 albedo, \n\tfloat transmission,\n\tfloat refractionIndex\n#if defined(LIT_IRIDESCENCE)\n\t, vec3 iridescenceFresnel,\n\tfloat iridescenceIntensity\n#endif \n) {\n\tvec4 tmpRefl = dReflection;\n\tvec3 reflectionDir = refract2(-viewDir, worldNormal, refractionIndex);\n\tdReflection = vec4(0);\n\taddReflection(reflectionDir, gloss);\n\tdDiffuseLight = mix(dDiffuseLight, dReflection.rgb * albedo, transmission);\n\tdReflection = tmpRefl;\n}\n",refractionDynamicPS:"\nuniform float material_invAttenuationDistance;\nuniform vec3 material_attenuation;\nvoid addRefraction(\n\tvec3 worldNormal, \n\tvec3 viewDir, \n\tfloat thickness, \n\tfloat gloss, \n\tvec3 specularity, \n\tvec3 albedo, \n\tfloat transmission,\n\tfloat refractionIndex\n#if defined(LIT_IRIDESCENCE)\n\t, vec3 iridescenceFresnel,\n\tfloat iridescenceIntensity\n#endif\n) {\n\tvec3 modelScale;\n\tmodelScale.x = length(vec3(matrix_model[0].xyz));\n\tmodelScale.y = length(vec3(matrix_model[1].xyz));\n\tmodelScale.z = length(vec3(matrix_model[2].xyz));\n\tvec3 refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndex)) * thickness * modelScale;\n\tvec4 pointOfRefraction = vec4(vPositionW + refractionVector, 1.0);\n\tvec4 projectionPoint = matrix_viewProjection * pointOfRefraction;\n\tvec2 uv = getGrabScreenPos(projectionPoint);\n\t#ifdef SUPPORTS_TEXLOD\n\t\tfloat iorToRoughness = (1.0 - gloss) * clamp((1.0 / refractionIndex) * 2.0 - 2.0, 0.0, 1.0);\n\t\tfloat refractionLod = log2(uScreenSize.x) * iorToRoughness;\n\t\tvec3 refraction = texture2DLodEXT(uSceneColorMap, uv, refractionLod).rgb;\n\t#else\n\t\tvec3 refraction = texture2D(uSceneColorMap, uv).rgb;\n\t#endif\n\tvec3 transmittance;\n\tif (material_invAttenuationDistance != 0.0)\n\t{\n\t\tvec3 attenuation = -log(material_attenuation) * material_invAttenuationDistance;\n\t\ttransmittance = exp(-attenuation * length(refractionVector));\n\t}\n\telse\n\t{\n\t\ttransmittance = refraction;\n\t}\n\tvec3 fresnel = vec3(1.0) - \n\t\tgetFresnel(\n\t\t\tdot(viewDir, worldNormal), \n\t\t\tgloss, \n\t\t\tspecularity\n\t\t#if defined(LIT_IRIDESCENCE)\n\t\t\t, iridescenceFresnel,\n\t\t\tiridescenceIntensity\n\t\t#endif\n\t\t);\n\tdDiffuseLight = mix(dDiffuseLight, refraction * transmittance * fresnel, transmission);\n}\n",reprojectPS:"\nvarying vec2 vUv0;\n#ifdef CUBEMAP_SOURCE\n\tuniform samplerCube sourceCube;\n#else\n\tuniform sampler2D sourceTex;\n#endif\n#ifdef USE_SAMPLES_TEX\n\tuniform sampler2D samplesTex;\n\tuniform vec2 samplesTexInverseSize;\n#endif\nuniform vec4 params;\nuniform vec2 params2;\nfloat targetFace() { return params.x; }\nfloat specularPower() { return params.y; }\nfloat sourceCubeSeamScale() { return params.z; }\nfloat targetCubeSeamScale() { return params.w; }\nfloat targetTotalPixels() { return params2.x; }\nfloat sourceTotalPixels() { return params2.y; }\nfloat PI = 3.141592653589793;\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\n"+po+"\n"+mo+"\nvec3 modifySeams(vec3 dir, float scale) {\n\tvec3 adir = abs(dir);\n\tfloat M = max(max(adir.x, adir.y), adir.z);\n\treturn dir / M * vec3(\n\t\tadir.x == M ? 1.0 : scale,\n\t\tadir.y == M ? 1.0 : scale,\n\t\tadir.z == M ? 1.0 : scale\n\t);\n}\nvec2 toSpherical(vec3 dir) {\n\treturn vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y));\n}\nvec3 fromSpherical(vec2 uv) {\n\treturn vec3(cos(uv.y) * sin(uv.x),\n\t\t\t\tsin(uv.y),\n\t\t\t\tcos(uv.y) * cos(uv.x));\n}\nvec3 getDirectionEquirect() {\n\treturn fromSpherical((vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0) * vec2(PI, PI * 0.5));\n}\nfloat signNotZero(float k){\n\treturn(k >= 0.0) ? 1.0 : -1.0;\n}\nvec2 signNotZero(vec2 v) {\n\treturn vec2(signNotZero(v.x), signNotZero(v.y));\n}\nvec3 octDecode(vec2 o) {\n\tvec3 v = vec3(o.x, 1.0 - abs(o.x) - abs(o.y), o.y);\n\tif (v.y < 0.0) {\n\t\tv.xz = (1.0 - abs(v.zx)) * signNotZero(v.xz);\n\t}\n\treturn normalize(v);\n}\nvec3 getDirectionOctahedral() {\n\treturn octDecode(vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0);\n}\nvec2 octEncode(in vec3 v) {\n\tfloat l1norm = abs(v.x) + abs(v.y) + abs(v.z);\n\tvec2 result = v.xz * (1.0 / l1norm);\n\tif (v.y < 0.0) {\n\t\tresult = (1.0 - abs(result.yx)) * signNotZero(result.xy);\n\t}\n\treturn result;\n}\n#ifdef CUBEMAP_SOURCE\n\tvec4 sampleCubemap(vec3 dir) {\n\t\treturn textureCube(sourceCube, modifySeams(dir, 1.0 - sourceCubeSeamScale()));\n\t}\n\tvec4 sampleCubemap(vec2 sph) {\n\treturn sampleCubemap(fromSpherical(sph));\n}\n\tvec4 sampleCubemap(vec3 dir, float mipLevel) {\n\t\treturn textureCubeLodEXT(sourceCube, modifySeams(dir, 1.0 - exp2(mipLevel) * sourceCubeSeamScale()), mipLevel);\n\t}\n\tvec4 sampleCubemap(vec2 sph, float mipLevel) {\n\t\treturn sampleCubemap(fromSpherical(sph), mipLevel);\n\t}\n#else\n\tvec4 sampleEquirect(vec2 sph) {\n\t\tvec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;\n\t\treturn texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n\t}\n\tvec4 sampleEquirect(vec3 dir) {\n\t\treturn sampleEquirect(toSpherical(dir));\n\t}\n\tvec4 sampleEquirect(vec2 sph, float mipLevel) {\n\t\tvec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;\n\t\treturn texture2DLodEXT(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);\n\t}\n\tvec4 sampleEquirect(vec3 dir, float mipLevel) {\n\t\treturn sampleEquirect(toSpherical(dir), mipLevel);\n\t}\n\tvec4 sampleOctahedral(vec3 dir) {\n\t\tvec2 uv = octEncode(dir) * 0.5 + 0.5;\n\t\treturn texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n\t}\n\tvec4 sampleOctahedral(vec2 sph) {\n\t\treturn sampleOctahedral(fromSpherical(sph));\n\t}\n\tvec4 sampleOctahedral(vec3 dir, float mipLevel) {\n\t\tvec2 uv = octEncode(dir) * 0.5 + 0.5;\n\t\treturn texture2DLodEXT(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);\n\t}\n\tvec4 sampleOctahedral(vec2 sph, float mipLevel) {\n\t\treturn sampleOctahedral(fromSpherical(sph), mipLevel);\n\t}\n#endif\nvec3 getDirectionCubemap() {\n\tvec2 st = vUv0 * 2.0 - 1.0;\n\tfloat face = targetFace();\n\tvec3 vec;\n\tif (face == 0.0) {\n\t\tvec = vec3(1, -st.y, -st.x);\n\t} else if (face == 1.0) {\n\t\tvec = vec3(-1, -st.y, st.x);\n\t} else if (face == 2.0) {\n\t\tvec = vec3(st.x, 1, st.y);\n\t} else if (face == 3.0) {\n\t\tvec = vec3(st.x, -1, -st.y);\n\t} else if (face == 4.0) {\n\t\tvec = vec3(st.x, -st.y, 1);\n\t} else {\n\t\tvec = vec3(-st.x, -st.y, -1);\n\t}\n\treturn normalize(modifySeams(vec, 1.0 / (1.0 - targetCubeSeamScale())));\n}\nmat3 matrixFromVector(vec3 n) {\n\tfloat a = 1.0 / (1.0 + n.z);\n\tfloat b = -n.x * n.y * a;\n\tvec3 b1 = vec3(1.0 - n.x * n.x * a, b, -n.x);\n\tvec3 b2 = vec3(b, 1.0 - n.y * n.y * a, -n.y);\n\treturn mat3(b1, b2, n);\n}\nmat3 matrixFromVectorSlow(vec3 n) {\n\tvec3 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\tvec3 x = normalize(cross(up, n));\n\tvec3 y = cross(n, x);\n\treturn mat3(x, y, n);\n}\nvec4 reproject() {\n\tif (NUM_SAMPLES <= 1) {\n\t\treturn ENCODE_FUNC(DECODE_FUNC(SOURCE_FUNC(TARGET_FUNC())));\n\t} else {\n\t\tvec3 t = TARGET_FUNC();\n\t\tvec3 tu = dFdx(t);\n\t\tvec3 tv = dFdy(t);\n\t\tvec3 result = vec3(0.0);\n\t\tfor (float u = 0.0; u < NUM_SAMPLES_SQRT; ++u) {\n\t\t\tfor (float v = 0.0; v < NUM_SAMPLES_SQRT; ++v) {\n\t\t\t\tresult += DECODE_FUNC(SOURCE_FUNC(normalize(t +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttu * (u / NUM_SAMPLES_SQRT - 0.5) +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttv * (v / NUM_SAMPLES_SQRT - 0.5))));\n\t\t\t}\n\t\t}\n\t\treturn ENCODE_FUNC(result / (NUM_SAMPLES_SQRT * NUM_SAMPLES_SQRT));\n\t}\n}\nvec4 unpackFloat = vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0);\n#ifdef USE_SAMPLES_TEX\n\tvoid unpackSample(int i, out vec3 L, out float mipLevel) {\n\t\tfloat u = (float(i * 4) + 0.5) * samplesTexInverseSize.x;\n\t\tfloat v = (floor(u) + 0.5) * samplesTexInverseSize.y;\n\t\tvec4 raw;\n\t\traw.x = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n\t\traw.y = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n\t\traw.z = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n\t\traw.w = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat);\n\t\tL.xyz = raw.xyz * 2.0 - 1.0;\n\t\tmipLevel = raw.w * 8.0;\n\t}\n\tvec4 prefilterSamples() {\n\t\tmat3 vecSpace = matrixFromVectorSlow(TARGET_FUNC());\n\t\tvec3 L;\n\t\tfloat mipLevel;\n\t\tvec3 result = vec3(0.0);\n\t\tfloat totalWeight = 0.0;\n\t\tfor (int i = 0; i < NUM_SAMPLES; ++i) {\n\t\t\tunpackSample(i, L, mipLevel);\n\t\t\tresult += DECODE_FUNC(SOURCE_FUNC(vecSpace * L, mipLevel)) * L.z;\n\t\t\ttotalWeight += L.z;\n\t\t}\n\t\treturn ENCODE_FUNC(result / totalWeight);\n\t}\n\tvec4 prefilterSamplesUnweighted() {\n\t\tmat3 vecSpace = matrixFromVectorSlow(TARGET_FUNC());\n\t\tvec3 L;\n\t\tfloat mipLevel;\n\t\tvec3 result = vec3(0.0);\n\t\tfloat totalWeight = 0.0;\n\t\tfor (int i = 0; i < NUM_SAMPLES; ++i) {\n\t\t\tunpackSample(i, L, mipLevel);\n\t\t\tresult += DECODE_FUNC(SOURCE_FUNC(vecSpace * L, mipLevel));\n\t\t}\n\t\treturn ENCODE_FUNC(result / float(NUM_SAMPLES));\n\t}\n#endif\nvoid main(void) {\n\tgl_FragColor = PROCESS_FUNC();\n}\n",screenDepthPS:"\nuniform highp sampler2D uSceneDepthMap;\n#ifndef SCREENSIZE\n#define SCREENSIZE\nuniform vec4 uScreenSize;\n#endif\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n#ifndef LINEARIZE_DEPTH\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n#endif\n#define LINEARIZE_DEPTH\n#ifdef GL2\nfloat linearizeDepth(float z) {\n\tif (camera_params.w == 0.0)\n\t\treturn (camera_params.z * camera_params.y) / (camera_params.y + z * (camera_params.z - camera_params.y));\n\telse\n\t\treturn camera_params.z + z * (camera_params.y - camera_params.z);\n}\n#else\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n\tconst vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n\treturn dot(rgbaDepth, bitShift);\n}\n#endif\n#endif\n#endif\nfloat getLinearScreenDepth(vec2 uv) {\n\t#ifdef GL2\n\t\treturn linearizeDepth(texture2D(uSceneDepthMap, uv).r);\n\t#else\n\t\treturn unpackFloat(texture2D(uSceneDepthMap, uv)) * camera_params.y;\n\t#endif\n}\n#ifndef VERTEXSHADER\nfloat getLinearScreenDepth() {\n\tvec2 uv = gl_FragCoord.xy * uScreenSize.zw;\n\treturn getLinearScreenDepth(uv);\n}\n#endif\nfloat getLinearDepth(vec3 pos) {\n\treturn -(matrix_view * vec4(pos, 1.0)).z;\n}\n",shadowCascadesPS:"\nconst float maxCascades = 4.0;\nmat4 cascadeShadowMat;\nvoid getShadowCascadeMatrix(mat4 shadowMatrixPalette[4], float shadowCascadeDistances[4], float shadowCascadeCount) {\n\tfloat depth = 1.0 / gl_FragCoord.w;\n\tfloat cascadeIndex = 0.0;\n\tfor (float i = 0.0; i < maxCascades; i++) {\n\t\tif (depth < shadowCascadeDistances[int(i)]) {\n\t\t\tcascadeIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tcascadeIndex = min(cascadeIndex, shadowCascadeCount - 1.0);\n\t#ifdef GL2\n\t\tcascadeShadowMat = shadowMatrixPalette[int(cascadeIndex)];\n\t#else\n\t\tif (cascadeIndex == 0.0) {\n\t\t\tcascadeShadowMat = shadowMatrixPalette[0];\n\t\t}\n\t\telse if (cascadeIndex == 1.0) {\n\t\t\tcascadeShadowMat = shadowMatrixPalette[1];\n\t\t}\n\t\telse if (cascadeIndex == 2.0) {\n\t\t\tcascadeShadowMat = shadowMatrixPalette[2];\n\t\t}\n\t\telse {\n\t\t\tcascadeShadowMat = shadowMatrixPalette[3];\n\t\t}\n\t#endif\n}\nvoid fadeShadow(float shadowCascadeDistances[4]) {\t\t\t\t \n\tfloat depth = 1.0 / gl_FragCoord.w;\n\tif (depth > shadowCascadeDistances[int(maxCascades - 1.0)]) {\n\t\tdShadowCoord.z = -9999999.0;\n\t}\n}\n",shadowEVSMPS:"\nfloat VSM$(sampler2D tex, vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n\tvec3 moments = texture2D(tex, texCoords).xyz;\n\treturn calculateEVSM(moments, Z, vsmBias, exponent);\n}\nfloat getShadowVSM$(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n\treturn VSM$(shadowMap, shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);\n}\nfloat getShadowSpotVSM$(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n\treturn VSM$(shadowMap, shadowCoord.xy, shadowParams.x, length(lightDir) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);\n}\n",shadowEVSMnPS:"\nfloat VSM$(TEXTURE_ACCEPT(tex), vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n\tfloat pixelSize = 1.0 / resolution;\n\ttexCoords -= vec2(pixelSize);\n\tvec3 s00 = texture2D(tex, texCoords).xyz;\n\tvec3 s10 = texture2D(tex, texCoords + vec2(pixelSize, 0)).xyz;\n\tvec3 s01 = texture2D(tex, texCoords + vec2(0, pixelSize)).xyz;\n\tvec3 s11 = texture2D(tex, texCoords + vec2(pixelSize)).xyz;\n\tvec2 fr = fract(texCoords * resolution);\n\tvec3 h0 = mix(s00, s10, fr.x);\n\tvec3 h1 = mix(s01, s11, fr.x);\n\tvec3 moments = mix(h0, h1, fr.y);\n\treturn calculateEVSM(moments, Z, vsmBias, exponent);\n}\nfloat getShadowVSM$(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n\treturn VSM$(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);\n}\nfloat getShadowSpotVSM$(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n\treturn VSM$(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, length(lightDir) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);\n}\n",shadowPCSSPS:"\n#define PCSS_SAMPLE_COUNT 16\nuniform float pcssDiskSamples[PCSS_SAMPLE_COUNT];\nuniform float pcssSphereSamples[PCSS_SAMPLE_COUNT];\nvec2 vogelDisk(int sampleIndex, float count, float phi, float r) {\n\tconst float GoldenAngle = 2.4;\n\tfloat theta = float(sampleIndex) * GoldenAngle + phi;\n\tfloat sine = sin(theta);\n\tfloat cosine = cos(theta);\n\treturn vec2(r * cosine, r * sine);\n}\nvec3 vogelSphere(int sampleIndex, float count, float phi, float r) {\n\tconst float GoldenAngle = 2.4;\n\tfloat theta = float(sampleIndex) * GoldenAngle + phi;\n\tfloat weight = float(sampleIndex) / count;\n\treturn vec3(cos(theta) * r, weight, sin(theta) * r);\n}\nfloat noise(vec2 screenPos) {\n\tconst float PHI = 1.61803398874989484820459;\n\treturn fract(sin(dot(screenPos * PHI, screenPos)) * screenPos.x);\n}\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n\tconst vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n\treturn dot(rgbaDepth, bitShift);\n}\n#endif\nfloat viewSpaceDepth(float depth, mat4 invProjection) {\n\tfloat z = depth * 2.0 - 1.0;\n\tvec4 clipSpace = vec4(0.0, 0.0, z, 1.0);\n\tvec4 viewSpace = invProjection * clipSpace;\n\treturn viewSpace.z;\n}\nfloat PCSSBlockerDistance(TEXTURE_ACCEPT(shadowMap), vec2 sampleCoords[PCSS_SAMPLE_COUNT], vec2 shadowCoords, vec2 searchSize, float z) {\n\tfloat blockers = 0.0;\n\tfloat averageBlocker = 0.0;\n\tfor (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {\n\t\tvec2 offset = sampleCoords[i] * searchSize;\n\t\tvec2 sampleUV = shadowCoords + offset;\n\t#ifdef GL2\n\t\tfloat blocker = textureLod(shadowMap, sampleUV, 0.0).r;\n\t#else\n\t\tfloat blocker = unpackFloat(texture2D(shadowMap, sampleUV));\n\t#endif\t\t\n\t\tfloat isBlocking = step(blocker, z);\n\t\tblockers += isBlocking;\n\t\taverageBlocker += blocker * isBlocking;\n\t}\n\tif (blockers > 0.0)\n\t\treturn averageBlocker /= blockers;\n\treturn -1.0;\n}\nfloat PCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoords, vec4 cameraParams, vec2 shadowSearchArea) {\n\tfloat receiverDepth = shadowCoords.z;\n#ifndef GL2\n\treceiverDepth *= 1.0 / (cameraParams.y - cameraParams.z);\n#endif\n\tvec2 samplePoints[PCSS_SAMPLE_COUNT];\n\tfloat noise = noise( gl_FragCoord.xy ) * 2.0 * PI;\n\tfor (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {\n\t\tfloat pcssPresample = pcssDiskSamples[i];\n\t\tsamplePoints[i] = vogelDisk(i, float(PCSS_SAMPLE_COUNT), noise, pcssPresample);\n\t}\n\tfloat averageBlocker = PCSSBlockerDistance(TEXTURE_PASS(shadowMap), samplePoints, shadowCoords.xy, shadowSearchArea, receiverDepth);\n\tif (averageBlocker == -1.0) {\n\t\treturn 1.0;\n\t} else {\n\t\tvec2 filterRadius = ((receiverDepth - averageBlocker) / averageBlocker) * shadowSearchArea * cameraParams.x;\n\t\tfloat shadow = 0.0;\n\t\tfor (int i = 0; i < PCSS_SAMPLE_COUNT; i ++)\n\t\t{\n\t\t\tvec2 sampleUV = samplePoints[i] * filterRadius;\n\t\t\tsampleUV = shadowCoords.xy + sampleUV;\n\t\t#ifdef GL2\n\t\t\tfloat depth = textureLod(shadowMap, sampleUV, 0.0).r;\n\t\t#else\n\t\t\tfloat depth = unpackFloat(texture2D(shadowMap, sampleUV));\n\t\t#endif\n\t\t\tshadow += step(receiverDepth, depth);\n\t\t}\n\t\treturn shadow / float(PCSS_SAMPLE_COUNT);\n\t} \n}\nfloat PCSSCubeBlockerDistance(samplerCube shadowMap, vec3 lightDirNorm, vec3 samplePoints[PCSS_SAMPLE_COUNT], float z, float shadowSearchArea) {\n\tfloat blockers = 0.0;\n\tfloat averageBlocker = 0.0;\n\tfor (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {\n\t\tvec3 sampleDir = lightDirNorm + samplePoints[i] * shadowSearchArea;\n\t\tsampleDir = normalize(sampleDir);\n\t#ifdef GL2\n\t\tfloat blocker = textureCubeLodEXT(shadowMap, sampleDir, 0.0).r;\n\t#else\n\t\tfloat blocker = unpackFloat(textureCube(shadowMap, sampleDir));\n\t#endif\n\t\tfloat isBlocking = step(blocker, z);\n\t\tblockers += isBlocking;\n\t\taverageBlocker += blocker * isBlocking;\n\t}\n\tif (blockers > 0.0)\n\t\treturn averageBlocker /= float(blockers);\n\treturn -1.0;\n}\nfloat PCSSCube(samplerCube shadowMap, vec4 shadowParams, vec3 shadowCoords, vec4 cameraParams, float shadowSearchArea, vec3 lightDir) {\n\t\n\tvec3 samplePoints[PCSS_SAMPLE_COUNT];\n\tfloat noise = noise( gl_FragCoord.xy ) * 2.0 * PI;\n\tfor (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {\n\t\tfloat r = pcssSphereSamples[i];\n\t\tsamplePoints[i] = vogelSphere(i, float(PCSS_SAMPLE_COUNT), noise, r);\n\t}\n\tfloat receiverDepth = length(lightDir) * shadowParams.w + shadowParams.z;\n\tvec3 lightDirNorm = normalize(lightDir);\n\t\n\tfloat averageBlocker = PCSSCubeBlockerDistance(shadowMap, lightDirNorm, samplePoints, receiverDepth, shadowSearchArea);\n\tif (averageBlocker == -1.0) {\n\t\treturn 1.0;\n\t} else {\n\t\tfloat filterRadius = ((receiverDepth - averageBlocker) / averageBlocker) * shadowSearchArea;\n\t\tfloat shadow = 0.0;\n\t\tfor (int i = 0; i < PCSS_SAMPLE_COUNT; i++)\n\t\t{\n\t\t\tvec3 offset = samplePoints[i] * filterRadius;\n\t\t\tvec3 sampleDir = lightDirNorm + offset;\n\t\t\tsampleDir = normalize(sampleDir);\n\t\t\t#ifdef GL2\n\t\t\t\tfloat depth = textureCubeLodEXT(shadowMap, sampleDir, 0.0).r;\n\t\t\t#else\n\t\t\t\tfloat depth = unpackFloat(textureCube(shadowMap, sampleDir));\n\t\t\t#endif\n\t\t\tshadow += step(receiverDepth, depth);\n\t\t}\n\t\treturn shadow / float(PCSS_SAMPLE_COUNT);\n\t}\n}\nfloat getShadowPointPCSS(samplerCube shadowMap, vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec2 shadowSearchArea, vec3 lightDir) {\n\treturn PCSSCube(shadowMap, shadowParams, shadowCoord, cameraParams, shadowSearchArea.x, lightDir);\n}\nfloat getShadowSpotPCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec2 shadowSearchArea, vec3 lightDir) {\n\treturn PCSS(TEXTURE_PASS(shadowMap), shadowCoord, cameraParams, shadowSearchArea);\n}\nfloat getShadowPCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec2 shadowSearchArea, vec3 lightDir) {\n\treturn PCSS(TEXTURE_PASS(shadowMap), shadowCoord, cameraParams, shadowSearchArea);\n}\n",shadowSampleCoordPS:"\nvec3 getShadowSampleCoord$LIGHT(mat4 shadowTransform, vec4 shadowParams, vec3 worldPosition, vec3 lightPos, inout vec3 lightDir, vec3 lightDirNorm, vec3 normal) {\n\tvec3 surfacePosition = worldPosition;\n#ifdef SHADOW_SAMPLE_POINT\n\t#ifdef SHADOW_SAMPLE_NORMAL_OFFSET\n\t\tfloat distScale = length(lightDir);\n\t\tsurfacePosition = worldPosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;\n\t\tlightDir = surfacePosition - lightPos;\n\t\treturn lightDir;\n\t#endif\n#else\n\t#ifdef SHADOW_SAMPLE_SOURCE_ZBUFFER\n\t\t#ifdef SHADOW_SAMPLE_NORMAL_OFFSET\n\t\t\tsurfacePosition = worldPosition + normal * shadowParams.y;\n\t\t#endif\n\t#else\n\t\t#ifdef SHADOW_SAMPLE_NORMAL_OFFSET\n\t\t\t#ifdef SHADOW_SAMPLE_ORTHO\n\t\t\t\tfloat distScale = 1.0;\n\t\t\t#else\n\t\t\t\tfloat distScale = abs(dot(vPositionW - lightPos, lightDirNorm));\n\t\t\t#endif\n\t\t\tsurfacePosition = worldPosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;\n\t\t#endif\n\t#endif\n\tvec4 positionInShadowSpace = shadowTransform * vec4(surfacePosition, 1.0);\n\t#ifdef SHADOW_SAMPLE_ORTHO\n\t\tpositionInShadowSpace.z = saturate(positionInShadowSpace.z) - 0.0001;\n\t#else\n\t\t#ifdef SHADOW_SAMPLE_SOURCE_ZBUFFER\n\t\t\tpositionInShadowSpace.xyz /= positionInShadowSpace.w;\n\t\t#else\n\t\t\tpositionInShadowSpace.xy /= positionInShadowSpace.w;\n\t\t\tpositionInShadowSpace.z = length(lightDir) * shadowParams.w;\n\t\t#endif\n\t#endif\n\t#ifdef SHADOW_SAMPLE_Z_BIAS\n\t\tpositionInShadowSpace.z += getShadowBias(shadowParams.x, shadowParams.z);\n\t#endif\n\tsurfacePosition = positionInShadowSpace.xyz;\n#endif\n\treturn surfacePosition;\n}\n",shadowStandardPS:"\nvec3 lessThan2(vec3 a, vec3 b) {\n\treturn clamp((b - a)*1000.0, 0.0, 1.0);\n}\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\n\tfloat unpackFloat(vec4 rgbaDepth) {\n\t\tconst vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n\t\treturn dot(rgbaDepth, bitShift);\n\t}\n#endif\n#ifdef GL2\nfloat _getShadowPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec3 shadowParams) {\n\tfloat z = shadowCoord.z;\n\tvec2 uv = shadowCoord.xy * shadowParams.x;\n\tfloat shadowMapSizeInv = 1.0 / shadowParams.x;\n\tvec2 base_uv = floor(uv + 0.5);\n\tfloat s = (uv.x + 0.5 - base_uv.x);\n\tfloat t = (uv.y + 0.5 - base_uv.y);\n\tbase_uv -= vec2(0.5);\n\tbase_uv *= shadowMapSizeInv;\n\tfloat sum = 0.0;\n\tfloat uw0 = (3.0 - 2.0 * s);\n\tfloat uw1 = (1.0 + 2.0 * s);\n\tfloat u0 = (2.0 - s) / uw0 - 1.0;\n\tfloat u1 = s / uw1 + 1.0;\n\tfloat vw0 = (3.0 - 2.0 * t);\n\tfloat vw1 = (1.0 + 2.0 * t);\n\tfloat v0 = (2.0 - t) / vw0 - 1.0;\n\tfloat v1 = t / vw1 + 1.0;\n\tu0 = u0 * shadowMapSizeInv + base_uv.x;\n\tv0 = v0 * shadowMapSizeInv + base_uv.y;\n\tu1 = u1 * shadowMapSizeInv + base_uv.x;\n\tv1 = v1 * shadowMapSizeInv + base_uv.y;\n\tsum += uw0 * vw0 * textureShadow(shadowMap, vec3(u0, v0, z));\n\tsum += uw1 * vw0 * textureShadow(shadowMap, vec3(u1, v0, z));\n\tsum += uw0 * vw1 * textureShadow(shadowMap, vec3(u0, v1, z));\n\tsum += uw1 * vw1 * textureShadow(shadowMap, vec3(u1, v1, z));\n\tsum *= 1.0f / 16.0;\n\treturn sum;\n}\nfloat getShadowPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\treturn _getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);\n}\nfloat getShadowSpotPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\treturn _getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);\n}\nfloat getShadowPCF1x1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\treturn textureShadow(shadowMap, shadowCoord);\n}\nfloat getShadowSpotPCF1x1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\treturn textureShadow(shadowMap, shadowCoord);\n}\n#else\nfloat _xgetShadowPCF3x3(mat3 depthKernel, vec3 shadowCoord, sampler2D shadowMap, vec3 shadowParams) {\n\tmat3 shadowKernel;\n\tvec3 shadowZ = vec3(shadowCoord.z);\n\tshadowKernel[0] = vec3(greaterThan(depthKernel[0], shadowZ));\n\tshadowKernel[1] = vec3(greaterThan(depthKernel[1], shadowZ));\n\tshadowKernel[2] = vec3(greaterThan(depthKernel[2], shadowZ));\n\tvec2 fractionalCoord = fract( shadowCoord.xy * shadowParams.x );\n\tshadowKernel[0] = mix(shadowKernel[0], shadowKernel[1], fractionalCoord.x);\n\tshadowKernel[1] = mix(shadowKernel[1], shadowKernel[2], fractionalCoord.x);\n\tvec4 shadowValues;\n\tshadowValues.x = mix(shadowKernel[0][0], shadowKernel[0][1], fractionalCoord.y);\n\tshadowValues.y = mix(shadowKernel[0][1], shadowKernel[0][2], fractionalCoord.y);\n\tshadowValues.z = mix(shadowKernel[1][0], shadowKernel[1][1], fractionalCoord.y);\n\tshadowValues.w = mix(shadowKernel[1][1], shadowKernel[1][2], fractionalCoord.y);\n\treturn dot( shadowValues, vec4( 1.0 ) ) * 0.25;\n}\nfloat _getShadowPCF3x3(sampler2D shadowMap, vec3 shadowCoord, vec3 shadowParams) {\n\tfloat xoffset = 1.0 / shadowParams.x;\n\tfloat dx0 = -xoffset;\n\tfloat dx1 = xoffset;\n\tmat3 depthKernel;\n\tdepthKernel[0][0] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx0, dx0)));\n\tdepthKernel[0][1] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx0, 0.0)));\n\tdepthKernel[0][2] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx0, dx1)));\n\tdepthKernel[1][0] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(0.0, dx0)));\n\tdepthKernel[1][1] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy));\n\tdepthKernel[1][2] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(0.0, dx1)));\n\tdepthKernel[2][0] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx1, dx0)));\n\tdepthKernel[2][1] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx1, 0.0)));\n\tdepthKernel[2][2] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx1, dx1)));\n\treturn _xgetShadowPCF3x3(depthKernel, shadowCoord, shadowMap, shadowParams);\n}\nfloat getShadowPCF3x3(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n\treturn _getShadowPCF3x3(shadowMap, shadowCoord, shadowParams.xyz);\n}\nfloat getShadowSpotPCF3x3(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n\treturn _getShadowPCF3x3(shadowMap, shadowCoord, shadowParams.xyz);\n}\nfloat _getShadowPCF1x1(sampler2D shadowMap, vec3 shadowCoord) {\n\tfloat shadowSample = unpackFloat(textureShadow(shadowMap, shadowCoord.xy));\n\treturn shadowSample > shadowCoord.z ? 1.0 : 0.0;\n}\nfloat getShadowPCF1x1(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n\treturn _getShadowPCF1x1(shadowMap, shadowCoord);\n}\nfloat getShadowSpotPCF1x1(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n\treturn _getShadowPCF1x1(shadowMap, shadowCoord);\n}\n#endif\n#ifndef WEBGPU\nfloat _getShadowPoint(samplerCube shadowMap, vec4 shadowParams, vec3 dir) {\n\tvec3 tc = normalize(dir);\n\tvec3 tcAbs = abs(tc);\n\tvec4 dirX = vec4(1,0,0, tc.x);\n\tvec4 dirY = vec4(0,1,0, tc.y);\n\tfloat majorAxisLength = tc.z;\n\tif ((tcAbs.x > tcAbs.y) && (tcAbs.x > tcAbs.z)) {\n\t\tdirX = vec4(0,0,1, tc.z);\n\t\tdirY = vec4(0,1,0, tc.y);\n\t\tmajorAxisLength = tc.x;\n\t} else if ((tcAbs.y > tcAbs.x) && (tcAbs.y > tcAbs.z)) {\n\t\tdirX = vec4(1,0,0, tc.x);\n\t\tdirY = vec4(0,0,1, tc.z);\n\t\tmajorAxisLength = tc.y;\n\t}\n\tfloat shadowParamsInFaceSpace = ((1.0/shadowParams.x) * 2.0) * abs(majorAxisLength);\n\tvec3 xoffset = (dirX.xyz * shadowParamsInFaceSpace);\n\tvec3 yoffset = (dirY.xyz * shadowParamsInFaceSpace);\n\tvec3 dx0 = -xoffset;\n\tvec3 dy0 = -yoffset;\n\tvec3 dx1 = xoffset;\n\tvec3 dy1 = yoffset;\n\tmat3 shadowKernel;\n\tmat3 depthKernel;\n\tdepthKernel[0][0] = unpackFloat(textureCube(shadowMap, tc + dx0 + dy0));\n\tdepthKernel[0][1] = unpackFloat(textureCube(shadowMap, tc + dx0));\n\tdepthKernel[0][2] = unpackFloat(textureCube(shadowMap, tc + dx0 + dy1));\n\tdepthKernel[1][0] = unpackFloat(textureCube(shadowMap, tc + dy0));\n\tdepthKernel[1][1] = unpackFloat(textureCube(shadowMap, tc));\n\tdepthKernel[1][2] = unpackFloat(textureCube(shadowMap, tc + dy1));\n\tdepthKernel[2][0] = unpackFloat(textureCube(shadowMap, tc + dx1 + dy0));\n\tdepthKernel[2][1] = unpackFloat(textureCube(shadowMap, tc + dx1));\n\tdepthKernel[2][2] = unpackFloat(textureCube(shadowMap, tc + dx1 + dy1));\n\tvec3 shadowZ = vec3(length(dir) * shadowParams.w + shadowParams.z);\n\tshadowKernel[0] = vec3(lessThan2(depthKernel[0], shadowZ));\n\tshadowKernel[1] = vec3(lessThan2(depthKernel[1], shadowZ));\n\tshadowKernel[2] = vec3(lessThan2(depthKernel[2], shadowZ));\n\tvec2 uv = (vec2(dirX.w, dirY.w) / abs(majorAxisLength)) * 0.5;\n\tvec2 fractionalCoord = fract( uv * shadowParams.x );\n\tshadowKernel[0] = mix(shadowKernel[0], shadowKernel[1], fractionalCoord.x);\n\tshadowKernel[1] = mix(shadowKernel[1], shadowKernel[2], fractionalCoord.x);\n\tvec4 shadowValues;\n\tshadowValues.x = mix(shadowKernel[0][0], shadowKernel[0][1], fractionalCoord.y);\n\tshadowValues.y = mix(shadowKernel[0][1], shadowKernel[0][2], fractionalCoord.y);\n\tshadowValues.z = mix(shadowKernel[1][0], shadowKernel[1][1], fractionalCoord.y);\n\tshadowValues.w = mix(shadowKernel[1][1], shadowKernel[1][2], fractionalCoord.y);\n\treturn 1.0 - dot( shadowValues, vec4( 1.0 ) ) * 0.25;\n}\nfloat getShadowPointPCF3x3(samplerCube shadowMap, vec3 shadowCoord, vec4 shadowParams, vec3 lightDir) {\n\treturn _getShadowPoint(shadowMap, shadowParams, lightDir);\n}\n#endif\n",shadowStandardGL2PS:"\nfloat _getShadowPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec3 shadowParams) {\n\tfloat z = shadowCoord.z;\n\tvec2 uv = shadowCoord.xy * shadowParams.x;\n\tfloat shadowMapSizeInv = 1.0 / shadowParams.x;\n\tvec2 base_uv = floor(uv + 0.5);\n\tfloat s = (uv.x + 0.5 - base_uv.x);\n\tfloat t = (uv.y + 0.5 - base_uv.y);\n\tbase_uv -= vec2(0.5);\n\tbase_uv *= shadowMapSizeInv;\n\tfloat uw0 = (4.0 - 3.0 * s);\n\tfloat uw1 = 7.0;\n\tfloat uw2 = (1.0 + 3.0 * s);\n\tfloat u0 = (3.0 - 2.0 * s) / uw0 - 2.0;\n\tfloat u1 = (3.0 + s) / uw1;\n\tfloat u2 = s / uw2 + 2.0;\n\tfloat vw0 = (4.0 - 3.0 * t);\n\tfloat vw1 = 7.0;\n\tfloat vw2 = (1.0 + 3.0 * t);\n\tfloat v0 = (3.0 - 2.0 * t) / vw0 - 2.0;\n\tfloat v1 = (3.0 + t) / vw1;\n\tfloat v2 = t / vw2 + 2.0;\n\tfloat sum = 0.0;\n\tu0 = u0 * shadowMapSizeInv + base_uv.x;\n\tv0 = v0 * shadowMapSizeInv + base_uv.y;\n\tu1 = u1 * shadowMapSizeInv + base_uv.x;\n\tv1 = v1 * shadowMapSizeInv + base_uv.y;\n\tu2 = u2 * shadowMapSizeInv + base_uv.x;\n\tv2 = v2 * shadowMapSizeInv + base_uv.y;\n\tsum += uw0 * vw0 * textureShadow(shadowMap, vec3(u0, v0, z));\n\tsum += uw1 * vw0 * textureShadow(shadowMap, vec3(u1, v0, z));\n\tsum += uw2 * vw0 * textureShadow(shadowMap, vec3(u2, v0, z));\n\tsum += uw0 * vw1 * textureShadow(shadowMap, vec3(u0, v1, z));\n\tsum += uw1 * vw1 * textureShadow(shadowMap, vec3(u1, v1, z));\n\tsum += uw2 * vw1 * textureShadow(shadowMap, vec3(u2, v1, z));\n\tsum += uw0 * vw2 * textureShadow(shadowMap, vec3(u0, v2, z));\n\tsum += uw1 * vw2 * textureShadow(shadowMap, vec3(u1, v2, z));\n\tsum += uw2 * vw2 * textureShadow(shadowMap, vec3(u2, v2, z));\n\tsum *= 1.0f / 144.0;\n\tsum = saturate(sum);\n\treturn sum;\n}\nfloat getShadowPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\treturn _getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);\n}\nfloat getShadowSpotPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n\treturn _getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);\n}\n",shadowVSM8PS:"\nfloat calculateVSM8(vec3 moments, float Z, float vsmBias) {\n\tfloat VSMBias = vsmBias;\n\tfloat depthScale = VSMBias * Z;\n\tfloat minVariance1 = depthScale * depthScale;\n\treturn chebyshevUpperBound(moments.xy, Z, minVariance1, 0.1);\n}\nfloat decodeFloatRG(vec2 rg) {\n\treturn rg.y*(1.0/255.0) + rg.x;\n}\nfloat VSM8(TEXTURE_ACCEPT(tex), vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n\tvec4 c = texture2D(tex, texCoords);\n\tvec3 moments = vec3(decodeFloatRG(c.xy), decodeFloatRG(c.zw), 0.0);\n\treturn calculateVSM8(moments, Z, vsmBias);\n}\nfloat getShadowVSM8(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n\treturn VSM8(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, 0.0);\n}\nfloat getShadowSpotVSM8(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n\treturn VSM8(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, length(lightDir) * shadowParams.w + shadowParams.z, shadowParams.y, 0.0);\n}\n",shadowVSM_commonPS:"\nfloat linstep(float a, float b, float v) {\n\treturn saturate((v - a) / (b - a));\n}\nfloat reduceLightBleeding(float pMax, float amount) {\n return linstep(amount, 1.0, pMax);\n}\nfloat chebyshevUpperBound(vec2 moments, float mean, float minVariance, float lightBleedingReduction) {\n\tfloat variance = moments.y - (moments.x * moments.x);\n\tvariance = max(variance, minVariance);\n\tfloat d = mean - moments.x;\n\tfloat pMax = variance / (variance + (d * d));\n\tpMax = reduceLightBleeding(pMax, lightBleedingReduction);\n\treturn (mean <= moments.x ? 1.0 : pMax);\n}\nfloat calculateEVSM(vec3 moments, float Z, float vsmBias, float exponent) {\n\tZ = 2.0 * Z - 1.0;\n\tfloat warpedDepth = exp(exponent * Z);\n\tmoments.xy += vec2(warpedDepth, warpedDepth*warpedDepth) * (1.0 - moments.z);\n\tfloat VSMBias = vsmBias;\n\tfloat depthScale = VSMBias * exponent * warpedDepth;\n\tfloat minVariance1 = depthScale * depthScale;\n\treturn chebyshevUpperBound(moments.xy, warpedDepth, minVariance1, 0.1);\n}\n",skinBatchConstVS:"\nattribute float vertex_boneIndices;\nuniform vec4 matrix_pose[BONE_LIMIT * 3];\nmat4 getBoneMatrix(const in float i) {\n\tvec4 v1 = matrix_pose[int(3.0 * i)];\n\tvec4 v2 = matrix_pose[int(3.0 * i + 1.0)];\n\tvec4 v3 = matrix_pose[int(3.0 * i + 2.0)];\n\treturn mat4(\n\t\tv1.x, v2.x, v3.x, 0,\n\t\tv1.y, v2.y, v3.y, 0,\n\t\tv1.z, v2.z, v3.z, 0,\n\t\tv1.w, v2.w, v3.w, 1\n\t);\n}\n",skinBatchTexVS:"\nattribute float vertex_boneIndices;\nuniform highp sampler2D texture_poseMap;\nuniform vec4 texture_poseMapSize;\nmat4 getBoneMatrix(const in float i) {\n\tfloat j = i * 3.0;\n\tfloat dx = texture_poseMapSize.z;\n\tfloat dy = texture_poseMapSize.w;\n\tfloat y = floor(j * dx);\n\tfloat x = j - (y * texture_poseMapSize.x);\n\ty = dy * (y + 0.5);\n\tvec4 v1 = texture2D(texture_poseMap, vec2(dx * (x + 0.5), y));\n\tvec4 v2 = texture2D(texture_poseMap, vec2(dx * (x + 1.5), y));\n\tvec4 v3 = texture2D(texture_poseMap, vec2(dx * (x + 2.5), y));\n\treturn mat4(\n\t\tv1.x, v2.x, v3.x, 0,\n\t\tv1.y, v2.y, v3.y, 0,\n\t\tv1.z, v2.z, v3.z, 0,\n\t\tv1.w, v2.w, v3.w, 1\n\t);\n}\n",skinConstVS:"\nattribute vec4 vertex_boneWeights;\nattribute vec4 vertex_boneIndices;\nuniform vec4 matrix_pose[BONE_LIMIT * 3];\nvoid getBoneMatrix(const in float i, out vec4 v1, out vec4 v2, out vec4 v3) {\n\tv1 = matrix_pose[int(3.0 * i)];\n\tv2 = matrix_pose[int(3.0 * i + 1.0)];\n\tv3 = matrix_pose[int(3.0 * i + 2.0)];\n}\nmat4 getSkinMatrix(const in vec4 indices, const in vec4 weights) {\n\tvec4 a1, a2, a3;\n\tgetBoneMatrix(indices.x, a1, a2, a3);\n\tvec4 b1, b2, b3;\n\tgetBoneMatrix(indices.y, b1, b2, b3);\n\tvec4 c1, c2, c3;\n\tgetBoneMatrix(indices.z, c1, c2, c3);\n\tvec4 d1, d2, d3;\n\tgetBoneMatrix(indices.w, d1, d2, d3);\n\tvec4 v1 = a1 * weights.x + b1 * weights.y + c1 * weights.z + d1 * weights.w;\n\tvec4 v2 = a2 * weights.x + b2 * weights.y + c2 * weights.z + d2 * weights.w;\n\tvec4 v3 = a3 * weights.x + b3 * weights.y + c3 * weights.z + d3 * weights.w;\n\tfloat one = dot(weights, vec4(1.0));\n\treturn mat4(\n\t\tv1.x, v2.x, v3.x, 0,\n\t\tv1.y, v2.y, v3.y, 0,\n\t\tv1.z, v2.z, v3.z, 0,\n\t\tv1.w, v2.w, v3.w, one\n\t);\n}\n",skinTexVS:"\nattribute vec4 vertex_boneWeights;\nattribute vec4 vertex_boneIndices;\nuniform highp sampler2D texture_poseMap;\nuniform vec4 texture_poseMapSize;\nvoid getBoneMatrix(const in float index, out vec4 v1, out vec4 v2, out vec4 v3) {\n\tfloat i = float(index);\n\tfloat j = i * 3.0;\n\tfloat dx = texture_poseMapSize.z;\n\tfloat dy = texture_poseMapSize.w;\n\t\n\tfloat y = floor(j * dx);\n\tfloat x = j - (y * texture_poseMapSize.x);\n\ty = dy * (y + 0.5);\n\tv1 = texture2D(texture_poseMap, vec2(dx * (x + 0.5), y));\n\tv2 = texture2D(texture_poseMap, vec2(dx * (x + 1.5), y));\n\tv3 = texture2D(texture_poseMap, vec2(dx * (x + 2.5), y));\n}\nmat4 getSkinMatrix(const in vec4 indices, const in vec4 weights) {\n\tvec4 a1, a2, a3;\n\tgetBoneMatrix(indices.x, a1, a2, a3);\n\tvec4 b1, b2, b3;\n\tgetBoneMatrix(indices.y, b1, b2, b3);\n\tvec4 c1, c2, c3;\n\tgetBoneMatrix(indices.z, c1, c2, c3);\n\tvec4 d1, d2, d3;\n\tgetBoneMatrix(indices.w, d1, d2, d3);\n\tvec4 v1 = a1 * weights.x + b1 * weights.y + c1 * weights.z + d1 * weights.w;\n\tvec4 v2 = a2 * weights.x + b2 * weights.y + c2 * weights.z + d2 * weights.w;\n\tvec4 v3 = a3 * weights.x + b3 * weights.y + c3 * weights.z + d3 * weights.w;\n\tfloat one = dot(weights, vec4(1.0));\n\treturn mat4(\n\t\tv1.x, v2.x, v3.x, 0,\n\t\tv1.y, v2.y, v3.y, 0,\n\t\tv1.z, v2.z, v3.z, 0,\n\t\tv1.w, v2.w, v3.w, one\n\t);\n}\n",skyboxEnvPS:"\nvarying vec3 vViewDir;\nuniform sampler2D texture_envAtlas;\nuniform float mipLevel;\nvoid main(void) {\n\tvec3 dir = vViewDir * vec3(-1.0, 1.0, 1.0);\n\tvec2 uv = toSphericalUv(normalize(dir));\n\tvec3 linear = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, mipLevel)));\n\tgl_FragColor = vec4(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0);\n}\n",skyboxHDRPS:"\nvarying vec3 vViewDir;\nuniform samplerCube texture_cubeMap;\nvoid main(void) {\n\tvec3 dir=vViewDir;\n\tdir.x *= -1.0;\n\tvec3 linear = $DECODE(textureCube(texture_cubeMap, fixSeamsStatic(dir, $FIXCONST)));\n\tgl_FragColor = vec4(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0);\n}\n",skyboxVS:"\nattribute vec3 aPosition;\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nuniform mat4 matrix_projectionSkybox;\nuniform mat3 cubeMapRotationMatrix;\nvarying vec3 vViewDir;\nvoid main(void) {\n\tmat4 view = matrix_view;\n\tview[3][0] = view[3][1] = view[3][2] = 0.0;\n\tgl_Position = matrix_projectionSkybox * view * vec4(aPosition, 1.0);\n\tgl_Position.z = gl_Position.w - 0.00001;\n\tvViewDir = aPosition * cubeMapRotationMatrix;\n}\n",specularPS:"\n#ifdef MAPCOLOR\nuniform vec3 material_specular;\n#endif\nvoid getSpecularity() {\n\tvec3 specularColor = vec3(1,1,1);\n\t#ifdef MAPCOLOR\n\tspecularColor *= material_specular;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tspecularColor *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tspecularColor *= saturate(vVertexColor.$VC);\n\t#endif\n\tdSpecularity = specularColor;\n}\n",sphericalPS:"\nconst float PI = 3.141592653589793;\nvec2 toSpherical(vec3 dir) {\n\treturn vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y));\n}\nvec2 toSphericalUv(vec3 dir) {\n\tvec2 uv = toSpherical(dir) / vec2(PI * 2.0, PI) + 0.5;\n\treturn vec2(uv.x, 1.0 - uv.y);\n}\n",specularityFactorPS:"\n#ifdef MAPFLOAT\nuniform float material_specularityFactor;\n#endif\nvoid getSpecularityFactor() {\n\tfloat specularityFactor = 1.0;\n\t#ifdef MAPFLOAT\n\tspecularityFactor *= material_specularityFactor;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tspecularityFactor *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tspecularityFactor *= saturate(vVertexColor.$VC);\n\t#endif\n\tdSpecularityFactor = specularityFactor;\n}\n",spotPS:"\nfloat getSpotEffect(vec3 lightSpotDir, float lightInnerConeAngle, float lightOuterConeAngle, vec3 lightDirNorm) {\n\tfloat cosAngle = dot(lightDirNorm, lightSpotDir);\n\treturn smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle);\n}\n",startPS:"\nvoid main(void) {\n\tdReflection = vec4(0);\n\t#ifdef LIT_CLEARCOAT\n\tccSpecularLight = vec3(0);\n\tccReflection = vec3(0);\n\t#endif\n",startVS:"\nvoid main(void) {\n\tgl_Position = getPosition();\n",startNineSlicedPS:"\n\tnineSlicedUv = vUv0;\n\tnineSlicedUv.y = 1.0 - nineSlicedUv.y;\n",startNineSlicedTiledPS:"\n\tvec2 tileMask = step(vMask, vec2(0.99999));\n\tvec2 tileSize = 0.5 * (innerOffset.xy + innerOffset.zw);\n\tvec2 tileScale = vec2(1.0) / (vec2(1.0) - tileSize);\n\tvec2 clampedUv = mix(innerOffset.xy * 0.5, vec2(1.0) - innerOffset.zw * 0.5, fract((vTiledUv - tileSize) * tileScale));\n\tclampedUv = clampedUv * atlasRect.zw + atlasRect.xy;\n\tnineSlicedUv = vUv0 * tileMask + clampedUv * (vec2(1.0) - tileMask);\n\tnineSlicedUv.y = 1.0 - nineSlicedUv.y;\n\t\n",storeEVSMPS:"\nfloat exponent = VSM_EXPONENT;\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\treturn normalize(dNormalMatrix * vertex_tangent.xyz);\n}\nvec3 getBinormal() {\n\treturn cross(vNormalW, vTangentW) * vertex_tangent.w;\n}\n",TBNPS:"\nvoid getTBN(vec3 tangent, vec3 binormal, vec3 normal) {\n\tdTBN = mat3(normalize(tangent), normalize(binormal), normalize(normal));\n}\n",TBNderivativePS:"\nuniform float tbnBasis;\nvoid getTBN(vec3 tangent, vec3 binormal, vec3 normal) {\n\tvec2 uv = $UV;\n\tvec3 dp1 = dFdx( vPositionW );\n\tvec3 dp2 = dFdy( vPositionW );\n\tvec2 duv1 = dFdx( uv );\n\tvec2 duv2 = dFdy( uv );\n\tvec3 dp2perp = cross( dp2, normal );\n\tvec3 dp1perp = cross( normal, dp1 );\n\tvec3 T = dp2perp * duv1.x + dp1perp * duv2.x;\n\tvec3 B = dp2perp * duv1.y + dp1perp * duv2.y;\n\tfloat denom = max( dot(T,T), dot(B,B) );\n\tfloat invmax = (denom == 0.0) ? 0.0 : tbnBasis / sqrt( denom );\n\tdTBN = mat3(T * invmax, -B * invmax, normal );\n}\n",TBNfastPS:"\nvoid getTBN(vec3 tangent, vec3 binormal, vec3 normal) {\n\tdTBN = mat3(tangent, binormal, normal);\n}\n",TBNObjectSpacePS:"\nvoid getTBN(vec3 tangent, vec3 binormal, vec3 normal) {\n\tvec3 B = cross(normal, vObjectSpaceUpW);\n\tvec3 T = cross(normal, B);\n\tif (dot(B,B)==0.0)\n\t{\n\t\tfloat major=max(max(normal.x, normal.y), normal.z);\n\t\tif (normal.x == major)\n\t\t{\n\t\t\tB=cross(normal, vec3(0,1,0));\n\t\t\tT=cross(normal, B);\n\t\t}\n\t\telse if (normal.y == major)\n\t\t{\n\t\t\tB=cross(normal, vec3(0,0,1));\n\t\t\tT=cross(normal, B);\n\t\t}\n\t\telse if (normal.z == major)\n\t\t{\n\t\t\tB=cross(normal, vec3(1,0,0));\n\t\t\tT=cross(normal, B);\n\t\t}\n\t}\n\tdTBN = mat3(normalize(T), normalize(B), normalize(normal));\n}\n",textureSamplePS:"\nvec4 texture2DSRGB(sampler2D tex, vec2 uv) {\n\treturn gammaCorrectInput(texture2D(tex, uv));\n}\nvec4 texture2DSRGB(sampler2D tex, vec2 uv, float bias) {\n\treturn gammaCorrectInput(texture2D(tex, uv, bias));\n}\nvec3 texture2DRGBM(sampler2D tex, vec2 uv) {\n\treturn decodeRGBM(texture2D(tex, uv));\n}\nvec3 texture2DRGBM(sampler2D tex, vec2 uv, float bias) {\n\treturn decodeRGBM(texture2D(tex, uv, bias));\n}\nvec3 texture2DRGBE(sampler2D tex, vec2 uv) {\n\treturn decodeRGBM(texture2D(tex, uv));\n}\nvec3 texture2DRGBE(sampler2D tex, vec2 uv, float bias) {\n\treturn decodeRGBM(texture2D(tex, uv, bias));\n}\n",thicknessPS:"\n#ifdef MAPFLOAT\nuniform float material_thickness;\n#endif\nvoid getThickness() {\n\tdThickness = 1.0;\n\t#ifdef MAPFLOAT\n\tdThickness *= material_thickness;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tdThickness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tdThickness *= saturate(vVertexColor.$VC);\n\t#endif\n}\n",tonemappingAcesPS:"\nuniform float exposure;\nvec3 toneMap(vec3 color) {\n\tfloat tA = 2.51;\n\tfloat tB = 0.03;\n\tfloat tC = 2.43;\n\tfloat tD = 0.59;\n\tfloat tE = 0.14;\n\tvec3 x = color * exposure;\n\treturn (x*(tA*x+tB))/(x*(tC*x+tD)+tE);\n}\n",tonemappingAces2PS:"\nuniform float exposure;\nconst mat3 ACESInputMat = mat3(\n\t0.59719, 0.35458, 0.04823,\n\t0.07600, 0.90834, 0.01566,\n\t0.02840, 0.13383, 0.83777\n);\nconst mat3 ACESOutputMat = mat3(\n\t 1.60475, -0.53108, -0.07367,\n\t-0.10208, 1.10813, -0.00605,\n\t-0.00327, -0.07276, 1.07602\n);\nvec3 RRTAndODTFit(vec3 v) {\n\tvec3 a = v * (v + 0.0245786) - 0.000090537;\n\tvec3 b = v * (0.983729 * v + 0.4329510) + 0.238081;\n\treturn a / b;\n}\nvec3 toneMap(vec3 color) {\n\tcolor *= exposure / 0.6;\n\tcolor = color * ACESInputMat;\n\tcolor = RRTAndODTFit(color);\n\tcolor = color * ACESOutputMat;\n\tcolor = clamp(color, 0.0, 1.0);\n\treturn 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;\nuniform float exposure;\nvec3 uncharted2Tonemap(vec3 x) {\n return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\n}\nvec3 toneMap(vec3 color) {\n\tcolor = uncharted2Tonemap(color * exposure);\n\tvec3 whiteScale = 1.0 / uncharted2Tonemap(vec3(W,W,W));\n\tcolor = color * whiteScale;\n\treturn color;\n}\n",tonemappingHejlPS:"\nuniform float exposure;\nvec3 toneMap(vec3 color) {\n\tcolor *= exposure;\n\tconst float A = 0.22, B = 0.3, C = .1, D = 0.2, E = .01, F = 0.3;\n\tconst float Scl = 1.25;\n\tvec3 h = max( vec3(0.0), color - vec3(0.004) );\n\treturn (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;\nvec3 toneMap(vec3 color) {\n\treturn color * exposure;\n}\n",tonemappingNonePS:"\nvec3 toneMap(vec3 color) {\n\treturn color;\n}\n",transformVS:"\n#ifdef PIXELSNAP\nuniform vec4 uScreenSize;\n#endif\n#ifdef SCREENSPACE\nuniform float projectionFlipY;\n#endif\n#ifdef MORPHING\nuniform vec4 morph_weights_a;\nuniform vec4 morph_weights_b;\n#endif\n#ifdef MORPHING_TEXTURE_BASED\n\tuniform vec4 morph_tex_params;\n\t#ifdef WEBGPU\n\t\tivec2 getTextureMorphCoords() {\n\t\t\tivec2 textureSize = ivec2(morph_tex_params.xy);\n\t\t\tint morphGridV = int(morph_vertex_id / textureSize.x);\n\t\t\tint morphGridU = int(morph_vertex_id - (morphGridV * textureSize.x));\n\t\t\tmorphGridV = textureSize.y - morphGridV - 1;\n\t\t\treturn ivec2(morphGridU, morphGridV);\n\t\t}\n\t#else\n\t\tvec2 getTextureMorphCoords() {\n\t\t\tvec2 textureSize = morph_tex_params.xy;\n\t\t\tvec2 invTextureSize = morph_tex_params.zw;\n\t\t\tfloat morphGridV = floor(morph_vertex_id * invTextureSize.x);\n\t\t\tfloat morphGridU = morph_vertex_id - (morphGridV * textureSize.x);\n\t\t\treturn vec2(morphGridU, morphGridV) * invTextureSize + (0.5 * invTextureSize);\n\t\t}\n\t#endif\n#endif\n#ifdef MORPHING_TEXTURE_BASED_POSITION\nuniform highp sampler2D morphPositionTex;\n#endif\nmat4 getModelMatrix() {\n\t#ifdef DYNAMICBATCH\n\treturn getBoneMatrix(vertex_boneIndices);\n\t#elif defined(SKIN)\n\treturn matrix_model * getSkinMatrix(vertex_boneIndices, vertex_boneWeights);\n\t#elif defined(INSTANCING)\n\treturn mat4(instance_line1, instance_line2, instance_line3, instance_line4);\n\t#else\n\treturn matrix_model;\n\t#endif\n}\nvec4 getPosition() {\n\tdModelMatrix = getModelMatrix();\n\tvec3 localPos = vertex_position;\n\t#ifdef NINESLICED\n\tlocalPos.xz *= outerScale;\n\tvec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0));\n\tvec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0));\n\tlocalPos.xz += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;\n\tvTiledUv = (localPos.xz - outerScale + innerOffset.xy) * -0.5 + 1.0;\n\tlocalPos.xz *= -0.5;\n\tlocalPos = localPos.xzy;\n\t#endif\n\t#ifdef MORPHING\n\t#ifdef MORPHING_POS03\n\tlocalPos.xyz += morph_weights_a[0] * morph_pos0;\n\tlocalPos.xyz += morph_weights_a[1] * morph_pos1;\n\tlocalPos.xyz += morph_weights_a[2] * morph_pos2;\n\tlocalPos.xyz += morph_weights_a[3] * morph_pos3;\n\t#endif\n\t#ifdef MORPHING_POS47\n\tlocalPos.xyz += morph_weights_b[0] * morph_pos4;\n\tlocalPos.xyz += morph_weights_b[1] * morph_pos5;\n\tlocalPos.xyz += morph_weights_b[2] * morph_pos6;\n\tlocalPos.xyz += morph_weights_b[3] * morph_pos7;\n\t#endif\n\t#endif\n\t#ifdef MORPHING_TEXTURE_BASED_POSITION\n\t\t#ifdef WEBGPU\n\t\t\tivec2 morphUV = getTextureMorphCoords();\n\t\t\tvec3 morphPos = texelFetch(morphPositionTex, ivec2(morphUV), 0).xyz;\n\t\t#else\n\t\t\tvec2 morphUV = getTextureMorphCoords();\n\t\t\tvec3 morphPos = texture2D(morphPositionTex, morphUV).xyz;\n\t\t#endif\n\t\tlocalPos += morphPos;\n\t#endif\n\tvec4 posW = dModelMatrix * vec4(localPos, 1.0);\n\t#ifdef SCREENSPACE\n\tposW.zw = vec2(0.0, 1.0);\n\t#endif\n\tdPositionW = posW.xyz;\n\tvec4 screenPos;\n\t#ifdef UV1LAYOUT\n\tscreenPos = vec4(vertex_texCoord1.xy * 2.0 - 1.0, 0.5, 1);\n\t#else\n\t#ifdef SCREENSPACE\n\tscreenPos = posW;\n\tscreenPos.y *= projectionFlipY;\n\t#else\n\tscreenPos = matrix_viewProjection * posW;\n\t#endif\n\t#ifdef PIXELSNAP\n\tscreenPos.xy = (screenPos.xy * 0.5) + 0.5;\n\tscreenPos.xy *= uScreenSize.xy;\n\tscreenPos.xy = floor(screenPos.xy);\n\tscreenPos.xy *= uScreenSize.zw;\n\tscreenPos.xy = (screenPos.xy * 2.0) - 1.0;\n\t#endif\n\t#endif\n\treturn screenPos;\n}\nvec3 getWorldPosition() {\n\treturn dPositionW;\n}\n",transformDeclVS:"\nattribute vec3 vertex_position;\nuniform mat4 matrix_model;\nuniform mat4 matrix_viewProjection;\nvec3 dPositionW;\nmat4 dModelMatrix;\n",transmissionPS:"\n#ifdef MAPFLOAT\nuniform float material_refraction;\n#endif\nvoid getRefraction() {\n\tfloat refraction = 1.0;\n\t#ifdef MAPFLOAT\n\trefraction = material_refraction;\n\t#endif\n\t#ifdef MAPTEXTURE\n\trefraction *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\trefraction *= saturate(vVertexColor.$VC);\n\t#endif\n\tdTransmission = refraction;\n}\n",uv0VS:"\n#ifdef NINESLICED\nvec2 getUv0() {\n\tvec2 uv = vertex_position.xz;\n\tvec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0));\n\tvec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0));\n\tuv += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;\n\tuv = uv * -0.5 + 0.5;\n\tuv = uv * atlasRect.zw + atlasRect.xy;\n\tvMask = vertex_texCoord0.xy;\n\treturn uv;\n}\n#else\nvec2 getUv0() {\n\treturn vertex_texCoord0;\n}\n#endif\n",uv1VS:"\nvec2 getUv1() {\n\treturn vertex_texCoord1;\n}\n",viewDirPS:"\nvoid getViewDir() {\n\tdViewDirW = normalize(view_position - vPositionW);\n}\n",viewNormalVS:"\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nvec3 getViewNormal() {\n\treturn mat3(matrix_view) * vNormalW;\n}\n",webgpuPS:$s,webgpuVS:Js},vo=new Bs;function go(t){return vo.get(t)}function yo(t,e){vo.get(t,(function(){return e}))}var xo=function(){function t(){}return t.begin=function(){return"void main(void)\n{\n"},t.end=function(){return"}\n"},t.skinCode=function(t,e){return e||(e=_o),t.supportsBoneTextures?e.skinTexVS:"#define BONE_LIMIT "+t.getBoneLimit()+"\n"+e.skinConstVS},t.fogCode=function(t,e){return e||(e=_o),"linear"===t?e.fogLinearPS?e.fogLinearPS:_o.fogLinearPS:"exp"===t?e.fogExpPS?e.fogExpPS:_o.fogExpPS:"exp2"===t?e.fogExp2PS?e.fogExp2PS:_o.fogExp2PS:e.fogNonePS?e.fogNonePS:_o.fogNonePS},t.gammaCode=function(t,e){return e||(e=_o),1===t||2===t?e.gamma2_2PS?e.gamma2_2PS:_o.gamma2_2PS:3===t?"#define HDR\n"+(e.gamma2_2PS?e.gamma2_2PS:_o.gamma2_2PS):e.gamma1_0PS?e.gamma1_0PS:_o.gamma1_0PS},t.tonemapCode=function(t,e){return e||(e=_o),1===t?e.tonemappingFilmicPS?e.tonemappingFilmicPS:_o.tonemappingFilmicPS:0===t?e.tonemappingLinearPS?e.tonemappingLinearPS:_o.tonemappingLinearPS:2===t?e.tonemappingHejlPS?e.tonemappingHejlPS:_o.tonemappingHejlPS:3===t?e.tonemappingAcesPS?e.tonemappingAcesPS:_o.tonemappingAcesPS:4===t?e.tonemappingAces2PS?e.tonemappingAces2PS:_o.tonemappingAces2PS:e.tonemapingNonePS?e.tonemapingNonePS:_o.tonemappingNonePS},t}();function So(t,e,i,n){return void 0===n&&(n=!1),new fs(t,ir.createDefinition(t,{name:e+"_"+i,vertexCode:_o[e],fragmentCode:_o[i],useTransformFeedback:n}))}function bo(t,e,i,n,s,r){void 0===r&&(r=!1);var a=go(t),o=a.getCachedShader(n);return o||(o=new fs(t,ir.createDefinition(t,{name:n,vertexCode:e,fragmentCode:i,attributes:s,useTransformFeedback:r})),a.setCachedShader(n,o)),o}var wo=function(t){function e(e,i){var n;return(n=t.call(this)||this).key=e,n.shaderDefinition=i,n}S(e,t);var i=e.prototype;return i.generateKey=function(t){return this.key},i.createShaderDefinition=function(t,e){return this.shaderDefinition},e}(xo);function To(t,e){var i,n=t.definition,s=(null!=(i=n.name)?i:"shader")+"-id-"+t.id,r=new wo(s,n),a="shader",o=go(t.device);o.register(a,r);var h=o.getProgram(a,{},e);return o.unregister(a),h}_o.createShader=So,_o.createShaderFromCode=bo;var Ao={type:be,base:0,count:4,indexed:!1},Co=new Pt,Eo=new Pt,Mo=function(){function t(t){this.uniformBuffer=void 0,this.bindGroup=void 0;var e=t.device;if(this.shader=t,e.supportsUniformBuffers){var i=new fo;this.shader=To(t,i);var n=this.shader.meshUniformBufferFormat;n&&(this.uniformBuffer=new xs(e,n,!1));var s=this.shader.meshBindGroupFormat;this.bindGroup=new ms(e,s,this.uniformBuffer)}}var e=t.prototype;return e.destroy=function(){var t,e;null==(t=this.uniformBuffer)||t.destroy(),this.uniformBuffer=null,null==(e=this.bindGroup)||e.destroy(),this.bindGroup=null},e.render=function(t,e){var i,n=this.shader.device;t&&(Co.set(n.vx,n.vy,n.vw,n.vh),Eo.set(n.sx,n.sy,n.sw,n.sh),e=null!=(i=e)?i:t,n.setViewport(t.x,t.y,t.z,t.w),n.setScissor(e.x,e.y,e.z,e.w));n.setVertexBuffer(n.quadVertexBuffer,0);var s=this.shader;if(n.setShader(s),n.supportsUniformBuffers){var r,a=this.bindGroup;null==(r=a.defaultUniformBuffer)||r.update(),a.update(),n.setBindGroup(0,a)}n.draw(Ao),t&&(n.setViewport(Co.x,Co.y,Co.z,Co.w),n.setScissor(Eo.x,Eo.y,Eo.z,Eo.w))},t}(),Po=new Pt;function Ro(t,e,i,n,s){t.setCullMode(se),t.setDepthState(Ni.NODEPTH),t.setStencilState(null,null);var r=new Mo(i);n||((n=Po).x=0,n.y=0,n.z=e?e.width:t.width,n.w=e?e.height:t.height);var a=new uo(t,(function(){r.render(n,s)}));a.init(e),a.colorOps.clear=!1,a.depthStencilOps.clearDepth=!1,t.isWebGPU&&null===e&&t.samples>1&&(a.colorOps.store=!0),a.render(),r.destroy()}var Io=new Bs,Lo=function(){function t(t,e,i){void 0===i&&(i={}),this.index=void 0,this.name=void 0,this.shaderDefine=void 0,this.name=t,this.index=e,Object.assign(this,i),this.initShaderDefines()}return t.prototype.initShaderDefines=function(){var t;this.isShadow?t="SHADOW":this.isForward?t="FORWARD":2===this.index?t="DEPTH":3===this.index&&(t="PICK");var e=t?"#define "+t+"_PASS\n":"",i="#define "+this.name.toUpperCase()+"_PASS\n";this.shaderDefines=e+i},t}(),Do=function(){function t(){var t=this;this.passesNamed=new Map,this.passesIndexed=[],this.nextIndex=0;var e=function(e,i,n){t.allocate(e,n)};e("forward",0,{isForward:!0}),e("forward_hdr",0,{isForward:!0}),e("depth"),e("pick"),e("shadow")}t.get=function(e){return Io.get(e,(function(){return new t}))};var e=t.prototype;return e.allocate=function(t,e){var i=this.passesNamed.get(t);return void 0===i&&(i=new Lo(t,this.nextIndex,e),this.passesNamed.set(i.name,i),this.passesIndexed[i.index]=i,this.nextIndex++),i},e.getByIndex=function(t){return this.passesIndexed[t]},e.getByName=function(t){return this.passesNamed.get(t)},t}(),Oo=function(t){function e(){return t.apply(this,arguments)||this}S(e,t);var i=e.prototype;return i.generateKey=function(t){var e="basic";return t.fog&&(e+="_fog"),t.alphaTest&&(e+="_atst"),t.vertexColors&&(e+="_vcol"),t.diffuseMap&&(e+="_diff"),t.skin&&(e+="_skin"),t.screenSpace&&(e+="_ss"),t.useInstancing&&(e+="_inst"),t.useMorphPosition&&(e+="_morphp"),t.useMorphNormal&&(e+="_morphn"),t.useMorphTextureBased&&(e+="_morpht"),e+="_"+t.pass},i.createShaderDefinition=function(t,e){var i={vertex_position:we};e.skin&&(i.vertex_boneWeights=Ce,i.vertex_boneIndices=Ee),e.vertexColors&&(i.vertex_color=Me),e.diffuseMap&&(i.vertex_texCoord0=Re);var n=Do.get(t).getByIndex(e.pass).shaderDefines,s=n;s+=_o.transformDeclVS,e.skin?(s+=xo.skinCode(t),s+=_o.transformSkinnedVS):s+=_o.transformVS,e.vertexColors&&(s+="attribute vec4 vertex_color;\n",s+="varying vec4 vColor;\n"),e.diffuseMap&&(s+="attribute vec2 vertex_texCoord0;\n",s+="varying vec2 vUv0;\n"),2===e.pass&&(s+="varying float vDepth;\n",s+="#ifndef VIEWMATRIX\n",s+="#define VIEWMATRIX\n",s+="uniform mat4 matrix_view;\n",s+="#endif\n",s+="#ifndef CAMERAPLANES\n",s+="#define CAMERAPLANES\n",s+="uniform vec4 camera_params;\n\n",s+="#endif\n"),s+=xo.begin(),s+=" gl_Position = getPosition();\n",2===e.pass&&(s+=" vDepth = -(matrix_view * vec4(getWorldPosition(),1.0)).z * camera_params.x;\n"),e.vertexColors&&(s+=" vColor = vertex_color;\n"),e.diffuseMap&&(s+=" vUv0 = vertex_texCoord0;\n"),s+=xo.end();var r=n;return e.vertexColors?r+="varying vec4 vColor;\n":r+="uniform vec4 uColor;\n",e.diffuseMap&&(r+="varying vec2 vUv0;\n",r+="uniform sampler2D texture_diffuseMap;\n"),e.fog&&(r+=xo.fogCode(e.fog)),e.alphaTest&&(r+=_o.alphaTestPS),2===e.pass&&(r+="varying float vDepth;\n",r+=_o.packDepthPS),r+=xo.begin(),e.vertexColors?r+=" gl_FragColor = vColor;\n":r+=" gl_FragColor = uColor;\n",e.diffuseMap&&(r+=" gl_FragColor *= texture2D(texture_diffuseMap, vUv0);\n"),e.alphaTest&&(r+=" alphaTest(gl_FragColor.a);\n"),3!==e.pass&&(2===e.pass?r+=" gl_FragColor = packFloat(vDepth);\n":e.fog&&(r+=" glFragColor.rgb = addFog(gl_FragColor.rgb);\n")),r+=xo.end(),ir.createDefinition(t,{name:"BasicShader",attributes:i,vertexCode:s,fragmentCode:r})},e}(xo),ko=new Oo,Fo=new Bs;function Bo(t){return Fo.get(t)}var Uo=[];Uo[0]={src:1,dst:1,op:2},Uo[3]={src:1,dst:0,op:0},Uo[2]={src:6,dst:8,op:0},Uo[4]={src:1,dst:8,op:0},Uo[1]={src:1,dst:1,op:0},Uo[6]={src:6,dst:1,op:0},Uo[7]={src:4,dst:2,op:0},Uo[8]={src:5,dst:1,op:0},Uo[5]={src:4,dst:0,op:0},Uo[9]={src:1,dst:1,op:3},Uo[10]={src:1,dst:1,op:4};var No=0,zo=function(){function t(){this._shader=null,this.meshInstances=[],this.name="Untitled",this.userId="",this.id=No++,this.variants=new Map,this.parameters={},this.alphaTest=0,this.alphaToCoverage=!1,this._blendState=new Ui,this._depthState=new Ni,this.cull=1,this.stencilFront=null,this.stencilBack=null,this.depthBias=0,this.slopeDepthBias=0,this._shaderVersion=0,this._scene=null,this.dirty=!0}var e=t.prototype;return e._updateTransparency=function(){for(var t=this.transparent,e=this.meshInstances,i=0;i0,vertexColors:this.vertexColors,diffuseMap:!!this.colorMap,pass:s},c=new fo(a,o,h),u=go(t);return u.register("basic",ko),u.getProgram("basic",l,c,this.userId)},e}(zo),Go=function(){function t(t,e,i){this._aabb=new Ht,this.origMeshInstances=void 0,this.meshInstance=null,this.dynamic=void 0,this.batchGroupId=void 0,this.origMeshInstances=t,this.dynamic=e,this.batchGroupId=i}var e=t.prototype;return e.destroy=function(t,e){this.meshInstance&&(this.removeFromLayers(t,e),this.meshInstance.destroy(),this.meshInstance=null)},e.addToLayers=function(t,e){for(var i=0;i=0;i--)this.matrices[i].mulAffine2(Wo,this.bones[i].getWorldTransform()),this.matrices[i].mulAffine2(this.matrices[i],this.skin.inverseBindPose[i])}},e.updateMatrices=function(t,e){this._updateBeforeCull&&this._updateMatrices(t,e)},e.updateMatrixPalette=function(t,e){this._updateMatrices(t,e);for(var i=this.matrixPalette,n=this.bones.length,s=0;s=0?t.insertChild(this,e):t.addChild(this))},i.setLocalEulerAngles=function(t,e,i){this.localRotation.setFromEulerAngles(t,e,i),this._dirtyLocal||this._dirtifyLocal()},i.setLocalPosition=function(t,e,i){t instanceof wt?this.localPosition.copy(t):this.localPosition.set(t,e,i),this._dirtyLocal||this._dirtifyLocal()},i.setLocalRotation=function(t,e,i,n){t instanceof Bt?this.localRotation.copy(t):this.localRotation.set(t,e,i,n),this._dirtyLocal||this._dirtifyLocal()},i.setLocalScale=function(t,e,i){t instanceof wt?this.localScale.copy(t):this.localScale.set(t,e,i),this._dirtyLocal||this._dirtifyLocal()},i._dirtifyLocal=function(){this._dirtyLocal||(this._dirtyLocal=!0,this._dirtyWorld||this._dirtifyWorld())},i._unfreezeParentToRoot=function(){for(var t=this._parent;t;)t._frozen=!1,t=t._parent},i._dirtifyWorld=function(){this._dirtyWorld||this._unfreezeParentToRoot(),this._dirtifyWorldInternal()},i._dirtifyWorldInternal=function(){if(!this._dirtyWorld){this._frozen=!1,this._dirtyWorld=!0;for(var t=0;t>16},set:function(t){var e=65535&this._shaderDefs;this._updateShaderDefs(e|t<<16)}},{key:"instancingCount",get:function(){return this.instancingData?this.instancingData.count:0},set:function(t){this.instancingData&&(this.instancingData.count=t)}}]),t}();function xh(t,e){if(t&&!e)return!1;if(!t&&e)return!1;if((t=t.data)===(e=e.data))return!0;if(t instanceof Float32Array&&e instanceof Float32Array){if(t.length!==e.length)return!1;for(var i=0;i=0&&(n._obj[t].splice(s,1),this.markGroupDirty(e))}},e._extractRender=function(t,e,i,n){return t.render&&(e=n[t.render.batchGroupId]=e.concat(t.render.meshInstances),t.render.removeFromLayers()),e},e._extractModel=function(t,e,i,n){return t.model&&t.model.model&&(e=n[t.model.batchGroupId]=e.concat(t.model.meshInstances),t.model.removeModelFromLayers()),e},e._extractElement=function(t,e,i){if(t.element){var n=!1;t.element._text&&t.element._text._model.meshInstances.length>0?(e.push(t.element._text._model.meshInstances[0]),t.element.removeModelFromLayers(t.element._text._model),n=!0):t.element._image&&(e.push(t.element._image._renderable.meshInstance),t.element.removeModelFromLayers(t.element._image._renderable.model),t.element._image._renderable.unmaskMeshInstance&&(e.push(t.element._image._renderable.unmaskMeshInstance),t.element._image._renderable.unmaskMeshInstance.stencilFront&&t.element._image._renderable.unmaskMeshInstance.stencilBack||(t.element._dirtifyMask(),t.element._onPrerender())),n=!0),n&&(i._ui=!0)}},e._collectAndRemoveMeshInstances=function(t,e){for(var i=0;i0;){u[d]=[p[0]],f=[];var _=p[0].material,v=p[0].layer,g=p[0]._shaderDefs,y=p[0].parameters,x=p[0].stencilFront,S=p[0].mesh.vertexBuffer.getNumVertices(),b=p[0].drawOrder;h.copy(p[0].aabb);var w=Ah(p[0]),T=p[0].mesh.vertexBuffer.format.batchingHash,A=p[0].mesh.primitive[0].indexed;c=null;for(var C=1;C=a){f=f.concat(p.slice(C));break}_!==E.material||v!==E.layer||T!==E.mesh.vertexBuffer.format.batchingHash||A!==E.mesh.primitive[0].indexed||g!==E._shaderDefs||S+E.mesh.vertexBuffer.getNumVertices()>o?m(E):(l.copy(h),l.add(E.aabb),l.halfExtents.x>r||l.halfExtents.y>r||l.halfExtents.z>r?m(E):(!x||(s=E.stencilFront)&&x.func===s.func&&x.zpass===s.zpass)&&w===Ah(E)&&Sh(y,E.parameters)?n&&c&&c.intersects(E.aabb)&&E.drawOrder!==b?m(E):(h.add(E.aabb),S+=E.mesh.vertexBuffer.getNumVertices(),u[d].push(E)):m(E))}d++,p=f}return u},e.collectBatchedMeshData=function(t,e){for(var i=null,n=0,s=0,r=null,a=0;a=3)if(s===we)for(var A=0;A0&&r.setIndices(S),r.update(4,!1),e&&((p=p.clone()).chunks.transformVS=this.transformVS,p.chunks.skinTexVS=this.skinTexVS,p.chunks.skinConstVS=this.skinConstVS,p.update());var I=new yh(r,p,this.rootNode);I.castShadow=h.origMeshInstances[0].castShadow,I.parameters=h.origMeshInstances[0].parameters,I.layer=h.origMeshInstances[0].layer,I._shaderDefs=h.origMeshInstances[0]._shaderDefs,I.cull=h.origMeshInstances[0].cull;var L=this._batchGroups[i];if(L&&L._ui&&(I.cull=!1),e){for(var D=[],O=0;O0&&this.generate(this._dirtyGroups);for(var t=0;t1&&(h=ce,o=!1));var l=null!=(t=null==(e=r.renderTarget)?void 0:e.depthBuffer)?t:null==(i=r.renderTarget)?void 0:i.colorBuffer;this.shouldReallocate(this.depthRenderTarget,l)&&(this.releaseRenderTarget(this.depthRenderTarget),this.depthRenderTarget=this.allocateRenderTarget(this.depthRenderTarget,r.renderTarget,a,h,o));var c=o?this.depthRenderTarget.depthBuffer:this.depthRenderTarget.colorBuffer;Rh.forEach((function(t){return a.scope.resolve(t).setValue(c)}))},i.execute=function(){var t=this.device;if(t.isWebGL2&&t.renderTarget.samples>1){var e=t.renderTarget.impl._glFrameBuffer,i=this.depthRenderTarget;t.renderTarget=i,t.updateBegin(),this.depthRenderTarget.impl.internalResolve(t,e,i.impl._glFrameBuffer,this.depthRenderTarget,t.gl.DEPTH_BUFFER_BIT)}else t.copyRenderTarget(t.renderTarget,this.depthRenderTarget,!1,!0)},e}(uo),Lh=new vt(254/255,254/255,254/255,254/255),Dh=[],Oh=[[],[],[]],kh=["uSceneDepthMap","uDepthMap"],Fh=function(t){function e(e,i,n){var s;return(s=t.call(this,e)||this).renderer=i,s.camera=n,s}S(e,t);var i=e.prototype;return i.destroy=function(){t.prototype.destroy.call(this),this.releaseRenderTarget(this.renderTarget)},i.update=function(t){this.scene=t},i.shouldReallocate=function(t,e){var i=e.width,n=e.height;return!t||i!==t.width||n!==t.height},i.allocateRenderTarget=function(t,e,i){var n,s,r=new Ls(i,{name:kh[0],format:7,width:null!=(n=null==e?void 0:e.width)?n:this.device.width,height:null!=(s=null==e?void 0:e.height)?s:this.device.height,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1});return t?(t.destroyFrameBuffers(),t._colorBuffer=r,t._colorBuffers=[r]):t=new rn({name:kh[0]+"RT}",colorBuffer:r,depth:!0,stencil:!1}),t},i.releaseRenderTarget=function(t){t&&(t.destroyTextureBuffers(),t.destroy())},i.before=function(){var t,e=this.camera,i=this.device,n=null!=(t=e.renderTarget)?t:i.backBuffer;if(this.shouldReallocate(this.renderTarget,n)){var s;null==(s=this.renderTarget)||s.destroyTextureBuffers();var r=this.allocateRenderTarget(this.renderTarget,e.renderTarget,i);this.renderTarget?this.renderTarget=r:(this.init(r),this.setClearColor(Lh),this.setClearDepth(1))}var a=this.renderTarget.colorBuffer;kh.forEach((function(t){return i.scope.resolve(t).setValue(a)}))},i.execute=function(){for(var t=this.device,e=this.renderer,i=this.camera,n=this.scene,s=this.renderTarget,r=n.layers.layerList,a=n.layers.subLayerEnabled,o=n.layers.subLayerList,h=0;h0,t.blendType=e.blendType,t.screenSpace=n&&0!=(n&Fa),t.skin=n&&0!=(2&n),t.useInstancing=n&&0!=(n&Oa),t.useMorphPosition=n&&0!=(n&Ua),t.useMorphNormal=n&&0!=(n&Na),t.useMorphTextureBased=n&&0!=(n&za),t.hasTangents=n&&0!=(n&Ba),t.nineSlicedMode=e.nineSlicedMode||0,e.useLighting&&i.clusteredLightingEnabled?(t.clusteredLightingEnabled=!0,t.clusteredLightingCookiesEnabled=i.lighting.cookiesEnabled,t.clusteredLightingShadowsEnabled=i.lighting.shadowsEnabled,t.clusteredLightingShadowType=i.lighting.shadowType,t.clusteredLightingAreaLightsEnabled=i.lighting.areaLightsEnabled):(t.clusteredLightingEnabled=!1,t.clusteredLightingCookiesEnabled=!1,t.clusteredLightingShadowsEnabled=!1,t.clusteredLightingAreaLightsEnabled=!1)},t.updateMaterialOptions=function(t,e){t.useAmbientTint=!1,t.separateAmbient=!1,t.customFragmentShader=null,t.pixelSnap=e.pixelSnap,t.shadingModel=e.shadingModel,t.ambientSH=e.ambientSH,t.fastTbn=e.fastTbn,t.twoSidedLighting=e.twoSidedLighting,t.occludeDirect=e.occludeDirect,t.occludeSpecular=e.occludeSpecular,t.occludeSpecularFloat=1!==e.occludeSpecularIntensity,t.useMsdf=!1,t.msdfTextAttribute=!1,t.alphaToCoverage=e.alphaToCoverage,t.opacityFadesSpecular=e.opacityFadesSpecular,t.cubeMapProjection=0,t.conserveEnergy=e.conserveEnergy&&1===e.shadingModel,t.useSpecular=e.hasSpecular,t.useSpecularityFactor=e.hasSpecularityFactor,t.enableGGXSpecular=e.ggxSpecular,t.fresnelModel=e.fresnelModel,t.useRefraction=e.hasRefraction,t.useClearCoat=e.hasClearCoat,t.useSheen=e.hasSheen,t.useIridescence=e.hasIrridescence,t.useMetalness=e.hasMetalness,t.useDynamicRefraction=e.dynamicRefraction,t.vertexColors=!1,t.lightMapEnabled=e.hasLighting,t.dirLightMapEnabled=e.dirLightMap,t.useHeights=e.hasHeights,t.useNormals=e.hasNormals,t.useClearCoatNormals=e.hasClearCoatNormals,t.useAo=e.hasAo,t.diffuseMapEnabled=e.hasDiffuseMap},t.updateEnvOptions=function(t,e,i){t.fog=e.useFog?i.fog:"none",t.gamma=e.useGammaTonemap?i.gammaCorrection:0,t.toneMap=e.useGammaTonemap?i.toneMapping:-1,t.fixSeams=!1,e.useSkybox&&i.envAtlas&&i.skybox?(t.reflectionSource="envAtlasHQ",t.reflectionEncoding=i.envAtlas.encoding,t.reflectionCubemapEncoding=i.skybox.encoding):e.useSkybox&&i.envAtlas?(t.reflectionSource="envAtlas",t.reflectionEncoding=i.envAtlas.encoding):e.useSkybox&&i.skybox?(t.reflectionSource="cubeMap",t.reflectionEncoding=i.skybox.encoding):(t.reflectionSource=null,t.reflectionEncoding=null),e.ambientSH?(t.ambientSource="ambientSH",t.ambientEncoding=null):t.reflectionSource&&i.envAtlas?(t.ambientSource="envAtlas",t.ambientEncoding=i.envAtlas.encoding):(t.ambientSource="constant",t.ambientEncoding=null);var n=!!t.reflectionSource;t.skyboxIntensity=n&&(1!==i.skyboxIntensity||i.physicalUnits),t.useCubeMapRotation=n&&i._skyboxRotationShaderInclude},t.updateLightingOptions=function(e,i,n,s){if(e.lightMapWithoutAmbient=!1,i.useLighting){var r=[],a=n?n>>16:1;e.lightMaskDynamic=!!(1&a),e.lightMapWithoutAmbient=!1,s&&(t.collectLights(0,s[0],r,a),t.collectLights(1,s[1],r,a),t.collectLights(2,s[2],r,a)),e.lights=r}else e.lights=[];0!==e.lights.length&&0==(1&n)||(e.noShadow=!0)},t.collectLights=function(t,e,i,n){for(var s=0;s>16&32768,n=e>>12&2047,s=e>>23&255;return s<103?i:s>142?(i|=31744,i|=(255===s?0:1)&&8388607&e):s<113?i|=((n|=2048)>>114-s)+(n>>113-s&1):(i|=s-112<<10|n>>1,i+=1&n)},t.float2Bytes=function(t,e,i,n){var s=255*t%1;if(e[i+0]=Math.round(255*(t%1-Kh*s)),n>1){var r=65025*t%1;if(e[i+1]=Math.round(255*(s-Kh*r)),n>2){var a=16581375*t%1;e[i+2]=Math.round(255*(r-Kh*a)),n>3&&(e[i+3]=Math.round(255*a))}}},t.float2BytesRange=function(e,i,n,s,r,a){e=_t.clamp((e-s)/(r-s),0,1),t.float2Bytes(e,i,n,a)},t.float2MantissaExponent=function(e,i,n,s){var r=Math.floor(Math.log2(Math.abs(e)))+1;e/=Math.pow(2,r),t.float2BytesRange(e,i,n,-1,1,s-1),i[n+s-1]=Math.round(r+127)},t}(),Jh=new Ft,tl=new Ft,el=new Ft,il=function(){function t(){}return t.create=function(e,i,n){var s=new Gh;switch(s.node=new hh(e),s.aspectRatio=1,s.aspectRatioMode=1,s._scissorRectClear=!0,i){case 1:s.node.setRotation(t.pointLightRotations[n]),s.fov=90,s.projection=0;break;case 2:s.projection=0;break;case 0:s.projection=1}return s},t.evalSpotCookieMatrix=function(e){var i=t._spotCookieCamera;i||(i=t.create("SpotCookieCamera",2),t._spotCookieCamera=i),i.fov=2*e._outerConeAngle;var n=i._node;n.setPosition(e._node.getPosition()),n.setRotation(e._node.getRotation()),n.rotateLocal(-90,0,0),Jh.setTRS(n.getPosition(),n.getRotation(),wt.ONE).invert(),tl.mul2(i.projectionMatrix,Jh);var s=e.cookieMatrix,r=e.atlasViewport;return el.setViewport(r.x,r.y,r.z,r.w),s.mul2(el,tl),s},t}();il.pointLightRotations=[(new Bt).setFromEulerAngles(0,90,180),(new Bt).setFromEulerAngles(0,-90,180),(new Bt).setFromEulerAngles(90,0,0),(new Bt).setFromEulerAngles(-90,0,0),(new Bt).setFromEulerAngles(0,180,180),(new Bt).setFromEulerAngles(0,0,180)],il._spotCookieCamera=null;var nl=new wt,sl=new Float32Array(6),rl=new wt(-.5,0,0),al=new wt(0,0,.5),ol={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},hl={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},ll=function(){function t(e){this.device=e,this.cookiesEnabled=!1,this.shadowsEnabled=!1,this.areaLightsEnabled=!1,this.maxLights=255;var i=ol.COUNT_ALWAYS,n=0;t.lightTextureFormat===t.FORMAT_FLOAT?n=hl.COUNT:i=ol.COUNT,this.lights8=new Uint8ClampedArray(4*i*this.maxLights),this.lightsTexture8=t.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=t.createTexture(this.device,n,this.maxLights,le,"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 wt,this.boundsDelta=new wt}t.initShaderDefines=function(){var e=t.lightTextureFormat===t.FORMAT_FLOAT?"FLOAT":"8BIT";t.shaderDefines="\n \n#define CLUSTER_TEXTURE_"+e+"\n "+t.buildShaderDefines(ol,"CLUSTER_TEXTURE_8_")+"\n "+t.buildShaderDefines(hl,"CLUSTER_TEXTURE_F_")+"\n "},t.buildShaderDefines=function(e,i){var n="",s=t.useTexelFetch?"":".5";return Object.keys(e).forEach((function(t){n+="\n#define "+i+t+" "+e[t]+s})),n},t.init=function(e){t.lightTextureFormat=e.extTextureFloat&&e.maxTextures>8?t.FORMAT_FLOAT:t.FORMAT_8BIT,t.useTexelFetch=e.supportsTextureFetch,t.initShaderDefines()},t.createTexture=function(t,e,i,n,s){return new Ls(t,{name:s,width:e,height:i,mipmaps:!1,format:n,addressU:1,addressV:1,type:ei,magFilter:0,minFilter:0,anisotropy:1})};var e=t.prototype;return e.destroy=function(){this.lightsTexture8&&(this.lightsTexture8.destroy(),this.lightsTexture8=null),this.lightsTextureFloat&&(this.lightsTextureFloat.destroy(),this.lightsTextureFloat=null)},e.setCompressionRanges=function(t,e){this.invMaxColorValue=1/e,this.invMaxAttenuation=1/t},e.setBounds=function(t,e){this.boundsMin.copy(t),this.boundsDelta.copy(e)},e.uploadTextures=function(){this.lightsTextureFloat&&(this.lightsTextureFloat.lock().set(this.lightsFloat),this.lightsTextureFloat.unlock()),this.lightsTexture8.lock().set(this.lights8),this.lightsTexture8.unlock()},e.updateUniforms=function(){this._lightsTexture8Id.setValue(this.lightsTexture8),t.lightTextureFormat===t.FORMAT_FLOAT&&this._lightsTextureFloatId.setValue(this.lightsTextureFloat),this._lightsTextureInvSizeId.setValue(this._lightsTextureInvSizeData)},e.getSpotDirection=function(t,e){e._node.getWorldTransform().getY(t).mulScalar(-1),t.normalize()},e.getLightAreaSizes=function(t){var e=t._node.getWorldTransform();return e.transformVector(rl,nl),sl[0]=nl.x,sl[1]=nl.y,sl[2]=nl.z,e.transformVector(al,nl),sl[3]=nl.x,sl[4]=nl.y,sl[5]=nl.z,sl},e.addLightDataFlags=function(t,e,i,n,s,r){t[e+0]=n?255:0,t[e+1]=64*i._shape,t[e+2]=255*i._falloffMode,t[e+3]=s?255*r:0},e.addLightDataColor=function(t,e,i,n,s){var r=this.invMaxColorValue,a=n?i._linearFinalColor:i._finalColor;$h.float2Bytes(a[0]*r,t,e+0,2),$h.float2Bytes(a[1]*r,t,e+2,2),$h.float2Bytes(a[2]*r,t,e+4,2),t[e+6]=s?255:0;var o=!!(1&i.mask),h=!!(2&i.mask);t[e+7]=o&&h?127:h?255:0},e.addLightDataSpotAngles=function(t,e,i){$h.float2Bytes(.499999*i._innerConeAngleCos+.5,t,e+0,2),$h.float2Bytes(.499999*i._outerConeAngleCos+.5,t,e+2,2)},e.addLightDataShadowBias=function(t,e,i){var n=i.getRenderData(null,0),s=i._getUniformBiasValues(n);$h.float2BytesRange(s.bias,t,e,-1,20,2),$h.float2Bytes(s.normalBias,t,e+2,2)},e.addLightDataPositionRange=function(t,e,i,n){var s=nl.sub2(n,this.boundsMin).div(this.boundsDelta);$h.float2Bytes(s.x,t,e+0,4),$h.float2Bytes(s.y,t,e+4,4),$h.float2Bytes(s.z,t,e+8,4),$h.float2Bytes(i.attenuationEnd*this.invMaxAttenuation,t,e+12,4)},e.addLightDataSpotDirection=function(t,e,i){this.getSpotDirection(nl,i),$h.float2Bytes(.499999*nl.x+.5,t,e+0,4),$h.float2Bytes(.499999*nl.y+.5,t,e+4,4),$h.float2Bytes(.499999*nl.z+.5,t,e+8,4)},e.addLightDataLightProjMatrix=function(t,e,i){for(var n=i.data,s=0;s<12;s++)$h.float2BytesRange(n[s],t,e+4*s,-2,2,4);for(var r=12;r<16;r++)$h.float2MantissaExponent(n[r],t,e+4*r,4)},e.addLightDataCookies=function(t,e,i){var n="rgb"===i._cookieChannel;if(t[e+0]=Math.floor(255*i.cookieIntensity),t[e+1]=n?255:0,!n){var s=i._cookieChannel;t[e+4]="rrr"===s?255:0,t[e+5]="ggg"===s?255:0,t[e+6]="bbb"===s?255:0,t[e+7]="aaa"===s?255:0}},e.addLightAtlasViewport=function(t,e,i){$h.float2Bytes(i.x,t,e+0,2),$h.float2Bytes(i.y,t,e+2,2),$h.float2Bytes(i.z/3,t,e+4,2)},e.addLightAreaSizes=function(t,e,i){for(var n=this.getLightAreaSizes(i),s=0;s<6;s++)$h.float2MantissaExponent(n[s],t,e+4*s,4)},e.addLightData=function(e,i,n){var s=2===e._type,r=e.atlasViewportAllocated,a=this.cookiesEnabled&&!!e._cookie&&r,o=this.areaLightsEnabled&&0!==e.shape,h=this.shadowsEnabled&&e.castShadows&&r,l=e._node.getPosition(),c=null,u=null;s?h?c=e.getRenderData(null,0).shadowMatrix:a&&(c=il.evalSpotCookieMatrix(e)):(h||a)&&(u=e.atlasViewport);var d=this.lights8,f=i*this.lightsTexture8.width*4;if(this.addLightDataFlags(d,f+4*ol.FLAGS,e,s,h,e.shadowIntensity),this.addLightDataColor(d,f+4*ol.COLOR_A,e,n,a),s&&this.addLightDataSpotAngles(d,f+4*ol.SPOT_ANGLES,e),e.castShadows&&this.addLightDataShadowBias(d,f+4*ol.SHADOW_BIAS,e),a&&this.addLightDataCookies(d,f+4*ol.COOKIE_A,e),t.lightTextureFormat===t.FORMAT_FLOAT){var p=this.lightsFloat,m=i*this.lightsTextureFloat.width*4;if(p[m+4*hl.POSITION_RANGE+0]=l.x,p[m+4*hl.POSITION_RANGE+1]=l.y,p[m+4*hl.POSITION_RANGE+2]=l.z,p[m+4*hl.POSITION_RANGE+3]=e.attenuationEnd,s&&(this.getSpotDirection(nl,e),p[m+4*hl.SPOT_DIRECTION+0]=nl.x,p[m+4*hl.SPOT_DIRECTION+1]=nl.y,p[m+4*hl.SPOT_DIRECTION+2]=nl.z),c)for(var _=c.data,v=0;v<16;v++)p[m+4*hl.PROJ_MAT_0+v]=_[v];if(u&&(p[m+4*hl.ATLAS_VIEWPORT+0]=u.x,p[m+4*hl.ATLAS_VIEWPORT+1]=u.y,p[m+4*hl.ATLAS_VIEWPORT+2]=u.z/3),o){var g=this.getLightAreaSizes(e);p[m+4*hl.AREA_DATA_WIDTH+0]=g[0],p[m+4*hl.AREA_DATA_WIDTH+1]=g[1],p[m+4*hl.AREA_DATA_WIDTH+2]=g[2],p[m+4*hl.AREA_DATA_HEIGHT+0]=g[3],p[m+4*hl.AREA_DATA_HEIGHT+1]=g[4],p[m+4*hl.AREA_DATA_HEIGHT+2]=g[5]}}else this.addLightDataPositionRange(d,f+4*ol.POSITION_X,e,l),s&&this.addLightDataSpotDirection(d,f+4*ol.SPOT_DIRECTION_X,e),c&&this.addLightDataLightProjMatrix(d,f+4*ol.PROJ_MAT_00,c),u&&this.addLightAtlasViewport(d,f+4*ol.ATLAS_VIEWPORT_A,u),o&&this.addLightAreaSizes(d,f+4*ol.AREA_DATA_WIDTH_X,e)},t}();Ch=ll,ll.FORMAT_FLOAT=0,ll.FORMAT_8BIT=1,ll.lightTextureFormat=Ch.FORMAT_8BIT,ll.useTexelFetch=!1,ll.shaderDefines="";var cl={vertex_normal:Te,vertex_tangent:Ae,vertex_texCoord0:Re,vertex_texCoord1:Ie,vertex_color:Me,vertex_boneWeights:Ce,vertex_boneIndices:Ee},ul={vVertexColor:"vec4",vPositionW:"vec3",vNormalV:"vec3",vNormalW:"vec3",vTangentW:"vec3",vBinormalW:"vec3",vObjectSpaceUpW:"vec3",vUv0:"vec2",vUv1:"vec2"},dl=function(){function t(t,e){if(this.device=t,this.options=e,this.attributes={vertex_position:we},e.userAttributes)for(var i=0,n=Object.entries(e.userAttributes);i=0&&(this.attributes[c]=cl[c]);this.chunks[h]=l}}else this.chunks=_o;this.shaderPassInfo=Do.get(this.device).getByIndex(e.pass),this.shadowPass=this.shaderPassInfo.isShadow,this.lighting=e.lights.length>0||e.dirLightMapEnabled||e.clusteredLightingEnabled,this.reflections=!!e.reflectionSource,this.needsNormal=this.lighting||this.reflections||e.useSpecular||e.ambientSH||e.useHeights||e.enableGGXSpecular||e.clusteredLightingEnabled&&!this.shadowPass||e.useClearCoatNormals,this.needsNormal=this.needsNormal&&!this.shadowPass,this.needsSceneColor=e.useDynamicRefraction,this.needsScreenSize=e.useDynamicRefraction,this.needsTransforms=e.useDynamicRefraction,this.varyings="",this.varyingDefines="",this.vshader=null,this.frontendDecl=null,this.frontendCode=null,this.frontendFunc=null,this.lightingUv=null,this.defines=[],this.fshader=null}var e=t.prototype;return e._vsAddBaseCode=function(t,e,i){return t+=e.baseVS,1!==i.nineSlicedMode&&2!==i.nineSlicedMode||(t+=e.baseNineSlicedVS),t},e._vsAddTransformCode=function(t,e,i,n){return t+=this.chunks.transformVS},e._setMapTransform=function(t,e,i,n){var s=i+100*n;if(!t[3][s]){var r="texture_"+e+"MapTransform";t[0]+="uniform vec3 "+r+"0;\n",t[0]+="uniform vec3 "+r+"1;\n",t[1]+="varying vec2 vUV"+n+"_"+i+";\n",t[2]+=" vUV"+n+"_"+i+" = vec2(dot(vec3(uv"+n+", 1), "+r+"0), dot(vec3(uv"+n+", 1), "+r+"1));\n",t[3][s]=!0}return t},e._fsGetBaseCode=function(){var t=this.options,e=this.chunks,i=this.chunks.basePS;return 1===t.nineSlicedMode?i+=e.baseNineSlicedPS:2===t.nineSlicedMode&&(i+=e.baseNineSlicedTiledPS),i},e._fsGetStartCode=function(t,e,i,n){var s=i.startPS;return 1===n.nineSlicedMode?s+=i.startNineSlicedPS:2===n.nineSlicedMode&&(s+=i.startNineSlicedTiledPS),s},e._getLightSourceShapeString=function(t){switch(t){case 1:return"Rect";case 2:return"Disk";case 3:return"Sphere";default:return""}},e.generateVertexShader=function(t,e,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=Qe,this.attributes.instance_line2=$e,this.attributes.instance_line3=Je,this.attributes.instance_line4=ti,o+=a.instancingVS),this.needsNormal&&(this.attributes.vertex_normal=Te,h+=" vNormalW = getNormal();\n","sphereMap"===r.reflectionSource&&s.fragmentUniformsCount<=16&&(o+=a.viewNormalVS,h+=" vNormalV = getViewNormal();\n"),r.hasTangents&&(r.useHeights||r.useNormals||r.enableGGXSpecular)?(this.attributes.vertex_tangent=Ae,o+=a.tangentBinormalVS,h+=" vTangentW = getTangent();\n",h+=" vBinormalW = getBinormal();\n"):!r.enableGGXSpecular&&s.extStandardDerivatives||(h+=" vObjectSpaceUpW = normalize(dNormalMatrix * vec3(0, 1, 0));\n"));for(var l=0;l<2;l++)t[l]&&(this.attributes["vertex_texCoord"+l]="TEXCOORD"+l,o+=a["uv"+l+"VS"],h+=" vec2 uv"+l+" = getUv"+l+"();\n"),e[l]&&(h+=" vUv"+l+" = uv"+l+";\n");var c=[o,this.varyings,h,[]];if(i.forEach((function(t){n._setMapTransform(c,t.name,t.id,t.uv)})),o=c[0],this.varyings=c[1],h=c[2],r.vertexColors&&(this.attributes.vertex_color=Me,h+=" vVertexColor = vertex_color;\n"),r.useMsdf&&r.msdfTextAttribute&&(this.attributes.vertex_outlineParameters=qe,this.attributes.vertex_shadowParameters=Ye,h+=" unpackMsdfParams();\n",o+=a.msdfVS),r.useMorphPosition||r.useMorphNormal)if(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=ti;var u=s.isWebGPU?"uint":"float";o+="attribute "+u+" morph_vertex_id;\n"}else o+="#define MORPHING\n",r.useMorphPosition?(this.attributes.morph_pos0=qe,this.attributes.morph_pos1=Ye,this.attributes.morph_pos2=Ke,this.attributes.morph_pos3=Ze,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=qe,this.attributes.morph_nrm1=Ye,this.attributes.morph_nrm2=Ke,this.attributes.morph_nrm3=Ze,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=Qe,this.attributes.morph_nrm5=$e,this.attributes.morph_nrm6=Je,this.attributes.morph_nrm7=ti,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=Qe,this.attributes.morph_pos5=$e,this.attributes.morph_pos6=Je,this.attributes.morph_pos7=ti,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=Ce,this.attributes.vertex_boneIndices=Ee,o+=xo.skinCode(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(ul).forEach((function(t){o.indexOf(t)>=0&&(n.varyings+="varying "+ul[t]+" "+t+";\n",n.varyingDefines+="#define VARYING_"+t.toUpperCase()+"\n")}));var d=this.shaderPassInfo.shaderDefines;this.vshader=d+this.varyings+o},e._fsGetBeginCode=function(){for(var t=this.shaderPassInfo.shaderDefines,e=0;e0&&this.defines.push("LIT_SPECULAR_FRESNEL"),e.conserveEnergy&&this.defines.push("LIT_CONSERVE_ENERGY"),e.useSheen&&this.defines.push("LIT_SHEEN"),e.useIridescence&&this.defines.push("LIT_IRIDESCENCE"));var o=[],h=0,l=!1,c=!1,u=!1,d=e.lights.some((function(t){return t._shape&&0!==t._shape}));e.clusteredLightingEnabled&&e.clusteredLightingAreaLightsEnabled&&(d=!0);var f="highp";7===t.areaLightLutFormat&&(n.append("#define AREA_R8_G8_B8_A8_LUTS"),f="lowp"),(d||e.clusteredLightingEnabled)&&(n.append("#define AREA_LIGHTS"),n.append("uniform "+f+" sampler2D areaLightsLutTex1;"),n.append("uniform "+f+" sampler2D areaLightsLutTex2;"));for(var p=0;p0?i.cubeMapProjectBoxPS:i.cubeMapProjectNonePS),s.append(e.skyboxIntensity?i.envMultiplyPS:i.envConstPS)),(this.lighting&&e.useSpecular||this.reflections)&&(e.useMetalness&&s.append(i.metalnessModulatePS),2===e.fresnelModel&&s.append(i.fresnelSchlickPS),e.useIridescence&&s.append(i.iridescenceDiffractionPS)),e.useAo)switch(s.append(i.aoDiffuseOccPS),e.occludeSpecular){case 1:s.append(e.occludeSpecularFloat?i.aoSpecOccSimplePS:i.aoSpecOccConstSimplePS);break;case 2:s.append(e.occludeSpecularFloat?i.aoSpecOccPS:i.aoSpecOccConstPS)}if("envAtlasHQ"===e.reflectionSource)s.append(e.fixSeams?i.fixCubemapSeamsStretchPS:i.fixCubemapSeamsNonePS),s.append(i.envAtlasPS),s.append(i.reflectionEnvHQPS.replace(/\$DECODE_CUBEMAP/g,Yh.decodeFunc(e.reflectionCubemapEncoding)).replace(/\$DECODE/g,Yh.decodeFunc(e.reflectionEncoding)));else if("envAtlas"===e.reflectionSource)s.append(i.envAtlasPS),s.append(i.reflectionEnvPS.replace(/\$DECODE/g,Yh.decodeFunc(e.reflectionEncoding)));else if("cubeMap"===e.reflectionSource)s.append(e.fixSeams?i.fixCubemapSeamsStretchPS:i.fixCubemapSeamsNonePS),s.append(i.reflectionCubePS.replace(/\$DECODE/g,Yh.decodeFunc(e.reflectionEncoding)));else if("sphereMap"===e.reflectionSource){var y=t.fragmentUniformsCount>16?i.reflectionSpherePS:i.reflectionSphereLowPS;s.append(y.replace(/\$DECODE/g,Yh.decodeFunc(e.reflectionEncoding)))}this.reflections&&(e.useClearCoat&&s.append(i.reflectionCCPS),e.useSheen&&s.append(i.reflectionSheenPS)),e.useRefraction&&(e.useDynamicRefraction?s.append(i.refractionDynamicPS):this.reflections&&s.append(i.refractionCubePS)),e.useSheen&&s.append(i.lightSheenPS),e.clusteredLightingEnabled&&(s.append(i.clusteredLightUtilsPS),e.clusteredLightingCookiesEnabled&&s.append(i.clusteredLightCookiesPS),e.clusteredLightingShadowsEnabled&&!e.noShadow&&(o[0]=!0,o[4]=!0,o[6]=!0)),(h>0||e.clusteredLightingEnabled)&&(l&&s.append(i.shadowCascadesPS),(o[5]||o[0])&&s.append(i.shadowStandardPS),o[4]&&!t.isWebGL1&&s.append(i.shadowStandardGL2PS),c&&(s.append(i.shadowVSM_commonPS),o[1]&&s.append(i.shadowVSM8PS),o[2]&&s.append(t.extTextureHalfFloatLinear?i.shadowEVSMPS.replace(/\$/g,"16"):i.shadowEVSMnPS.replace(/\$/g,"16")),o[3]&&s.append(t.extTextureFloatLinear?i.shadowEVSMPS.replace(/\$/g,"32"):i.shadowEVSMnPS.replace(/\$/g,"32"))),u&&(s.append(i.linearizeDepthPS),s.append(i.shadowPCSSPS)),t.isWebGL2||t.isWebGPU||t.extStandardDerivatives||s.append(i.biasConstPS)),e.enableGGXSpecular&&s.append("uniform float material_anisotropy;"),this.lighting&&(s.append(i.lightDiffuseLambertPS),(d||e.clusteredLightingAreaLightsEnabled)&&s.append(i.ltcPS));var x=!1;e.useSpecular&&(this.lighting&&s.append(0===e.shadingModel?i.lightSpecularPhongPS:e.enableGGXSpecular?i.lightSpecularAnisoGGXPS:i.lightSpecularBlinnPS),e.fresnelModel||this.reflections||e.diffuseMapEnabled||(n.append("uniform vec3 material_ambient;"),n.append("#define LIT_OLD_AMBIENT"),x=!0)),s.append(i.combinePS),e.lightMapEnabled&&s.append(e.useSpecular&&e.dirLightMapEnabled?i.lightmapDirAddPS:i.lightmapAddPS);var S=!e.lightMapEnabled||e.lightMapWithoutAmbient;S&&("ambientSH"===e.ambientSource?s.append(i.ambientSHPS):"envAtlas"===e.ambientSource?("envAtlas"!==e.reflectionSource&&"envAtlasHQ"!==e.reflectionSource&&s.append(i.envAtlasPS),s.append(i.ambientEnvPS.replace(/\$DECODE/g,Yh.decodeFunc(e.ambientEncoding)))):s.append(i.ambientConstantPS)),e.useAmbientTint&&!x&&n.append("uniform vec3 material_ambient;"),e.useMsdf&&(e.msdfTextAttribute||n.append("#define UNIFORM_TEXT_PARAMETERS"),s.append(i.msdfPS)),this.needsNormal&&(s.append(i.viewDirPS),e.useSpecular&&s.append(e.enableGGXSpecular?i.reflDirAnisoPS:i.reflDirPS));var b,w=!1,T=!1,A=!1,C=!1,E=!1;if(e.clusteredLightingEnabled&&this.lighting&&(C=!0,w=!0,T=!0,E=!0,s.append(i.floatUnpackingPS),e.lightMaskDynamic&&n.append("#define CLUSTER_MESH_DYNAMIC_LIGHTS"),e.clusteredLightingCookiesEnabled&&n.append("#define CLUSTER_COOKIES"),e.clusteredLightingShadowsEnabled&&!e.noShadow&&(n.append("#define CLUSTER_SHADOWS"),n.append("#define CLUSTER_SHADOW_TYPE_"+La[e.clusteredLightingShadowType])),e.clusteredLightingAreaLightsEnabled&&n.append("#define CLUSTER_AREALIGHTS"),n.append(ll.shaderDefines),e.clusteredLightingShadowsEnabled&&!e.noShadow&&s.append(i.clusteredLightShadowsPS),s.append(i.clusteredLightPS)),e.twoSidedLighting&&n.append("uniform float twoSidedLightingNegScaleFactor;"),a.append(this._fsGetStartCode(a,t,i,e)),this.needsNormal&&(e.twoSidedLighting?a.append(" dVertexNormalW = normalize(gl_FrontFacing ? vNormalW * twoSidedLightingNegScaleFactor : -vNormalW * twoSidedLightingNegScaleFactor);"):a.append(" dVertexNormalW = normalize(vNormalW);"),(e.useHeights||e.useNormals)&&e.hasTangents&&(e.twoSidedLighting?(a.append(" dTangentW = gl_FrontFacing ? vTangentW * twoSidedLightingNegScaleFactor : -vTangentW * twoSidedLightingNegScaleFactor;"),a.append(" dBinormalW = gl_FrontFacing ? vBinormalW * twoSidedLightingNegScaleFactor : -vBinormalW * twoSidedLightingNegScaleFactor;")):(a.append(" dTangentW = vTangentW;"),a.append(" dBinormalW = vBinormalW;"))),a.append(" getViewDir();"),g&&a.append(" getTBN(dTangentW, dBinormalW, dVertexNormalW);")),a.append(this.frontendFunc),this.needsNormal&&(e.useSpecular&&r.append(" getReflDir(litArgs_worldNormal, dViewDirW, litArgs_gloss, dTBN);"),e.useClearCoat&&r.append(" ccReflDirW = normalize(-reflect(dViewDirW, litArgs_clearcoat_worldNormal));")),(this.lighting&&e.useSpecular||this.reflections)&&(e.useMetalness&&(r.append(" float f0 = 1.0 / litArgs_ior; f0 = (f0 - 1.0) / (f0 + 1.0); f0 *= f0;"),r.append(" litArgs_specularity = getSpecularModulate(litArgs_specularity, litArgs_albedo, litArgs_metalness, f0);"),r.append(" litArgs_albedo = getAlbedoModulate(litArgs_albedo, litArgs_metalness);")),e.useIridescence&&r.append(" vec3 iridescenceFresnel = getIridescence(saturate(dot(dViewDirW, litArgs_worldNormal)), litArgs_specularity, litArgs_iridescence_thickness);")),S&&(r.append(" addAmbient(litArgs_worldNormal);"),e.conserveEnergy&&e.useSpecular&&r.append(" dDiffuseLight = dDiffuseLight * (1.0 - litArgs_specularity);"),e.separateAmbient&&r.append("\n vec3 dAmbientLight = dDiffuseLight;\n dDiffuseLight = vec3(0);\n ")),e.useAmbientTint&&!x&&r.append(" dDiffuseLight *= material_ambient;"),e.useAo&&!e.occludeDirect&&r.append(" occludeDiffuse(litArgs_ao);"),e.lightMapEnabled&&r.append(" addLightMap(\n litArgs_lightmap, \n litArgs_lightmapDir, \n litArgs_worldNormal, \n dViewDirW, \n dReflDirW, \n litArgs_gloss, \n litArgs_specularity, \n dVertexNormalW,\n dTBN\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n litArgs_iridescence_intensity\n #endif\n );"),this.lighting||this.reflections){this.reflections&&(e.useClearCoat&&(r.append(" addReflectionCC(ccReflDirW, litArgs_clearcoat_gloss);"),e.fresnelModel>0?(r.append(" ccFresnel = getFresnelCC(dot(dViewDirW, litArgs_clearcoat_worldNormal));"),r.append(" ccReflection.rgb *= ccFresnel;")):r.append(" ccFresnel = 0.0;")),e.useSpecularityFactor&&r.append(" ccReflection.rgb *= litArgs_specularityFactor;"),e.useSheen&&r.append(" addReflectionSheen(litArgs_worldNormal, dViewDirW, litArgs_sheen_gloss);"),r.append(" addReflection(dReflDirW, litArgs_gloss);"),e.fresnelModel>0?r.append(" dReflection.rgb *= \n getFresnel(\n dot(dViewDirW, litArgs_worldNormal), \n litArgs_gloss, \n litArgs_specularity\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n litArgs_iridescence_intensity\n #endif\n );"):r.append(" dReflection.rgb *= litArgs_specularity;"),e.useSpecularityFactor&&r.append(" dReflection.rgb *= litArgs_specularityFactor;")),d&&(r.append(" dSpecularLight *= litArgs_specularity;"),e.useSpecular&&r.append(" calcLTCLightValues(litArgs_gloss, litArgs_worldNormal, dViewDirW, litArgs_specularity, litArgs_clearcoat_gloss, litArgs_clearcoat_worldNormal, litArgs_clearcoat_specularity);"));for(var M=0;M 0.00001) {"),2===R&&(b&&!P._cookieFalloff||(r.append(" dAtten *= getSpotEffect(light"+M+"_direction, light"+M+"_innerConeAngle, light"+M+"_outerConeAngle, dLightDirNormW);"),C=!0))),0!==I?0===R?r.append(" dAttenD = getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirW, dLightDirNormW);"):r.append(" dAttenD = get"+L+"LightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirW, dLightDirNormW) * 16.0;"):r.append(" dAtten *= getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirW, dLightDirNormW);"),P.castShadows&&!e.noShadow){var D=6===P._shadowType,O=1===P._shadowType||2===P._shadowType||3===P._shadowType,k=5===P._shadowType||0===P._shadowType||4===P._shadowType,F=null,B=void 0;switch(P._shadowType){case 1:F="VSM8",B="0.0";break;case 2:F="VSM16",B="5.54";break;case 3:F="VSM32",B=t.textureFloatHighPrecision?"15.0":"5.54";break;case 5:F="PCF1x1";break;case 4:F="PCF5x5";break;case 6:F="PCSS";break;default:F="PCF3x3"}if(null!==F){P._normalOffsetBias&&!P._isVsm&&s.append("#define SHADOW_SAMPLE_NORMAL_OFFSET"),0===R&&s.append("#define SHADOW_SAMPLE_ORTHO"),((k||D)&&t.isWebGL2||t.isWebGPU||t.extStandardDerivatives)&&s.append("#define SHADOW_SAMPLE_SOURCE_ZBUFFER"),1===R&&s.append("#define SHADOW_SAMPLE_POINT");var U=i.shadowSampleCoordPS;s.append(U.replace("$LIGHT",M)),s.append("#undef SHADOW_SAMPLE_NORMAL_OFFSET"),s.append("#undef SHADOW_SAMPLE_ORTHO"),s.append("#undef SHADOW_SAMPLE_SOURCE_ZBUFFER"),s.append("#undef SHADOW_SAMPLE_POINT");var N="light"+M+"_shadowMatrix";0===R&&P.numCascades>1&&(r.append(" getShadowCascadeMatrix(light"+M+"_shadowMatrixPalette, light"+M+"_shadowCascadeDistances, light"+M+"_shadowCascadeCount);"),N="cascadeShadowMat"),r.append(" dShadowCoord = getShadowSampleCoord"+M+"("+N+", light"+M+"_shadowParams, vPositionW, dLightPosW, dLightDirW, dLightDirNormW, dVertexNormalW);"),0===R&&r.append(" fadeShadow(light"+M+"_shadowCascadeDistances);");var z="SHADOWMAP_PASS(light"+M+"_shadowMap), dShadowCoord, light"+M+"_shadowParams";if(O)z=z+", "+B+", dLightDirW";else if(D){var V="vec2(light"+M+"_shadowSearchArea)";0!==I&&(V="vec2(length(light"+M+"_halfWidth), length(light"+M+"_halfHeight)) * light"+M+"_shadowSearchArea"),z=z+", light"+M+"_cameraParams, "+V+", dLightDirW"}1===R?(F="Point"+F,D||(z+=", dLightDirW")):2===R&&(F="Spot"+F),r.append(" float shadow"+M+" = getShadow"+F+"("+z+");"),r.append(" dAtten *= mix(1.0, shadow"+M+", light"+M+"_shadowIntensity);")}}if(0!==I?e.conserveEnergy&&e.useSpecular?r.append(" dDiffuseLight += ((dAttenD * dAtten) * light"+M+"_color"+(b?" * dAtten3":"")+") * (1.0 - dLTCSpecFres);"):r.append(" dDiffuseLight += (dAttenD * dAtten) * light"+M+"_color"+(b?" * dAtten3":"")+";"):d&&e.conserveEnergy&&e.useSpecular?r.append(" dDiffuseLight += (dAtten * light"+M+"_color"+(b?" * dAtten3":"")+") * (1.0 - litArgs_specularity);"):r.append(" dDiffuseLight += dAtten * light"+M+"_color"+(b?" * dAtten3":"")+";"),e.useSpecular&&r.append(" dHalfDirW = normalize(-dLightDirNormW + dViewDirW);"),P.affectSpecularity)if(0!==I)e.useClearCoat&&r.append(" ccSpecularLight += ccLTCSpecFres * get"+L+"LightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * light"+M+"_color"+(b?" * dAtten3":"")+";"),e.useSpecular&&r.append(" dSpecularLight += dLTCSpecFres * get"+L+"LightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * light"+M+"_color"+(b?" * dAtten3":"")+";");else{var G=!1;0===R&&e.fresnelModel>0&&(G=!0),e.useClearCoat&&r.append(" ccSpecularLight += getLightSpecular(dHalfDirW, ccReflDirW, litArgs_clearcoat_worldNormal, dViewDirW, dLightDirNormW, litArgs_clearcoat_gloss, dTBN) * dAtten * light"+M+"_color"+(b?" * dAtten3":"")+(G?" * getFresnelCC(dot(dViewDirW, dHalfDirW));":";")),e.useSheen&&r.append(" sSpecularLight += getLightSpecularSheen(dHalfDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_sheen_gloss) * dAtten * light"+M+"_color"+(b?" * dAtten3;":";")),e.useSpecular&&r.append(" dSpecularLight += getLightSpecular(dHalfDirW, dReflDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_gloss, dTBN) * dAtten * light"+M+"_color"+(b?" * dAtten3":"")+(G?" \n * getFresnel(\n dot(dViewDirW, dHalfDirW), \n litArgs_gloss, \n litArgs_specularity\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel, \n litArgs_iridescence_intensity\n #endif\n );":"* litArgs_specularity;"))}0!==R&&r.append(" }")}}e.clusteredLightingEnabled&&this.lighting&&(T=!0,A=!0,w=!0,r.append(" addClusteredLights(\n litArgs_worldNormal, \n dViewDirW, \n dReflDirW,\n #if defined(LIT_CLEARCOAT)\n ccReflDirW,\n #endif\n litArgs_gloss, \n litArgs_specularity, \n dVertexNormalW, \n dTBN, \n #if defined(LIT_IRIDESCENCE)\n iridescenceFresnel,\n #endif\n litArgs_clearcoat_worldNormal, \n litArgs_clearcoat_gloss,\n litArgs_sheen_gloss,\n litArgs_iridescence_intensity\n );")),d&&(e.useClearCoat&&r.append(" litArgs_clearcoat_specularity = 1.0;"),e.useSpecular&&r.append(" litArgs_specularity = vec3(1);")),e.useRefraction&&r.append(" addRefraction(\n litArgs_worldNormal, \n dViewDirW, \n litArgs_thickness, \n litArgs_gloss, \n litArgs_specularity, \n litArgs_albedo, \n litArgs_transmission,\n litArgs_ior\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel, \n litArgs_iridescence_intensity\n #endif\n );")}e.useAo&&(e.occludeDirect&&r.append(" occludeDiffuse(litArgs_ao);"),1!==e.occludeSpecular&&2!==e.occludeSpecular||r.append(" occludeSpecular(litArgs_gloss, litArgs_ao, litArgs_worldNormal, dViewDirW);")),e.useSpecularityFactor&&r.append(" dSpecularLight *= litArgs_specularityFactor;"),!1===e.opacityFadesSpecular&&(2!==e.blendType&&4!==e.blendType||(r.append("float specLum = dot((dSpecularLight + dReflection.rgb * dReflection.a), vec3( 0.2126, 0.7152, 0.0722 ));"),r.append("#ifdef LIT_CLEARCOAT\n specLum += dot(ccSpecularLight * litArgs_clearcoat_specularity + ccReflection.rgb * litArgs_clearcoat_specularity, vec3( 0.2126, 0.7152, 0.0722 ));\n#endif"),r.append("litArgs_opacity = clamp(litArgs_opacity + gammaCorrectInput(specLum), 0.0, 1.0);")),r.append("litArgs_opacity *= material_alphaFade;")),r.append(i.endPS),2===e.blendType||6===e.blendType||e.alphaToCoverage?r.append(i.outputAlphaPS):4===e.blendType?r.append(i.outputAlphaPremulPS):r.append(i.outputAlphaOpaquePS),e.useMsdf&&r.append(" gl_FragColor = applyMsdf(gl_FragColor);"),r.append(i.outputPS),r.append(i.debugOutputPS),w&&s.prepend(i.lightDirPointPS),T&&s.prepend(i.falloffLinearPS),A&&s.prepend(i.falloffInvSquaredPS),C&&s.prepend(i.spotPS),E&&!e.clusteredLightingEnabled&&s.prepend(i.cookiePS);var H="",W="void evaluateBackend() {\n"+r.code+"\n}";s.append(W),a.append(i.debugProcessFrontendPS),a.append(" evaluateBackend();"),a.append(xo.end());var X=n.code+s.code+a.code;return X.includes("dTBN")&&(H+="mat3 dTBN;\n"),X.includes("dVertexNormalW")&&(H+="vec3 dVertexNormalW;\n"),X.includes("dTangentW")&&(H+="vec3 dTangentW;\n"),X.includes("dBinormalW")&&(H+="vec3 dBinormalW;\n"),X.includes("dViewDirW")&&(H+="vec3 dViewDirW;\n"),X.includes("dReflDirW")&&(H+="vec3 dReflDirW;\n"),X.includes("dHalfDirW")&&(H+="vec3 dHalfDirW;\n"),X.includes("ccReflDirW")&&(H+="vec3 ccReflDirW;\n"),X.includes("dLightDirNormW")&&(H+="vec3 dLightDirNormW;\n"),X.includes("dLightDirW")&&(H+="vec3 dLightDirW;\n"),X.includes("dLightPosW")&&(H+="vec3 dLightPosW;\n"),X.includes("dShadowCoord")&&(H+="vec3 dShadowCoord;\n"),X.includes("dReflection")&&(H+="vec4 dReflection;\n"),X.includes("dDiffuseLight")&&(H+="vec3 dDiffuseLight;\n"),X.includes("dSpecularLight")&&(H+="vec3 dSpecularLight;\n"),X.includes("dAtten")&&(H+="float dAtten;\n"),X.includes("dAttenD")&&(H+="float dAttenD;\n"),X.includes("dAtten3")&&(H+="vec3 dAtten3;\n"),X.includes("dMsdf")&&(H+="vec4 dMsdf;\n"),X.includes("ccFresnel")&&(H+="float ccFresnel;\n"),X.includes("ccReflection")&&(H+="vec3 ccReflection;\n"),X.includes("ccSpecularLight")&&(H+="vec3 ccSpecularLight;\n"),X.includes("ccSpecularityNoFres")&&(H+="float ccSpecularityNoFres;\n"),X.includes("sSpecularLight")&&(H+="vec3 sSpecularLight;\n"),X.includes("sReflection")&&(H+="vec3 sReflection;\n"),this._fsGetBeginCode()+this.varyings+this.varyingDefines+this._fsGetBaseCode()+H+this.frontendDecl+X},e.generateFragmentShader=function(t,e,i,n){var s,r=this.options;this.frontendDecl=t,this.frontendCode=e,this.frontendFunc=i,this.lightingUv=n,3===r.pass?this.fshader=this._fsGetPickPassCode():2===r.pass?this.fshader=this._fsGetDepthPassCode():this.shadowPass?this.fshader=this._fsGetShadowPassCode():r.customFragmentShader?this.fshader=this._fsGetBeginCode()+r.customFragmentShader:this.fshader=this._fsGetLitPassCode(),null==(s=this.handleCompatibility)||s.call(this)},e.getDefinition=function(){var t=ir.createDefinition(this.device,{name:"LitShader",attributes:this.attributes,vertexCode:this.vshader,fragmentCode:this.fshader});return this.shaderPassInfo.isForward&&(t.tag=1),t},t}(),fl={generateKey:function(t){return"lit"+Object.keys(t).sort().map((function(e){return"chunks"===e?fl.generateChunksKey(t):"lights"===e?fl.generateLightsKey(t):e+t[e]})).join("\n")},generateLightsKey:function(t){return"lights:"+t.lights.map((function(e){return t.clusteredLightingEnabled&&0!==e._type?"":e.key+","})).join("")},generateChunksKey:function(t){var e;return"chunks:\n"+Object.keys(null!=(e=t.chunks)?e:{}).sort().map((function(e){return e+t.chunks[e]})).join("")}},pl=[0,1,2,3,4,5,6,7],ml=function(t){function e(){return t.apply(this,arguments)||this}S(e,t);var i=e.prototype;return i.generateKey=function(t){return"lit"+pl.map((function(e,i){return t.usedUvs[i]?"1":"0"})).join("")+t.shaderChunk+fl.generateKey(t.litOptions)},i.createShaderDefinition=function(t,e){var i=new dl(t,e.litOptions),n=new Xh,s=new Xh,r=new Xh;n.append("uniform float textureBias;"),n.append(i.chunks.litShaderArgsPS),s.append(e.shaderChunk),r.code="evaluateFrontend();",r.code="\n"+r.code.split("\n").map((function(t){return" "+t})).join("\n")+"\n\n";var a=e.usedUvs||[!0];return i.generateVertexShader(a,a,[]),i.generateFragmentShader(n.code,s.code,r.code,"vUv0"),i.getDefinition()},e}(xo),_l=new ml,vl=new function(){this.usedUvs=void 0,this.shaderChunk=void 0,this.litOptions=new Hh},gl=function(t){function e(){for(var e,i=arguments.length,n=new Array(i),s=0;s1?0:1),this.lightsBuffer.updateUniforms(),this._clusterWorldTextureId.setValue(this.clusterTexture),this._clusterMaxCellsId.setValue(this.maxCellLightCount);var t=this.boundsDelta;this._clusterCellsCountByBoundsSizeData[0]=this._cells.x/t.x,this._clusterCellsCountByBoundsSizeData[1]=this._cells.y/t.y,this._clusterCellsCountByBoundsSizeData[2]=this._cells.z/t.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]=t.x,this._clusterBoundsDeltaData[1]=t.y,this._clusterBoundsDeltaData[2]=t.z,this._clusterCompressionLimit0Data[0]=this._maxAttenuation,this._clusterCompressionLimit0Data[1]=this._maxColorValue,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)},e.evalLightCellMinMax=function(t,e,i){e.copy(t.min),e.sub(this.boundsMin),e.div(this.boundsDelta),e.mul2(e,this.cells),e.floor(),i.copy(t.max),i.sub(this.boundsMin),i.div(this.boundsDelta),i.mul2(i,this.cells),i.ceil(),e.max(wt.ZERO),i.min(this._cellsLimit)},e.collectLights=function(t){var e=this.lightsBuffer.maxLights,i=this._usedLights,n=1;t.forEach((function(t){var s,r=!!(3&t.mask),a=2===t.type&&0===t._outerConeAngle;t.enabled&&0!==t.type&&t.visibleThisFrame&&t.intensity>0&&r&&!a&&(n1){e.copy(t[1].min),i.copy(t[1].max);for(var n=2;n1)for(var h=1/o,l=0;l1)for(var f=0;f0){for(var n=this.slots,s=0;ss&&(s=a)}return Vl.min=n,Vl.max=s,Vl}var Hl=function(){function t(t,e){this.renderer=void 0,this.shadowRenderer=void 0,this.device=void 0,this.renderer=t,this.shadowRenderer=e,this.device=t.device}var e=t.prototype;return e.cull=function(t,e,i,n){void 0===n&&(n=null),t.visibleThisFrame=!0,t._shadowMap||(t._shadowMap=Cl.create(this.device,t));var s=i._nearClip;this.generateSplitDistances(t,s,Math.min(i._farClip,t.shadowDistance));for(var r=t.shadowUpdateOverrides,a=0;a_&&(_=g)}var y=l.right,x=l.up,S=l.forward,b=.25*t._shadowResolution/_,w=Math.ceil(Ul.dot(x)*b)/b,T=Math.ceil(Ul.dot(y)*b)/b,A=x.mulScalar(w),C=y.mulScalar(T),E=Ul.dot(S),M=S.mulScalar(E);Ul.add2(A,C).add(M),l.setPosition(Ul),l.translateLocal(0,0,1e6),h.nearClip=.01,h.farClip=2e6,h.orthoHeight=_,this.renderer.updateCameraFrustum(h),this.shadowRenderer.cullShadowCasters(e,t,o.visibleCasters,h,n);for(var P=!0,R=o.visibleCasters,I=0;I=1&&e<=3?new vt(0,0,0,0):new vt(1,1,1,1),s.clearDepthBuffer=!0,s.clearStencilBuffer=!1,s},t.setShadowCameraSettings=function(t,e,i,n,s){var r=4===i||(5===i||0===i)&&e.supportsDepthShadow;1!==n||s||(r=!1),t.clearColorBuffer=!r};var e=t.prototype;return e._cullShadowCastersInternal=function(t,e,i){for(var n=t.length,s=0;s1&&(this.renderer.scene.clusteredLightingEnabled&&0!==t._type||this.applyVsmBlur(t,e))},e.getVsmBlurShader=function(t,e,i){var n=(t?this.blurPackedVsmShader:this.blurVsmShader)[e][i];if(!n){this.blurVsmWeights[i]=function(t){for(var e=(t-1)/6,i=.5*(t-1),n=new Array(t),s=0,r=0;r0},i.filter=function(t,e){for(var i=0;i1?this.quadRendererCube:this.quadRenderer2D;a>1&&this.initInvViewProjMatrices(),this.blitTextureId.setValue(r.cookie);for(var h=0;h1){var l=ec.z/3,c=i[h];ec.x+=l*c.x,ec.y+=l*c.y,ec.z=l,ec.w=l,this.invViewProjId.setValue(ic[h].data)}ec.mulScalar(e),o.render(ec)}}n.length=0},y(e,[{key:"quadRenderer2D",get:function(){if(!this._quadRenderer2D){var t=bo(this.device,tc,"\n\tvarying vec2 uv0;\n\tuniform sampler2D blitTexture;\n\tvoid main(void) {\n\t\tgl_FragColor = texture2D(blitTexture, uv0);\n\t}","cookieRenderer2d");this._quadRenderer2D=new Mo(t)}return this._quadRenderer2D}},{key:"quadRendererCube",get:function(){if(!this._quadRendererCube){var t=bo(this.device,tc,"\n\tvarying vec2 uv0;\n\tuniform samplerCube blitTexture;\n\tuniform mat4 invViewProj;\n\tvoid main(void) {\n\t\tvec4 projPos = vec4(uv0 * 2.0 - 1.0, 0.5, 1.0);\n\t\tvec4 worldPos = invViewProj * projPos;\n\t\tgl_FragColor = textureCube(blitTexture, worldPos.xyz);\n\t}","cookieRendererCube");this._quadRendererCube=new Mo(t)}return this._quadRendererCube}}]),e}(uo),sc=0,rc=[0,0,0,0],ac=new Ft,oc=new Ft,hc=new Ft,lc=new At,cc=new jt,uc=(new Ft).setScale(1,-1,1),dc=new Set,fc=new Set,pc=(new Ft).set([1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1]),mc=new Ft,_c=new Ft,vc=new Ft,gc=new Ft,yc=new Set,xc=[],Sc=[],bc=function(){function t(t){this.clustersDebugRendered=!1,this.processingMeshInstances=new Set,this.worldClustersAllocator=void 0,this.lights=[],this.localLights=[],this.device=t,this.scene=null,this.worldClustersAllocator=new Jl(t),this.lightTextureAtlas=new Ll(t),this.shadowMapCache=new kl,this.shadowRenderer=new Ql(this,this.lightTextureAtlas),this._shadowRendererLocal=new Fl(this,this.shadowRenderer),this._shadowRendererDirectional=new Hl(this,this.shadowRenderer),this.cookiesRenderPass=nc.create(this.lightTextureAtlas.cookieRenderTarget,this.lightTextureAtlas.cubeSlotsOffsets),this.viewUniformFormat=null,this.viewBindGroupFormat=null,this._skinTime=0,this._morphTime=0,this._cullTime=0,this._shadowMapTime=0,this._lightClustersTime=0,this._layerCompositionUpdateTime=0,this._shadowDrawCalls=0,this._skinDrawCalls=0,this._instancedDrawCalls=0,this._shadowMapUpdates=0,this._numDrawCallsCulled=0,this._camerasRendered=0,this._lightClusters=0;var e=t.scope;this.boneTextureId=e.resolve("texture_poseMap"),this.boneTextureSizeId=e.resolve("texture_poseMapSize"),this.poseMatrixId=e.resolve("matrix_pose[0]"),this.modelMatrixId=e.resolve("matrix_model"),this.normalMatrixId=e.resolve("matrix_normal"),this.viewInvId=e.resolve("matrix_viewInverse"),this.viewPos=new Float32Array(3),this.viewPosId=e.resolve("view_position"),this.projId=e.resolve("matrix_projection"),this.projSkyboxId=e.resolve("matrix_projectionSkybox"),this.viewId=e.resolve("matrix_view"),this.viewId3=e.resolve("matrix_view3"),this.viewProjId=e.resolve("matrix_viewProjection"),this.flipYId=e.resolve("projectionFlipY"),this.tbnBasis=e.resolve("tbnBasis"),this.nearClipId=e.resolve("camera_near"),this.farClipId=e.resolve("camera_far"),this.cameraParams=new Float32Array(4),this.cameraParamsId=e.resolve("camera_params"),this.alphaTestId=e.resolve("alpha_ref"),this.opacityMapId=e.resolve("texture_opacityMap"),this.exposureId=e.resolve("exposure"),this.twoSidedLightingNegScaleFactorId=e.resolve("twoSidedLightingNegScaleFactor"),this.twoSidedLightingNegScaleFactorId.setValue(0),this.morphWeightsA=e.resolve("morph_weights_a"),this.morphWeightsB=e.resolve("morph_weights_b"),this.morphPositionTex=e.resolve("morphPositionTex"),this.morphNormalTex=e.resolve("morphNormalTex"),this.morphTexParams=e.resolve("morph_tex_params"),this.lightCube=new Ol,this.constantLightCube=e.resolve("lightCube[0]")}var e=t.prototype;return e.destroy=function(){this.shadowRenderer=null,this._shadowRendererLocal=null,this._shadowRendererDirectional=null,this.shadowMapCache.destroy(),this.shadowMapCache=null,this.cookiesRenderPass.destroy(),this.cookiesRenderPass=null,this.lightTextureAtlas.destroy(),this.lightTextureAtlas=null},e.sortCompare=function(t,e){if(t.layer===e.layer){if(t.drawOrder&&e.drawOrder)return t.drawOrder-e.drawOrder;if(t.zdist&&e.zdist)return e.zdist-t.zdist;if(t.zdist2&&e.zdist2)return t.zdist2-e.zdist2}return e._key[0]-t._key[0]},e.sortCompareMesh=function(t,e){if(t.layer===e.layer){if(t.drawOrder&&e.drawOrder)return t.drawOrder-e.drawOrder;if(t.zdist&&e.zdist)return e.zdist-t.zdist}var i=t._key[0],n=e._key[0];return i===n&&t.mesh&&e.mesh?e.mesh.id-t.mesh.id:n-i},e.sortCompareDepth=function(t,e){var i=t._key[1],n=e._key[1];return i===n&&t.mesh&&e.mesh?e.mesh.id-t.mesh.id:n-i},e.setupViewport=function(t,e){var i=this.device,n=e?e.width:i.width,s=e?e.height:i.height,r=t.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),t._scissorRectClear){var c=t.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)},e.setCameraUniforms=function(t,e){var i=null==e?void 0:e.flipY,n=1;if(t.xr&&t.xr.session){var s,r=t._node.parent;r&&(s=r.getWorldTransform());var a=t.xr.views;n=a.length;for(var o=0;o0)&&this.alphaTestId.setValue(e.alphaTest)},e.updateCpuSkinMatrices=function(t){sc++;var e=t.length;if(0!==e)for(var i=0;i0&&(this._instancedDrawCalls++,t.setVertexBuffer(a.vertexBuffer),t.draw(i.primitive[n],a.count)):t.draw(i.primitive[n])},e.drawInstance2=function(t,e,i,n){var s=e.instancingData;s?s.count>0&&(this._instancedDrawCalls++,t.draw(i.primitive[n],s.count,!0)):t.draw(i.primitive[n],void 0,!0)},e.cull=function(t,e,i){var n=i.opaque;n.length=0;var s=i.transparent;s.length=0;for(var r=t.frustumCulling,a=e.length,o=0;o>>16)>>>0;return 2.3283064365386963e-10*(e=((16711935&(e=((252645135&(e=((858993459&(e=((1431655765&e)<<1|(2863311530&e)>>>1)>>>0))<<2|(3435973836&e)>>>2)>>>0))<<4|(4042322160&e)>>>4)>>>0))<<8|(4278255360&e)>>>8)>>>0)},Ec=function(t){switch(t){case ui:return"Cubemap";case fi:return"Octahedral";default:return"Equirect"}},Mc=function(t,e,i){if(t<=0)e[i+0]=0,e[i+1]=0,e[i+2]=0,e[i+3]=0;else if(t>=1)e[i+0]=255,e[i+1]=0,e[i+2]=0,e[i+3]=0;else{var n=1*t%1,s=255*t%1,r=65025*t%1,a=16581375*t%1;n-=s/255,s-=r/255,r-=a/255,e[i+0]=Math.min(255,Math.floor(256*n)),e[i+1]=Math.min(255,Math.floor(256*s)),e[i+2]=Math.min(255,Math.floor(256*r)),e[i+3]=Math.min(255,Math.floor(256*a))}},Pc=function(t,e,i,n){var s=2*i*Math.PI,r=Math.pow(1-e,1/(n+1)),a=Math.sqrt(1-r*r);t.set(Math.cos(s)*a,Math.sin(s)*a,r).normalize()},Rc=function(t,e,i){var n=2*i*Math.PI,s=Math.sqrt(1-e),r=Math.sqrt(e);t.set(Math.cos(n)*r,Math.sin(n)*r,s).normalize()},Ic=function(t,e,i,n){var s=2*i*Math.PI,r=Math.sqrt((1-e)/(1+(n*n-1)*e)),a=Math.sqrt(1-r*r);t.set(Math.cos(s)*a,Math.sin(s)*a,r).normalize()},Lc=function(t,e){var i=t*e,n=e/(1-t*t+i*i);return n*n*(1/Math.PI)},Dc={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}},Oc=function(t,e,i){for(var n=i/t,s=1-Math.log2(e)/11,r=s*s,a=new wt,o=new wt,h=new wt(0,0,1),l=[],c=function(t,e){var i=Dc[t];return i&&i[e]||t}(t,e),u=0;u0){var f=Lc(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*t;)l.push(0,0,0,0);return l},kc=function(t,e,i){var n=function(t){for(var e=t.length,i=Math.min(e,512),n=Math.ceil(e/i),s=new Uint8Array(i*n*4),r=0,a=0;a>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),Gc(t,n,{numSamples:(null==e?void 0:e.numAmbientSamples)||2048,distribution:"lambert",rect:r,seamPixels:s}),n},t.generatePrefilteredAtlas=function(t,e){for(var i=t[0].device,n=t[0].format,s=t[0].type,r=(null==e?void 0:e.target)||new Ls(i,{name:"envPrefilteredAtlas",width:(null==e?void 0:e.size)||512,height:(null==e?void 0:e.size)||512,format:n,type:s,projection:di,addressU:1,addressV:1,mipmaps:!1}),a=r.width/512,o=new Pt(0,0,512*a,256*a),h=Hc(512),l=0;l0){if(i[t]e.length){for(var n=e,s=n.charAt(n.length-1),r=i[t]-n.length,a=0;a0,t.litOptions.blendType=i.blendType,t.litOptions.screenSpace=n&&0!=(n&Fa),t.litOptions.skin=n&&0!=(2&n),t.litOptions.useInstancing=n&&0!=(n&Oa),t.litOptions.useMorphPosition=n&&0!=(n&Ua),t.litOptions.useMorphNormal=n&&0!=(n&Na),t.litOptions.useMorphTextureBased=n&&0!=(n&za),t.litOptions.nineSlicedMode=i.nineSlicedMode||0,e.clusteredLightingEnabled&&i.useLighting?(t.litOptions.clusteredLightingEnabled=!0,t.litOptions.clusteredLightingCookiesEnabled=e.lighting.cookiesEnabled,t.litOptions.clusteredLightingShadowsEnabled=e.lighting.shadowsEnabled,t.litOptions.clusteredLightingShadowType=e.lighting.shadowType,t.litOptions.clusteredLightingAreaLightsEnabled=e.lighting.areaLightsEnabled):(t.litOptions.clusteredLightingEnabled=!1,t.litOptions.clusteredLightingCookiesEnabled=!1,t.litOptions.clusteredLightingShadowsEnabled=!1,t.litOptions.clusteredLightingAreaLightsEnabled=!1)},e._updateUVOptions=function(t,e,i,n){var s=!1,r=!1,a=!1;i&&(s=0!=(4&i),r=0!=(8&i),a=0!=(16&i)),t.litOptions.vertexColors=!1,this._mapXForms=[];var o={};for(var h in jc)this._updateTexOptions(t,e,h,s,r,a,n,o);this._mapXForms=null,t.litOptions.lightMapEnabled=t.lightMap,t.litOptions.dirLightMapEnabled=t.dirLightMap,t.litOptions.useHeights=t.heightMap,t.litOptions.useNormals=t.normalMap,t.litOptions.useClearCoatNormals=t.clearCoatNormalMap,t.litOptions.useAo=t.aoMap||t.aoVertexColor,t.litOptions.diffuseMapEnabled=t.diffuseMap},e._updateTexOptions=function(t,e,i,n,s,r,a,o){var h="opacity"===i;if(!a||h){var l=i+"Map",c=i+"VertexColor",u=i+"VertexColorChannel",d=l+"Channel",f=l+"Transform",p=l+"Uv",m=l+"Identifier";if("light"!==i&&(t[l]=!1,t[m]=void 0,t[d]="",t[f]=0,t[p]=0),t[c]=!1,t[u]="",h&&3===e.blendType&&0===e.alphaTest&&!e.alphaToCoverage)return;if("height"!==i&&e[c]&&r&&(t[c]=e[c],t[u]=e[u],t.litOptions.vertexColors=!0),e[l]){var _=!0;if(0!==e[p]||n||(_=!1),1!==e[p]||s||(_=!1),_){var v=e[l].id,g=o[v];void 0===g&&(o[v]=i,g=i),t[l]=!!e[l],t[m]=g,t[f]=this._getMapTransformID(e.getUniform(f),e[p]),t[d]=e[d],t[p]=e[p]}}}},e._updateMinOptions=function(t,e){t.opacityTint=1!==e.opacity&&3!==e.blendType,t.litOptions.lights=[]},e._updateMaterialOptions=function(t,e){var i,n,s,r,a,o=(e.diffuseTint||!e.diffuseMap&&!e.diffuseVertexColor)&&Qc(e.diffuse),h=!!(e.useMetalness||e.specularMap||e.sphereMap||e.cubeMap||(a=e.specular,0!==a.r||0!==a.g||0!==a.b)||e.specularityFactor>0&&e.useMetalness||e.enableGGXSpecular||e.clearCoat>0),l=!e.useMetalness||e.useMetalnessSpecularColor,c=h&&(e.specularTint||!e.specularMap&&!e.specularVertexColor)&&Qc(e.specular),u=h&&e.useMetalnessSpecularColor&&(e.specularityFactorTint||e.specularityFactor<1&&!e.specularityFactorMap),d=!e.emissiveMap||Qc(e.emissive)&&e.emissiveTint,f=1!==e.emissiveIntensity,p=!!e.normalMap&&(e.normalMap.format===re||e.normalMap.type===ri);t.opacityTint=1!==e.opacity&&3!==e.blendType?1:0,t.ambientTint=e.ambientTint,t.diffuseTint=o?2:0,t.specularTint=c?2:0,t.specularityFactorTint=u?1:0,t.metalnessTint=e.useMetalness&&e.metalness<1?1:0,t.glossTint=1,t.emissiveTint=(d?2:0)+(f?1:0),t.diffuseEncoding=null==(i=e.diffuseMap)?void 0:i.encoding,t.diffuseDetailEncoding=null==(n=e.diffuseDetailMap)?void 0:n.encoding,t.emissiveEncoding=null==(s=e.emissiveMap)?void 0:s.encoding,t.lightMapEncoding=null==(r=e.lightMap)?void 0:r.encoding,t.packedNormal=p,t.refractionTint=1!==e.refraction?1:0,t.refractionIndexTint=e.refractionIndex!==1/1.5?1:0,t.thicknessTint=e.useDynamicRefraction&&1!==e.thickness?1:0,t.specularEncoding=e.specularEncoding||"linear",t.sheenEncoding=e.sheenEncoding||"linear",t.aoMapUv=e.aoUvSet,t.aoDetail=!!e.aoMap,t.diffuseDetail=!!e.diffuseMap,t.normalDetail=!!e.normalMap,t.diffuseDetailMode=e.diffuseDetailMode,t.aoDetailMode=e.aoDetailMode,t.clearCoatTint=1!==e.clearCoat?1:0,t.clearCoatGloss=!!e.clearCoatGloss,t.clearCoatGlossTint=1!==e.clearCoatGloss?1:0,t.iorTint=e.refractionIndex!==1/1.5?1:0,t.iridescenceTint=1!==e.iridescence?1:0,t.sheenTint=e.useSheen&&Qc(e.sheen)?2:0,t.sheenGlossTint=1,t.glossInvert=e.glossInvert,t.sheenGlossInvert=e.sheenGlossInvert,t.clearCoatGlossInvert=e.clearCoatGlossInvert,t.useSpecularColor=l,t.litOptions.separateAmbient=!1,t.litOptions.useAmbientTint=e.ambientTint,t.litOptions.customFragmentShader=e.customFragmentShader,t.litOptions.pixelSnap=e.pixelSnap,t.litOptions.shadingModel=e.shadingModel,t.litOptions.ambientSH=!!e.ambientSH,t.litOptions.fastTbn=e.fastTbn,t.litOptions.twoSidedLighting=e.twoSidedLighting,t.litOptions.occludeSpecular=e.occludeSpecular,t.litOptions.occludeSpecularFloat=1!==e.occludeSpecularIntensity,t.litOptions.useMsdf=!!e.msdfMap,t.litOptions.msdfTextAttribute=!!e.msdfTextAttribute,t.litOptions.alphaToCoverage=e.alphaToCoverage,t.litOptions.opacityFadesSpecular=e.opacityFadesSpecular,t.litOptions.cubeMapProjection=e.cubeMapProjection,t.litOptions.occludeDirect=e.occludeDirect,t.litOptions.conserveEnergy=e.conserveEnergy&&0!==e.shadingModel,t.litOptions.useSpecular=h,t.litOptions.useSpecularityFactor=(u||!!e.specularityFactorMap)&&e.useMetalnessSpecularColor,t.litOptions.enableGGXSpecular=e.enableGGXSpecular,t.litOptions.fresnelModel=e.fresnelModel,t.litOptions.useRefraction=(e.refraction||!!e.refractionMap)&&(e.useDynamicRefraction||!!t.litOptions.reflectionSource),t.litOptions.useClearCoat=!!e.clearCoat,t.litOptions.useSheen=e.useSheen,t.litOptions.useIridescence=e.useIridescence&&0!==e.iridescence,t.litOptions.useMetalness=e.useMetalness,t.litOptions.useDynamicRefraction=e.useDynamicRefraction},e._updateEnvOptions=function(t,e,i){t.litOptions.fog=e.useFog?i.fog:"none",t.litOptions.gamma=e.useGammaTonemap?i.gammaCorrection:0,t.litOptions.toneMap=e.useGammaTonemap?i.toneMapping:-1,t.litOptions.fixSeams=!!e.cubeMap&&e.cubeMap.fixCubemapSeams;var n=0===e.shadingModel,s=!1;if(e.envAtlas&&e.cubeMap&&!n?(t.litOptions.reflectionSource="envAtlasHQ",t.litOptions.reflectionEncoding=e.envAtlas.encoding,t.litOptions.reflectionCubemapEncoding=e.cubeMap.encoding):e.envAtlas&&!n?(t.litOptions.reflectionSource="envAtlas",t.litOptions.reflectionEncoding=e.envAtlas.encoding):e.cubeMap?(t.litOptions.reflectionSource="cubeMap",t.litOptions.reflectionEncoding=e.cubeMap.encoding):e.sphereMap?(t.litOptions.reflectionSource="sphereMap",t.litOptions.reflectionEncoding=e.sphereMap.encoding):e.useSkybox&&i.envAtlas&&i.skybox&&!n?(t.litOptions.reflectionSource="envAtlasHQ",t.litOptions.reflectionEncoding=i.envAtlas.encoding,t.litOptions.reflectionCubemapEncoding=i.skybox.encoding,s=!0):e.useSkybox&&i.envAtlas&&!n?(t.litOptions.reflectionSource="envAtlas",t.litOptions.reflectionEncoding=i.envAtlas.encoding,s=!0):e.useSkybox&&i.skybox?(t.litOptions.reflectionSource="cubeMap",t.litOptions.reflectionEncoding=i.skybox.encoding,s=!0):(t.litOptions.reflectionSource=null,t.litOptions.reflectionEncoding=null),e.ambientSH&&!n)t.litOptions.ambientSource="ambientSH",t.litOptions.ambientEncoding=null;else{var r=e.envAtlas||(e.useSkybox&&i.envAtlas?i.envAtlas:null);r&&!n?(t.litOptions.ambientSource="envAtlas",t.litOptions.ambientEncoding=r.encoding):(t.litOptions.ambientSource="constant",t.litOptions.ambientEncoding=null)}t.litOptions.skyboxIntensity=s&&(1!==i.skyboxIntensity||i.physicalUnits),t.litOptions.useCubeMapRotation=s&&i._skyboxRotationShaderInclude},e._updateLightOptions=function(t,e,i,n,s){if(t.lightMap=!1,t.lightMapChannel="",t.lightMapUv=0,t.lightMapTransform=0,t.litOptions.lightMapWithoutAmbient=!1,t.dirLightMap=!1,n&&(t.litOptions.noShadow=0!=(1&n),0!=(64&n)&&(t.lightMapEncoding=7===e.lightmapPixelFormat?"rgbm":"linear",t.lightMap=!0,t.lightMapChannel="rgb",t.lightMapUv=1,t.lightMapTransform=0,t.litOptions.lightMapWithoutAmbient=!i.lightMap,0!=(n&ka)&&(t.dirLightMap=!0),0!=(n&Va)&&(t.litOptions.lightMapWithoutAmbient=!1))),i.useLighting){var r=[],a=n?n>>16:1;t.litOptions.lightMaskDynamic=!!(1&a),s&&(Wh.collectLights(0,s[0],r,a),Wh.collectLights(1,s[1],r,a),Wh.collectLights(2,s[2],r,a)),t.litOptions.lights=r}else t.litOptions.lights=[];0===t.litOptions.lights.length&&(t.litOptions.noShadow=!0)},e._getMapTransformID=function(t,e){if(!t)return 0;var i=this._mapXForms[e];i||(i=[],this._mapXForms[e]=i);for(var n=0;n0&&(this._setParameter("material_clearCoat",this.clearCoat),this._setParameter("material_clearCoatGloss",this.clearCoatGloss),this._setParameter("material_clearCoatBumpiness",this.clearCoatBumpiness)),this._setParameter("material_gloss",n("gloss")),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.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")),jc)this._updateMap(s);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 r=0===this.shadingModel;this.envAtlas&&this.cubeMap&&!r?(this._setParameter("texture_envAtlas",this.envAtlas),this._setParameter("texture_cubeMap",this.cubeMap)):this.envAtlas&&!r?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(t,e){var i=0===this.shadingModel;!(this.envAtlas&&!i||this.cubeMap||this.sphereMap)&&this.useSkybox&&(e.envAtlas&&e.skybox&&!i?(this._setParameter("texture_envAtlas",e.envAtlas),this._setParameter("texture_cubeMap",e.skybox)):e.envAtlas&&!i?this._setParameter("texture_envAtlas",e.envAtlas):e.skybox&&this._setParameter("texture_cubeMap",e.skybox)),this._processParameters("_activeLightingParams")},i.getShaderVariant=function(t,e,i,n,s,r,a,o,h){this.updateEnvUniforms(t,e);var l=Do.get(t).getByIndex(s),c=2===s||3===s||l.isShadow,u=c?Kc.optionsContextMin:Kc.optionsContext;c?this.shaderOptBuilder.updateMinRef(u,e,this,i,s,r):this.shaderOptBuilder.updateRef(u,e,this,i,s,r),this.onUpdateShader&&(u=this.onUpdateShader(u));var d=new fo(a,o,h),f=go(t);f.register("standard",Kc);var p=f.getProgram("standard",u,d,this.userId);return this._dirtyShader=!1,p},i.destroy=function(){for(var e in this._assetReferences)this._assetReferences[e]._unbind();this._assetReferences=null,t.prototype.destroy.call(this)},y(e,[{key:"shader",get:function(){return null},set:function(t){}},{key:"chunks",get:function(){return this._dirtyShader=!0,this._chunks},set:function(t){this._dirtyShader=!0,this._chunks=t}}]),e}(zo);lu.TEXTURE_PARAMETERS=eu,lu.CUBEMAP_PARAMETERS=nu;var cu=function(t,e){ou[t]=e},uu=function(t,e,i,n){Object.defineProperty(lu.prototype,t,{get:n||function(){return this["_"+t]},set:i}),au[t]={value:e}},du=function(t){return t.defaultValue&&t.defaultValue.clone?function(t){var e="_"+t.name,i=t.dirtyShaderFunc||function(){return!0};uu(t.name,(function(){return t.defaultValue.clone()}),(function(t){var n=this[e];n.equals(t)||(this._dirtyShader=this._dirtyShader||i(n,t),this[e]=n.copy(t))}),t.getterFunc)}(t):function(t){var e="_"+t.name,i=t.dirtyShaderFunc||function(){return!0};uu(t.name,(function(){return t.defaultValue}),(function(t){var n=this[e];n!==t&&(this._dirtyShader=this._dirtyShader||i(n,t),this[e]=t)}),t.getterFunc)}(t)};function fu(t,e,i,n){void 0===e&&(e="rgb"),void 0===i&&(i=!0),void 0===n&&(n=0),jc[t]=e.length||-1,du({name:t+"Map",defaultValue:null,dirtyShaderFunc:function(t,e){return!!t!=!!e||t&&(t.type!==e.type||t.fixCubemapSeams!==e.fixCubemapSeams||t.format!==e.format)}}),du({name:t+"MapTiling",defaultValue:new Et(1,1)}),du({name:t+"MapOffset",defaultValue:new Et(0,0)}),du({name:t+"MapRotation",defaultValue:0}),du({name:t+"MapUv",defaultValue:n}),e&&(du({name:t+"MapChannel",defaultValue:e}),i&&(du({name:t+"VertexColor",defaultValue:!1}),du({name:t+"VertexColorChannel",defaultValue:e})));var s=t+"MapTiling",r=t+"MapOffset",a=t+"MapRotation",o=t+"MapTransform";cu(o,(function(t,e,i){var n=t[s],h=t[r],l=t[a];if(1===n.x&&1===n.y&&0===h.x&&0===h.y&&0===l)return null;var c=t._allocUniform(o,(function(){return[{name:"texture_"+o+"0",value:new Float32Array(3)},{name:"texture_"+o+"1",value:new Float32Array(3)}]})),u=Math.cos(l*_t.DEG_TO_RAD),d=Math.sin(l*_t.DEG_TO_RAD),f=c[0].value;f[0]=u*n.x,f[1]=-d*n.y,f[2]=h.x;var p=c[1].value;return p[0]=d*n.x,p[1]=u*n.y,p[2]=1-n.y-h.y,c}))}function pu(t,e){du({name:t,defaultValue:e,getterFunc:function(){return this._dirtyShader=!0,this["_"+t]}}),cu(t,(function(e,i,n){var s=e._allocUniform(t,(function(){return new Float32Array(3)})),r=e[t];return e.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 mu(t,e,i){du({name:t,defaultValue:e,dirtyShaderFunc:function(t,e){return(0===t||1===t)!=(0===e||1===e)}}),cu(t,i)}function _u(t,e){du({name:t,defaultValue:null,dirtyShaderFunc:function(t,e){return!!t==!!e}}),cu(t,e)}function vu(t,e){du({name:t,defaultValue:e})}!function(){pu("ambient",new vt(.7,.7,.7)),pu("diffuse",new vt(1,1,1)),pu("specular",new vt(0,0,0)),pu("emissive",new vt(0,0,0)),pu("sheen",new vt(1,1,1)),pu("attenuation",new vt(1,1,1)),mu("emissiveIntensity",1),mu("specularityFactor",1),mu("sheenGloss",0),mu("gloss",.25,(function(t,e,i){return 0===t.shadingModel?Math.pow(2,11*t.gloss):t.gloss})),mu("heightMapFactor",1,(function(t,e,i){return.025*t.heightMapFactor})),mu("opacity",1),mu("alphaFade",1),mu("alphaTest",0),mu("bumpiness",1),mu("normalDetailMapBumpiness",1),mu("reflectivity",1),mu("occludeSpecularIntensity",1),mu("refraction",0),mu("refractionIndex",1/1.5),mu("thickness",0),mu("attenuationDistance",0),mu("metalness",1),mu("anisotropy",0),mu("clearCoat",0),mu("clearCoatGloss",1),mu("clearCoatBumpiness",1),mu("aoUvSet",0,null),mu("iridescence",0),mu("iridescenceRefractionIndex",1/1.5),mu("iridescenceThicknessMin",0),mu("iridescenceThicknessMax",0),_u("ambientSH"),_u("cubeMapProjectionBox",(function(t,e,i){var n=t._allocUniform("cubeMapProjectionBox",(function(){return[{name:"envBoxMin",value:new Float32Array(3)},{name:"envBoxMax",value:new Float32Array(3)}]})),s=t.cubeMapProjectionBox.getMin(),r=n[0].value;r[0]=s.x,r[1]=s.y,r[2]=s.z;var a=t.cubeMapProjectionBox.getMax(),o=n[1].value;return o[0]=a.x,o[1]=a.y,o[2]=a.z,n})),vu("ambientTint",!1),vu("diffuseTint",!1),vu("specularTint",!1),vu("specularityFactorTint",!1),vu("emissiveTint",!1),vu("fastTbn",!1),vu("useMetalness",!1),vu("useMetalnessSpecularColor",!1),vu("useSheen",!1),vu("enableGGXSpecular",!1),vu("occludeDirect",!1),vu("normalizeNormalMap",!0),vu("conserveEnergy",!0),vu("opacityFadesSpecular",!0),vu("occludeSpecular",1),vu("shadingModel",1),vu("fresnelModel",2),vu("useDynamicRefraction",!1),vu("cubeMapProjection",0),vu("customFragmentShader",null),vu("useFog",!0),vu("useLighting",!0),vu("useGammaTonemap",!0),vu("useSkybox",!0),vu("forceUv1",!1),vu("pixelSnap",!1),vu("twoSidedLighting",!1),vu("nineSlicedMode",void 0),vu("msdfTextAttribute",!1),vu("useIridescence",!1),vu("glossInvert",!1),vu("sheenGlossInvert",!1),vu("clearCoatGlossInvert",!1),fu("diffuse"),fu("specular"),fu("emissive"),fu("thickness","g"),fu("specularityFactor","g"),fu("normal",""),fu("metalness","g"),fu("gloss","g"),fu("opacity","a"),fu("refraction","g"),fu("height","g",!1),fu("ao","g"),fu("light","rgb",!0,1),fu("msdf",""),fu("diffuseDetail","rgb",!1),fu("normalDetail",""),fu("aoDetail","g",!1),fu("clearCoat","g"),fu("clearCoatGloss","g"),fu("clearCoatNormal",""),fu("sheen","rgb"),fu("sheenGloss","g"),fu("iridescence","g"),fu("iridescenceThickness","g"),vu("diffuseDetailMode",Da),vu("aoDetailMode",Da),_u("cubeMap"),_u("sphereMap"),_u("envAtlas");var t=[null,null,null,null,null,null];uu("prefilteredCubemaps",(function(){return t.slice()}),(function(t){var e=this._prefilteredCubemaps;t=t||[];for(var i=!1,n=!0,s=0;s<6;++s){var r=t[s]||null;e[s]!==r&&(e[s]=r,i=!0),n=n&&!!e[s]}i&&(n?this.envAtlas=Wc.generatePrefilteredAtlas(e,{target:this.envAtlas}):this.envAtlas&&(this.envAtlas.destroy(),this.envAtlas=null),this._dirtyShader=!0)}),(function(){return this._prefilteredCubemaps}))}(),new wt(1,1,1),new wt(40,0,0);var gu={drawCalls:[],shaderInstances:[],isNewMaterial:[],lightMaskChanged:[],clear:function(){this.drawCalls.length=0,this.shaderInstances.length=0,this.isNewMaterial.length=0,this.lightMaskChanged.length=0}};var yu=function(t){function e(e){var i,n=(i=t.call(this,e)||this).device;i._forwardDrawCalls=0,i._materialSwitches=0,i._depthMapTime=0,i._forwardTime=0,i._sortTime=0;var s=n.scope;return i.fogColorId=s.resolve("fog_color"),i.fogStartId=s.resolve("fog_start"),i.fogEndId=s.resolve("fog_end"),i.fogDensityId=s.resolve("fog_density"),i.ambientId=s.resolve("light_globalAmbient"),i.skyboxIntensityId=s.resolve("skyboxIntensity"),i.cubeMapRotationMatrixId=s.resolve("cubeMapRotationMatrix"),i.pcssDiskSamplesId=s.resolve("pcssDiskSamples[0]"),i.pcssSphereSamplesId=s.resolve("pcssSphereSamples[0]"),i.lightColorId=[],i.lightDir=[],i.lightDirId=[],i.lightShadowMapId=[],i.lightShadowMatrixId=[],i.lightShadowParamsId=[],i.lightShadowIntensity=[],i.lightRadiusId=[],i.lightPos=[],i.lightPosId=[],i.lightWidth=[],i.lightWidthId=[],i.lightHeight=[],i.lightHeightId=[],i.lightInAngleId=[],i.lightOutAngleId=[],i.lightCookieId=[],i.lightCookieIntId=[],i.lightCookieMatrixId=[],i.lightCookieOffsetId=[],i.lightShadowSearchAreaId=[],i.lightCameraParamsId=[],i.shadowMatrixPaletteId=[],i.shadowCascadeDistancesId=[],i.shadowCascadeCountId=[],i.screenSizeId=s.resolve("uScreenSize"),i._screenSize=new Float32Array(4),i.fogColor=new Float32Array(3),i.ambientColor=new Float32Array(3),i.pcssDiskSamples=function(t){for(var e=[],i=0;i0){var a=this._shaderVersion;Tu.forEach((function(t){a>=0&&t._shaderVersion!==a&&(t.getShaderVariant!==zo.prototype.getShaderVariant&&t.clearVariants(),t._shaderVersion=a)})),Tu.clear()}},e.removeMeshInstances=function(t,e){for(var i=this.meshInstances,n=this.meshInstancesSet,s=0;s=0&&i.splice(a,1)}}e||this.removeShadowCasters(t)},e.addShadowCasters=function(t){for(var e=this.shadowCasters,i=this.shadowCastersSet,n=0;n=0&&e.splice(r,1)}}},e.clearMeshInstances=function(t){void 0===t&&(t=!1),this.meshInstances.length=0,this.meshInstancesSet.clear(),t||(this.shadowCasters.length=0,this.shadowCastersSet.clear())},e.markLightsDirty=function(){this._lightHashDirty=!0,this._lightIdHashDirty=!0,this._splitLightsDirty=!0},e.addLight=function(t){var e=t.light;this._lightsSet.has(e)||(this._lightsSet.add(e),this._lights.push(e),this.markLightsDirty()),0!==e.type&&this._clusteredLightsSet.add(e)},e.removeLight=function(t){var e=t.light;this._lightsSet.has(e)&&(this._lightsSet.delete(e),this._lights.splice(this._lights.indexOf(e),1),this.markLightsDirty()),0!==e.type&&this._clusteredLightsSet.delete(e)},e.clearLights=function(){var t=this;this._lightsSet.forEach((function(e){return e.removeLayer(t)})),this._lightsSet.clear(),this._clusteredLightsSet.clear(),this._lights.length=0,this.markLightsDirty()},e.evaluateLightHash=function(t,e,i){for(var n=0,s=this._lights,r=0;r0&&(wu.sort(),n=Yi(wu),wu.length=0),n},e.getLightHash=function(t){return this._lightHashDirty&&(this._lightHashDirty=!1,this._lightHash=this.evaluateLightHash(!t,!0,!1)),this._lightHash},e.getLightIdHash=function(){return this._lightIdHashDirty&&(this._lightIdHashDirty=!1,this._lightIdHash=this.evaluateLightHash(!0,!1,!0)),this._lightIdHash},e.addCamera=function(t){this.camerasSet.has(t.camera)||(this.camerasSet.add(t.camera),this.cameras.push(t),this._dirtyCameras=!0)},e.removeCamera=function(t){if(this.camerasSet.has(t.camera)){this.camerasSet.delete(t.camera);var e=this.cameras.indexOf(t);this.cameras.splice(e,1),this._dirtyCameras=!0}},e.clearCameras=function(){this.cameras.length=0,this.camerasSet.clear(),this._dirtyCameras=!0},e._calculateSortDistances=function(t,e,i,n){for(var s=0;s0}},{key:"clusteredLightsSet",get:function(){return this._clusteredLightsSet}},{key:"splitLights",get:function(){if(this._splitLightsDirty){this._splitLightsDirty=!1;for(var t=this._splitLights,e=0;e0}}]),t}(),Ru=function(t){function e(e){var i;return void 0===e&&(e="Untitled"),(i=t.call(this)||this).layerList=[],i.layerIdMap=new Map,i.layerNameMap=new Map,i.subLayerList=[],i.subLayerEnabled=[],i.cameras=[],i.camerasMap=new Map,i._renderActions=[],i.name=e,i._opaqueOrder={},i._transparentOrder={},i._dirtyCameras=!1,i}S(e,t);var i=e.prototype;return i.destroy=function(){this._renderActions.forEach((function(t){return t.destroy()})),this._renderActions=null},i._update=function(){var t=this.layerList.length;if(!this._dirtyCameras)for(var e=0;e1&&Mu(this.cameras),this.camerasMap.clear();for(var a=0;a0&&c.layers.indexOf(_.id)>=0&&(o.push(_),p||_.id!==c.disablePostEffectsLayer||(p=!0,f&&(f.triggerPostprocess=!0)),f=this.addRenderAction(this._renderActions,h,_,m,c,u,p),h++,u=!1)}d=0;c--)if(t[c].camera===s&&t[c].renderTarget===h){l=!0;break}var u=r||!l,d=!!u&&s.clearColorBuffer,f=!!u&&s.clearDepthBuffer,p=!!u&&s.clearStencilBuffer;return d||(d=i.clearColorBuffer),f||(f=i.clearDepthBuffer),p||(p=i.clearStencilBuffer),a&&s.postEffectsEnabled&&(h=null),o.triggerPostprocess=!1,o.layerIndex=n,o.layer=i,o.camera=s,o.renderTarget=h,o.clearColor=d,o.clearDepth=f,o.clearStencil=p,o.firstCameraUse=r,o.lastCameraUse=!1,o},i.propagateRenderTarget=function(t,e){for(var i=t;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&&(!e.camera.rect.equals(r.rect)||!e.camera.scissorRect.equals(r.scissorRect)))break;n.renderTarget=e.renderTarget}}},i._logRenderActions=function(){},i._isLayerAdded=function(t){return this.layerIdMap.get(t.id)===t},i._isSublayerAdded=function(t,e){for(var i=0;i=0;)this.layerList.splice(e,1),this.subLayerList.splice(e,1),this.subLayerEnabled.splice(e,1),e=this.layerList.indexOf(t),this._dirtyCameras=!0,this.fire("remove",t);var i=this.layerList.length;this._updateOpaqueOrder(0,i-1),this._updateTransparentOrder(0,i-1),this._updateLayerMaps()},i.pushOpaque=function(t){this._isSublayerAdded(t,!1)||(this.layerList.push(t),this._opaqueOrder[t.id]=this.subLayerList.push(!1)-1,this.subLayerEnabled.push(!0),this._updateLayerMaps(),this._dirtyCameras=!0,this.fire("add",t))},i.insertOpaque=function(t,e){if(!this._isSublayerAdded(t,!1)){this.layerList.splice(e,0,t),this.subLayerList.splice(e,0,!1);var i=this.subLayerList.length;this._updateOpaqueOrder(e,i-1),this.subLayerEnabled.splice(e,0,!0),this._updateLayerMaps(),this._dirtyCameras=!0,this.fire("add",t)}},i.removeOpaque=function(t){for(var e=0,i=this.layerList.length;e45?(t.radius=e*this._outerConeAngleSin,Iu.mulScalar(-e*n)):(t.radius=e/(2*n),Iu.mulScalar(-t.radius)),t.center.add2(s.getPosition(),Iu)}else 1===this._type&&(t.center=this._node.getPosition(),t.radius=this.attenuationEnd)},e.getBoundingBox=function(t){if(2===this._type){var e=this.attenuationEnd,i=this._outerConeAngle,n=this._node,s=Math.abs(Math.sin(i*_t.DEG_TO_RAD)*e);t.center.set(0,.5*-e,0),t.halfExtents.set(s,.5*e,s),t.setFromTransformedAabb(t,n.getWorldTransform(),!0)}else 1===this._type&&(t.center.copy(this._node.getPosition()),t.halfExtents.set(this.attenuationEnd,this.attenuationEnd,this.attenuationEnd))},e._updateFinalColor=function(){var e=this._color,i=e.r,n=e.g,s=e.b,r=this._intensity;this._usePhysicalUnits&&(r=this._luminance/t.getLightUnitConversion(this._type,this._outerConeAngle*_t.DEG_TO_RAD,this._innerConeAngle*_t.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))},e.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()},e.layersDirty=function(){this.layers.forEach((function(t){t.markLightsDirty()}))},e.updateKey=function(){var t=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|Du[this._cookieChannel.charAt(0)]<<18|(this._cookieTransform?1:0)<<12|this._shape<<10|this.numCascades-1<<8|(this.affectSpecularity?1:0)<<7|this.mask<<6;3===this._cookieChannel.length&&(t|=Du[this._cookieChannel.charAt(1)]<<16,t|=Du[this._cookieChannel.charAt(2)]<<14),t!==this.key&&this.layersDirty(),this.key=t},y(t,[{key:"numCascades",get:function(){return this.cascades.length},set:function(t){this.cascades&&this.numCascades===t||(this.cascades=ku[t-1],this._shadowMatrixPalette=new Float32Array(64),this._shadowCascadeDistances=new Float32Array(4),this._destroyShadowMap(),this.updateKey())}},{key:"shadowMap",get:function(){return this._shadowMap},set:function(t){this._shadowMap!==t&&(this._destroyShadowMap(),this._shadowMap=t)}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask!==t&&(this._mask=t,this.updateKey())}},{key:"numShadowFaces",get:function(){var t=this._type;return 0===t?this.numCascades:1===t?6:1}},{key:"type",get:function(){return this._type},set:function(t){if(this._type!==t){this._type=t,this._destroyShadowMap(),this.updateKey();var e=this._shadowType;this._shadowType=null,this.shadowUpdateOverrides=null,this.shadowType=e}}},{key:"shape",get:function(){return this._shape},set:function(t){if(this._shape!==t){this._shape=t,this._destroyShadowMap(),this.updateKey();var e=this._shadowType;this._shadowType=null,this.shadowType=e}}},{key:"usePhysicalUnits",get:function(){return this._usePhysicalUnits},set:function(t){this._usePhysicalUnits!==t&&(this._usePhysicalUnits=t,this._updateFinalColor())}},{key:"shadowType",get:function(){return this._shadowType},set:function(t){if(this._shadowType!==t){var e=this.device;1===this._type&&0!==t&&6!==t&&(t=0);var i=e.supportsDepthShadow;4!==t||i||(t=0),3!==t||e.textureFloatRenderable&&e.textureFloatFilterable||(t=2),2!==t||e.textureHalfFloatRenderable||(t=1),this._isVsm=t>=1&&t<=3,this._isPcf=5===t||0===t||4===t,this._shadowType=t,this._destroyShadowMap(),this.updateKey()}}},{key:"enabled",get:function(){return this._enabled},set:function(t){this._enabled!==t&&(this._enabled=t,this.layersDirty())}},{key:"castShadows",get:function(){return this._castShadows&&4!==this._mask&&0!==this._mask},set:function(t){this._castShadows!==t&&(this._castShadows=t,this._destroyShadowMap(),this.layersDirty(),this.updateKey())}},{key:"shadowResolution",get:function(){return this._shadowResolution},set:function(t){this._shadowResolution!==t&&(t=1===this._type?Math.min(t,this.device.maxCubeMapSize):Math.min(t,this.device.maxTextureSize),this._shadowResolution=t,this._destroyShadowMap())}},{key:"vsmBlurSize",get:function(){return this._vsmBlurSize},set:function(t){this._vsmBlurSize!==t&&(t%2==0&&t++,this._vsmBlurSize=t)}},{key:"normalOffsetBias",get:function(){return this._normalOffsetBias},set:function(t){this._normalOffsetBias!==t&&((!this._normalOffsetBias&&t||this._normalOffsetBias&&!t)&&this.updateKey(),this._normalOffsetBias=t)}},{key:"falloffMode",get:function(){return this._falloffMode},set:function(t){this._falloffMode!==t&&(this._falloffMode=t,this.updateKey())}},{key:"innerConeAngle",get:function(){return this._innerConeAngle},set:function(t){this._innerConeAngle!==t&&(this._innerConeAngle=t,this._innerConeAngleCos=Math.cos(t*Math.PI/180),this._usePhysicalUnits&&this._updateFinalColor())}},{key:"outerConeAngle",get:function(){return this._outerConeAngle},set:function(t){this._outerConeAngle!==t&&(this._outerConeAngle=t,this._updateOuterAngle(t),this._usePhysicalUnits&&this._updateFinalColor())}},{key:"penumbraSize",get:function(){return this._penumbraSize},set:function(t){this._penumbraSize=t}},{key:"intensity",get:function(){return this._intensity},set:function(t){this._intensity!==t&&(this._intensity=t,this._updateFinalColor())}},{key:"affectSpecularity",get:function(){return this._affectSpecularity},set:function(t){0===this._type&&(this._affectSpecularity=t,this.updateKey())}},{key:"luminance",get:function(){return this._luminance},set:function(t){this._luminance!==t&&(this._luminance=t,this._updateFinalColor())}},{key:"cookieMatrix",get:function(){return this._cookieMatrix||(this._cookieMatrix=new Ft),this._cookieMatrix}},{key:"atlasViewport",get:function(){return this._atlasViewport||(this._atlasViewport=new Pt(0,0,1,1)),this._atlasViewport}},{key:"cookie",get:function(){return this._cookie},set:function(t){this._cookie!==t&&(this._cookie=t,this.updateKey())}},{key:"cookieFalloff",get:function(){return this._cookieFalloff},set:function(t){this._cookieFalloff!==t&&(this._cookieFalloff=t,this.updateKey())}},{key:"cookieChannel",get:function(){return this._cookieChannel},set:function(t){if(this._cookieChannel!==t){if(t.length<3)for(var e=t.charAt(t.length-1),i=3-t.length,n=0;n0&&(e+="varying vec2 uv0;\nuniform highp float morphFactor["+t+"];\n");for(var i=0;i=this.maxSubmitCount&&(s(r,a),r=0,a=!0))}(r>0||0===o&&!this.zeroTextures)&&s(r,a)},e._updateTextureMorph=function(){this.device,(this._activeTargets.length>0||!this.zeroTextures)&&(this.rtPositions&&this._updateTextureRenderTarget(this.rtPositions,"texturePositions"),this.rtNormals&&this._updateTextureRenderTarget(this.rtNormals,"textureNormals"),this.zeroTextures=0===this._activeTargets.length)},e._updateVertexMorph=function(){for(var t=this.maxSubmitCount,e=0;e1e-5){this._activeTargets.length<=e&&(this._activeTargets[e]={});var s=this._activeTargets[e++];s.absWeight=n,s.weight=this.getWeight(i),s.target=t[i]}}this._activeTargets.length=e;var r=this.morph.maxActiveTargets;this._activeTargets.length>r&&(this._activeTargets.sort((function(t,e){return t.absWeightl)return!1;this.morphTextureWidth=c,this.morphTextureHeight=u;var d=!1,f=3,p=$h.float2Half;this._textureFormat===oe&&(d=!0,f=4);for(var m=[],_=0;_0&&(s+=_o.screenDepthPS),s+=_o.particle_cpuVS,e.localSpace&&(s+=_o.particle_localShiftVS),e.animTex&&(s+=this._animTex(e)),e.alignToMotion&&(s+=_o.particle_pointAlongVS),s+=e.mesh?_o.particle_meshVS:r,1===e.normal&&(s+=_o.particle_normalVS),2===e.normal&&(s+=_o.particle_TBNVS),e.stretch>0&&(s+=_o.particle_stretchVS),s+=_o.particle_cpu_endVS,e.soft>0&&(s+=_o.particle_softVS)):(s+=_o.particle_initVS,s+=e.pack8?_o.particleInputRgba8PS:_o.particleInputFloatPS,e.soft>0&&(s+=_o.screenDepthPS),s+=_o.particleVS,e.localSpace&&(s+=_o.particle_localShiftVS),e.animTex&&(s+=this._animTex(e)),e.wrap&&(s+=_o.particle_wrapVS),e.alignToMotion&&(s+=_o.particle_pointAlongVS),s+=e.mesh?_o.particle_meshVS:r,1===e.normal&&(s+=_o.particle_normalVS),2===e.normal&&(s+=_o.particle_TBNVS),e.stretch>0&&(s+=_o.particle_stretchVS),s+=_o.particle_endVS,e.soft>0&&(s+=_o.particle_softVS)),s+="}\n",e.normal>0&&(1===e.normal?n+="\nvarying vec3 Normal;\n":2===e.normal&&(n+="\nvarying mat3 ParticleMat;\n"),n+="\nuniform vec3 lightCube[6];\n"),e.soft&&(n+="\nvarying float vDepth;\n"),0===e.normal&&"none"===e.fog&&(e.srgb=!1),n+=_o.decodePS,n+=xo.gammaCode(e.gamma),n+=xo.tonemapCode(e.toneMap),"linear"===e.fog?n+=_o.fogLinearPS:"exp"===e.fog?n+=_o.fogExpPS:"exp2"===e.fog?n+=_o.fogExp2PS:n+=_o.fogNonePS,2===e.normal&&(n+="\nuniform sampler2D normalMap;\n"),e.soft>0&&(n+=_o.screenDepthPS),n+=_o.particlePS,e.soft>0&&(n+=_o.particle_softPS),1===e.normal&&(n+="\nvec3 normal = Normal;\n"),2===e.normal&&(n+=_o.particle_normalMapPS),e.normal>0&&(n+=e.halflambert?_o.particle_halflambertPS:_o.particle_lambertPS),e.normal>0&&(n+=_o.particle_lightingPS),2===e.blend?n+=_o.particle_blendNormalPS:1===e.blend?n+=_o.particle_blendAddPS:5===e.blend&&(n+=_o.particle_blendMultiplyPS),n+=_o.particle_endPS,ir.createDefinition(t,{name:"ParticleShader",vertexCode:s,fragmentCode:n})},e}(xo),ju=new Xu,qu=1,Yu=new Ft,Ku=new Ft,Zu=new wt,Qu=new wt,$u=new wt,Ju=new wt,td=new wt,ed=new wt,id=new wt,nd=new wt,sd=new wt,rd=new wt,ad=new wt,od=new wt,hd=new wt;function ld(t){return t-Math.floor(t)}function cd(t){return Math.max(Math.min(t,1),0)}function ud(t,e){return t-e*Math.floor(t/e)}function dd(t){var e=ld(t),i=ld(255*t);return[e-=i/255,i-=i/255]}var fd=function(){function t(t){this._emitter=t}var e=t.prototype;return e.calcSpawnPosition=function(t,e,i,n,s){var r=this._emitter,a=Math.random(),o=Math.random(),h=Math.random(),l=Math.random();if(r.useCpu&&(t[4*s+0+2*r.numParticlesPot*4]=a,t[4*s+1+2*r.numParticlesPot*4]=o,t[4*s+2+2*r.numParticlesPot*4]=h),Qu.x=a-.5,Qu.y=o-.5,Qu.z=h-.5,0===r.emitterShape){var c=Math.max(Math.abs(Qu.x),Math.max(Math.abs(Qu.y),Math.abs(Qu.z))),u=c+(.5-c)*i[0],d=c+(.5-c)*i[1],f=c+(.5-c)*i[2];Qu.x=u*(c===Math.abs(Qu.x)?Math.sign(Qu.x):2*Qu.x),Qu.y=d*(c===Math.abs(Qu.y)?Math.sign(Qu.y):2*Qu.y),Qu.z=f*(c===Math.abs(Qu.z)?Math.sign(Qu.z):2*Qu.z),r.localSpace?Zu.copy(e.transformPoint(Qu)):Zu.copy(n).add(e.transformPoint(Qu))}else{Qu.normalize();var p=0===r.emitterRadius?0:r.emitterRadiusInner/r.emitterRadius,m=l*(1-p)+p;r.localSpace?Zu.copy(Qu.mulScalar(m*r.emitterRadius)):Zu.copy(n).add(Qu.mulScalar(m*r.emitterRadius))}var _,v,g,y,x,S=-_t.lerp(r.rate,r.rate2,a)*s;if(r.pack8){var b=(Zu.x-r.worldBounds.center.x)/r.worldBoundsSize.x+.5,w=(Zu.y-r.worldBounds.center.y)/r.worldBoundsSize.y+.5,T=(Zu.z-r.worldBounds.center.z)/r.worldBoundsSize.z+.5,A=_t.lerp(r.startAngle*_t.DEG_TO_RAD,r.startAngle2*_t.DEG_TO_RAD,a);A=A%(2*Math.PI)/(2*Math.PI);var C=dd(b);t[4*s]=C[0],t[4*s+1]=C[1];var E=dd(w);t[4*s+2]=E[0],t[4*s+3]=E[1];var M=dd(T);t[4*s+0+4*r.numParticlesPot]=M[0],t[4*s+1+4*r.numParticlesPot]=M[1];var P=dd(A);t[4*s+2+4*r.numParticlesPot]=P[0],t[4*s+3+4*r.numParticlesPot]=P[1];t[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=(v=ld(_=S=(S+R)/(R+I)),g=ld(255*_),y=ld(65025*_),x=ld(160581375*_),[v-=g/255,g-=y/255,y-=x/255,x-=x/255]);t[4*s+0+4*r.numParticlesPot*3]=L[0],t[4*s+1+4*r.numParticlesPot*3]=L[1],t[4*s+2+4*r.numParticlesPot*3]=L[2],t[4*s+3+4*r.numParticlesPot*3]=L[3]}else t[4*s]=Zu.x,t[4*s+1]=Zu.y,t[4*s+2]=Zu.z,t[4*s+3]=_t.lerp(r.startAngle*_t.DEG_TO_RAD,r.startAngle2*_t.DEG_TO_RAD,a),t[4*s+3+4*r.numParticlesPot]=S},e.update=function(t,e,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++)Yu.data[f]=d.data[f];Ku.copy(Yu),Ku.invert(),xu=u.meshInstance.node.localScale,qu=Math.max(Math.max(xu.x,xu.y),xu.z)}r=null===u.meshInstance.node||u.localSpace?wt.ZERO:u.meshInstance.node.getPosition();for(var p,m,_,v,g,y,x,S,b=u.camera?u.camera._node.getPosition():wt.ZERO,w=u.useMesh?17:15,T=u.precision-1,A=0;A=P)&&this.calcSpawnPosition(i,n,s,r,C);var O=R>0&&R0&&(1===u.emitterShape?(Qu.copy($u).mulScalar(2).sub(wt.ONE).normalize(),ed.add(Qu.mulScalar(u.initialVelocity))):ed.add(wt.FORWARD.mulScalar(u.initialVelocity))),td.x+=(id.x-td.x)*$u.x,td.y+=(id.y-td.y)*$u.y,td.z+=(id.z-td.z)*$u.z,_+=(v-_)*$u.y,L=(L+1e4*E%1*(g-L))*qu,D=1e3*E%1*(x-y),u.meshInstance.node&&(u.localSpace?(ed.x/=xu.x,ed.y/=xu.y,ed.z/=xu.z):Yu.transformPoint(ed,ed)),u.localSpace?(Ku.transformPoint(td,td),ed.add(td).add(sd)):(ed.add(td.mul(xu)),ed.add(sd.mul(xu))),od.copy(ed),rd.copy(Ju).add(ed.mulScalar(a)),ad.copy(rd),i[4*C]=ad.x,i[4*C+1]=ad.y,i[4*C+2]=ad.z,i[4*C+3]+=_*a,u.wrap&&u.wrapBounds&&(u.localSpace||ad.sub(r),ad.x=ud(ad.x,u.wrapBounds.x)-.5*u.wrapBounds.x,ad.y=ud(ad.y,u.wrapBounds.y)-.5*u.wrapBounds.y,ad.z=ud(ad.z,u.wrapBounds.z)-.5*u.wrapBounds.z,u.localSpace||ad.add(r)),u.sort>0&&(1===u.sort?(hd.copy(ad).sub(b),u.particleDistance[C]=-(hd.x*hd.x+hd.y*hd.y+hd.z*hd.z)):2===u.sort?u.particleDistance[C]=R:3===u.sort&&(u.particleDistance[C]=-R))),o?R<0&&(i[4*C+3+2*u.numParticlesPot*4]=-1):(R>=P&&(R-=Math.max(P,(u.numParticles-1)*M),i[4*C+3+2*u.numParticlesPot*4]=u.loop?1:-1),R<0&&u.loop&&(i[4*C+3+2*u.numParticlesPot*4]=1)),i[4*C+3+2*u.numParticlesPot*4]<0&&(O=!1),i[4*C+3+4*u.numParticlesPot]=R;for(var k=0;k0&&u.camera){for(var V=u.useMesh?6:4,G=u.particleDistance,H=0;Ht.maxTextureSize&&(this.numParticles=t.maxTextureSize),Dd("rate",1),Dd("rate2",this.rate),Dd("lifetime",50),Dd("emitterExtents",new wt(0,0,0)),Dd("emitterExtentsInner",new wt(0,0,0)),Dd("emitterRadius",0),Dd("emitterRadiusInner",0),Dd("emitterShape",0),Dd("initialVelocity",1),Dd("wrap",!1),Dd("localSpace",!1),Dd("screenSpace",!1),Dd("wrapBounds",null),Dd("colorMap",this.defaultParamTexture),Dd("normalMap",null),Dd("loop",!0),Dd("preWarm",!1),Dd("sort",0),Dd("mode",0),Dd("scene",null),Dd("lighting",!1),Dd("halfLambert",!1),Dd("intensity",1),Dd("stretch",0),Dd("alignToMotion",!1),Dd("depthSoftening",0),Dd("mesh",null),Dd("particleNormal",new wt(0,1,0)),Dd("orientation",0),Dd("depthWrite",!1),Dd("noFog",!1),Dd("blendType",2),Dd("node",null),Dd("startAngle",0),Dd("startAngle2",this.startAngle),Dd("animTilesX",1),Dd("animTilesY",1),Dd("animStartFrame",0),Dd("animNumFrames",1),Dd("animNumAnimations",1),Dd("animIndex",0),Dd("randomizeAnimIndex",!1),Dd("animSpeed",1),Dd("animLoop",!0),this._gpuUpdater=new vd(this,i),this._cpuUpdater=new fd(this),this.emitterPosUniform=new Float32Array(3),this.wrapBoundsUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),Dd("colorGraph",Cd),Dd("colorGraph2",this.colorGraph),Dd("scaleGraph",Td),Dd("scaleGraph2",this.scaleGraph),Dd("alphaGraph",Td),Dd("alphaGraph2",this.alphaGraph),Dd("localVelocityGraph",Ad),Dd("localVelocityGraph2",this.localVelocityGraph),Dd("velocityGraph",Ad),Dd("velocityGraph2",this.velocityGraph),Dd("rotationSpeedGraph",wd),Dd("rotationSpeedGraph2",this.rotationSpeedGraph),Dd("radialSpeedGraph",wd),Dd("radialSpeedGraph2",this.radialSpeedGraph),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=!t.supportsGpuParticles,this.pack8=!0,this.localBounds=new Ht,this.worldBoundsNoTrail=new Ht,this.worldBoundsTrail=[new Ht,new Ht],this.worldBounds=new Ht,this.worldBoundsSize=new wt,this.prevWorldBoundsSize=new wt,this.prevWorldBoundsCenter=new wt,this.prevEmitterExtents=this.emitterExtents,this.prevEmitterRadius=this.emitterRadius,this.worldBoundsMul=new wt,this.worldBoundsAdd=new wt,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 e=t.prototype;return e.onChangeCamera=function(){this.regenShader(),this.resetMaterial()},e.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},e.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 t=this.node.getWorldTransform();this.localSpace?this.worldBoundsNoTrail.copy(this.localBounds):this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,t),this.worldBoundsTrail[0].add(this.worldBoundsNoTrail),this.worldBoundsTrail[1].add(this.worldBoundsNoTrail);var e=this.simTimeTotal;e>=this.timeToSwitchBounds&&(this.worldBoundsTrail[0].copy(this.worldBoundsTrail[1]),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.timeToSwitchBounds=e+this.lifetime),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.localSpace?(this.meshInstance.aabb.setFromTransformedAabb(this.worldBounds,t),this.meshInstance.mesh.aabb.setFromTransformedAabb(this.worldBounds,t)):(this.meshInstance.aabb.copy(this.worldBounds),this.meshInstance.mesh.aabb.copy(this.worldBounds)),this.meshInstance._aabbVer=1-this.meshInstance._aabbVer,this.pack8&&this.calculateBoundsMad()}},e.resetWorldBounds=function(){this.node&&(this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,this.localSpace?Ft.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)},e.calculateLocalBounds=function(){for(var t,e,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],v=[0,0],g=[0,0],y=0;y0||t.maxVertexTextures<=1||t.fragmentUniformsCount<64||t.forceCpuParticles||!t.extTextureFloat,this._destroyResources(),this.pack8=(this.pack8||!t.textureFloatRenderable)&&!this.useCpu,Ed=this.useCpu||this.pack8?4:2,this.useMesh=!1,this.mesh)&&(this.numParticles*this.mesh.vertexBuffer.numVertices>65535||(this.useMesh=!0));this.numParticlesPot=_t.nextPowerOfTwo(this.numParticles),this.rebuildGraphs(),this.calculateLocalBounds(),this.resetWorldBounds(),this.node&&(this.worldBounds.setFromTransformedAabb(this.localBounds,this.localSpace?Ft.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 e=0;e=1&&(this.animTilesX>1||this.animTilesY>1)&&(this.colorMap&&this.colorMap!==this.defaultParamTexture||this.normalMap)},e.rebuildGraphs=function(){var t=this.precision,e=this.graphicsDevice;this.qLocalVelocity=this.localVelocityGraph.quantize(t),this.qVelocity=this.velocityGraph.quantize(t),this.qColor=this.colorGraph.quantizeClamped(t,0,1),this.qRotSpeed=this.rotationSpeedGraph.quantize(t),this.qScale=this.scaleGraph.quantize(t),this.qAlpha=this.alphaGraph.quantize(t),this.qRadialSpeed=this.radialSpeedGraph.quantize(t),this.qLocalVelocity2=this.localVelocityGraph2.quantize(t),this.qVelocity2=this.velocityGraph2.quantize(t),this.qColor2=this.colorGraph2.quantizeClamped(t,0,1),this.qRotSpeed2=this.rotationSpeedGraph2.quantize(t),this.qScale2=this.scaleGraph2.quantize(t),this.qAlpha2=this.alphaGraph2.quantize(t),this.qRadialSpeed2=this.radialSpeedGraph2.quantize(t);for(var i=0;i0&&t.setParameter("softening",1/(this.depthSoftening*this.depthSoftening*100)),this.stretch>0&&(t.cull=se),this._compParticleFaceParams()},e._compParticleFaceParams=function(){var t,e;if(0===this.orientation)t=new Float32Array([1,0,0]),e=new Float32Array([0,0,1]);else{var i;if(1===this.orientation)i=this.particleNormal.normalize();else i=(null===this.node?Ft.IDENTITY:this.node.getWorldTransform()).transformVector(this.particleNormal).normalize();var n=new wt(1,0,0);1===Math.abs(n.dot(i))&&n.set(0,0,1);var s=(new wt).cross(i,n).normalize();n.cross(s,i).normalize(),t=new Float32Array([n.x,n.y,n.z]),e=new Float32Array([s.x,s.y,s.z])}this.material.setParameter("faceTangent",t),this.material.setParameter("faceBinorm",e)},e._allocate=function(t){var e=t*this.numParticleVerts,i=t*this.numParticleIndices;if(void 0===this.vertexBuffer||this.vertexBuffer.getNumVertices()!==e){if(this.useCpu){var n=[{semantic:Ne,components:4,type:6},{semantic:ze,components:4,type:6},{semantic:Ve,components:4,type:6},{semantic:Ge,components:1,type:6},{semantic:He,components:this.useMesh?4:2,type:6}],s=new Ji(this.graphicsDevice,n);this.vertexBuffer=new ji(this.graphicsDevice,s,e,1),this.indexBuffer=new vr(this.graphicsDevice,1,i)}else{var r=[{semantic:Ne,components:4,type:6}];this.useMesh&&r.push({semantic:ze,components:2,type:6});var a=new Ji(this.graphicsDevice,r);this.vertexBuffer=new ji(this.graphicsDevice,a,e,1),this.indexBuffer=new vr(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;uthis.endTime&&(this.onFinished&&this.onFinished(),this.meshInstance.visible=!1),this.meshInstance&&(this.meshInstance.drawOrder=this.drawOrder)},e._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)},e.destroy=function(){this.camera=null,this._destroyResources()},y(t,[{key:"defaultParamTexture",get:function(){var t=this;return Ud.get(this.graphicsDevice,(function(){for(var e=16,i=new Float32Array(1024),n=0;n0&&this.material.transparent===e&&(this.mesh.setPositions(this.positions),this.mesh.setColors(this.colors),this.mesh.update(1,!1),this.meshInstance||(this.meshInstance=new yh(this.mesh,this.material,Hd)),this.positions.length=0,this.colors.length=0,t.push(this.meshInstance))},t}(),Xd=function(){function t(t){this.device=t,this.map=new Map}var e=t.prototype;return e.getBatch=function(t,e){var i=this.map.get(t);return i||(i=new Wd(this.device,t,e),this.map.set(t,i)),i},e.onPreRender=function(t,e){this.map.forEach((function(i){i.onPreRender(t,e)}))},t}(),jd=[],qd=function(){function t(t){this.device=t,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 e=t.prototype;return e.createMaterial=function(t){var e=new Vo;return e.vertexColors=!0,e.blendType=2,e.depthTest=t,e.update(),e},e.getBatch=function(t,e){var i=this.batchesMap.get(t);i||(i=new Xd(this.device),this.batchesMap.set(t,i)),this.allBatches.add(i);var n=e?this.materialDepth:this.materialNoDepth;return i.getBatch(n,t)},e.getShader=function(t,e){if(!this[t]){this[t]=bo(this.device,"\n\t\t\t\tattribute vec2 vertex_position;\n\t\t\t\tuniform mat4 matrix_model;\n\t\t\t\tvarying vec2 uv0;\n\t\t\t\tvoid main(void) {\n\t\t\t\t\tgl_Position = matrix_model * vec4(vertex_position, 0, 1);\n\t\t\t\t\tuv0 = vertex_position.xy + 0.5;\n\t\t\t\t}\n\t\t\t",e,"DebugShader:"+t)}return this[t]},e.getTextureShader=function(){return this.getShader("textureShader","\n\t\t\tvarying vec2 uv0;\n\t\t\tuniform sampler2D colorMap;\n\t\t\tvoid main (void) {\n\t\t\t\tgl_FragColor = vec4(texture2D(colorMap, uv0).xyz, 1);\n\t\t\t}\n\t\t")},e.getUnfilterableTextureShader=function(){return this.getShader("textureShaderUnfilterable","\n\t\t\tvarying vec2 uv0;\n\t\t\tuniform highp sampler2D colorMap;\n\t\t\tvoid main (void) {\n\t\t\t\tivec2 uv = ivec2(uv0 * textureSize(colorMap, 0));\n\t\t\t\tgl_FragColor = vec4(texelFetch(colorMap, uv, 0).xyz, 1);\n\t\t\t}\n\t\t")},e.getDepthTextureShader=function(){return this.getShader("depthTextureShader","\n\t\t\t"+_o.screenDepthPS+"\n\t\t\tvarying vec2 uv0;\n\t\t\tvoid main() {\n\t\t\t\tfloat depth = getLinearScreenDepth(uv0) * camera_params.x;\n\t\t\t\tgl_FragColor = vec4(vec3(depth), 1.0);\n\t\t\t}\n\t\t")},e.getQuadMesh=function(){return this.quadMesh||(this.quadMesh=new qa(this.device),this.quadMesh.setPositions([-.5,-.5,0,.5,-.5,0,-.5,.5,0,.5,.5,0]),this.quadMesh.update(be)),this.quadMesh},e.drawMesh=function(t,e,i,n,s){if(!n){var r=this.getGraphNode(e);n=new yh(i,t,r)}var a=this.layerMeshInstances.get(s);a||(a=[],this.layerMeshInstances.set(s,a)),a.push(n)},e.drawWireAlignedBox=function(t,e,i,n,s){jd.push(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,t.z,e.x,t.y,t.z,e.x,t.y,t.z,t.x,t.y,t.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,e.z,e.x,t.y,e.z,e.x,t.y,e.z,t.x,t.y,e.z,t.x,t.y,t.z,t.x,t.y,e.z,t.x,e.y,t.z,t.x,e.y,e.z,e.x,e.y,t.z,e.x,e.y,e.z,e.x,t.y,t.z,e.x,t.y,e.z),this.getBatch(s,n).addLinesArrays(jd,i),jd.length=0},e.drawWireSphere=function(t,e,i,n,s,r){for(var a=2*Math.PI/n,o=0,h=0;hi){this._time=this.looping?0:i;for(var n=0;n=0?1:-1,l=0;l=0;m+=h){var _=d[m],v=d[m+1];if(_.time<=this._time&&v.time>=this._time){var g=(this._time-_.time)/(v.time-_.time);f._pos.lerp(_.position,v.position,g),f._quat.slerp(_.rotation,v.rotation,g),f._scale.lerp(_.scale,v.scale,g),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)}}}},e.blend=function(t,e,i){for(var n=this._interpolatedKeys.length,s=0;s 0.5) {\n\t\tif (dAtten > 0.00001) {\n\t\t\tdirLm.xyz = dirLm.xyz * 2.0 - vec3(1.0);\n\t\t\tdAtten = saturate(dAtten);\n\t\t\tgl_FragColor.rgb = normalize(dLightDirNormW.xyz*dAtten + dirLm.xyz*dirLm.w) * 0.5 + vec3(0.5);\n\t\t\tgl_FragColor.a = dirLm.w + dAtten;\n\t\t\tgl_FragColor.a = max(gl_FragColor.a, 1.0 / 255.0);\n\t\t} else {\n\t\t\tgl_FragColor = dirLm;\n\t\t}\n\t} else {\n\t\tgl_FragColor.rgb = dirLm.xyz;\n\t\tgl_FragColor.a = max(dirLm.w, dAtten > 0.00001? (1.0/255.0) : 0.0);\n\t}\n",bakeLmEndPS:"\n#ifdef LIGHTMAP_RGBM\n\tgl_FragColor.rgb = dDiffuseLight;\n\tgl_FragColor.rgb = pow(gl_FragColor.rgb, vec3(0.5));\n\tgl_FragColor.rgb /= 8.0;\n\tgl_FragColor.a = clamp( max( max( gl_FragColor.r, gl_FragColor.g ), max( gl_FragColor.b, 1.0 / 255.0 ) ), 0.0,1.0 );\n\tgl_FragColor.a = ceil(gl_FragColor.a * 255.0) / 255.0;\n\tgl_FragColor.rgb /= gl_FragColor.a;\n#else\n\tgl_FragColor = vec4(dDiffuseLight, 1.0);\n#endif\n",dilatePS:"\nvarying vec2 vUv0;\nuniform sampler2D source;\nuniform vec2 pixelOffset;\nvoid main(void) {\n\tvec4 c = texture2D(source, vUv0);\n\tc = c.a>0.0? c : texture2D(source, vUv0 - pixelOffset);\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(0, -pixelOffset.y));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(pixelOffset.x, -pixelOffset.y));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(-pixelOffset.x, 0));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(pixelOffset.x, 0));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(-pixelOffset.x, pixelOffset.y));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(0, pixelOffset.y));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + pixelOffset);\n\tgl_FragColor = c;\n}\n",bilateralDeNoisePS:"\nfloat normpdf3(in vec3 v, in float sigma) {\n\treturn 0.39894 * exp(-0.5 * dot(v, v) / (sigma * sigma)) / sigma;\n}\nvec3 decodeRGBM(vec4 rgbm) {\n\tvec3 color = (8.0 * rgbm.a) * rgbm.rgb;\n\treturn color * color;\n}\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\nvec4 encodeRGBM(vec3 color) {\n\tvec4 encoded;\n\tencoded.rgb = pow(color.rgb, vec3(0.5));\n\tencoded.rgb *= 1.0 / 8.0;\n\tencoded.a = saturate( max( max( encoded.r, encoded.g ), max( encoded.b, 1.0 / 255.0 ) ) );\n\tencoded.a = ceil(encoded.a * 255.0) / 255.0;\n\tencoded.rgb /= encoded.a;\n\treturn encoded;\n}\n#define MSIZE 15\nvarying vec2 vUv0;\nuniform sampler2D source;\nuniform vec2 pixelOffset;\nuniform vec2 sigmas;\nuniform float bZnorm;\nuniform float kernel[MSIZE];\nvoid main(void) {\n\t\n\tvec4 pixelRgbm = texture2D(source, vUv0);\n\tif (pixelRgbm.a <= 0.0) {\n\t\tgl_FragColor = pixelRgbm;\n\t\treturn ;\n\t}\n\tfloat sigma = sigmas.x;\n\tfloat bSigma = sigmas.y;\n\tvec3 pixelHdr = decodeRGBM(pixelRgbm);\n\tvec3 accumulatedHdr = vec3(0.0);\n\tfloat accumulatedFactor = 0.0;\n\tconst int kSize = (MSIZE-1)/2;\n\tfor (int i = -kSize; i <= kSize; ++i) {\n\t\tfor (int j = -kSize; j <= kSize; ++j) {\n\t\t\t\n\t\t\tvec2 coord = vUv0 + vec2(float(i), float(j)) * pixelOffset;\n\t\t\tvec4 rgbm = texture2D(source, coord);\n\t\t\tif (rgbm.a > 0.0) {\n\t\t\t\tvec3 hdr = decodeRGBM(rgbm);\n\t\t\t\tfloat factor = kernel[kSize + j] * kernel[kSize + i];\n\t\t\t\tfactor *= normpdf3(hdr - pixelHdr, bSigma) * bZnorm;\n\t\t\t\taccumulatedHdr += factor * hdr;\n\t\t\t\taccumulatedFactor += factor;\n\t\t\t}\n\t\t}\n\t}\n\tgl_FragColor = encodeRGBM(accumulatedHdr / accumulatedFactor);\n}\n"},ff="FILL_WINDOW",pf="KEEP_ASPECT",mf="AUTO",_f="FIXED";function vf(){return cf}function gf(t){cf=t,Ha.set(null==t?void 0:t.graphicsDevice)}var yf=function(){function t(){}return t.push=function(e,i){i&&t._types.length>0?console.assert("Script Ordering Error. Contact support@playcanvas.com"):t._types.push(e)},t}();yf._types=[];var xf=!1,Sf=!1,bf={app:null,create:function(t,e){if(xf){var i=e(bf.app);i._pcScriptName=t,yf.push(i,xf),this.fire("created",t,e)}},attribute:function(t,e,i,n){},createLoadingScreen:function(t){Sf||(Sf=!0,t(vf()))}};Object.defineProperty(bf,"legacy",{get:function(){return xf},set:function(t){xf=t}}),R.attach(bf);var wf=function(){function t(){this.renderPasses=[],this.renderTargetMap=new Map}var e=t.prototype;return e.addRenderPass=function(t){this.renderPasses.push(t)},e.reset=function(){this.renderPasses.length=0},e.compile=function(){for(var t=this.renderTargetMap,e=this.renderPasses,i=0;i=0&&t<=1?0:1})),Rf(["fr","pt"],(function(t){return t>=0&&t<2?0:1})),Rf(["da"],(function(t){return 1===t||!Number.isInteger(t)&&t>=0&&t<=1?0:1})),Rf(["de","en","it","el","es","tr","fi","sv","nb","no","ur"],(function(t){return 1===t?0:1})),Rf(["ru","uk"],(function(t){if(Number.isInteger(t)){var e=t%10,i=t%100;if(1===e&&11!==i)return 0;if(e>=2&&e<=4&&(i<12||i>14))return 1;if(0===e||e>=5&&e<=9||i>=11&&i<=14)return 2}return 3})),Rf(["pl"],(function(t){if(Number.isInteger(t)){if(1===t)return 0;var e=t%10,i=t%100;if(e>=2&&e<=4&&(i<12||i>14))return 1;if(e>=0&&e<=1||e>=5&&e<=9||i>=12&&i<=14)return 2}return 3})),Rf(["ar"],(function(t){if(0===t)return 0;if(1===t)return 1;if(2===t)return 2;if(Number.isInteger(t)){var e=t%100;if(e>=3&&e<=10)return 3;if(e>=11&&e<=99)return 4}return 5}));var Df=Pf[If(Ef)];function Of(t){return Pf[t]||Df}var kf,Ff=new RegExp("^\\s*(?:(?:[a-z]+[a-z0-9\\-\\+\\.]*:)?//|data:|blob:)","i"),Bf=function(){function t(t,e,i,n,s,r){void 0===t&&(t=""),void 0===e&&(e=""),void 0===i&&(i=null),void 0===n&&(n=null),void 0===s&&(s=null),void 0===r&&(r=null),this.url=t,this.filename=e,this.hash=i,this.size=n,this.opt=s,this.contents=r}return t.prototype.equals=function(t){return this.url===t.url&&this.filename===t.filename&&this.hash===t.hash&&this.size===t.size&&this.opt===t.opt&&this.contents===t.contents},t}(),Uf=-1,Nf={pvr:"extCompressedTexturePVRTC",dxt:"extCompressedTextureS3TC",etc2:"extCompressedTextureETC",etc1:"extCompressedTextureETC1",basis:"canvas"},zf=["pvr","dxt","etc2","etc1","basis"],Vf=function(t){function e(e,i,n,s,r){var a;return(a=t.call(this)||this)._id=Uf--,a._name=e||"",a.type=i,a.tags=new ut(w(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}S(e,t);var i=e.prototype;return i.getFileUrl=function(){var t=this.file;if(!t||!t.url)return null;var e=t.url;if(this.registry&&this.registry.prefix&&!Ff.test(e)&&(e=this.registry.prefix+e),"script"!==this.type&&t.hash){var i=-1!==e.indexOf("?")?"&":"?";e+=i+"t="+t.hash}return e},i.getAbsoluteUrl=function(t){if(t.startsWith("blob:")||t.startsWith("data:"))return t;var e=L.getDirectory(this.file.url);return L.join(e,t)},i.getLocalizedAssetId=function(t){return t=Lf(t,this._i18n),this._i18n[t]||null},i.addLocalizedAssetId=function(t,e){this._i18n[t]=e,this.fire("add:localized",t,e)},i.removeLocalizedAssetId=function(t){var e=this._i18n[t];e&&(delete this._i18n[t],this.fire("remove:localized",t,e))},i.ready=function(t,e){e=e||this,this.loaded?t.call(e,this):this.once("load",(function(i){t.call(e,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 t=this._resources;this.resources=[],this.loaded=!1,this.file&&this.registry._loader.clearCache(this.getFileUrl(),this.type);for(var e=0;e0,maxRetries:n},e)},y(e,[{key:"id",get:function(){return this._id},set:function(t){this._id=t}},{key:"name",get:function(){return this._name},set:function(t){if(this._name!==t){var e=this._name;this._name=t,this.fire("name",this,this._name,e)}}},{key:"file",get:function(){return this._file},set:function(t){var e=this;if(t&&t.variants&&-1!==["texture","textureatlas","bundle"].indexOf(this.type)){var i,n=(null==(i=this.registry)||null==(i=i._loader)?void 0:i._app)||vf(),s=null==n?void 0:n.graphicsDevice;if(s)for(var r=function(){var i=zf[a];if(t.variants[i]&&s[Nf[i]])return t=t.variants[i],0;if(n.enableBundles){var r=n.bundles.listBundlesForAsset(e);if(r&&r.find((function(t){var e;return null==t||null==(e=t.file)?void 0:e.variants[i]})))return 0}},a=0,o=zf.length;a=s)throw new Error("Invalid PAX header data format.");var l=parseInt(e.decode(new Uint8Array(t,i+a,h-a)),10),c=e.decode(new Uint8Array(t,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(t){for(var e=0;e0&&(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(t){if(!e)return console.error("Cannot untar because TextDecoder interface is not available for this platform."),[];for(var i=[];this._hasNext();){var n=this._readNextFile();n&&(t&&n.name&&(n.name=t+n.name),i.push(n))}return i},t&&(self.onmessage=function(t){var e=t.data.id;try{var i=new s(t.data.arrayBuffer).untar(t.data.prefix);postMessage({id:e,files:i,arrayBuffer:t.data.arrayBuffer},[t.data.arrayBuffer])}catch(t){postMessage({id:e,error:t.toString()})}})}var Yf=null;var Kf=function(){function t(t){this._requestId=0,this._pendingRequests={},this._filenamePrefix=t,this._worker=new Worker(function(){if(!Yf){var t="("+qf.toString()+")(true)\n\n",e=new Blob([t],{type:"application/javascript"});Yf=URL.createObjectURL(e)}return Yf}()),this._worker.addEventListener("message",this._onMessage.bind(this))}var e=t.prototype;return e._onMessage=function(t){var e=t.data.id;if(this._pendingRequests[e]){var i=this._pendingRequests[e];if(delete this._pendingRequests[e],t.data.error)i(t.data.error);else{for(var n=t.data.arrayBuffer,s=0,r=t.data.files.length;s0},e.destroy=function(){this._worker&&(this._worker.terminate(),this._worker=null,this._pendingRequests=null)},t}();qf();var Zf=function(){function t(t){this.handlerType="bundle",this._assets=t.assets,this._worker=null,this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t});var i=this;_a.get(t.load,{responseType:ma.ResponseType.ARRAY_BUFFER,retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(n,s){if(n)e("Error loading bundle resource "+t.original+": "+n);else try{i._untar(s,e)}catch(i){e("Error loading bundle resource "+t.original+": "+i)}}))},e._untar=function(t,e){var i=this;if(G.workers)i._worker||(i._worker=new Kf(i._assets.prefix)),i._worker.untar(t,(function(t,n){e(t,n),i._worker.hasPendingRequests()||(i._worker.destroy(),i._worker=null)}));else{var n=new kf(t).untar(i._assets.prefix);e(null,n)}},e.open=function(t,e){return new jf(e)},e.patch=function(t,e){},t}(),Qf=function(){function t(t){this._handlers={},this._requests={},this._cache={},this._app=t}var e=t.prototype;return e.addHandler=function(t,e){this._handlers[t]=e,e._loader=this},e.removeHandler=function(t){delete this._handlers[t]},e.getHandler=function(t){return this._handlers[t]},t.makeKey=function(t,e){return t+"-"+e},e.load=function(e,i,n,s){var r=this._handlers[i];if(r)if(e){var a=t.makeKey(e,i);if(void 0!==this._cache[a])n(null,this._cache[a]);else if(this._requests[a])this._requests[a].push(n);else{this._requests[a]=[n];var o=this,h=function(t,e){t?o._onFailure(a,t):r.load(e,(function(t,i,n){if(o._requests[a])if(t)o._onFailure(a,t);else try{o._onSuccess(a,r.open(e.original,i,s),n)}catch(t){o._onFailure(a,t)}}),s)},l=e.split("?")[0];if(this._app.enableBundles&&this._app.bundles.hasUrl(l)){if(!this._app.bundles.canLoadUrl(l))return void h("Bundle for "+e+" not loaded yet");this._app.bundles.loadUrl(l,(function(t,e){h(t,{load:e,original:l})}))}else h(null,{load:e,original:s&&s.file.filename||e})}}else this._loadNull(r,n,s);else n("No resource handler for asset type: '"+i+"' when loading ["+e+"]")},e._loadNull=function(t,e,i){t.load(null,(function(n,s,r){if(n)e(n);else try{e(null,t.open(null,s,i),r)}catch(t){e(t)}}),i)},e._onSuccess=function(t,e,i){null!==e?this._cache[t]=e:delete this._cache[t];for(var n=0;n0&&this.loader.enableRetry(t.maxAssetRetries),t.useDevicePixelRatio||(t.useDevicePixelRatio=t.use_device_pixel_ratio),t.resolutionMode||(t.resolutionMode=t.resolution_mode),t.fillMode||(t.fillMode=t.fill_mode),this._width=t.width,this._height=t.height,t.useDevicePixelRatio&&(this.graphicsDevice.maxPixelRatio=window.devicePixelRatio),this.setCanvasResolution(t.resolutionMode,this._width,this._height),this.setCanvasFillMode(t.fillMode,this._width,this._height),t.layers&&t.layerOrder){var i=new Ru("application"),n={};for(var s in t.layers){var r=t.layers[s];r.id=parseInt(s,10),r.enabled=1!==r.id,n[s]=new Cu(r)}for(var a=0,o=t.layerOrder.length;a0,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(t){var e=[];t.settings.priority_scripts&&(e=t.settings.priority_scripts);for(var i=[],n={},s=0;sn._timeToCountFrames?(n.fps=n._fpsAccum,n._fpsAccum=0,n._timeToCountFrames=t+1e3):n._fpsAccum++,this.stats.drawCalls.total=this.graphicsDevice._drawCallsPerFrame,this.graphicsDevice._drawCallsPerFrame=0},n._fillFrameStats=function(){var t=this.stats.frame;t.cameras=this.renderer._camerasRendered,t.materials=this.renderer._materialSwitches,t.shaders=this.graphicsDevice._shaderSwitchesPerFrame,t.shadowMapUpdates=this.renderer._shadowMapUpdates,t.shadowMapTime=this.renderer._shadowMapTime,t.depthMapTime=this.renderer._depthMapTime,t.forwardTime=this.renderer._forwardTime;var e=this.graphicsDevice._primsPerFrame;t.triangles=e[4]/3+Math.max(e[be]-2,0)+Math.max(e[6]-2,0),t.cullTime=this.renderer._cullTime,t.sortTime=this.renderer._sortTime,t.skinTime=this.renderer._skinTime,t.morphTime=this.renderer._morphTime,t.lightClusters=this.renderer._lightClusters,t.lightClustersTime=this.renderer._lightClustersTime,t.otherPrimitives=0;for(var i=0;ii/n?e=(t=i)/s:t=(e=n)*s}else this._fillMode===ff&&(t=i,e=n);return this.graphicsDevice.canvas.style.width=t+"px",this.graphicsDevice.canvas.style.height=e+"px",this.updateCanvasSize(),{width:t,height:e}}},n.updateCanvasSize=function(){var t;if(this._allowResize&&(null==(t=this.xr)||!t.active)&&this._resolutionMode===mf){var e=this.graphicsDevice.canvas;this.graphicsDevice.resizeCanvas(e.clientWidth,e.clientHeight)}},n.onLibrariesLoaded=function(){this._librariesLoaded=!0,this.systems.rigidbody&&this.systems.rigidbody.onLibraryLoaded()},n.applySceneSettings=function(t){var e;if(this.systems.rigidbody&&"undefined"!=typeof Ammo){var i=t.physics.gravity;this.systems.rigidbody.gravity.set(i[0],i[1],i[2])}this.scene.applySettings(t),t.render.hasOwnProperty("skybox")&&(t.render.skybox?(e=this.assets.get(t.render.skybox))?this.setSkybox(e):this.assets.once("add:"+t.render.skybox,this.setSkybox,this):this.setSkybox(null))},n.setAreaLightLuts=function(t,e){t&&e&&Cf.set(this.graphicsDevice,t,e)},n.setSkybox=function(t){var e=this;if(t!==this._skyboxAsset){var i=function(){e.setSkybox(null)},n=function(){e.scene.setSkybox(e._skyboxAsset?e._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=t,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 t;null==(t=this.lightmapper)||t.bake(null,this.scene.lightmapMode)},n._firstBatch=function(){var t;null==(t=this.batcher)||t.generate()},n._processTimestamp=function(t){return t},n.drawLine=function(t,e,i,n,s){this.scene.drawLine(t,e,i,n,s)},n.drawLines=function(t,e,i,n){void 0===i&&(i=!0),void 0===n&&(n=this.scene.defaultDrawLayer),this.scene.drawLines(t,e,i,n)},n.drawLineArrays=function(t,e,i,n){void 0===i&&(i=!0),void 0===n&&(n=this.scene.defaultDrawLayer),this.scene.drawLineArrays(t,e,i,n)},n.drawWireSphere=function(t,e,i,n,s,r){void 0===i&&(i=vt.WHITE),void 0===n&&(n=20),void 0===s&&(s=!0),void 0===r&&(r=this.scene.defaultDrawLayer),this.scene.immediate.drawWireSphere(t,e,i,n,s,r)},n.drawWireAlignedBox=function(t,e,i,n,s){void 0===i&&(i=vt.WHITE),void 0===n&&(n=!0),void 0===s&&(s=this.scene.defaultDrawLayer),this.scene.immediate.drawWireAlignedBox(t,e,i,n,s)},n.drawMeshInstance=function(t,e){void 0===e&&(e=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(null,null,null,t,e)},n.drawMesh=function(t,e,i,n){void 0===n&&(n=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(e,i,t,null,n)},n.drawQuad=function(t,e,i){void 0===i&&(i=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(e,t,this.scene.immediate.getQuadMesh(),null,i)},n.drawTexture=function(t,e,i,n,s,r,a,o){if(void 0===a&&(a=this.scene.defaultDrawLayer),void 0===o&&(o=!0),!1!==o||this.graphicsDevice.isWebGPU){var h=new Ft;h.setTRS(new wt(t,e,0),Bt.IDENTITY,new wt(i,-n,0)),r||((r=new zo).cull=se,r.setParameter("colorMap",s),r.shader=o?this.scene.immediate.getTextureShader():this.scene.immediate.getUnfilterableTextureShader(),r.update()),this.drawQuad(h,r,a)}},n.drawDepthTexture=function(t,e,i,n,s){void 0===s&&(s=this.scene.defaultDrawLayer);var r=new zo;r.cull=se,r.shader=this.scene.immediate.getDepthTextureShader(),r.update(),this.drawTexture(t,e,i,n,null,r,s)},n.destroy=function(){var t,e,n,s;if(this._inFrameUpdate)this._destroyRequested=!0;else{var r=this.graphicsDevice.canvas.id;this.fire("destroy",this),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.gamepads&&(this.gamepads.destroy(),this.gamepads=null),this.controller&&(this.controller=null),this.systems.destroy(),this.scene.layers&&this.scene.layers.destroy();for(var a=this.assets.list(),o=0;o0){var n=i.bakeArea;Tc(pp,t,e),pp.mulScalar(.5*n),i._node.rotateLocal(pp.x,0,pp.y)}i._node.getWorldTransform();var s=this.scene.gammaCorrection?2.2:1,r=Math.pow(this.intensity,s);i.intensity=Math.pow(r/e,1/s)},y(e,[{key:"numVirtualLights",get:function(){return 0===this.light.type?this.light.bakeNumSamples:1}}]),e}(fp),_p=new wt,vp=function(t){function e(e){var i=new ip("AmbientLight");return i.addComponent("light",{type:"directional",affectDynamic:!0,affectLightmapped:!1,bake:!0,bakeNumSamples:e.ambientBakeNumSamples,castShadows:!0,normalOffsetBias:.05,shadowBias:.2,shadowDistance:1,shadowResolution:2048,shadowType:0,color:vt.WHITE,intensity:1,bakeDir:!1}),t.call(this,e,i.light.light)||this}return S(e,t),e.prototype.prepareVirtualLight=function(t,e){Ac(_p,t,e,0,this.scene.ambientBakeSpherePart),this.light._node.lookAt(_p.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/e,1/i)},y(e,[{key:"numVirtualLights",get:function(){return this.light.bakeNumSamples}}]),e}(fp),gp=function(){function t(t,e){void 0===e&&(e=null),this.node=t,this.component=t.render||t.model,e=e||this.component.meshInstances,this.store(),this.meshInstances=e,this.bounds=null,this.renderTargets=[]}var e=t.prototype;return e.store=function(){this.castShadows=this.component.castShadows},e.restore=function(){this.component.castShadows=this.castShadows},t}(),yp=function(){function t(t){this.device=t,this.shaderDilate=bo(t,_o.fullscreenQuadVS,df.dilatePS,"lmDilate"),this.constantTexSource=t.scope.resolve("source"),this.constantPixelOffset=t.scope.resolve("pixelOffset"),this.pixelOffset=new Float32Array(2),this.shaderDenoise=null,this.sigmas=null,this.constantSigmas=null,this.kernel=null}var e=t.prototype;return e.setSourceTexture=function(t){this.constantTexSource.setValue(t)},e.prepare=function(t,e){this.pixelOffset[0]=1/t,this.pixelOffset[1]=1/e,this.constantPixelOffset.setValue(this.pixelOffset)},e.prepareDenoise=function(t,e){this.shaderDenoise||(this.shaderDenoise=bo(this.device,_o.fullscreenQuadVS,df.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]=t,this.sigmas[1]=e,this.constantSigmas.setValue(this.sigmas),this.evaluateDenoiseUniforms(t,e)},e.evaluateDenoiseUniforms=function(t,e){function i(t,e){return.39894*Math.exp(-.5*t*t/(e*e))/e}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,t);n[s+r]=a,n[s-r]=a}this.constantKernel.setValue(this.kernel);var o=1/i(0,e);this.bZnorm.setValue(o)},t}(),xp=new wt,Sp=function(){function t(t,e,i,n,s){this.device=t,this.root=e,this.scene=i,this.renderer=n,this.assets=s,this.shadowMapCache=n.shadowMapCache,this._tempSet=new Set,this._initCalled=!1,this.passMaterials=[],this.ambientAOMaterial=null,this.fog="",this.ambientLight=new vt,this.renderTargets=new Map,this.stats={renderPasses:0,lightmapCount:0,totalRenderTime:0,forwardTime:0,fboTime:0,shadowMapTime:0,compileTime:0,shadersLinked:0}}var e=t.prototype;return e.destroy=function(){var t;ch.decRef(this.blackTex),this.blackTex=null,ch.destroy(),this.device=null,this.root=null,this.scene=null,this.renderer=null,this.assets=null,null==(t=this.camera)||t.destroy(),this.camera=null},e.initBake=function(t){if(!this._initCalled){this._initCalled=!0,this.lightmapFilters=new yp(t),this.constantBakeDir=t.scope.resolve("bakeDir"),this.materials=[],this.blackTex=new Ls(this.device,{width:4,height:4,format:7,type:ii,name:"lightmapBlack"}),ch.incRef(this.blackTex);var e=new Gh;e.clearColor.set(0,0,0,0),e.clearColorBuffer=!0,e.clearDepthBuffer=!1,e.clearStencilBuffer=!1,e.frustumCulling=!1,e.projection=1,e.aspectRatio=1,e.node=new hh,this.camera=e}if(this.scene.clusteredLightingEnabled){var i=new Nu(t.supportsAreaLights,t.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 wt(3,3,3),i.maxLightsPerCell=4,this.worldClusters=new Al(t),this.worldClusters.name="ClusterLightmapper"}},e.finishBake=function(t){function e(t){ch.decRef(t.colorBuffer),t.destroy()}this.materials=[],this.renderTargets.forEach((function(t){e(t)})),this.renderTargets.clear(),t.forEach((function(t){t.renderTargets.forEach((function(t){e(t)})),t.renderTargets.length=0})),this.ambientAOMaterial=null,this.worldClusters&&(this.worldClusters.destroy(),this.worldClusters=null)},e.createMaterialForPass=function(t,e,i,n){var s=new lu;if(s.name="lmMaterial-pass:"+i+"-ambient:"+n,s.chunks.APIVersion=Di,s.chunks.transformVS="#define UV1LAYOUT\n"+_o.transformVS,0===i){var r=df.bakeLmEndPS;n?r="\n dDiffuseLight = ((dDiffuseLight - 0.5) * max("+e.ambientBakeOcclusionContrast.toFixed(1)+" + 1.0, 0.0)) + 0.5;\n dDiffuseLight += vec3("+e.ambientBakeOcclusionBrightness.toFixed(1)+");\n dDiffuseLight = saturate(dDiffuseLight);\n dDiffuseLight *= dAmbientLight;\n "+r:(s.ambient=new vt(0,0,0),s.ambientTint=!0),s.chunks.basePS=_o.basePS+(7===e.lightmapPixelFormat?"\n#define LIGHTMAP_RGBM\n":""),s.chunks.endPS=r,s.lightMap=this.blackTex}else s.chunks.basePS=_o.basePS+"\nuniform sampler2D texture_dirLightMap;\nuniform float bakeDir;\n",s.chunks.endPS=df.bakeDirLmEndPS;return s.chunks.outputAlphaPS="\n",s.chunks.outputAlphaOpaquePS="\n",s.chunks.outputAlphaPremulPS="\n",s.cull=se,s.forceUv1=!0,s.update(),s},e.createMaterials=function(t,e,i){for(var n=0;n0&&e.push(new gp(t,l))}}for(var d=0;d0){this.renderer.shadowRenderer.frameUpdate();var c=1===e?2:1;this.setLightmapping(o,!1,c),this.initBake(i),this.bakeInternal(c,o,h);var u=64;1===e&&(u|=ka),this.scene.ambientBake&&(u|=Va),this.setLightmapping(o,!0,c,u),this.finishBake(o)}var d=dt();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}},e.allocateTextures=function(t,e){for(var i=0;i0){e.copy(t[0].aabb);for(var i=1;i1&&b>1&&y.light.bakeDir&&(b=1);for(var w=0;w1&&y.prepareVirtualLight(w,b),y.startBake();var T=!1,A=this.lightCameraPrepare(r,y);for(_=0;_0&&w>0)&&!(x&&m>0);m++){var M=C.renderTargets[m],P=C.renderTargets[m].colorBuffer.width,R=this.renderTargets.get(P),I=R.colorBuffer;0===m?g=n.updateShaders:g&&(n.updateShaders=!0);var L=this.passMaterials[m];for(x&&w+1===b&&0===m&&(L=this.ambientAOMaterial),u=0;u=this._right){var i=e.length;if(i)if(t=e[i-1])this._left=e[i-1],this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=i-1;else{var n=this._findKey(t,e);this._left=e[n],this._right=e[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:(t-this._left)*this._recip,this._hermite.valid=!1},e._findKey=function(t,e){for(var i=0;t>=e[i+1];)i++;return i},e.eval=function(t,e,i){var n=i._data,s=i._components,r=this._p0*s;if(0===e)for(var a=0;a=t)},e.nextEventBehindTime=function(t){return!!this.nextEvent&&(t===this.track.duration?this.isReverse?this.nextEvent.time>=t:this.nextEvent.time<=t:this.isReverse?this.nextEvent.time>t:this.nextEvent.time=this.track.events.length?this._eventCursor=0:this._eventCursor<0&&(this._eventCursor=this.track.events.length-1)},e.clipFrameTime=function(e){var i=t.eventFrame;i.start=0,i.end=e,i.residual=0,this.isReverse?e<0&&(i.start=this.track.duration,i.end=0,i.residual=e+this.track.duration):e>this.track.duration&&(i.start=0,i.end=this.track.duration,i.residual=e-this.track.duration)},e.alignCursorToCurrentTime=function(){for(this.resetEventCursor();this.nextEventBehindTime(this._time)&&this._eventCursor!==this.eventCursorEnd;)this.moveEventCursor()},e.fireNextEvent=function(){this._eventHandler.fire(this.nextEvent.name,x({track:this.track},this.nextEvent)),this.moveEventCursor()},e.fireNextEventInFrame=function(t,e){return!(!this.nextEventAheadOfTime(t)||!this.nextEventBehindTime(e))&&(this.fireNextEvent(),!0)},e.activeEventsForFrame=function(e,i){var n=t.eventFrame;this.clipFrameTime(i);for(var s=this.eventCursor;this.fireNextEventInFrame(e,n.end)&&s!==this.eventCursor;);this.loop&&Math.abs(n.residual)>0&&this.activeEventsForFrame(n.start,n.residual)},e.progressForTime=function(t){return t*this._speed/this._track.duration},e._update=function(t){if(this._playing){var e=this._time,i=this._track.duration,n=this._speed,s=this._loop;this._track.events.length>0&&i>0&&this.activeEventsForFrame(e,e+n*t),e+=n*t,n>=0?e>i&&(s?e=e%i||0:(e=this._track.duration,this.pause())):e<0&&(s?e=i+(e%i||0):(e=0,this.pause())),this._time=e}this._time!==this._snapshot._time&&this._track.eval(this._time,this._snapshot)},e.play=function(){this._playing=!0,this._time=0},e.stop=function(){this._playing=!1,this._time=0},e.pause=function(){this._playing=!1},e.resume=function(){this._playing=!0},e.reset=function(){this._time=0},y(t,[{key:"name",get:function(){return this._name},set:function(t){this._name=t}},{key:"track",get:function(){return this._track},set:function(t){this._track=t,this._snapshot=new Cp(t)}},{key:"snapshot",get:function(){return this._snapshot}},{key:"time",get:function(){return this._time},set:function(t){this._time=t,this.alignCursorToCurrentTime()}},{key:"speed",get:function(){return this._speed},set:function(t){var e=Math.sign(t)!==Math.sign(this._speed);this._speed=t,e&&this.alignCursorToCurrentTime()}},{key:"loop",get:function(){return this._loop},set:function(t){this._loop=t}},{key:"blendWeight",get:function(){return this._blendWeight},set:function(t){this._blendWeight=t}},{key:"blendOrder",get:function(){return this._blendOrder},set:function(t){this._blendOrder=t}},{key:"eventCursor",get:function(){return this._eventCursor},set:function(t){this._eventCursor=t}},{key:"eventCursorEnd",get:function(){return this.isReverse?0:this._track.events.length-1}},{key:"nextEvent",get:function(){return this._track.events[this._eventCursor]}},{key:"isReverse",get:function(){return this._speed<0}}]),t}();Ep.eventFrame={start:0,end:0,residual:0};var Mp="NONE",Pp="PREV_STATE",Rp="NEXT_STATE",Ip="PREV_STATE_NEXT_STATE",Lp="NEXT_STATE_PREV_STATE",Dp="GREATER_THAN",Op="LESS_THAN",kp="GREATER_THAN_EQUAL_TO",Fp="LESS_THAN_EQUAL_TO",Bp="EQUAL_TO",Up="NOT_EQUAL_TO",Np="INTEGER",zp="FLOAT",Vp="BOOLEAN",Gp="TRIGGER",Hp="2D_DIRECTIONAL",Wp="2D_CARTESIAN",Xp="DIRECT",jp="START",qp="END",Yp="ANY",Kp=[jp,qp,Yp],Zp="OVERWRITE",Qp="ADDITIVE",$p=function(){function t(){}return t.dot=function(t,e){for(var i=t.length,n=0,s=0;s0){i=1/Math.sqrt(i);for(var n=e.length,s=0;s0&&(r=1/Math.sqrt(r));for(var a=0;a0;)this.removeClip(0)},e.updateClipTrack=function(t,e){this._clips.forEach((function(i){i.name.includes(t)&&(i.track=e)})),this.rebind()},e.findClip=function(t){for(var e=this._clips,i=0;i0&&a._update(t),!e)break;var c=void 0,u=void 0,d=void 0;if(l>=1)for(var f=0;f0)for(var p=0;p0&&i.push(n),i},t.encode=function(t,e,i){return(Array.isArray(t)?t.join("/"):t)+"/"+e+"/"+(Array.isArray(i)?i.join("/"):i)};var e=t.prototype;return e.resolve=function(t){return null},e.unresolve=function(t){},e.update=function(t){},t}(),rm=function(){function t(t,e,i,n){t.set?(this._set=t.set,this._get=t.get):this._set=t,this._type=e,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 y(t,[{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}}]),t}(),am=function(){function t(e){var i=this;if(this._isPathInMask=function(t,e){var n=i._mask[t];return!!n&&!!(n.children||e&&!1!==n.value)},this.graph=e,e){this._mask=null;var n={};!function t(e){n[e.name]=e;for(var i=0;i0&&!!this.prevAnim,this.blending&&(this.blend=0,this.blendSpeed=1/e),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 Ep(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(t){return this.animations[t]},i.setModel=function(t){t!==this.model&&(this._resetAnimationController(),this.model=t,this.animations&&this.currAnim&&this.animations[this.currAnim]&&this.play(this.currAnim))},i.onSetAnimations=function(){var t=this.entity.model;if(t){var e=t.model;e&&e!==this.model&&this.setModel(e)}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 t=this.model,e=this.animations,i=!1,n=!1;for(var s in e){if(e.hasOwnProperty(s))e[s].constructor===nm?n=!0:i=!0}var r=t.getGraph();i?(this.fromSkel=new rf(r),this.toSkel=new rf(r),this.skeleton=new rf(r),this.skeleton.looping=this.loop,this.skeleton.setGraph(r)):n&&(this.animEvaluator=new em(new am(this.entity)))},i.loadAnimationAssets=function(t){var e=this;if(t&&t.length)for(var i=this.system.app.assets,n=function(t){if(t.resources.length>1)for(var i=0;i1){if(n&&n.length>1)for(var r=0;r1)for(var o=0;o1)for(var h=0;h1)for(var e=0;e0&&this.play(a[0])}},i.onBeforeRemove=function(){for(var t=0;t=1&&(this.blend=1)),this.playing){var e=this.skeleton;if(null!==e&&null!==this.model){if(this.blending)e.blend(this.fromSkel,this.toSkel,this.blend);else{var i=t*this.speed;e.addTime(i),(this.speed>0&&e._time===e.animation.duration&&!this.loop||this.speed<0&&0===e._time&&!this.loop)&&(this.playing=!1)}this.blending&&1===this.blend&&(e.animation=this.toSkel.animation),e.updateGraph()}}var n=this.animEvaluator;if(n){for(var s=0;s1&&(n.clips[1].blendWeight=this.blend),n.update(t)}this.blending&&1===this.blend&&(this.blending=!1)},y(e,[{key:"animations",get:function(){return this._animations},set:function(t){this._animations=t,this.onSetAnimations()}},{key:"assets",get:function(){return this._assets},set:function(t){var e=this._assets;if(e&&e.length)for(var i=0;i0)return t[t.length-1].time}return 0},set:function(t){if(this.skeleton&&(this.skeleton.currentTime=t,this.skeleton.addTime(0),this.skeleton.updateGraph()),this.animEvaluator)for(var e=this.animEvaluator.clips,i=0;i=0)this._animationList[n].animTrack=e;else{var s=this._getNodeFromPath(t);s.animTrack=e,this._animationList.push(s)}this._updateHasAnimations()},e._updateHasAnimations=function(){this._hasAnimations=this._animationList.length>0&&this._animationList.every((function(t){return t.animTrack&&t.animTrack!==nm.EMPTY}))},y(t,[{key:"name",get:function(){return this._name}},{key:"animations",get:function(){return this._animationList},set:function(t){this._animationList=t,this._updateHasAnimations()}},{key:"hasAnimations",get:function(){return this._hasAnimations}},{key:"speed",get:function(){return this._speed},set:function(t){this._speed=t}},{key:"loop",get:function(){return this._loop},set:function(t){this._loop=t}},{key:"nodeCount",get:function(){return this._blendTree&&this._blendTree.constructor!==um?this._blendTree.getNodeCount():1}},{key:"playable",get:function(){return-1!==Kp.indexOf(this.name)||this.animations.length===this.nodeCount}},{key:"looping",get:function(){if(this.animations.length>0){var t=this.name+"."+this.animations[0].animTrack.name,e=this._controller.animEvaluator.findClip(t);if(e)return e.loop}return!1}},{key:"totalWeight",get:function(){for(var t=0,e=0;et&&(t=i.animTrack.duration)}return t}}]),t}(),gm=function(){function t(t){var e=t.from,i=t.to,n=t.time,s=void 0===n?0:n,r=t.priority,a=void 0===r?0:r,o=t.conditions,h=void 0===o?[]:o,l=t.exitTime,c=void 0===l?null:l,u=t.transitionOffset,d=void 0===u?null:u,f=t.interruptionSource,p=void 0===f?Mp:f;this._from=e,this._to=i,this._time=s,this._priority=a,this._conditions=h,this._exitTime=c,this._transitionOffset=d,this._interruptionSource=p}return y(t,[{key:"from",get:function(){return this._from}},{key:"to",get:function(){return this._to},set:function(t){this._to=t}},{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}}]),t}(),ym=function(){function t(t,e,i,n,s,r,a){var o=this;this.findParameter=function(t){return o._findParameter(t)},this._animEvaluator=t,this._states={},this._stateNames=[],this._eventHandler=s,this._findParameter=r,this._consumeTrigger=a;for(var h=0;h"+e];return i||(i=this._transitions.filter((function(i){return i.from===t&&i.to===e})),Mu(i),this._findTransitionsBetweenStatesCache[t+"->"+e]=i),i},e._transitionHasConditionsMet=function(t){for(var e=t.conditions,i=0;in.value))return!1;break;case Op:if(!(s.value=n.value))return!1;break;case Fp:if(!(s.value<=n.value))return!1;break;case Bp:if(s.value!==n.value)return!1;break;case Up:if(s.value===n.value)return!1}}return!0},e._findTransition=function(t,e){var i=this,n=[];if(t&&e)n=n.concat(this._findTransitionsBetweenStates(t,e));else if(this._isTransitioning)switch(this._transitionInterruptionSource){case Pp:n=(n=n.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(Yp));break;case Rp:n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Yp));break;case Ip:n=(n=(n=n.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Yp));break;case Lp:n=(n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(Yp))}else n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Yp));if(n=n.filter((function(t){if(t.to===i.activeStateName)return!1;if(t.hasExitTime){var e=i._getActiveStateProgressForTime(i._timeInStateBefore),n=i._getActiveStateProgressForTime(i._timeInState);if(t.exitTime<1&&i.activeState.loop&&(e-=Math.floor(e),n-=Math.floor(n)),n===e){if(n!==t.exitTime)return null}else if(!(t.exitTime>e&&t.exitTime<=n))return null}return i._transitionHasConditionsMet(t)})),n.length>0){var s=n[0];if(s.to===qp){var r=this._findTransitionsFromState(jp)[0];s.to=r.to}return s}return null},e.updateStateFromTransition=function(t){var e,i,n;this.previousState=t.from?this.activeStateName:null,this.activeState=t.to,this._activeStateDurationDirty=!0;for(var s=0;s0&&t.transitionOffset<1,u=0,d=0;if(c){var f=l.timelineDuration*t.transitionOffset;u=f,d=f}this._timeInState=u,this._timeInStateBefore=d;for(var p=0;p0?n.blendWeight=0:n.blendWeight=l.animations[p].normalizedWeight,n.play(),c)n.time=l.timelineDuration*t.transitionOffset;else{var _=l.speed>=0?0:this.activeStateDuration;n.time=_}}},e._transitionToState=function(t){if(this._findState(t)){var e=this._findTransition(this._activeStateName,t);e||(this._animEvaluator.removeClips(),e=new gm({from:null,to:t})),this.updateStateFromTransition(e)}},e.assignAnimation=function(t,e,i,n){var s=t.split("."),r=this._findState(s[0]);r||(r=new vm(this,s[0],i),this._states[s[0]]=r,this._stateNames.push(s[0])),r.addAnimation(s,e),this._animEvaluator.updateClipTrack(r.name,e),void 0!==i&&(r.speed=i),void 0!==n&&(r.loop=n),!this._playing&&this._activate&&this.playable&&this.play(),this._activeStateDurationDirty=!0},e.removeNodeAnimations=function(t){if(-1!==Kp.indexOf(t))return!1;var e=this._findState(t);return!!e&&(e.animations=[],!0)},e.play=function(t){t&&this._transitionToState(t),this._playing=!0},e.pause=function(){this._playing=!1},e.reset=function(){this._previousStateName=null,this._activeStateName=jp,this._playing=!1,this._currTransitionTime=1,this._totalTransitionTime=1,this._isTransitioning=!1,this._timeInState=0,this._timeInStateBefore=0,this._animEvaluator.removeClips()},e.rebind=function(){this._animEvaluator.rebind()},e.update=function(t){if(this._playing){var e,i,n;(this.activeState.loop||this._timeInStatethis.activeStateDuration&&(this._timeInState=this.activeStateDuration,t=this.activeStateDuration-this._timeInStateBefore));var s=this._findTransition(this._activeStateName);if(s&&this.updateStateFromTransition(s),this._isTransitioning)if(this._currTransitionTime+=t,this._currTransitionTime<=this._totalTransitionTime){for(var r=0!==this._totalTransitionTime?this._currTransitionTime/this._totalTransitionTime:1,a=0;a1){var l=e.length>2?this._resolvePath(t,e.slice(0,-1)):t,c=e[e.length-2];return function(t){n[s]=i(t),l[c]=n}}return function(t){n[s]=i(t)}},i._createAnimTargetForProperty=function(t,i,n){if(this.handlers&&i[0].startsWith("weight."))return this.handlers.weight(t,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(t,s)}var r,a,o,h=this._resolvePath(t,i,!0);if(void 0===h)return null;if("number"==typeof h)r=this._setter(t,i,e._packFloat),a="vector",o=1;else if("boolean"==typeof h)r=this._setter(t,i,e._packBoolean),a="vector",o=1;else if("object"==typeof h)switch(h.constructor){case Et:r=this._setter(t,i,e._packVec2),a="vector",o=2;break;case wt:r=this._setter(t,i,e._packVec3),a="vector",o=3;break;case Pt:r=this._setter(t,i,e._packVec4),a="vector",o=4;break;case vt:r=this._setter(t,i,e._packColor),a="vector",o=4;break;case Bt:r=this._setter(t,i,e._packQuat),a="quaternion",o=4;break;default:return null}return-1!==i.indexOf("material")?new rm((function(e){r(e),t.material.update()}),a,o,n):new rm(r,a,o,n)},i.rebind=function(){this.targetCache={},this.animComponent.rootBone?this.graph=this.animComponent.rootBone:this.graph=this.animComponent.entity;var t={};!function e(i){t[i.name]=i;for(var n=0;n0?this._layers[0]:null}}]),e}(bp),Pm=function(){this.enabled=!0},Rm=["enabled"],Im=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="anim",i.ComponentType=Mm,i.DataType=Pm,i.schema=Rm,i.on("beforeremove",i.onBeforeRemove,w(i)),i.app.systems.on("animationUpdate",i.onAnimationUpdate,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){var s=this;t.prototype.initializeComponentData.call(this,e,i,Rm);var r=["animationAssets","stateGraph","layers","masks"];Object.keys(i).forEach((function(t){r.includes(t)||(e[t]=i[t])})),i.stateGraph&&(e.stateGraph=i.stateGraph,e.loadStateGraph(e.stateGraph)),i.layers?i.layers.forEach((function(t,i){t._controller.states.forEach((function(n){t._controller._states[n]._animationList.forEach((function(n){if(n.animTrack&&n.animTrack!==nm.EMPTY)e.layers[i].assignAnimation(n.name,n.animTrack);else{var r=s.app.assets.get(t._component._animationAssets[t.name+":"+n.name].asset);r&&!r.loaded&&r.once("load",(function(){e.layers[i].assignAnimation(n.name,r.resource)}))}}))}))})):i.animationAssets&&(e.animationAssets=Object.assign(e.animationAssets,i.animationAssets)),i.masks&&Object.keys(i.masks).forEach((function(t){if(e.layers[t]){var n=i.masks[t].mask,s={};Object.keys(n).forEach((function(t){s[decodeURI(t)]=n[t]})),e.layers[t].mask=s}}))},i.onAnimationUpdate=function(t){var e=this.store;for(var i in e)if(e.hasOwnProperty(i)){var n=e[i].entity.anim;n.data.enabled&&n.entity.enabled&&n.playing&&n.update(t)}},i.cloneComponent=function(t,e){var i;t.anim.rootBone&&t.anim.rootBone!==t||(i={},t.anim.layers.forEach((function(t,n){if(t.mask){var s={};Object.keys(t.mask).forEach((function(i){var n=i.split("/");n.shift();var r=[e.name].concat(n).join("/");s[r]=t.mask[i]})),i[n]={mask:s}}})));var n={stateGraphAsset:t.anim.stateGraphAsset,animationAssets:t.anim.animationAssets,speed:t.anim.speed,activate:t.anim.activate,playing:t.anim.playing,rootBone:t.anim.rootBone,stateGraph:t.anim.stateGraph,layers:t.anim.layers,layerIndices:t.anim.layerIndices,parameters:t.anim.parameters,normalizeWeights:t.anim.normalizeWeights,masks:i};return this.addComponent(e,n)},i.onBeforeRemove=function(t,e){e.onBeforeRemove()},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("animationUpdate",this.onAnimationUpdate,this)},e}(wp);bp._buildAccessors(Mm.prototype,Rm);var Lm=function(t){function e(e,i){return t.call(this,e,i)||this}S(e,t);var i=e.prototype;return i.setCurrentListener=function(){if(this.enabled&&this.entity.audiolistener&&this.entity.enabled){this.system.current=this.entity;var t=this.system.current.getPosition();this.system.manager.listener.setPosition(t)}},i.onEnable=function(){this.setCurrentListener()},i.onDisable=function(){this.system.current===this.entity&&(this.system.current=null)},e}(bp),Dm=function(){this.enabled=!0},Om=["enabled"],km=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="audiolistener",i.ComponentType=Lm,i.DataType=Dm,i.schema=Om,i.manager=e.soundManager,i.current=null,i.app.systems.on("update",i.onUpdate,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){n=["enabled"],t.prototype.initializeComponentData.call(this,e,i,n)},i.onUpdate=function(t){if(this.current){var e=this.current.getPosition();this.manager.listener.setPosition(e);var i=this.current.getWorldTransform();this.manager.listener.setOrientation(i)}},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},e}(wp);bp._buildAccessors(Lm.prototype,Om);var Fm=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this).on("set_assets",n.onSetAssets,w(n)),n.on("set_loop",n.onSetLoop,w(n)),n.on("set_volume",n.onSetVolume,w(n)),n.on("set_pitch",n.onSetPitch,w(n)),n.on("set_minDistance",n.onSetMinDistance,w(n)),n.on("set_maxDistance",n.onSetMaxDistance,w(n)),n.on("set_rollOffFactor",n.onSetRollOffFactor,w(n)),n.on("set_distanceModel",n.onSetDistanceModel,w(n)),n.on("set_3d",n.onSet3d,w(n)),n}S(e,t);var i=e.prototype;return i.play=function(t){if(this.enabled&&this.entity.enabled){var e;this.channel&&this.stop();var i=this.data;if(i.sources[t])if(i["3d"]){var n=this.entity.getPosition();e=this.system.manager.playSound3d(i.sources[t],n,i),i.currentSource=t,i.channel=e}else e=this.system.manager.playSound(i.sources[t],i),i.currentSource=t,i.channel=e}},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(t,e,i){var n=[],s=i.length;if(e&&e.length)for(var r=0;r1e-5){var i=this._tweenInfo.lerpColor;i.lerp(this._tweenInfo.from,this._tweenInfo.to,e),this._applyTintImmediately(new vt(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()},e}(bp);function e_(t){return new vt(t.r,t.g,t.b)}var i_=function(){this.enabled=!0,this.active=!0,this.imageEntity=null,this.hitPadding=new Pt,this.transitionMode=0,this.hoverTint=new vt(.75,.75,.75),this.pressedTint=new vt(.5,.5,.5),this.inactiveTint=new vt(.25,.25,.25),this.fadeDuration=0,this.hoverSpriteAsset=null,this.hoverSpriteFrame=0,this.pressedSpriteAsset=null,this.pressedSpriteFrame=0,this.inactiveSpriteAsset=null,this.inactiveSpriteFrame=0},n_=["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"],s_=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="button",i.ComponentType=t_,i.DataType=i_,i.schema=n_,i.on("beforeremove",i._onRemoveComponent,w(i)),i.app.systems.on("update",i.onUpdate,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){t.prototype.initializeComponentData.call(this,e,i,n_)},i.onUpdate=function(t){var e=this.store;for(var i in e){var n=e[i].entity,s=n.button;s.enabled&&n.enabled&&s.onUpdate()}},i._onRemoveComponent=function(t,e){e.onRemove()},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},e}(wp);bp._buildAccessors(t_.prototype,n_);var r_,a_,o_,h_=new wt,l_=new Bt,c_=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._compoundParent=null,n._hasOffset=!1,n.entity.on("insert",n._onInsert,w(n)),n.on("set_type",n.onSetType,w(n)),n.on("set_halfExtents",n.onSetHalfExtents,w(n)),n.on("set_linearOffset",n.onSetOffset,w(n)),n.on("set_angularOffset",n.onSetOffset,w(n)),n.on("set_radius",n.onSetRadius,w(n)),n.on("set_height",n.onSetHeight,w(n)),n.on("set_axis",n.onSetAxis,w(n)),n.on("set_asset",n.onSetAsset,w(n)),n.on("set_renderAsset",n.onSetRenderAsset,w(n)),n.on("set_model",n.onSetModel,w(n)),n.on("set_render",n.onSetRender,w(n)),n}S(e,t);var i=e.prototype;return i.onSetType=function(t,e,i){e!==i&&this.system.changeType(this,e,i)},i.onSetHalfExtents=function(t,e,i){var n=this.data.type;this.data.initialized&&"box"===n&&this.system.recreatePhysicalShapes(this)},i.onSetOffset=function(t,e,i){this._hasOffset=!this.data.linearOffset.equals(wt.ZERO)||!this.data.angularOffset.equals(Bt.IDENTITY),this.data.initialized&&this.system.recreatePhysicalShapes(this)},i.onSetRadius=function(t,e,i){var n=this.data.type;!this.data.initialized||"sphere"!==n&&"capsule"!==n&&"cylinder"!==n&&"cone"!==n||this.system.recreatePhysicalShapes(this)},i.onSetHeight=function(t,e,i){var n=this.data.type;!this.data.initialized||"capsule"!==n&&"cylinder"!==n&&"cone"!==n||this.system.recreatePhysicalShapes(this)},i.onSetAxis=function(t,e,i){var n=this.data.type;!this.data.initialized||"capsule"!==n&&"cylinder"!==n&&"cone"!==n||this.system.recreatePhysicalShapes(this)},i.onSetAsset=function(t,e,i){var n=this.system.app.assets;if(e){var s=n.get(e);s&&s.off("remove",this.onAssetRemoved,this)}if(i){i instanceof Vf&&(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(t,e,i){var n=this.system.app.assets;if(e){var s=n.get(e);s&&s.off("remove",this.onRenderAssetRemoved,this)}if(i){i instanceof Vf&&(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(t,e,i){this.data.initialized&&"mesh"===this.data.type&&this.system.implementations.mesh.doRecreatePhysicalShape(this)},i.onSetRender=function(t,e,i){this.onSetModel(t,e,i)},i.onAssetRemoved=function(t){t.off("remove",this.onAssetRemoved,this),this.data.asset===t.id&&(this.asset=null)},i.onRenderAssetRemoved=function(t){t.off("remove",this.onRenderAssetRemoved,this),this.data.renderAsset===t.id&&(this.renderAsset=null)},i._getCompoundChildShapeIndex=function(t){for(var e=this.data.shape,i=e.getNumChildShapes(),n=0;n-1&&e.rigidbody._triggers.splice(i,1),e.rigidbody.removeBody(t),t.forceActivationState(5)}},t}(),g_=new Ft,y_=new wt,x_=new wt,S_=new Bt,b_=new hh,w_=["enabled","type","halfExtents","linearOffset","angularOffset","radius","axis","height","asset","renderAsset","shape","model","render"],T_=function(){function t(t){this.system=t}var e=t.prototype;return e.beforeInitialize=function(t,e){e.shape=null,e.model=new Gu,e.model.graph=new hh},e.afterInitialize=function(t,e){this.recreatePhysicalShapes(t),t.data.initialized=!0},e.reset=function(t,e){this.beforeInitialize(t,e),this.afterInitialize(t,e)},e.recreatePhysicalShapes=function(t){var e=t.entity,i=t.data;if("undefined"!=typeof Ammo){e.trigger&&(e.trigger.destroy(),delete e.trigger),i.shape&&(t._compoundParent&&(this.system._removeCompoundChild(t._compoundParent,i.shape),t._compoundParent.entity.rigidbody&&t._compoundParent.entity.rigidbody.activate()),this.destroyShape(i)),i.shape=this.createPhysicalShape(t.entity,i);var n=!t._compoundParent;if("compound"!==i.type||t._compoundParent&&t!==t._compoundParent){if("compound"!==i.type&&(t._compoundParent&&t===t._compoundParent&&e.forEach(this.system.implementations.compound._updateEachDescendant,t),!t.rigidbody)){t._compoundParent=null;for(var s=e.parent;s;){if(s.collision&&"compound"===s.collision.type){t._compoundParent=s.collision;break}s=s.parent}}}else t._compoundParent=t,e.forEach(this._addEachDescendant,t);t._compoundParent&&t!==t._compoundParent&&(n&&0===t._compoundParent.shape.getNumChildShapes()?this.system.recreatePhysicalShapes(t._compoundParent):(this.system.updateCompoundChildTransform(e),t._compoundParent.entity.rigidbody&&t._compoundParent.entity.rigidbody.activate())),e.rigidbody?(e.rigidbody.disableSimulation(),e.rigidbody.createBody(),e.enabled&&e.rigidbody.enabled&&e.rigidbody.enableSimulation()):t._compoundParent||(e.trigger?e.trigger.initialize(i):e.trigger=new v_(this.system.app,t,i))}},e.createPhysicalShape=function(t,e){},e.updateTransform=function(t,e,i,n){t.entity.trigger&&t.entity.trigger.updateTransform()},e.destroyShape=function(t){t.shape&&(Ammo.destroy(t.shape),t.shape=null)},e.beforeRemove=function(t,e){e.data.shape&&(e._compoundParent&&!e._compoundParent.entity._destroying&&(this.system._removeCompoundChild(e._compoundParent,e.data.shape),e._compoundParent.entity.rigidbody&&e._compoundParent.entity.rigidbody.activate()),e._compoundParent=null,this.destroyShape(e.data))},e.remove=function(t,e){t.rigidbody&&t.rigidbody.body&&t.rigidbody.disableSimulation(),t.trigger&&(t.trigger.destroy(),delete t.trigger)},e.clone=function(t,e){var i=this.system.store[t.getGuid()],n={enabled:i.data.enabled,type:i.data.type,halfExtents:[i.data.halfExtents.x,i.data.halfExtents.y,i.data.halfExtents.z],linearOffset:[i.data.linearOffset.x,i.data.linearOffset.y,i.data.linearOffset.z],angularOffset:[i.data.angularOffset.x,i.data.angularOffset.y,i.data.angularOffset.z,i.data.angularOffset.w],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(e,n)},t}(),A_=function(t){function e(){return t.apply(this,arguments)||this}return S(e,t),e.prototype.createPhysicalShape=function(t,e){if("undefined"!=typeof Ammo){var i=e.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}},e}(T_),C_=function(t){function e(){return t.apply(this,arguments)||this}return S(e,t),e.prototype.createPhysicalShape=function(t,e){if("undefined"!=typeof Ammo)return new Ammo.btSphereShape(e.radius)},e}(T_),E_=function(t){function e(){return t.apply(this,arguments)||this}return S(e,t),e.prototype.createPhysicalShape=function(t,e){var i,n,s,r=null!=(i=e.axis)?i:1,a=null!=(n=e.radius)?n:.5,o=Math.max((null!=(s=e.height)?s:2)-2*a,0),h=null;if("undefined"!=typeof Ammo)switch(r){case 0:h=new Ammo.btCapsuleShapeX(a,o);break;case 1:h=new Ammo.btCapsuleShape(a,o);break;case 2:h=new Ammo.btCapsuleShapeZ(a,o)}return h},e}(T_),M_=function(t){function e(){return t.apply(this,arguments)||this}return S(e,t),e.prototype.createPhysicalShape=function(t,e){var i,n,s,r=null!=(i=e.axis)?i:1,a=null!=(n=e.radius)?n:.5,o=null!=(s=e.height)?s:1,h=null,l=null;if("undefined"!=typeof Ammo)switch(r){case 0:h=new Ammo.btVector3(.5*o,a,a),l=new Ammo.btCylinderShapeX(h);break;case 1:h=new Ammo.btVector3(a,.5*o,a),l=new Ammo.btCylinderShape(h);break;case 2:h=new Ammo.btVector3(a,a,.5*o),l=new Ammo.btCylinderShapeZ(h)}return h&&Ammo.destroy(h),l},e}(T_),P_=function(t){function e(){return t.apply(this,arguments)||this}return S(e,t),e.prototype.createPhysicalShape=function(t,e){var i,n,s,r=null!=(i=e.axis)?i:1,a=null!=(n=e.radius)?n:.5,o=null!=(s=e.height)?s:1,h=null;if("undefined"!=typeof Ammo)switch(r){case 0:h=new Ammo.btConeShapeX(a,o);break;case 1:h=new Ammo.btConeShape(a,o);break;case 2:h=new Ammo.btConeShapeZ(a,o)}return h},e}(T_),R_=function(t){function e(){return t.apply(this,arguments)||this}S(e,t);var i=e.prototype;return i.beforeInitialize=function(t,e){},i.createAmmoMesh=function(t,e,i){var n;if(this.system._triMeshCache[t.id])n=this.system._triMeshCache[t.id];else{for(var s,r,a=t.vertexBuffer,o=a.getFormat(),h=0;h=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))}},e.setMaterial=function(t){this.meshInstance&&(this.meshInstance.material=t,this.unmaskMeshInstance&&(this.unmaskMeshInstance.material=t))},e.setParameter=function(t,e){this.meshInstance&&(this.meshInstance.setParameter(t,e),this.unmaskMeshInstance&&this.unmaskMeshInstance.setParameter(t,e))},e.deleteParameter=function(t){this.meshInstance&&(this.meshInstance.deleteParameter(t),this.unmaskMeshInstance&&this.unmaskMeshInstance.deleteParameter(t))},e.setUnmaskDrawOrder=function(){if(this.meshInstance){if(this.unmaskMeshInstance){var t=function t(e){var i,n=e.children,s=n.length;if(s){for(var r=0;r0){var s=e.calculatedWidth/e.calculatedHeight;e.fitMode===Xm&&s>this._targetAspectRatio||e.fitMode===jm&&s0&&(this._targetAspectRatio=i.rect.z/i.rect.w)}this.mesh=t?e:this._defaultMesh,this.refreshMesh()},e.refreshMesh=function(){this.mesh&&(this._element._beingInitialized?this._meshDirty=!0:this._updateMesh(this.mesh))},e._updateAabb=function(t){return t.center.set(0,0,0),t.halfExtents.set(.5*this._outerScale.x,.5*this._outerScale.y,.001),t.setFromTransformedAabb(t,this._renderable.node.getWorldTransform()),t},e._toggleMask=function(){this._element._dirtifyMask();var t=this._element._isScreenSpace();this._updateMaterial(t),this._renderable.setMask(!!this._mask)},e._onMaterialLoad=function(t){this.material=t.resource},e._onMaterialAdded=function(t){this._system.app.assets.off("add:"+t.id,this._onMaterialAdded,this),this._materialAsset===t.id&&this._bindMaterialAsset(t)},e._bindMaterialAsset=function(t){this._entity.enabled&&(t.on("load",this._onMaterialLoad,this),t.on("change",this._onMaterialChange,this),t.on("remove",this._onMaterialRemove,this),t.resource?this._onMaterialLoad(t):this._system.app.assets.load(t))},e._unbindMaterialAsset=function(t){t.off("load",this._onMaterialLoad,this),t.off("change",this._onMaterialChange,this),t.off("remove",this._onMaterialRemove,this)},e._onMaterialChange=function(){},e._onMaterialRemove=function(){},e._onTextureAdded=function(t){this._system.app.assets.off("add:"+t.id,this._onTextureAdded,this),this._textureAsset===t.id&&this._bindTextureAsset(t)},e._bindTextureAsset=function(t){this._entity.enabled&&(t.on("load",this._onTextureLoad,this),t.on("change",this._onTextureChange,this),t.on("remove",this._onTextureRemove,this),t.resource?this._onTextureLoad(t):this._system.app.assets.load(t))},e._unbindTextureAsset=function(t){t.off("load",this._onTextureLoad,this),t.off("change",this._onTextureChange,this),t.off("remove",this._onTextureRemove,this)},e._onTextureLoad=function(t){this.texture=t.resource},e._onTextureChange=function(t){},e._onTextureRemove=function(t){},e._onSpriteAssetAdded=function(t){this._system.app.assets.off("add:"+t.id,this._onSpriteAssetAdded,this),this._spriteAsset===t.id&&this._bindSpriteAsset(t)},e._bindSpriteAsset=function(t){this._entity.enabled&&(t.on("load",this._onSpriteAssetLoad,this),t.on("change",this._onSpriteAssetChange,this),t.on("remove",this._onSpriteAssetRemove,this),t.resource?this._onSpriteAssetLoad(t):this._system.app.assets.load(t))},e._unbindSpriteAsset=function(t){t.off("load",this._onSpriteAssetLoad,this),t.off("change",this._onSpriteAssetChange,this),t.off("remove",this._onSpriteAssetRemove,this),t.data.textureAtlasAsset&&this._system.app.assets.off("load:"+t.data.textureAtlasAsset,this._onTextureAtlasLoad,this)},e._onSpriteAssetLoad=function(t){if(t&&t.resource)if(t.resource.atlas)this.sprite=t.resource;else{var e=t.data.textureAtlasAsset;if(e){var i=this._system.app.assets;i.off("load:"+e,this._onTextureAtlasLoad,this),i.once("load:"+e,this._onTextureAtlasLoad,this)}}else this.sprite=null},e._onSpriteAssetChange=function(t){this._onSpriteAssetLoad(t)},e._onSpriteAssetRemove=function(t){},e._bindSprite=function(t){t.on("set:meshes",this._onSpriteMeshesChange,this),t.on("set:pixelsPerUnit",this._onSpritePpuChange,this),t.on("set:atlas",this._onAtlasTextureChange,this),t.atlas&&t.atlas.on("set:texture",this._onAtlasTextureChange,this)},e._unbindSprite=function(t){t.off("set:meshes",this._onSpriteMeshesChange,this),t.off("set:pixelsPerUnit",this._onSpritePpuChange,this),t.off("set:atlas",this._onAtlasTextureChange,this),t.atlas&&t.atlas.off("set:texture",this._onAtlasTextureChange,this)},e._onSpriteMeshesChange=function(){this._sprite&&(this._spriteFrame=_t.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite()},e._onSpritePpuChange=function(){0!==this.sprite.renderMode&&null===this._pixelsPerUnit&&this._updateSprite()},e._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"))},e._onTextureAtlasLoad=function(t){var e=this._spriteAsset;e instanceof Vf?this._onSpriteAssetLoad(e):this._onSpriteAssetLoad(this._system.app.assets.get(e))},e.onEnable=function(){if(this._materialAsset){var t=this._system.app.assets.get(this._materialAsset);t&&t.resource!==this._material&&this._bindMaterialAsset(t)}if(this._textureAsset){var e=this._system.app.assets.get(this._textureAsset);e&&e.resource!==this._texture&&this._bindTextureAsset(e)}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)},e.onDisable=function(){this._element.removeModelFromLayers(this._renderable.model)},e._setStencil=function(t){this._renderable.meshInstance.stencilFront=t,this._renderable.meshInstance.stencilBack=t;var e=0;if(this._element.maskedBy&&(e=this._element.maskedBy.element._image._maskRef),this._renderable.unmaskMeshInstance){var i=new en({ref:e+1,func:2,zpass:5});this._renderable.unmaskMeshInstance.stencilFront=i,this._renderable.unmaskMeshInstance.stencilBack=i}},e._removeMaterialAssetEvents=function(){if(this._materialAsset){var t=this._system.app.assets;t.off("add:"+this._materialAsset,this._onMaterialAdded,this);var e=t.get(this._materialAsset);e&&(e.off("load",this._onMaterialLoad,this),e.off("change",this._onMaterialChange,this),e.off("remove",this._onMaterialRemove,this))}},y(t,[{key:"color",get:function(){return this._color},set:function(t){var e=t.r,i=t.g,n=t.b;this._color.r===e&&this._color.g===i&&this._color.b===n||(this._color.r=e,this._color.g=i,this._color.b=n,this._colorUniform[0]=e,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(t){t!==this._color.a&&(this._color.a=t,this._renderable.setParameter("material_opacity",t)),this._element&&this._element.fire("set:opacity",t)}},{key:"rect",get:function(){return this._rect},set:function(t){var e,i,n,s;t instanceof Pt?(e=t.x,i=t.y,n=t.z,s=t.w):(e=t[0],i=t[1],n=t[2],s=t[3]),e===this._rect.x&&i===this._rect.y&&n===this._rect.z&&s===this._rect.w||(this._rect.set(e,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(t){if(this._material!==t){if(!t){var e=this._element._isScreenSpace();t=this.mask?e?this._system.defaultScreenSpaceImageMaskMaterial:this._system.defaultImageMaskMaterial:e?this._system.defaultScreenSpaceImageMaterial:this._system.defaultImageMaterial}if(this._material=t,this._materialAsset){var i=this._system.app.assets.get(this._materialAsset);i&&i.resource===t||(this._removeMaterialAssetEvents(),this._materialAsset=null)}t&&(this._renderable.setMaterial(t),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(t){var e=this._system.app.assets,i=t;if(t instanceof Vf&&(i=t.id),this._materialAsset!==i)if(this._removeMaterialAssetEvents(),this._materialAsset=i,this._materialAsset){var n=e.get(this._materialAsset);n?this._bindMaterialAsset(n):(this._materialAsset=null,this.material=null,this._materialAsset=i,e.on("add:"+this._materialAsset,this._onMaterialAdded,this))}else this._materialAsset=null,this.material=null,this._materialAsset=i}},{key:"texture",get:function(){return this._texture},set:function(t){if(this._texture!==t){if(this._textureAsset){var e=this._system.app.assets.get(this._textureAsset);e&&e.resource!==t&&(this.textureAsset=null)}if(this._texture=t,t){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!==Wm&&this.refreshMesh())}else this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"),this._targetAspectRatio=-1,this._element.fitMode!==Wm&&this.refreshMesh()}}},{key:"textureAsset",get:function(){return this._textureAsset},set:function(t){var e=this._system.app.assets,i=t;if(t instanceof Vf&&(i=t.id),this._textureAsset!==i){if(this._textureAsset){e.off("add:"+this._textureAsset,this._onTextureAdded,this);var n=e.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=e.get(this._textureAsset);s?this._bindTextureAsset(s):(this.texture=null,e.on("add:"+this._textureAsset,this._onTextureAdded,this))}else this.texture=null}}},{key:"spriteAsset",get:function(){return this._spriteAsset},set:function(t){var e=this._system.app.assets,i=t;if(t instanceof Vf&&(i=t.id),this._spriteAsset!==i){if(this._spriteAsset){e.off("add:"+this._spriteAsset,this._onSpriteAssetAdded,this);var n=e.get(this._spriteAsset);n&&this._unbindSpriteAsset(n)}if(this._spriteAsset=i,this._spriteAsset){var s=e.get(this._spriteAsset);s?this._bindSpriteAsset(s):(this.sprite=null,e.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(t){if(this._sprite!==t){if(this._sprite&&this._unbindSprite(this._sprite),this._spriteAsset){var e=this._system.app.assets.get(this._spriteAsset);e&&e.resource!==t&&(this.spriteAsset=null)}this._sprite=t,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=_t.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite()}}},{key:"spriteFrame",get:function(){return this._spriteFrame},set:function(t){var e=this._spriteFrame;this._sprite?this._spriteFrame=_t.clamp(t,0,this._sprite.frameKeys.length-1):this._spriteFrame=t,this._spriteFrame!==e&&this._updateSprite(),this._element&&this._element.fire("set:spriteFrame",t)}},{key:"mesh",get:function(){return this._renderable.mesh},set:function(t){this._renderable.setMesh(t),this._defaultMesh===t?this._renderable.setAabbFunc(null):this._renderable.setAabbFunc(this._updateAabbFunc)}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask!==t&&(this._mask=t,this._toggleMask())}},{key:"pixelsPerUnit",get:function(){return this._pixelsPerUnit},set:function(t){this._pixelsPerUnit!==t&&(this._pixelsPerUnit=t,!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}}]),t}(),F_=function(t){function e(e){var i;return(i=t.call(this)||this)._app=e,e.i18n.on("set:locale",i._onSetLocale,w(i)),i._autoLoad=!1,i._disableLocalization=!1,i._defaultAsset=null,i._localizedAsset=null,i}S(e,t);var i=e.prototype;return i._bindDefaultAsset=function(){var t=this._app.assets.get(this._defaultAsset);t?this._onDefaultAssetAdd(t):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 t=this._app.assets.get(this._defaultAsset);t&&(t.off("add:localized",this._onLocaleAdd,this),t.off("remove:localized",this._onLocaleRemove,this),t.off("remove",this._onDefaultAssetRemove,this))}},i._onDefaultAssetAdd=function(t){this._defaultAsset===t.id&&(t.on("add:localized",this._onLocaleAdd,this),t.on("remove:localized",this._onLocaleRemove,this),t.once("remove",this._onDefaultAssetRemove,this))},i._onDefaultAssetRemove=function(t){this._defaultAsset===t.id&&(t.off("add:localized",this._onLocaleAdd,this),t.off("remove:localized",this._onLocaleAdd,this),this._app.assets.once("add:"+this._defaultAsset,this._onDefaultAssetAdd,this))},i._bindLocalizedAsset=function(){if(this._autoLoad){var t=this._app.assets.get(this._localizedAsset);t&&(t.on("load",this._onLocalizedAssetLoad,this),t.on("change",this._onLocalizedAssetChange,this),t.on("remove",this._onLocalizedAssetRemove,this),t.resource?this._onLocalizedAssetLoad(t):this._app.assets.load(t))}},i._unbindLocalizedAsset=function(){var t=this._app.assets.get(this._localizedAsset);t&&(t.off("load",this._onLocalizedAssetLoad,this),t.off("change",this._onLocalizedAssetChange,this),t.off("remove",this._onLocalizedAssetRemove,this))},i._onLocalizedAssetAdd=function(t){this._localizedAsset===t.id&&this._bindLocalizedAsset()},i._onLocalizedAssetLoad=function(t){this.fire("load",t)},i._onLocalizedAssetChange=function(t,e,i,n){this.fire("change",t,e,i,n)},i._onLocalizedAssetRemove=function(t){this._localizedAsset===t.id&&(this.localizedAsset=this._defaultAsset),this.fire("remove",t)},i._onLocaleAdd=function(t,e){this._app.i18n.locale===t&&this._onSetLocale(t)},i._onLocaleRemove=function(t,e){this._app.i18n.locale===t&&this._onSetLocale(t)},i._onSetLocale=function(t){if(this._defaultAsset){var e=this._app.assets.get(this._defaultAsset);if(e&&!this._disableLocalization){var i=e.getLocalizedAssetId(t);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()},y(e,[{key:"defaultAsset",get:function(){return this._defaultAsset},set:function(t){var e=t instanceof Vf?t.id:t;this._defaultAsset!==e&&(this._defaultAsset&&this._unbindDefaultAsset(),this._defaultAsset=e,this._defaultAsset&&this._bindDefaultAsset(),this._onSetLocale(this._app.i18n.locale))}},{key:"localizedAsset",get:function(){return this._localizedAsset},set:function(t){var e=t instanceof Vf?t.id:t;this._localizedAsset!==e&&(this._localizedAsset&&(this._app.assets.off("add:"+this._localizedAsset,this._onLocalizedAssetAdd,this),this._unbindLocalizedAsset(),this._localizedAsset=null),this._localizedAsset=e,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(t){this._autoLoad!==t&&(this._autoLoad=t,this._autoLoad&&this._localizedAsset&&(this._unbindLocalizedAsset(),this._bindLocalizedAsset()))}},{key:"disableLocalization",get:function(){return this._disableLocalization},set:function(t){this._disableLocalization!==t&&(this._disableLocalization=t,this._onSetLocale(this._app.i18n.locale))}}]),e}(P),B_="msdf",U_="bitmap",N_=/[A-Z|a-z|0-9|_|-|/]/,z_=function(){function t(t){this._symbols=t,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 e=t.prototype;return e.read=function(){for(var t=this._read();8===t;)t=this._read();return 0!==t&&1!==t&&(this._last=this._index),t},e.buf=function(){return this._buf},e.last=function(){return this._last},e.error=function(){return this._error},e.debugPrint=function(){for(var t=["EOF","ERROR","TEXT","OPEN_BRACKET","CLOSE_BRACKET","EQUALS","STRING","IDENTIFIER","WHITESPACE"],e=this.read(),i="";i+=(i.length>0?"\n":"")+t[e]+" '"+this.buf().join("")+"'",0!==e&&1!==e;)e=this.read();return i},e._read=function(){return this._buf=[],this._eof()?0:"text"===this._mode?this._text():this._tag()},e._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()}},e._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)}},e._whitespace=function(){for(this._store();-1!==" \t\n\r\v\f".indexOf(this._cur);)this._store();return 8},e._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()}},e._identifier=function(){for(this._store();null!==this._cur&&this._isIdentifierSymbol(this._cur);)this._store();return 7},e._isIdentifierSymbol=function(t){return 1===t.length&&null!==t.match(N_)},e._eof=function(){return null===this._cur},e._next=function(){return this._eof()||(this._index++,this._cur=this._index=0;--s)if(n==="/"+e[s].name&&null===e[s].end)return e[s].end=t.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:t.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 e.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()}},t}();function G_(t,e){for(var i in e)if(e.hasOwnProperty(i)){var n=e[i];n instanceof Object?(t.hasOwnProperty(i)||(t[i]={}),G_(t[i],e[i])):t[i]=n}}function H_(t){if(0===t.length)return null;for(var e={},i=0;i=1e-4,g=this._element.calculatedWidth;(this.autoWidth&&!v||!this._wrapLines)&&(g=Number.POSITIVE_INFINITY);var y,x,S,b,w=0,T=0;function A(t,i,n){e._lineWidths.push(Math.abs(n));var s=f>i?i+1:f,r=f>i?f+1:i,h=t.slice(s,r);if(_)for(var l=h.length;l--&&_>0;)Y_.test(h[l])&&(h.splice(l,1),_--);e._lineContents.push(h.join("")),a=0,o-=e._scaledLineHeight,c++,p=0,m=0,_=0,u=0,f=i}for(var C=!0;C;){C=!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 E=this._fontSize/32;w=this._fontMinY*E,T=this._fontMaxY*E;for(var M=0;M=r?null:this._symbols[U+1],Y_.test(y))_++,(!this._wrapLines||this._maxLines<0||c0){var j=this._font.data.kerning;if(j){var q=j[rt.getCodePoint(this._symbols[U-1])||0];q&&(X=q[rt.getCodePoint(this._symbols[U])||0]||0)}}H=x.scale||1,G=E*((x.width+x.height)/2)/H,V=(x.xadvance+X)*E,N=(x.xoffset-X)*E,z=x.yoffset*E}else console.error("Couldn't substitute missing character: '"+y+"'");var Y=K_.test(y),K=x&&x.map||0,Z=-this._font.data.info.maps[K].width/this._font.data.info.maps[K].height,Q=this._meshInfo[K],$=a+this._spacing*V;if($>g&&m>0&&!Y&&(this._maxLines<0||cthis._element.calculatedWidth&&(ut=Math.floor(this._element.fontSize*this._element.calculatedWidth/(this.width||1e-4)),(ut=_t.clamp(ut,i,n))!==this._element.fontSize)){this._fontSize=ut,C=!0;break}if(this.height=Math.max(this.height,T-(o+w)),this._shouldAutoFitHeight()&&this.height>this._element.calculatedHeight&&(ut=_t.clamp(this._fontSize-1,i,n))!==this._element.fontSize){this._fontSize=ut,C=!0;break}a+=this._spacing*V,Y||(l=a),(this._isWordBoundary(y)||this._isValidNextChar(b)&&(this._isNextCJKBoundary(y,b)||this._isNextCJKWholeWord(b)))&&(p++,u=l,d=U+1),m++;var dt=this._getUv(y);if(Q.uvs[4*S*2+0]=dt[0],Q.uvs[4*S*2+1]=1-dt[1],Q.uvs[4*S*2+2]=dt[2],Q.uvs[4*S*2+3]=1-dt[1],Q.uvs[4*S*2+4]=dt[2],Q.uvs[4*S*2+5]=1-dt[3],Q.uvs[4*S*2+6]=dt[0],Q.uvs[4*S*2+7]=1-dt[3],this._symbolColors){var ft=3*this._symbolColors[U];P=this._colorPalette[ft],R=this._colorPalette[ft+1],I=this._colorPalette[ft+2]}if(Q.colors[4*S*4+0]=P,Q.colors[4*S*4+1]=R,Q.colors[4*S*4+2]=I,Q.colors[4*S*4+3]=255,Q.colors[4*S*4+4]=P,Q.colors[4*S*4+5]=R,Q.colors[4*S*4+6]=I,Q.colors[4*S*4+7]=255,Q.colors[4*S*4+8]=P,Q.colors[4*S*4+9]=R,Q.colors[4*S*4+10]=I,Q.colors[4*S*4+11]=255,Q.colors[4*S*4+12]=P,Q.colors[4*S*4+13]=R,Q.colors[4*S*4+14]=I,Q.colors[4*S*4+15]=255,this._symbolOutlineParams){var pt=5*this._symbolOutlineParams[U];L=this._outlinePalette[pt]+256*this._outlinePalette[pt+1],D=this._outlinePalette[pt+2]+256*this._outlinePalette[pt+3],O=this._outlinePalette[pt+4]}if(Q.outlines[4*S*3+0]=L,Q.outlines[4*S*3+1]=D,Q.outlines[4*S*3+2]=O,Q.outlines[4*S*3+3]=L,Q.outlines[4*S*3+4]=D,Q.outlines[4*S*3+5]=O,Q.outlines[4*S*3+6]=L,Q.outlines[4*S*3+7]=D,Q.outlines[4*S*3+8]=O,Q.outlines[4*S*3+9]=L,Q.outlines[4*S*3+10]=D,Q.outlines[4*S*3+11]=O,this._symbolShadowParams){var mt=6*this._symbolShadowParams[U];k=this._shadowPalette[mt]+256*this._shadowPalette[mt+1],F=this._shadowPalette[mt+2]+256*this._shadowPalette[mt+3],B=this._shadowPalette[mt+4]+127+256*Math.round(Z*this._shadowPalette[mt+5]+127)}Q.shadows[4*S*3+0]=k,Q.shadows[4*S*3+1]=F,Q.shadows[4*S*3+2]=B,Q.shadows[4*S*3+3]=k,Q.shadows[4*S*3+4]=F,Q.shadows[4*S*3+5]=B,Q.shadows[4*S*3+6]=k,Q.shadows[4*S*3+7]=F,Q.shadows[4*S*3+8]=B,Q.shadows[4*S*3+9]=k,Q.shadows[4*S*3+10]=F,Q.shadows[4*S*3+11]=B,Q.quad++}}C||f=kt?(Ft.element[we].set(0,0,0),Ft.element[Re].set(0,0),Ft.element[Me].set(0,0,0,0),Ft.element[qe].set(0,0,0,0),Ft.element[Ye].set(0,0,0,0)):(Ft.element[we].set(this._meshInfo[St].positions[3*Bt+0],this._meshInfo[St].positions[3*Bt+1],this._meshInfo[St].positions[3*Bt+2]),Ft.element[Re].set(this._meshInfo[St].uvs[2*Bt+0],this._meshInfo[St].uvs[2*Bt+1]),Ft.element[Me].set(this._meshInfo[St].colors[4*Bt+0],this._meshInfo[St].colors[4*Bt+1],this._meshInfo[St].colors[4*Bt+2],this._meshInfo[St].colors[4*Bt+3]),Ft.element[qe].set(this._meshInfo[St].outlines[3*Bt+0],this._meshInfo[St].outlines[3*Bt+1],this._meshInfo[St].outlines[3*Bt+2]),Ft.element[Ye].set(this._meshInfo[St].shadows[3*Bt+0],this._meshInfo[St].shadows[3*Bt+1],this._meshInfo[St].shadows[3*Bt+2])),Ft.next();Ft.end(),this._meshInfo[St].meshInstance.mesh.aabb.compute(this._meshInfo[St].positions),this._meshInfo[St].meshInstance._aabbVer=-1}this._aabbDirty=!0},e._onFontRender=function(){this.font=this._font},e._onFontLoad=function(t){this.font!==t.resource&&(this.font=t.resource)},e._onFontChange=function(t,e,i,n){if("data"===e){this._font.data=i;for(var s=this._font.data.info.maps.length,r=0;rthis._font.textures.length&&(this._meshInfo.length=this._font.textures.length),this._updateText()}}},{key:"alignment",get:function(){return this._alignment},set:function(t){t instanceof Et?this._alignment.set(t.x,t.y):this._alignment.set(t[0],t[1]),this._font&&this._updateText()}},{key:"autoWidth",get:function(){return this._autoWidth},set:function(t){var e=this._autoWidth;if(this._autoWidth=t,t&&Math.abs(this._element.anchor.x-this._element.anchor.z)<1e-4&&(this._element.width=this.width),e!==t){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(t){var e=this._autoHeight;if(this._autoHeight=t,t&&Math.abs(this._element.anchor.y-this._element.anchor.w)<1e-4&&(this._element.height=this.height),e!==t){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(t){this._rtlReorder!==t&&(this._rtlReorder=t,this._font&&this._updateText())}},{key:"unicodeConverter",get:function(){return this._unicodeConverter},set:function(t){this._unicodeConverter!==t&&(this._unicodeConverter=t,this._setText(this._text))}},{key:"aabb",get:function(){if(this._aabbDirty){for(var t=!1,e=0;e=0&&this.system._prerender.splice(i,1),this.system._prerender.indexOf(t)<0&&this.system._prerender.push(t)}t=e}},i._onPrerender=function(){for(var t=0;t=0)&&(null==(t=this.system.app.batcher)||t.insert(Ho.ELEMENT,this.batchGroupId,this.entity));this.fire("enableelement")},i.onDisable=function(){var t;(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==(t=this.system.app.batcher)||t.remove(Ho.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(t,e){if(this.entity._parent||this.screen){this._calculateLocalAnchors();var i=this._absRight-this._absLeft,n=this._absTop-this._absBottom;t?this._setWidth(i):this._setCalculatedWidth(i,!1),e?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(t){this._width=t,this._setCalculatedWidth(t,!1),this.fire("set:width",this._width)},i._setHeight=function(t){this._height=t,this._setCalculatedHeight(t,!1),this.fire("set:height",this._height)},i._setCalculatedWidth=function(t,e){if(!(Math.abs(t-this._calculatedWidth)<=1e-4)){if(this._calculatedWidth=t,this.entity._dirtifyLocal(),e){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(t,e){if(!(Math.abs(t-this._calculatedHeight)<=1e-4)){if(this._calculatedHeight=t,this.entity._dirtifyLocal(),e){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 t=this.entity._children,e=0,i=t.length;e=0&&this._addedModels.splice(e,1);for(var i=0;ii||f>n||p.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(t){var e;t instanceof Pt?this._anchor.copy(t):(e=this._anchor).set.apply(e,t);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(t){if(this._batchGroupId!==t){var e,i;if(this.entity.enabled&&this._batchGroupId>=0)null==(e=this.system.app.batcher)||e.remove(Ho.ELEMENT,this.batchGroupId,this.entity);if(this.entity.enabled&&t>=0)null==(i=this.system.app.batcher)||i.insert(Ho.ELEMENT,t,this.entity);t<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=t}}},{key:"bottom",get:function(){return this._margin.y},set:function(t){this._margin.y=t;var e=this.entity.getLocalPosition(),i=this._absTop,n=this._localAnchor.y+t;this._setHeight(i-n),e.y=t+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(e)}},{key:"calculatedWidth",get:function(){return this._calculatedWidth},set:function(t){this._setCalculatedWidth(t,!0)}},{key:"calculatedHeight",get:function(){return this._calculatedHeight},set:function(t){this._setCalculatedHeight(t,!0)}},{key:"canvasCorners",get:function(){if(!this._canvasCornersDirty||!this.screen||!this.screen.screen.screenSpace)return this._canvasCorners;for(var t=this.system.app.graphicsDevice,e=this.screenCorners,i=t.canvas.clientWidth/t.width,n=t.canvas.clientHeight/t.height,s=0;s<4;s++)this._canvasCorners[s].set(e[s].x*i,(t.height-e[s].y)*n);return this._canvasCornersDirty=!1,this._canvasCorners}},{key:"drawOrder",get:function(){return this._drawOrder},set:function(t){var e=0;this.screen&&(e=this.screen.screen.priority),t>16777215&&(t=16777215),this._drawOrder=(e<<24)+t,this.fire("set:draworder",this._drawOrder)}},{key:"height",get:function(){return this._height},set:function(t){this._height=t,this._hasSplitAnchorsY||this._setCalculatedHeight(t,!0),this.fire("set:height",this._height)}},{key:"layers",get:function(){return this._layers},set:function(t){if(this._addedModels.length)for(var e=0;e.001,a=Math.abs(e.anchor.y-e.anchor.w)>.001,o=!1;void 0!==i.margin&&(i.margin instanceof Pt?e.margin.copy(i.margin):e._margin.set(i.margin[0],i.margin[1],i.margin[2],i.margin[3]),o=!0),void 0!==i.left&&(e._margin.x=i.left,o=!0),void 0!==i.bottom&&(e._margin.y=i.bottom,o=!0),void 0!==i.right&&(e._margin.z=i.right,o=!0),void 0!==i.top&&(e._margin.w=i.top,o=!0),o&&(e.margin=e._margin);var h=!1;void 0===i.width||r?r&&(h=!0):e.width=i.width,void 0===i.height||a?a&&(h=!0):e.height=i.height,h&&(e.anchor=e.anchor),void 0!==i.enabled&&(e.enabled=i.enabled),void 0!==i.useInput&&(e.useInput=i.useInput),void 0!==i.fitMode&&(e.fitMode=i.fitMode),e.batchGroupId=void 0===i.batchGroupId||null===i.batchGroupId?-1:i.batchGroupId,i.layers&&Array.isArray(i.layers)&&(e.layers=i.layers.slice(0)),void 0!==i.type&&(e.type=i.type),e.type===Gm?(void 0!==i.rect&&(e.rect=i.rect),void 0!==i.color&&((s=i.color)instanceof vt||(s=new vt(i.color[0],i.color[1],i.color[2])),e.color=s),void 0!==i.opacity&&(e.opacity=i.opacity),void 0!==i.textureAsset&&(e.textureAsset=i.textureAsset),i.texture&&(e.texture=i.texture),void 0!==i.spriteAsset&&(e.spriteAsset=i.spriteAsset),i.sprite&&(e.sprite=i.sprite),void 0!==i.spriteFrame&&(e.spriteFrame=i.spriteFrame),void 0!==i.pixelsPerUnit&&null!==i.pixelsPerUnit&&(e.pixelsPerUnit=i.pixelsPerUnit),void 0!==i.materialAsset&&(e.materialAsset=i.materialAsset),i.material&&(e.material=i.material),void 0!==i.mask&&(e.mask=i.mask)):e.type===Hm&&(void 0!==i.autoWidth&&(e.autoWidth=i.autoWidth),void 0!==i.autoHeight&&(e.autoHeight=i.autoHeight),void 0!==i.rtlReorder&&(e.rtlReorder=i.rtlReorder),void 0!==i.unicodeConverter&&(e.unicodeConverter=i.unicodeConverter),null!==i.text&&void 0!==i.text?e.text=i.text:null!==i.key&&void 0!==i.key&&(e.key=i.key),void 0!==i.color&&((s=i.color)instanceof vt||(s=new vt(s[0],s[1],s[2])),e.color=s),void 0!==i.opacity&&(e.opacity=i.opacity),void 0!==i.spacing&&(e.spacing=i.spacing),void 0!==i.fontSize&&(e.fontSize=i.fontSize,i.lineHeight||(e.lineHeight=i.fontSize)),void 0!==i.lineHeight&&(e.lineHeight=i.lineHeight),void 0!==i.maxLines&&(e.maxLines=i.maxLines),void 0!==i.wrapLines&&(e.wrapLines=i.wrapLines),void 0!==i.minFontSize&&(e.minFontSize=i.minFontSize),void 0!==i.maxFontSize&&(e.maxFontSize=i.maxFontSize),i.autoFitWidth&&(e.autoFitWidth=i.autoFitWidth),i.autoFitHeight&&(e.autoFitHeight=i.autoFitHeight),void 0!==i.fontAsset&&(e.fontAsset=i.fontAsset),void 0!==i.font&&(e.font=i.font),void 0!==i.alignment&&(e.alignment=i.alignment),void 0!==i.outlineColor&&(e.outlineColor=i.outlineColor),void 0!==i.outlineThickness&&(e.outlineThickness=i.outlineThickness),void 0!==i.shadowColor&&(e.shadowColor=i.shadowColor),void 0!==i.shadowOffset&&(e.shadowOffset=i.shadowOffset),void 0!==i.enableMarkup&&(e.enableMarkup=i.enableMarkup));var l=e._parseUpToScreen();l.screen&&e._updateScreen(l.screen),t.prototype.initializeComponentData.call(this,e,i,n),e._beingInitialized=!1,e.type===Gm&&e._image._meshDirty&&e._image._updateMesh(e._image.mesh)},i.onRemoveComponent=function(t,e){e.onRemove()},i.cloneComponent=function(t,e){var i=t.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(e,n)},i.getTextElementMaterial=function(t,e,i){var n=(t&&1)|(e&&2)|(i&&4),s=this._defaultTextMaterials[n];if(s)return s;var r="TextMaterial";return s=new lu,e?(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"),t&&(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 t=new lu;return t.diffuse.set(0,0,0),t.emissive.set(.5,.5,.5),t.emissiveMap=this._defaultTexture,t.emissiveTint=!0,t.opacityMap=this._defaultTexture,t.opacityMapChannel="a",t.opacityTint=!0,t.opacity=0,t.useLighting=!1,t.useGammaTonemap=!1,t.useFog=!1,t.useSkybox=!1,t.blendType=4,t.depthWrite=!1,t},i.getImageElementMaterial=function(t,e,i,n){return t?e?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):e?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(t){this._unicodeConverter=t},i.registerRtlReorder=function(t){this._rtlReorder=t},i.getUnicodeConverter=function(){return this._unicodeConverter},i.getRtlReorder=function(){return this._rtlReorder},e}(wp);bp._buildAccessors(fv.prototype,_v);var gv="free",yv="limited",xv="locked",Sv=["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"],bv=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._constraint=null,n._entityA=null,n._entityB=null,n._breakForce=34e37,n._enableCollision=!0,n._linearMotionX=xv,n._linearLimitsX=new Et(0,0),n._linearSpringX=!1,n._linearStiffnessX=0,n._linearDampingX=1,n._linearEquilibriumX=0,n._linearMotionY=xv,n._linearLimitsY=new Et(0,0),n._linearSpringY=!1,n._linearStiffnessY=0,n._linearDampingY=1,n._linearEquilibriumY=0,n._linearMotionZ=xv,n._linearLimitsZ=new Et(0,0),n._linearSpringZ=!1,n._linearStiffnessZ=0,n._linearDampingZ=1,n._linearEquilibriumZ=0,n._angularMotionX=xv,n._angularLimitsX=new Et(0,0),n._angularSpringX=!1,n._angularStiffnessX=0,n._angularDampingX=1,n._angularEquilibriumX=0,n._angularMotionY=xv,n._angularLimitsY=new Et(0,0),n._angularSpringY=!1,n._angularStiffnessY=0,n._angularDampingY=1,n._angularEquilibriumY=0,n._angularMotionZ=xv,n._angularLimitsZ=new Et(0,0),n._angularSpringZ=!1,n._angularEquilibriumZ=0,n._angularDampingZ=1,n._angularStiffnessZ=0,n.on("set_enabled",n._onSetEnabled,w(n)),n}S(e,t);var i=e.prototype;return i._convertTransform=function(t,e){var i=t.getTranslation(),n=new Bt;n.setFromMat4(t);var s=new Ammo.btVector3(i.x,i.y,i.z),r=new Ammo.btQuaternion(n.x,n.y,n.z,n.w);e.setOrigin(s),e.setRotation(r),Ammo.destroy(s),Ammo.destroy(r)},i._updateAngularLimits=function(){var t=this._constraint;if(t){var e,i,n,s,r,a;this._angularMotionX===yv?(e=this._angularLimitsX.x*_t.DEG_TO_RAD,s=this._angularLimitsX.y*_t.DEG_TO_RAD):this._angularMotionX===gv?(e=1,s=0):e=s=0,this._angularMotionY===yv?(i=this._angularLimitsY.x*_t.DEG_TO_RAD,r=this._angularLimitsY.y*_t.DEG_TO_RAD):this._angularMotionY===gv?(i=1,r=0):i=r=0,this._angularMotionZ===yv?(n=this._angularLimitsZ.x*_t.DEG_TO_RAD,a=this._angularLimitsZ.y*_t.DEG_TO_RAD):this._angularMotionZ===gv?(n=1,a=0):n=a=0;var o=new Ammo.btVector3(e,i,n);t.setAngularLowerLimit(o),o.setValue(s,r,a),t.setAngularUpperLimit(o),Ammo.destroy(o)}},i._updateLinearLimits=function(){var t=this._constraint;if(t){var e,i,n,s,r,a;this._linearMotionX===yv?(e=this._linearLimitsX.x,s=this._linearLimitsX.y):this._linearMotionX===gv?(e=1,s=0):e=s=0,this._linearMotionY===yv?(i=this._linearLimitsY.x,r=this._linearLimitsY.y):this._linearMotionY===gv?(i=1,r=0):i=r=0,this._linearMotionZ===yv?(n=this._linearLimitsZ.x,a=this._linearLimitsZ.y):this._linearMotionZ===gv?(n=1,a=0):n=a=0;var o=new Ammo.btVector3(e,i,n);t.setLinearLowerLimit(o),o.setValue(s,r,a),t.setLinearUpperLimit(o),Ammo.destroy(o)}},i._createConstraint=function(){if(this._entityA&&this._entityA.rigidbody){this._destroyConstraint();var t=new Ft,e=this._entityA.rigidbody.body;e.activate();var i=this.entity.getWorldTransform(),n=this._entityA.getWorldTransform().clone().invert();t.mul2(n,i);var s=new Ammo.btTransform;if(this._convertTransform(t,s),this._entityB&&this._entityB.rigidbody){var r=this._entityB.rigidbody.body;r.activate();var a=this._entityB.getWorldTransform().clone().invert();t.mul2(a,i);var o=new Ammo.btTransform;this._convertTransform(t,o),this._constraint=new Ammo.btGeneric6DofSpringConstraint(e,r,s,o,!this._enableCollision),Ammo.destroy(o)}else this._constraint=new Ammo.btGeneric6DofSpringConstraint(e,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(t){for(var e=0,i=Sv;e=i?Fv:Ov;case 3:return e=0;--n)i[e[n]]=i[e[n+1]]+t[e[n]];return i}return function(t,d){t=t.filter(o),e=d,Bv.x=e.containerSize.x-e.padding.x-e.padding.z,Bv.y=e.containerSize.y-e.padding.y-e.padding.w,function(t){for(var e=0;e0&&(r+=e.spacing[i.axis]);var h=s[o][i.size];r+=h,!a&&r>Bv[i.axis]&&0!==n[n.length-1].length&&(r=h,n.push([])),n[n.length-1].push(t[o]),a&&r>Bv[i.axis]&&o!==t.length-1&&(r=0,n.push([]))}return n}(t)),m=function(t,i){for(var s=[],r=[],a=0;ao.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(e[n.fitting],p,Bv[n.axis]);m===kv?c(r,p,n):m===Fv&&u(r,p,n);for(var _=0;_0;){var e=this._reflowQueue.slice();this._reflowQueue.length=0,e.sort((function(t,e){return t.entity.graphDepth-e.entity.graphDepth}));for(var i=0;i=100){console.warn("Max reflow iterations limit reached, bailing.");break}}},i._onRemoveComponent=function(t,e){e.onRemove()},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("postUpdate",this._onPostUpdate,this)},e}(wp);bp._buildAccessors(Hv.prototype,Xv);var qv=function(t){function e(e,i){var n;return(n=t.call(this,e,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=e.defaultMaterial,i.on("remove",n.onRemoveChild,w(n)),i.on("removehierarchy",n.onRemoveChild,w(n)),i.on("insert",n.onInsertChild,w(n)),i.on("inserthierarchy",n.onInsertChild,w(n)),n}S(e,t);var i=e.prototype;return i.addModelToLayers=function(){for(var t=this.system.app.scene.layers,e=0;e=0&&(null==(n=t.batcher)||n.insert(Ho.MODEL,this.batchGroupId,this.entity))},i.onDisable=function(){var t,e=this.system.app,i=e.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==(t=e.batcher)||t.remove(Ho.MODEL,this.batchGroupId,this.entity));this._model&&this.removeModelFromLayers()},i.hide=function(){if(this._model)for(var t=this._model.meshInstances,e=0,i=t.length;e=0)null==(e=this.system.app.batcher)||e.remove(Ho.MODEL,this.batchGroupId,this.entity);if(this.entity.enabled&&t>=0)null==(i=this.system.app.batcher)||i.insert(Ho.MODEL,t,this.entity);t<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addModelToLayers(),this._batchGroupId=t}}},{key:"materialAsset",get:function(){return this._materialAsset},set:function(t){var e=t;t instanceof Vf&&(e=t.id);var i=this.system.app.assets;if(e!==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=e,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(t){this._material!==t&&(this.materialAsset=null,this._setMaterial(t))}},{key:"mapping",get:function(){return this._mapping},set:function(t){if("asset"===this._type&&(this._unsetMaterialEvents(),t||(t={}),this._mapping=t,this._model))for(var e=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=e.length;r=0))continue;n=this.system.app.assets.get(n)}n&&!n.resource&&this.system.app.assets.load(n)}}if(!this.system.app.graphicsDevice.disableParticleSystem){if(!this.emitter){var s=t.mesh;s instanceof qa||(s=null),this.emitter=new Nd(this.system.app.graphicsDevice,{numParticles:t.numParticles,emitterExtents:t.emitterExtents,emitterExtentsInner:t.emitterExtentsInner,emitterRadius:t.emitterRadius,emitterRadiusInner:t.emitterRadiusInner,emitterShape:t.emitterShape,initialVelocity:t.initialVelocity,wrap:t.wrap,localSpace:t.localSpace,screenSpace:t.screenSpace,wrapBounds:t.wrapBounds,lifetime:t.lifetime,rate:t.rate,rate2:t.rate2,orientation:t.orientation,particleNormal:t.particleNormal,animTilesX:t.animTilesX,animTilesY:t.animTilesY,animStartFrame:t.animStartFrame,animNumFrames:t.animNumFrames,animNumAnimations:t.animNumAnimations,animIndex:t.animIndex,randomizeAnimIndex:t.randomizeAnimIndex,animSpeed:t.animSpeed,animLoop:t.animLoop,startAngle:t.startAngle,startAngle2:t.startAngle2,scaleGraph:t.scaleGraph,scaleGraph2:t.scaleGraph2,colorGraph:t.colorGraph,colorGraph2:t.colorGraph2,alphaGraph:t.alphaGraph,alphaGraph2:t.alphaGraph2,localVelocityGraph:t.localVelocityGraph,localVelocityGraph2:t.localVelocityGraph2,velocityGraph:t.velocityGraph,velocityGraph2:t.velocityGraph2,rotationSpeedGraph:t.rotationSpeedGraph,rotationSpeedGraph2:t.rotationSpeedGraph2,radialSpeedGraph:t.radialSpeedGraph,radialSpeedGraph2:t.radialSpeedGraph2,colorMap:t.colorMap,normalMap:t.normalMap,loop:t.loop,preWarm:t.preWarm,sort:t.sort,stretch:t.stretch,alignToMotion:t.alignToMotion,lighting:t.lighting,halfLambert:t.halfLambert,intensity:t.intensity,depthSoftening:t.depthSoftening,scene:this.system.app.scene,mesh:s,depthWrite:t.depthWrite,noFog:t.noFog,node:this.entity,blendType:t.blendType}),this.emitter.meshInstance.node=this.entity,this.emitter.drawOrder=this.drawOrder,t.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&&t.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 t=0;tc.fixedTimeStep&&(e=Math.floor(c.simTime/c.fixedTimeStep),c.simTime-=e*c.fixedTimeStep),e){e=Math.min(e,c.maxSubSteps);for(var p=0;p=0){var r=n[s];r.decRefCount(),0===r.refCount&&(n.splice(s,1),n.length||t._skinInstanceCache.delete(i),e&&(e.destroy(),r.skinInstance=null))}}}}},t}();og._skinInstanceCache=new Map;var hg=function(){function t(t,e,i,n,s){this.propertyName=t,this.parent=e,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 e=t.prototype;return e._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))},e._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))},e._onLoad=function(t){this._onAssetLoad.call(this._scope,this.propertyName,this.parent,t)},e._onAdd=function(t){this.asset=t,this._onAssetAdd.call(this._scope,this.propertyName,this.parent,t)},e._onRemove=function(t){this._onAssetRemove.call(this._scope,this.propertyName,this.parent,t),this.asset=null},e._onUnload=function(t){this._onAssetUnload.call(this._scope,this.propertyName,this.parent,t)},y(t,[{key:"id",get:function(){return this._id},set:function(t){if(this.url)throw Error("Can't set id and url");this._unbind(),this._id=t,this.asset=this._registry.get(this._id),this._bind()}},{key:"url",get:function(){return this._url},set:function(t){if(this.id)throw Error("Can't set id and url");this._unbind(),this._url=t,this.asset=this._registry.getByUrl(this._url),this._bind()}}]),t}(),lg=function(t){function e(e,i){var n;return(n=t.call(this,e,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 zm(w(n),"rootBone"),n._rootBone.on("set:entity",n._onSetRootBone,w(n)),n._assetReference=new hg("asset",w(n),e.app.assets,{add:n._onRenderAssetAdded,load:n._onRenderAssetLoad,remove:n._onRenderAssetRemove,unload:n._onRenderAssetUnload},w(n)),n._material=e.defaultMaterial,i.on("remove",n.onRemoveChild,w(n)),i.on("removehierarchy",n.onRemoveChild,w(n)),i.on("insert",n.onInsertChild,w(n)),i.on("inserthierarchy",n.onInsertChild,w(n)),n}S(e,t);var i=e.prototype;return i.assignAsset=function(t){var e=t instanceof Vf?t.id:t;this._assetReference.id=e},i._onSetRootBone=function(t){t&&this._onRootBoneChanged()},i._onRootBoneChanged=function(){this._clearSkinInstances(),this.enabled&&this.entity.enabled&&this._cloneSkinInstances()},i.destroyMeshInstances=function(){var t=this._meshInstances;if(t){this.removeFromLayers(),this._clearSkinInstances();for(var e=0;e=0&&(null==(i=t.batcher)||i.insert(Ho.RENDER,this.batchGroupId,this.entity))},i.onDisable=function(){var t,e=this.system.app,i=e.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==(t=e.batcher)||t.remove(Ho.RENDER,this.batchGroupId,this.entity));this.removeFromLayers()},i.hide=function(){if(this._meshInstances)for(var t=0;t=0)null==(e=this.system.app.batcher)||e.remove(Ho.RENDER,this.batchGroupId,this.entity);if(this.entity.enabled&&t>=0)null==(i=this.system.app.batcher)||i.insert(Ho.RENDER,t,this.entity);t<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addToLayers(),this._batchGroupId=t}}},{key:"material",get:function(){return this._material},set:function(t){if(this._material!==t&&(this._material=t,this._meshInstances&&"asset"!==this._type))for(var e=0;et.length){for(var e=t.length;ethis._pool.length)for(var e=this._pool.length;e=this._pool.length&&this._resize(2*this._pool.length),this._pool[this._count++]},e.freeAll=function(){this._count=0},t}(),Sg=new Bt,bg=new Bt,wg=new wt,Tg=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._angularDamping=0,n._angularFactor=new wt(1,1,1),n._angularVelocity=new wt,n._body=null,n._friction=.5,n._group=2,n._linearDamping=0,n._linearFactor=new wt(1,1,1),n._linearVelocity=new wt,n._mask=__,n._mass=1,n._restitution=0,n._rollingFriction=0,n._simulationEnabled=!1,n._type=d_,n}S(e,t),e.onLibraryLoaded=function(){"undefined"!=typeof Ammo&&(pg=new Ammo.btTransform,mg=new Ammo.btVector3,_g=new Ammo.btVector3,vg=new Ammo.btQuaternion)};var i=e.prototype;return i.createBody=function(){var t,e=this.entity;if(e.collision&&(t=e.collision.shape,e.trigger&&(e.trigger.destroy(),delete e.trigger)),t){this._body&&this.system.onRemove(e,this);var i=this._type===f_?this._mass:0;this._getEntityTransform(pg);var n=this.system.createBody(i,t,pg);if(n.setRestitution(this._restitution),n.setFriction(this._friction),n.setRollingFriction(this._rollingFriction),n.setDamping(this._linearDamping,this._angularDamping),this._type===f_){var s=this._linearFactor;mg.setValue(s.x,s.y,s.z),n.setLinearFactor(mg);var r=this._angularFactor;mg.setValue(r.x,r.y,r.z),n.setAngularFactor(mg)}else this._type===p_&&(n.setCollisionFlags(2|n.getCollisionFlags()),n.setActivationState(4));n.entity=e,this.body=n,this.enabled&&e.enabled&&this.enableSimulation()}},i.isActive=function(){return!!this._body&&this._body.isActive()},i.activate=function(){this._body&&this._body.activate()},i.enableSimulation=function(){var t=this.entity;if(t.collision&&t.collision.enabled&&!this._simulationEnabled){var e=this._body;if(e){switch(this.system.addBody(e,this._group,this._mask),this._type){case f_:this.system._dynamic.push(this),e.forceActivationState(1),this.syncEntityToBody();break;case p_:this.system._kinematic.push(this),e.forceActivationState(4);break;case d_:e.forceActivationState(1),this.syncEntityToBody()}"compound"===t.collision.type&&this.system._compounds.push(t.collision),e.activate(),this._simulationEnabled=!0}}},i.disableSimulation=function(){var t=this._body;if(t&&this._simulationEnabled){var e=this.system,i=e._compounds.indexOf(this.entity.collision);i>-1&&e._compounds.splice(i,1),(i=e._dynamic.indexOf(this))>-1&&e._dynamic.splice(i,1),(i=e._kinematic.indexOf(this))>-1&&e._kinematic.splice(i,1),e.removeBody(t),t.forceActivationState(5),this._simulationEnabled=!1}},i.applyForce=function(t,e,i,n,s,r){var a=this._body;a&&(a.activate(),t instanceof wt?mg.setValue(t.x,t.y,t.z):mg.setValue(t,e,i),e instanceof wt?_g.setValue(e.x,e.y,e.z):void 0!==n?_g.setValue(n,s,r):_g.setValue(0,0,0),a.applyForce(mg,_g))},i.applyTorque=function(t,e,i){var n=this._body;n&&(n.activate(),t instanceof wt?mg.setValue(t.x,t.y,t.z):mg.setValue(t,e,i),n.applyTorque(mg))},i.applyImpulse=function(t,e,i,n,s,r){var a=this._body;a&&(a.activate(),t instanceof wt?mg.setValue(t.x,t.y,t.z):mg.setValue(t,e,i),e instanceof wt?_g.setValue(e.x,e.y,e.z):void 0!==n?_g.setValue(n,s,r):_g.setValue(0,0,0),a.applyImpulse(mg,_g))},i.applyTorqueImpulse=function(t,e,i){var n=this._body;n&&(n.activate(),t instanceof wt?mg.setValue(t.x,t.y,t.z):mg.setValue(t,e,i),n.applyTorqueImpulse(mg))},i.isStatic=function(){return this._type===d_},i.isStaticOrKinematic=function(){return this._type===d_||this._type===p_},i.isKinematic=function(){return this._type===p_},i._getEntityTransform=function(t){var e=this.entity,i=e.collision;if(i){var n=i.getShapePosition(),s=i.getShapeRotation();mg.setValue(n.x,n.y,n.z),vg.setValue(s.x,s.y,s.z,s.w)}else{var r=e.getPosition(),a=e.getRotation();mg.setValue(r.x,r.y,r.z),vg.setValue(a.x,a.y,a.z,a.w)}t.setOrigin(mg),t.setRotation(vg)},i.syncEntityToBody=function(){var t=this._body;if(t){if(this._getEntityTransform(pg),t.setWorldTransform(pg),this._type===p_){var e=t.getMotionState();e&&e.setWorldTransform(pg)}t.activate()}},i._updateDynamic=function(){var t=this._body;if(t.isActive()){var e=t.getMotionState();if(e){var i=this.entity;e.getWorldTransform(pg);var n=pg.getOrigin(),s=pg.getRotation(),r=i.collision;if(r&&r._hasOffset){var a=r.data.linearOffset,o=r.data.angularOffset,h=bg.copy(o).invert(),l=Sg.set(s.x(),s.y(),s.z(),s.w()).mul(h);l.transformVector(a,wg),i.setPosition(n.x()-wg.x,n.y()-wg.y,n.z()-wg.z),i.setRotation(l)}else i.setPosition(n.x(),n.y(),n.z()),i.setRotation(s.x(),s.y(),s.z(),s.w())}}},i._updateKinematic=function(){var t=this._body.getMotionState();t&&(this._getEntityTransform(pg),t.setWorldTransform(pg))},i.teleport=function(t,e,i,n,s,r){t instanceof wt?this.entity.setPosition(t):this.entity.setPosition(t,e,i),e instanceof Bt?this.entity.setRotation(e):e instanceof wt?this.entity.setEulerAngles(e):void 0!==n&&this.entity.setEulerAngles(n,s,r),this.syncEntityToBody()},i.onEnable=function(){this._body||this.createBody(),this.enableSimulation()},i.onDisable=function(){this.disableSimulation()},y(e,[{key:"angularDamping",get:function(){return this._angularDamping},set:function(t){this._angularDamping!==t&&(this._angularDamping=t,this._body&&this._body.setDamping(this._linearDamping,t))}},{key:"angularFactor",get:function(){return this._angularFactor},set:function(t){this._angularFactor.equals(t)||(this._angularFactor.copy(t),this._body&&this._type===f_&&(mg.setValue(t.x,t.y,t.z),this._body.setAngularFactor(mg)))}},{key:"angularVelocity",get:function(){if(this._body&&this._type===f_){var t=this._body.getAngularVelocity();this._angularVelocity.set(t.x(),t.y(),t.z())}return this._angularVelocity},set:function(t){this._body&&this._type===f_&&(this._body.activate(),mg.setValue(t.x,t.y,t.z),this._body.setAngularVelocity(mg),this._angularVelocity.copy(t))}},{key:"body",get:function(){return this._body},set:function(t){this._body!==t&&(this._body=t,t&&this._simulationEnabled&&t.activate())}},{key:"friction",get:function(){return this._friction},set:function(t){this._friction!==t&&(this._friction=t,this._body&&this._body.setFriction(t))}},{key:"group",get:function(){return this._group},set:function(t){this._group!==t&&(this._group=t,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()))}},{key:"linearDamping",get:function(){return this._linearDamping},set:function(t){this._linearDamping!==t&&(this._linearDamping=t,this._body&&this._body.setDamping(t,this._angularDamping))}},{key:"linearFactor",get:function(){return this._linearFactor},set:function(t){this._linearFactor.equals(t)||(this._linearFactor.copy(t),this._body&&this._type===f_&&(mg.setValue(t.x,t.y,t.z),this._body.setLinearFactor(mg)))}},{key:"linearVelocity",get:function(){if(this._body&&this._type===f_){var t=this._body.getLinearVelocity();this._linearVelocity.set(t.x(),t.y(),t.z())}return this._linearVelocity},set:function(t){this._body&&this._type===f_&&(this._body.activate(),mg.setValue(t.x,t.y,t.z),this._body.setLinearVelocity(mg),this._linearVelocity.copy(t))}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask!==t&&(this._mask=t,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()))}},{key:"mass",get:function(){return this._mass},set:function(t){if(this._mass!==t&&(this._mass=t,this._body&&this._type===f_)){var e=this.enabled&&this.entity.enabled;e&&this.disableSimulation(),this._body.getCollisionShape().calculateLocalInertia(t,mg),this._body.setMassProps(t,mg),this._body.updateInertiaTensor(),e&&this.enableSimulation()}}},{key:"restitution",get:function(){return this._restitution},set:function(t){this._restitution!==t&&(this._restitution=t,this._body&&this._body.setRestitution(t))}},{key:"rollingFriction",get:function(){return this._rollingFriction},set:function(t){this._rollingFriction!==t&&(this._rollingFriction=t,this._body&&this._body.setRollingFriction(t))}},{key:"type",get:function(){return this._type},set:function(t){if(this._type!==t){switch(this._type=t,this.disableSimulation(),t){case f_:this._group=1,this._mask=m_;break;case p_:this._group=4,this._mask=m_;break;default:this._group=2,this._mask=__}this.createBody()}}}]),e}(bp),Ag=function(){this.enabled=!0},Cg=function(t,e,i,n){this.entity=t,this.point=e,this.normal=i,this.hitFraction=n},Eg=function(t,e,i){0===arguments.length?(this.a=null,this.b=null,this.impulse=0,this.localPointA=new wt,this.localPointB=new wt,this.pointA=new wt,this.pointB=new wt,this.normal=new wt):(this.a=t,this.b=e,this.impulse=i.impulse,this.localPointA=i.localPoint,this.localPointB=i.localPointOther,this.pointA=i.point,this.pointB=i.pointOther,this.normal=i.normal)},Mg=function(t,e,i,n,s,r){void 0===t&&(t=new wt),void 0===e&&(e=new wt),void 0===i&&(i=new wt),void 0===n&&(n=new wt),void 0===s&&(s=new wt),void 0===r&&(r=0),this.localPoint=t,this.localPointOther=e,this.point=i,this.pointOther=n,this.normal=s,this.impulse=r},Pg=function(t,e){this.other=t,this.contacts=e},Rg=["enabled"],Ig=function(t){function e(e){var i;return(i=t.call(this,e)||this).maxSubSteps=10,i.fixedTimeStep=1/60,i.gravity=new wt(0,-9.81,0),i._gravityFloat32=new Float32Array(3),i._dynamic=[],i._kinematic=[],i._triggers=[],i._compounds=[],i.id="rigidbody",i._stats=e.stats.frame,i.ComponentType=Tg,i.DataType=Ag,i.contactPointPool=null,i.contactResultPool=null,i.singleContactResultPool=null,i.schema=Rg,i.collisions={},i.frameCollisions={},i.on("beforeremove",i.onBeforeRemove,w(i)),i.on("remove",i.onRemove,w(i)),i}S(e,t);var i=e.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 t=Ammo.addFunction(this._checkForCollisions.bind(this),"vif");this.dynamicsWorld.setInternalTickCallback(t)}gg=new Ammo.btVector3,yg=new Ammo.btVector3,Tg.onLibraryLoaded(),this.contactPointPool=new xg(Mg,1),this.contactResultPool=new xg(Pg,1),this.singleContactResultPool=new xg(Eg,1),this.app.systems.on("update",this.onUpdate,this)}else this.app.systems.off("update",this.onUpdate,this)},i.initializeComponentData=function(e,i,n){for(var s=0,r=["mass","linearDamping","angularDamping","linearFactor","angularFactor","friction","rollingFriction","restitution","type","group","mask"];s0)if(4&d||4&f){var g=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")),S=u.rigidbody&&(u.rigidbody.hasEvent("triggerenter")||u.rigidbody.hasEvent("triggerleave"));g&&(!(v=this._storeCollision(c,u))||4&f||c.collision.fire("triggerenter",u)),y&&(!(v=this._storeCollision(u,c))||4&d||u.collision.fire("triggerenter",c)),x&&(v||(v=this._storeCollision(u,c)),v&&c.rigidbody.fire("triggerenter",u)),S&&(v||(v=this._storeCollision(c,u)),v&&u.rigidbody.fire("triggerenter",c))}else{var b=this._hasContactEvent(c),w=this._hasContactEvent(u),T=this.hasEvent("contact");if(T||b||w){for(var A=0;A=0&&n!==t.element.drawOrder)null==(i=this.system.app.batcher)||i.markGroupDirty(t.element._batchGroupId)}t.particlesystem&&(t.particlesystem.drawOrder=e++);for(var s=t.children,r=0;r255&&(t=255),this._priority!==t&&(this._priority=t,this.syncDrawOrder())}}]),e}(bp),Fg=function(){this.enabled=!0},Bg=["enabled"],Ug=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="screen",i.ComponentType=kg,i.DataType=Fg,i.schema=Bg,i.windowResolution=new Et,i._drawOrderSyncQueue=new at,i.app.graphicsDevice.on("resizecanvas",i._onResize,w(i)),i.app.systems.on("update",i._onUpdate,w(i)),i.on("beforeremove",i.onRemoveComponent,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){void 0!==i.priority&&(e.priority=i.priority),void 0!==i.screenSpace&&(e.screenSpace=i.screenSpace),e.cull=e.screenSpace,void 0!==i.scaleMode&&(e.scaleMode=i.scaleMode),void 0!==i.scaleBlend&&(e.scaleBlend=i.scaleBlend),void 0!==i.resolution&&(i.resolution instanceof Et?e._resolution.copy(i.resolution):e._resolution.set(i.resolution[0],i.resolution[1]),e.resolution=e._resolution),void 0!==i.referenceResolution&&(i.referenceResolution instanceof Et?e._referenceResolution.copy(i.referenceResolution):e._referenceResolution.set(i.referenceResolution[0],i.referenceResolution[1]),e.referenceResolution=e._referenceResolution),e.syncDrawOrder(),t.prototype.initializeComponentData.call(this,e,i,n)},i.destroy=function(){t.prototype.destroy.call(this),this.app.graphicsDevice.off("resizecanvas",this._onResize,this),this.app.systems.off("update",this._onUpdate,this)},i._onUpdate=function(t){var e=this.store;for(var i in e)e[i].entity.screen.update&&e[i].entity.screen.update(t)},i._onResize=function(t,e){this.windowResolution.x=t,this.windowResolution.y=e},i.cloneComponent=function(t,e){var i=t.screen;return this.addComponent(e,{enabled:i.enabled,screenSpace:i.screenSpace,scaleMode:i.scaleMode,resolution:i.resolution.clone(),referenceResolution:i.referenceResolution.clone()})},i.onRemoveComponent=function(t,e){e.onRemove()},i.processDrawOrderSyncQueue=function(){for(var t=this._drawOrderSyncQueue.list(),e=0;e=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)}t.instances[i].instance===t[i]&&delete t[i],delete t.instances[i]}},i._postInitializeScriptComponent=function(t){this._callInstancesMethod(t,Hg),t.data.postInitialized=!0},i._updateInstances=function(t,e,i){for(var n=0,s=e.length;nthis.dragThreshold||Math.abs(i)>this.dragThreshold)&&this._disableContentInput()}},i._onSetContentOrViewportSize=function(){this._syncAll()},i._onSetHorizontalScrollbarValue=function(t){!this._scrollbarUpdateFlags[0]&&this.enabled&&this.entity.enabled&&this._onSetScroll(t,null)},i._onSetVerticalScrollbarValue=function(t){!this._scrollbarUpdateFlags[1]&&this.enabled&&this.entity.enabled&&this._onSetScroll(null,t)},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(t,e,i){!1!==i&&this._velocity.set(0,0,0);var n=this._updateAxis(t,"x",0),s=this._updateAxis(e,"y",1);(n||s)&&this.fire("set:scroll",this._scroll)},i._updateAxis=function(t,e,i){var n=null!==t&&Math.abs(t-this._scroll[e])>1e-5;return(n||this._isDragging()||0===t)&&(this._scroll[e]=this._determineNewScrollValue(t,e,i),this._syncContentPosition(i),this._syncScrollbarPosition(i)),n},i._determineNewScrollValue=function(t,e,i){if(!this._getScrollingEnabled(i))return this._scroll[e];switch(this.scrollMode){case 0:return _t.clamp(t,0,this._getMaxScrollValue(i));case 1:return this._setVelocityFromOvershoot(t,e,i),t;case 2:return t;default:return console.warn("Unhandled scroll mode:"+this.scrollMode),t}},i._syncAll=function(){this._syncContentPosition(0),this._syncContentPosition(1),this._syncScrollbarPosition(0),this._syncScrollbarPosition(1),this._syncScrollbarEnabledState(0),this._syncScrollbarEnabledState(1)},i._syncContentPosition=function(t){var e=this._getAxis(t),i=this._getSign(t),n=this._contentReference.entity;if(n){var s=this._prevContentSizes[t],r=this._getContentSize(t);if(null!==s&&Math.abs(s-r)>1e-4){var a=this._getMaxOffset(t,s),o=this._getMaxOffset(t,r);this._scroll[e]=0===o?1:_t.clamp(this._scroll[e]*a/o,0,1)}var h=this._scroll[e]*this._getMaxOffset(t),l=n.getLocalPosition();l[e]=h*i,n.setLocalPosition(l),this._prevContentSizes[t]=r}},i._syncScrollbarPosition=function(t){var e=this._getAxis(t),i=this._scrollbarReferences[t].entity;i&&i.scrollbar&&(this._scrollbarUpdateFlags[t]=!0,i.scrollbar.value=this._scroll[e],i.scrollbar.handleSize=this._getScrollbarHandleSize(e,t),this._scrollbarUpdateFlags[t]=!1)},i._syncScrollbarEnabledState=function(t){var e=this._scrollbarReferences[t].entity;if(e){var i=this._getScrollingEnabled(t),n=this._getScrollbarVisibility(t);switch(n){case 0:return void(e.enabled=i);case 1:return void(e.enabled=i&&this._contentIsLargerThanViewport(t));default:console.warn("Unhandled scrollbar visibility:"+n),e.enabled=i}}},i._contentIsLargerThanViewport=function(t){return this._getContentSize(t)>this._getViewportSize(t)},i._contentPositionToScrollValue=function(t){var e=this._getMaxOffset(0),i=this._getMaxOffset(1);return sy.x=0===e?0:t.x/e,sy.y=0===i?0:t.y/-i,sy},i._getMaxOffset=function(t,e){e=void 0===e?this._getContentSize(t):e;var i=this._getViewportSize(t);return e1e-4||Math.abs(this._velocity.y)>1e-4){var t=this._contentReference.entity.getLocalPosition();t.x+=this._velocity.x,t.y+=this._velocity.y,this._contentReference.entity.setLocalPosition(t),this._setScrollFromContentPosition(t)}this._velocity.x*=1-this.friction,this._velocity.y*=1-this.friction}},i._hasOvershoot=function(t,e){return Math.abs(this._toOvershoot(this.scroll[t],e))>.001},i._toOvershoot=function(t,e){var i=this._getMaxScrollValue(e);return t<0?t:t>i?t-i:0},i._setVelocityFromOvershoot=function(t,e,i){var n=this._toOvershoot(t,i)*this._getMaxOffset(i)*this._getSign(i);Math.abs(n)>0&&(this._velocity[e]=-n/(50*this.bounceAmount+1))},i._setVelocityFromContentPositionDelta=function(t){this._prevContentDragPosition?(this._velocity.sub2(t,this._prevContentDragPosition),this._prevContentDragPosition.copy(t)):(this._velocity.set(0,0,0),this._prevContentDragPosition=t.clone())},i._setScrollFromContentPosition=function(t){var e=this._contentPositionToScrollValue(t);this._isDragging()&&(e=this._applyScrollValueTension(e)),this._onSetScroll(e.x,e.y,!1)},i._applyScrollValueTension=function(t){var e=this._getMaxScrollValue(0),i=this._toOvershoot(t.x,0);return i>0?t.x=e+1*Math.log10(1+i):i<0&&(t.x=-1*Math.log10(1-i)),e=this._getMaxScrollValue(1),(i=this._toOvershoot(t.y,1))>0?t.y=e+1*Math.log10(1+i):i<0&&(t.y=-1*Math.log10(1-i)),t},i._isDragging=function(){return this._contentDragHelper&&this._contentDragHelper.isDragging},i._setScrollbarComponentsEnabled=function(t){this._scrollbarReferences[0].hasComponent("scrollbar")&&(this._scrollbarReferences[0].entity.scrollbar.enabled=t),this._scrollbarReferences[1].hasComponent("scrollbar")&&(this._scrollbarReferences[1].entity.scrollbar.enabled=t)},i._setContentDraggingEnabled=function(t){this._contentDragHelper&&(this._contentDragHelper.enabled=t)},i._onMouseWheel=function(t){if(this.useMouseWheel){var e=t.event,i=e.deltaX/this._contentReference.entity.element.calculatedWidth*this.mouseWheelSensitivity.x,n=e.deltaY/this._contentReference.entity.element.calculatedHeight*this.mouseWheelSensitivity.y,s=_t.clamp(this._scroll.x+i,0,this._getMaxScrollValue(0)),r=_t.clamp(this._scroll.y+n,0,this._getMaxScrollValue(1));this.scroll=new Et(s,r)}},i._enableContentInput=function(){for(;this._disabledContentInputEntities.length;){var t=this._disabledContentInputEntities.pop();t.element&&(t.element.useInput=!0)}this._disabledContentInput=!1},i._disableContentInput=function(){var t=this,e=function e(i){i.element&&i.element.useInput&&(t._disabledContentInputEntities.push(i),i.element.useInput=!1);for(var n=i.children,s=0,r=n.length;s1e-5&&(this.data.value=_t.clamp(i,0,1),this._updateHandlePositionAndSize(),this.fire("set:value",this.data.value))},i._onSetHandleSize=function(t,e,i){Math.abs(i-e)>1e-5&&(this.data.handleSize=_t.clamp(i,0,1),this._updateHandlePositionAndSize())},i._onSetHandleAlignment=function(){this._updateHandlePositionAndSize()},i._onSetOrientation=function(t,e,i){i!==e&&this._handleReference.hasComponent("element")&&(this._handleReference.entity.element[this._getOppositeDimension()]=0)},i._updateHandlePositionAndSize=function(){var t=this._handleReference.entity,e=t&&t.element;if(t){var i=t.getLocalPosition();i[this._getAxis()]=this._getHandlePosition(),this._handleReference.entity.setLocalPosition(i)}e&&(e[this._getDimension()]=this._getHandleLength())},i._handlePositionToScrollValue=function(t){return t*this._getSign()/this._getUsableTrackLength()},i._scrollValueToHandlePosition=function(t){return t*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(t){this._handleDragHelper&&(this._handleDragHelper.enabled=t)},i.onEnable=function(){this._handleReference.onParentComponentEnable(),this._setHandleDraggingEnabled(!0)},i.onDisable=function(){this._setHandleDraggingEnabled(!1)},i.onRemove=function(){this._destroyDragHelper(),this._toggleLifecycleListeners("off")},e}(bp),cy=function(){this.enabled=!0},uy=[{name:"enabled",type:"boolean"},{name:"orientation",type:"number"},{name:"value",type:"number"},{name:"handleSize",type:"number"},{name:"handleEntity",type:"entity"}],dy=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="scrollbar",i.ComponentType=ly,i.DataType=cy,i.schema=uy,i.on("beforeremove",i._onRemoveComponent,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){t.prototype.initializeComponentData.call(this,e,i,uy)},i._onRemoveComponent=function(t,e){e.onRemove()},e}(wp);bp._buildAccessors(ly.prototype,uy);var fy={volume:0,pitch:0,loop:!1,startTime:0,duration:0,position:new wt,maxDistance:0,refDistance:0,rollOffFactor:0,distanceModel:0,onPlay:null,onPause:null,onResume:null,onStop:null,onEnd:null},py=function(t){function e(e,i,n){var s;return void 0===i&&(i="Untitled"),void 0===n&&(n={}),(s=t.call(this)||this).name=void 0,s.instances=[],s._component=e,s._assets=e.system.app.assets,s._manager=e.system.manager,s.name=i,s._volume=void 0!==n.volume?_t.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 Vf&&(s._asset=s._asset.id),s._onInstancePlayHandler=s._onInstancePlay.bind(w(s)),s._onInstancePauseHandler=s._onInstancePause.bind(w(s)),s._onInstanceResumeHandler=s._onInstanceResume.bind(w(s)),s._onInstanceStopHandler=s._onInstanceStop.bind(w(s)),s._onInstanceEndHandler=s._onInstanceEnd.bind(w(s)),s}S(e,t);var i=e.prototype;return i.play=function(){if(this.overlap||this.stop(),this.isLoaded||this._hasAsset()){var t=this._createInstance();if(this.instances.push(t),this.isLoaded)t.play();else{var e=function(e){var i=t._playWhenLoaded;t.sound=e,i&&t.play()};this.off("load",e),this.once("load",e),this.load()}return t}},i.pause=function(){for(var t=!1,e=this.instances,i=0,n=e.length;i=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(t){var e=this._slots;if(e)for(var i in e)e[i].stop();var n={};for(var s in t)t[s]instanceof py?n[t[s].name]=t[s]:t[s].name&&(n[t[s].name]=new py(this,t[s].name,t[s]));this._slots=n,this.enabled&&this.entity.enabled&&this.onEnable()}}]),e}(bp),_y=function(){this.enabled=!0},vy=["enabled"],gy=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="sound",i.ComponentType=my,i.DataType=_y,i.schema=vy,i.manager=e.soundManager,i.app.systems.on("update",i.onUpdate,w(i)),i.on("beforeremove",i.onBeforeRemove,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){n=["volume","pitch","positional","refDistance","maxDistance","rollOffFactor","distanceModel","slots"];for(var s=0;sn||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(t){this._time=t;var e=this.duration;this._time<0?this.loop?this._time=this._time%e+e:this._time=0:this._time>e&&(this.loop?this._time%=e:this._time=e)},i._setFrame=function(t){this._sprite?this._frame=_t.clamp(t,0,this._sprite.frameKeys.length-1):this._frame=t,this._component.currentClip===this&&this._component._showFrame(this._frame)},i._destroy=function(){if(this._spriteAsset){var t=this._component.system.app.assets;this._unbindSpriteAsset(t.get(this._spriteAsset))}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))},y(e,[{key:"duration",get:function(){if(this._sprite){var t=this.fps||Number.MIN_VALUE;return this._sprite.frameKeys.length/Math.abs(t)}return 0}},{key:"frame",get:function(){return this._frame},set:function(t){this._setFrame(t);var e=this.fps||Number.MIN_VALUE;this._setTime(this._frame/e)}},{key:"isPaused",get:function(){return this._paused}},{key:"isPlaying",get:function(){return this._playing}},{key:"sprite",get:function(){return this._sprite},set:function(t){var e;(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=t,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)&&(t&&t.atlas?(t.atlas.texture&&((e=this._component._meshInstance)&&(e.setParameter("texture_emissiveMap",t.atlas.texture),e.setParameter("texture_opacityMap",t.atlas.texture)),this._component.enabled&&this._component.entity.enabled&&this._component._showModel()),this.time&&this.fps?this.time=this.time:this.frame=this.frame):((e=this._component._meshInstance)&&(e.deleteParameter("texture_emissiveMap"),e.deleteParameter("texture_opacityMap")),this._component._hideModel()))}},{key:"spriteAsset",get:function(){return this._spriteAsset},set:function(t){var e=this._component.system.app.assets,i=t;if(t instanceof Vf&&(i=t.id),this._spriteAsset!==i){if(this._spriteAsset){var n=e.get(this._spriteAsset);n&&this._unbindSpriteAsset(n)}if(this._spriteAsset=i,this._spriteAsset){var s=e.get(this._spriteAsset);s?this._bindSpriteAsset(s):(this.sprite=null,e.on("add:"+this._spriteAsset,this._onSpriteAssetAdded,this))}else this.sprite=null}}},{key:"time",get:function(){return this._time},set:function(t){this._setTime(t),this._sprite?this.frame=Math.min(this._sprite.frameKeys.length-1,Math.floor(this._time*Math.abs(this.fps))):this.frame=0}}]),e}(P),by="texture_emissiveMap",wy="texture_opacityMap",Ty="material_emissive",Ay="material_opacity",Cy=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._type=yy,n._material=e.defaultMaterial,n._color=new vt(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 Et(1,1),n._outerScaleUniform=new Float32Array(2),n._innerOffset=new Pt,n._innerOffsetUniform=new Float32Array(4),n._atlasRect=new Pt,n._atlasRectUniform=new Float32Array(4),n._batchGroupId=-1,n._batchGroup=null,n._node=new hh,n._model=new Gu,n._model.graph=n._node,n._meshInstance=null,i.addChild(n._model.graph),n._model._entity=i,n._updateAabbFunc=n._updateAabb.bind(w(n)),n._addedModel=!1,n._autoPlayClip=null,n._clips={},n._defaultClip=new Sy(w(n),{name:n.entity.name,fps:0,loop:!1,spriteAsset:null}),n._currentClip=n._defaultClip,n}S(e,t);var i=e.prototype;return i.onEnable=function(){var t,e=this.system.app,i=e.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==(t=e.batcher)||t.insert(Ho.SPRITE,this._batchGroupId,this.entity))},i.onDisable=function(){var t,e=this.system.app,i=e.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==(t=e.batcher)||t.remove(Ho.SPRITE,this._batchGroupId,this.entity))},i.onDestroy=function(){var t;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,null==(t=this._node)||t.remove(),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 t=[this._meshInstance],e=0,i=this._layers.length;e=0)null==(e=this.system.app.batcher)||e.remove(Ho.SPRITE,n,this.entity);if(this.entity.enabled&&t>=0)null==(i=this.system.app.batcher)||i.insert(Ho.SPRITE,t,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(t){this._autoPlayClip=t instanceof Sy?t.name:t,this._tryAutoPlay()}},{key:"drawOrder",get:function(){return this._drawOrder},set:function(t){this._drawOrder=t,this._meshInstance&&(this._meshInstance.drawOrder=t)}},{key:"layers",get:function(){return this._layers},set:function(t){this._addedModel&&this._hideModel(),this._layers=t,this._meshInstance&&this.enabled&&this.entity.enabled&&this._showModel()}},{key:"aabb",get:function(){return this._meshInstance?this._meshInstance.aabb:null}}]),e}(bp),Ey=function(){this.enabled=!0},My=["enabled"],Py=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="sprite",i.ComponentType=Cy,i.DataType=Ey,i.schema=My,i._defaultTexture=null,i._defaultMaterial=null,i._default9SlicedMaterialSlicedMode=null,i._default9SlicedMaterialTiledMode=null,i.app.systems.on("update",i.onUpdate,w(i)),i.on("beforeremove",i.onBeforeRemove,w(i)),i}S(e,t);var i=e.prototype;return i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this),this._defaultTexture&&(this._defaultTexture.destroy(),this._defaultTexture=null)},i.initializeComponentData=function(e,i,n){if(void 0!==i.enabled&&(e.enabled=i.enabled),e.type=i.type,i.layers&&Array.isArray(i.layers)&&(e.layers=i.layers.slice(0)),void 0!==i.drawOrder&&(e.drawOrder=i.drawOrder),void 0!==i.color){var s,r;if(i.color instanceof vt)e.color.set(i.color.r,i.color.g,i.color.b,null!=(s=i.opacity)?s:1);else e.color.set(i.color[0],i.color[1],i.color[2],null!=(r=i.opacity)?r:1);e.color=e.color}if(void 0!==i.opacity&&(e.opacity=i.opacity),void 0!==i.flipX&&(e.flipX=i.flipX),void 0!==i.flipY&&(e.flipY=i.flipY),void 0!==i.width&&(e.width=i.width),void 0!==i.height&&(e.height=i.height),void 0!==i.spriteAsset&&(e.spriteAsset=i.spriteAsset),i.sprite&&(e.sprite=i.sprite),void 0!==i.frame&&(e.frame=i.frame),i.clips)for(var a in i.clips)e.addClip(i.clips[a]);void 0!==i.speed&&(e.speed=i.speed),i.autoPlayClip&&(e.autoPlayClip=i.autoPlayClip),e.batchGroupId=void 0===i.batchGroupId||null===i.batchGroupId?-1:i.batchGroupId,t.prototype.initializeComponentData.call(this,e,i,n)},i.cloneComponent=function(t,e){var i=t.sprite;return this.addComponent(e,{enabled:i.enabled,type:i.type,spriteAsset:i.spriteAsset,sprite:i.sprite,width:i.width,height:i.height,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(t){var e=this.store;for(var i in e)if(e.hasOwnProperty(i)){var n=e[i];if(n.data.enabled&&n.entity.enabled){var s=n.entity.sprite;s._currentClip&&s._currentClip._update(t)}}},i.onBeforeRemove=function(t,e){e.onDestroy()},y(e,[{key:"defaultMaterial",get:function(){if(!this._defaultMaterial){var t=new Ls(this.app.graphicsDevice,{width:1,height:1,format:7,name:"sprite"}),e=new Uint8Array(t.lock());e[0]=e[1]=e[2]=e[3]=255,t.unlock();var i=new lu;i.diffuse.set(0,0,0),i.emissive.set(.5,.5,.5),i.emissiveMap=t,i.emissiveTint=!0,i.opacityMap=t,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=se,i.update(),this._defaultTexture=t,this._defaultMaterial=i}return this._defaultMaterial},set:function(t){this._defaultMaterial=t}},{key:"default9SlicedMaterialSlicedMode",get:function(){if(!this._default9SlicedMaterialSlicedMode){var t=this.defaultMaterial.clone();t.nineSlicedMode=1,t.update(),this._default9SlicedMaterialSlicedMode=t}return this._default9SlicedMaterialSlicedMode},set:function(t){this._default9SlicedMaterialSlicedMode=t}},{key:"default9SlicedMaterialTiledMode",get:function(){if(!this._default9SlicedMaterialTiledMode){var t=this.defaultMaterial.clone();t.nineSlicedMode=2,t.update(),this._default9SlicedMaterialTiledMode=t}return this._default9SlicedMaterialTiledMode},set:function(t){this._default9SlicedMaterialTiledMode=t}}]),e}(wp);bp._buildAccessors(Cy.prototype,My);var Ry=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._oldState=!0,n._size=new wt,n.on("set_enabled",n._onSetEnabled,w(n)),n}S(e,t);var i=e.prototype;return i.onEnable=function(){this._checkState()},i.onDisable=function(){this._checkState()},i._onSetEnabled=function(t,e,i){this._checkState()},i._checkState=function(){var t=this.enabled&&this.entity.enabled;t!==this._oldState&&(this._oldState=t,this.fire("enable"),this.fire("state",this.enabled))},i._onBeforeRemove=function(){this.fire("remove")},y(e,[{key:"size",get:function(){return this._size},set:function(t){t instanceof wt?this._size.copy(t):t instanceof Array&&t.length>=3&&this.size.set(t[0],t[1],t[2])}}]),e}(bp),Iy=function(){this.enabled=!0},Ly=["enabled"],Dy=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="zone",i.ComponentType=Ry,i.DataType=Iy,i.schema=Ly,i.on("beforeremove",i._onBeforeRemove,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(t,e,i){t.enabled=!e.hasOwnProperty("enabled")||!!e.enabled,e.size&&(e.size instanceof wt?t.size.copy(e.size):e.size instanceof Array&&e.size.length>=3&&t.size.set(e.size[0],e.size[1],e.size[2]))},i.cloneComponent=function(t,e){var i={size:t.zone.size};return this.addComponent(e,i)},i._onBeforeRemove=function(t,e){e._onBeforeRemove()},e}(wp);bp._buildAccessors(Ry.prototype,Ly);var Oy=function(t,e){this.effect=t,this.inputTarget=e,this.outputTarget=null,this.name=t.constructor.name},ky=function(){function t(t,e){this.app=t,this.camera=e,this.destinationRenderTarget=null,this.effects=[],this.enabled=!1,this.depthTarget=null,e.on("set:rect",this.onCameraRectChanged,this)}var e=t.prototype;return e._allocateColorBuffer=function(t,e){var i,n,s=this.camera.rect,r=this.destinationRenderTarget,a=this.app.graphicsDevice,o=Math.floor(s.z*(null!=(i=null==r?void 0:r.width)?i:a.width)),h=Math.floor(s.w*(null!=(n=null==r?void 0:r.height)?n:a.height));return new Ls(a,{name:e,format:t,width:o,height:h,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1})},e._createOffscreenTarget=function(t,e){var i=this.app.graphicsDevice,n=e&&i.getHdrFormat(!1,!0,!1,!1)||7,s=this.camera.entity.name+"-posteffect-"+this.effects.length,r=this._allocateColorBuffer(n,s);return new rn({colorBuffer:r,depth:t,stencil:t&&this.app.graphicsDevice.supportsStencil,samples:t?i.samples:1})},e._resizeOffscreenTarget=function(t){var e=t.colorBuffer.format,i=t.colorBuffer.name;t.destroyFrameBuffers(),t.destroyTextureBuffers(),t._colorBuffer=this._allocateColorBuffer(e,i),t._colorBuffers=[t._colorBuffer]},e._destroyOffscreenTarget=function(t){t.destroyTextureBuffers(),t.destroy()},e.addEffect=function(t){var e=this.effects,i=0===e.length,n=this._createOffscreenTarget(i,t.hdr),s=new Oy(t,n);e.push(s),this._sourceTarget=s.inputTarget,e.length>1&&(e[e.length-2].outputTarget=s.inputTarget),this._newPostEffect=t,t.needsDepthBuffer&&this._requestDepthMap(),this.enable(),this._newPostEffect=void 0},e.removeEffect=function(t){for(var e=-1,i=0,n=this.effects.length;i=0&&(e>0?this.effects[e-1].outputTarget=e+11&&(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[e].inputTarget),this.effects.splice(e,1)),this.enabled&&t.needsDepthBuffer&&this._releaseDepthMap(),0===this.effects.length&&this.disable()},e._requestDepthMaps=function(){for(var t=0,e=this.effects.length;t0},set:function(t){t&&!this._sceneColorMapRequested?(this.requestSceneColorMap(!0),this._sceneColorMapRequested=!0):this._sceneColorMapRequested&&(this.requestSceneColorMap(!1),this._sceneColorMapRequested=!1)}},{key:"renderSceneDepthMap",get:function(){return this._renderSceneDepthMap>0},set:function(t){t&&!this._sceneDepthMapRequested?(this.requestSceneDepthMap(!0),this._sceneDepthMapRequested=!0):this._sceneDepthMapRequested&&(this.requestSceneDepthMap(!1),this._sceneDepthMapRequested=!1)}},{key:"renderTarget",get:function(){return this._camera.renderTarget},set:function(t){this._camera.renderTarget=t,this.dirtyLayerCompositionCameras()}},{key:"scissorRect",get:function(){return this._camera.scissorRect},set:function(t){this._camera.scissorRect=t}},{key:"sensitivity",get:function(){return this._camera.sensitivity},set:function(t){this._camera.sensitivity=t}},{key:"shutter",get:function(){return this._camera.shutter},set:function(t){this._camera.shutter=t}},{key:"viewMatrix",get:function(){return this._camera.viewMatrix}}]),e}(bp),By=function(){this.enabled=!0},Uy=["enabled"],Ny=function(t){function e(e){var i;return(i=t.call(this,e)||this).cameras=[],i.id="camera",i.ComponentType=Fy,i.DataType=By,i.schema=Uy,i.on("beforeremove",i.onBeforeRemove,w(i)),i.app.on("prerender",i.onAppPrerender,w(i)),i.app.systems.on("update",i.onUpdate,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(e,i,n){n=["aspectRatio","aspectRatioMode","calculateProjection","calculateTransform","clearColor","clearColorBuffer","clearDepthBuffer","clearStencilBuffer","renderSceneColorMap","renderSceneDepthMap","cullFaces","farClip","flipFaces","fov","frustumCulling","horizontalFov","layers","renderTarget","nearClip","orthoHeight","projection","priority","rect","scissorRect","aperture","shutter","sensitivity"];for(var s=0;s=0&&(this.cameras.splice(e,1),Mu(this.cameras))},i.destroy=function(){t.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},e}(wp);bp._buildAccessors(Fy.prototype,Uy);var zy=[],Vy=[],Gy=function(t){function e(e,i){var n;return(n=t.call(this,e,i)||this)._cookieAsset=null,n._cookieAssetId=null,n._cookieAssetAdd=!1,n._cookieMatrix=null,n}S(e,t);var i=e.prototype;return i.addLightToLayers=function(){for(var t=0;t=0&&this.enabled&&this.entity.enabled&&(t.addLight(this),this.light.addLayer(t))},i.onLayerRemoved=function(t){this.layers.indexOf(t.id)>=0&&(t.removeLight(this),this.light.removeLayer(t))},i.refreshProperties=function(){for(var t=0;t=3&&i.length<=4){for(var u=0;ue.ind&&(o=e.ind),this._insertScriptInstance(r,o,a),this._scriptsIndex[s]={instance:r,onSwap:function(){i.swap(s)}},this[s]=r,e.preloading||r.__initializeAttributes(),this.fire("create",s,r),this.fire("create:"+s,r),this.system.app.scripts.on("swap:"+s,this._scriptsIndex[s].onSwap),e.preloading||(r.enabled&&!r._initialized&&(r._initialized=!0,r.initialize&&this._scriptMethod(r,Zy)),r.enabled&&!r._postInitialized&&(r._postInitialized=!0,r.postInitialize&&this._scriptMethod(r,Qy))),r}}else this._scriptsIndex[s]={awaiting:!0,ind:this._scripts.length};return null},i.destroy=function(t){var e=t,i=t;"string"==typeof i?i=this.system.app.scripts.get(i):i&&(e=i.__name);var n=this._scriptsIndex[e];if(delete this._scriptsIndex[e],!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:"+e,n.onSwap),delete this[e],this.fire("destroy",e,s||null),this.fire("destroy:"+e,s||null),s&&s.fire("destroy"),!0},i.swap=function(t){var e=t,i=t;"string"==typeof i?i=this.system.app.scripts.get(i):i&&(e=i.__name);var n=this._scriptsIndex[e];if(!n||!n.instance)return!1;var s=n.instance,r=this._scripts.indexOf(s),a=new i({app:this.system.app,entity:this.entity,enabled:s.enabled,attributes:s.__attributes});return!!a.swap&&(a.__initializeAttributes(),this._scripts[r]=a,this._scriptsIndex[e].instance=a,this[e]=a,a.__executionOrder=r,s.update&&this._updateList.remove(s),s.postUpdate&&this._postUpdateList.remove(s),a.update&&this._updateList.insert(a),a.postUpdate&&this._postUpdateList.insert(a),this._scriptMethod(a,"swap",s),this.fire("swap",e,a),this.fire("swap:"+e,a),!0)},i.resolveDuplicatedEntityReferenceProperties=function(t,e){var i=this.entity.script;for(var n in t._scriptsIndex){var s=this.system.app.scripts.get(n);if(s){var r=t._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,e);else if("json"===u.type&&Array.isArray(u.schema))for(var d=l[c],f=a?a[c]:o[c],p=0;p=i||e<0)return!1;var n=t,s=t;"string"!=typeof s?s=t.__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!==e&&(this._scripts.splice(e,0,this._scripts.splice(o,1)[0]),this._resetExecutionOrder(0,i),this._updateList.sort(),this._postUpdateList.sort(),this.fire("move",s,a,e,o),this.fire("move:"+s,a,e,o),!0)},y(e,[{key:"scripts",get:function(){return this._scripts},set:function(t){for(var e in this._scriptsData=t,t)if(t.hasOwnProperty(e)){var i=this._scriptsIndex[e];if(i){if("boolean"==typeof t[e].enabled&&(i.enabled=!!t[e].enabled),"object"==typeof t[e].attributes)for(var n in t[e].attributes)if(!Ky.reservedNames.has(n)){if(!i.__attributes.hasOwnProperty(n)){var s=this.system.app.scripts.get(e);s&&s.attributes.add(n,{})}i[n]=t[e].attributes[n]}}else console.log(this.order)}}},{key:"enabled",get:function(){return this._enabled},set:function(t){var e=this._enabled;this._enabled=t,this.fire("set","enabled",e,t)}}]),e}(bp),Jy=function(){this.enabled=!0},tx=0,ex=function(t){function e(e){var i;return(i=t.call(this,e)||this).id="script",i.ComponentType=$y,i.DataType=Jy,i._components=new ct({sortBy:"_executionOrder"}),i._enabledComponents=new ct({sortBy:"_executionOrder"}),i.preloading=!0,i.on("beforeremove",i._onBeforeRemove,w(i)),i.app.systems.on("initialize",i._onInitialize,w(i)),i.app.systems.on("postInitialize",i._onPostInitialize,w(i)),i.app.systems.on("update",i._onUpdate,w(i)),i.app.systems.on("postUpdate",i._onPostUpdate,w(i)),i}S(e,t);var i=e.prototype;return i.initializeComponentData=function(t,e){if(t._executionOrder=tx++,this._components.append(t),tx>Number.MAX_SAFE_INTEGER&&this._resetExecutionOrder(),t.enabled=!e.hasOwnProperty("enabled")||!!e.enabled,t.enabled&&t.entity.enabled&&this._enabledComponents.append(t),e.hasOwnProperty("order")&&e.hasOwnProperty("scripts")){t._scriptsData=e.scripts;for(var i=0;i=0&&e._onBeforeRemove(),this._removeComponentFromEnabled(e),this._components.remove(e)},i.destroy=function(){t.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)},e}(wp),ix=function(t){function e(){var e;return(e=t.call(this)||this)._meshes=null,e}S(e,t);var i=e.prototype;return i.destroy=function(){this.meshes=null},i.decRefMeshes=function(){if(this._meshes)for(var t=this._meshes.length,e=0;e0){var r=e.jobQueue.shift();e.run(t,r)}else{var a=e.workers[2].indexOf(t);if(-1!==a)e.workers[2].splice(a,1),e.workers[1].push(t);else{var o=e.workers[1].indexOf(t);-1!==o&&(e.workers[1].splice(o,1),e.workers[0].push(t))}}}))})),this.workers[0]=t;this.jobQueue.length&&(this.workers[0].length||this.workers[1].length);){var i=this.jobQueue.shift();if(this.workers[0].length>0){var n=this.workers[0].shift();this.workers[1].push(n),this.run(n,i)}else{var s=this.workers[1].shift();this.workers[2].push(s),this.run(s,i)}}},e.enqueueJob=function(t,e){var i={jobId:this.jobId++,buffer:t};if(this.jobCallbacks.set(i.jobId,e),this.workers[0].length>0){var n=this.workers[0].shift();this.workers[1].push(n),this.run(n,i)}else if(this.workers[1].length>0){var s=this.workers[1].shift();this.workers[2].push(s),this.run(s,i)}else this.jobQueue.push(i)},t}(),mx=function(t){var e=function(){return fetch(t).then((function(t){return t.arrayBuffer()})).then((function(t){return WebAssembly.compile(t)}))};return WebAssembly.compileStreaming?WebAssembly.compileStreaming(fetch(t)).catch((function(t){return e()})):e()},_x=function(t){if(cx)return!0;if(!t)if(ux)t=ux;else{var e=ht.getConfig("DracoDecoderModule");t=e?{jsUrl:e.glueUrl,wasmUrl:e.wasmUrl,numWorkers:e.numWorkers}:{jsUrl:"draco.wasm.js",wasmUrl:"draco.wasm.wasm",numWorkers:1}}return!(!t.jsUrl||!t.wasmUrl)&&(cx=new px,Promise.all([(i=t.jsUrl,new Promise((function(t,e){var n={cache:!0,responseType:"text",retry:!0,maxRetries:3};_a.get(i,n,(function(i,n){i?e(i):t(n)}))}))),mx(t.wasmUrl)]).then((function(e){for(var i=e[0],n=e[1],s=["/* draco */",i,"/* worker */","(\n"+lx.toString()+"\n)()\n\n"].join("\n"),r=new Blob([s],{type:"application/javascript"}),a=URL.createObjectURL(r),o=Math.max(1,Math.min(16,t.numWorkers||1)),h=[],l=0;l0&&o(n,Float32Array,1),s.length>0&&o(s,Uint16Array,65535),r.length>0&&o(r,Uint8Array,255)}(y),y.unlock(),y},Lx=function(t,e,i,n,s,r,a){var o,h=new qa(t);h.aabb=Ex(i[e.attributes.POSITION]);for(var l=[],c=0,u=Object.entries(e.attributes);c0?i.name=t.name:i.name="node_"+e,t.hasOwnProperty("matrix")&&(jx.data.set(t.matrix),jx.getTranslation(qx),i.setLocalPosition(qx),jx.getEulerAngles(qx),i.setLocalEulerAngles(qx),jx.getScale(qx),i.setLocalScale(qx)),t.hasOwnProperty("rotation")){var n=t.rotation;i.setLocalRotation(n[0],n[1],n[2],n[3])}if(t.hasOwnProperty("translation")){var s=t.translation;i.setLocalPosition(s[0],s[1],s[2])}if(t.hasOwnProperty("scale")){var r=t.scale;i.setLocalScale(r[0],r[1],r[2])}return i},Kx=function(t,e){var i="orthographic"===t.type?1:0,n=1===i?t.orthographic:t.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*_t.RAD_TO_DEG,n.aspectRatio&&(s.aspectRatioMode=1,s.aspectRatio=n.aspectRatio));var r=new ip(t.name);return r.addComponent("camera",s),r},Zx=function(t,e){var i={enabled:!1,type:"point"===t.type?"omni":t.type,color:t.hasOwnProperty("color")?new vt(t.color):vt.WHITE,range:t.hasOwnProperty("range")?t.range:9999,falloffMode:1,intensity:t.hasOwnProperty("intensity")?_t.clamp(t.intensity,0,2):1};t.hasOwnProperty("spot")&&(i.innerConeAngle=t.spot.hasOwnProperty("innerConeAngle")?t.spot.innerConeAngle*_t.RAD_TO_DEG:0,i.outerConeAngle=t.spot.hasOwnProperty("outerConeAngle")?t.spot.outerConeAngle*_t.RAD_TO_DEG:Math.PI/4),t.hasOwnProperty("intensity")&&(i.luminance=t.intensity*Uu.getLightUnitConversion(Ou[i.type],i.outerConeAngle,i.innerConeAngle));var n=new ip(e.name);return n.rotateLocal(90,0,0),n.addComponent("light",i),n},Qx=function(t,e,i,n){if(!e.hasOwnProperty("skins")||0===e.skins.length)return[];var s=new Map;return e.skins.map((function(r){return function(t,e,i,n,s,r){var a,o,h,l=e.joints,c=l.length,u=[];if(e.hasOwnProperty("inverseBindMatrices")){var d=e.inverseBindMatrices,f=Ax(i[d],n,!0),p=[];for(a=0;a0&&"localRotation"===D.paths[0].propertyPath[0]&&2!==D.interpolation&&v.push(P[P.length-1].output))}v.sort();var O,k=null;for(o=0;o0){var s,r,a,o,h=null==i||null==(s=i.camera)?void 0:s.preprocess,l=null!=(r=null==i||null==(a=i.camera)?void 0:a.process)?r:Kx,c=null==i||null==(o=i.camera)?void 0:o.postprocess;t.nodes.forEach((function(i,s){if(i.hasOwnProperty("camera")){var r=t.cameras[i.camera];if(r){h&&h(r);var a=l(r,e[s]);c&&c(r,a),a&&(n||(n=new Map),n.set(i,a))}}}))}return n},rS=function(t,e,i){var n=null;if(t.hasOwnProperty("nodes")&&t.hasOwnProperty("extensions")&&t.extensions.hasOwnProperty("KHR_lights_punctual")&&t.extensions.KHR_lights_punctual.hasOwnProperty("lights")){var s=t.extensions.KHR_lights_punctual.lights;if(s.length){var r,a,o,h,l=null==i||null==(r=i.light)?void 0:r.preprocess,c=null!=(a=null==i||null==(o=i.light)?void 0:o.process)?a:Zx,u=null==i||null==(h=i.light)?void 0:h.postprocess;t.nodes.forEach((function(t,i){if(t.hasOwnProperty("extensions")&&t.extensions.hasOwnProperty("KHR_lights_punctual")&&t.extensions.KHR_lights_punctual.hasOwnProperty("light")){var r=t.extensions.KHR_lights_punctual.light,a=s[r];if(a){l&&l(a);var o=c(a,e[i]);u&&u(a,o),o&&(n||(n=new Map),n.set(t,o))}}}))}}return n},aS=function(t,e,i){t.nodes.forEach((function(t){t.hasOwnProperty("mesh")&&t.hasOwnProperty("skin")&&e[t.mesh].meshes.forEach((function(e){e.skin=i[t.skin]}))}))},oS=(fx=v(m().mark((function t(e,i,n,s,r){var a,o,h,l,c,u,d,f,p,_,v,g,y,x,S,b,w,T,A,C,E,M,P,R;return m().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return h=null==r||null==(a=r.global)?void 0:a.preprocess,l=null==r||null==(o=r.global)?void 0:o.postprocess,h&&h(i),c=i.asset&&"PlayCanvas"===i.asset.generator,u=iS(i,r),d=nS(i,u),f=rS(i,u,r),p=sS(i,u,r),_=tS(i),t.next=12,Promise.all(n);case 12:return v=t.sent,g=$x(e,i,v,c,r),y=g.meshes,x=g.meshVariants,S=g.meshDefaultMaterials,b=g.promises,w=eS(i,u,v,r),t.next=17,Promise.all(s);case 17:for(T=t.sent,A=T.map((function(t){return t.resource})),C=Jx(i,A,r,c),E=Qx(e,i,u,v),M=[],P=0;Pi.byteLength)e("Invalid length found in glb header. Found "+r);else{for(var a=[],o=12;oi.byteLength&&e("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?e("Invalid chunk type found in glb file. Expected 0x004E4942, found 0x"+a[1].type.toString(16)):e(null,{gltfChunk:a[0].data,binaryChunk:2===a.length?a[1].data:null}):e("Invalid chunk type found in glb file. Expected 0x4E4F534A, found 0x"+a[0].type.toString(16)):e("Invalid number of chunks found in glb file.")}else e("Invalid version number found in glb header. Expected 2, found "+s);else e("Invalid magic number found in glb header. Expected 0x46546C67, found 0x"+n.toString(16))}(e,i):i(null,{gltfChunk:e,binaryChunk:null})},cS=function(){function t(){}return t.parse=function(t,e,i,n,s,r,a){lS(t,i,(function(t,i){t?a(t):function(t,e){var i=JSON.parse(function(t){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(t);for(var e="",i=0;i0,maxRetries:this.maxRetries};(t.load.startsWith("blob:")||t.load.startsWith("data:"))&&(".glb"===L.getExtension(t.original).toLowerCase()?s.responseType=ma.ResponseType.ARRAY_BUFFER:s.responseType=ma.ResponseType.JSON),_a.get(t.load,s,(function(s,r){var a;s?e("Error loading animation resource: "+t.original+" ["+s+"]"):".glb"===L.getExtension(t.original).toLowerCase()?cS.parse("filename.glb","",r,n.device,n.assets,null!=(a=null==i?void 0:i.options)?a:{},(function(t,n){if(t)e(t);else{var s,r=n.animations;if(null!=i&&null!=(s=i.data)&&s.events)for(var a=0;a0,maxRetries:this.maxRetries};t.load.startsWith("blob:")&&(i.responseType=ma.ResponseType.JSON),_a.get(t.load,i,(function(i,n){i?e("Error loading animation clip resource: "+t.original+" ["+i+"]"):e(null,n)}))},e.open=function(t,e){var i=e.name,n=e.duration,s=e.inputs.map((function(t){return new hx(1,t)})),r=e.outputs.map((function(t){return new hx(t.components,t.data)})),a=e.curves.map((function(t){return new ox([t.path],t.inputIndex,t.outputIndex,t.interpolation)}));return new nm(i,n,s,r,a)},e.patch=function(t,e){},t}(),fS=function(){function t(t){this.handlerType="animstategraph",this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};t.load.startsWith("blob:")&&(i.responseType=ma.ResponseType.JSON),_a.get(t.load,i,(function(i,n){i?e("Error loading animation state graph resource: "+t.original+" ["+i+"]"):e(null,n)}))},e.open=function(t,e){return new Em(e)},e.patch=function(t,e){},t}(),pS=function(){if("undefined"==typeof window)return!1;var t=window.navigator.userAgent,e=t.indexOf("MSIE ");if(e>0)return parseInt(t.substring(e+5,t.indexOf(".",e)),10);if(t.indexOf("Trident/")>0){var i=t.indexOf("rv:");return parseInt(t.substring(i+3,t.indexOf(".",i)),10)}return!1}(),mS=[".ogg",".mp3",".wav",".mp4a",".m4a",".mp4",".aac",".opus"],_S=function(){function t(t){this.handlerType="audio",this.manager=t.soundManager,this.maxRetries=0}var e=t.prototype;return e._isSupported=function(t){var e=L.getExtension(t);return mS.indexOf(e)>-1},e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t});var i=function(i){var n="Error loading audio url: "+t.original;i&&(n+=": "+(i.message||i)),console.warn(n),e(n)};if(this._createSound){if(!this._isSupported(t.original))return void i("Audio format for "+t.original+" not supported");this._createSound(t.load,(function(t){e(null,new Aa(t))}),i)}else i(null)},e.open=function(t,e){return e},e.patch=function(t,e){},e._createSound=function(t,e,i){if(va()){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};(t.startsWith("blob:")||t.startsWith("data:"))&&(s.responseType=ma.ResponseType.ARRAY_BUFFER),_a.get(t,s,(function(t,s){t?i(t):n.context.decodeAudioData(s,e,i)}))}else{var r=null;try{r=new Audio}catch(t){return void i("No support for Audio element")}pS&&document.body.appendChild(r);r.onerror=function(){r.onerror=null,pS&&document.body.removeChild(r),i()},r.addEventListener("canplaythrough",(function t(){r.removeEventListener("canplaythrough",t),pS&&document.body.removeChild(r),e(r)})),r.src=t}},t}(),vS=function(){function t(t){this.handlerType="binary",this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t}),_a.get(t.load,{responseType:ma.ResponseType.ARRAY_BUFFER,retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?e("Error loading binary resource: "+t.original+" ["+i+"]"):e(null,n)}))},e.open=function(t,e){return e},e.patch=function(t,e){},t}(),gS=function(){function t(e,i,n,s){for(var r=function(e,s,r){var a=t.createAsset(i.name,e,s,r);return n.add(a),a},a=[],o=0;o=0?t.split("?")[0]:t},e.load=function(t,e,i){var n=this;Vf.fetchArrayBuffer(t.load,(function(s,r){s?e(s):cS.parse(n._getUrlWithoutParams(t.original),L.extractPath(t.load),r,n._device,i.registry,i.options,(function(t,s){t?e(t):e(null,new gS(s,i,n._assets,n._defaultMaterial))}))}),i,this.maxRetries)},e.open=function(t,e,i){return e},e.patch=function(t,e){},t}(),xS=function(){function t(){}var e=t.prototype;return e.instantiateModelEntity=function(t){return null},e.instantiateRenderEntity=function(t){return null},e.getMaterialVariants=function(){return null},e.applyMaterialVariant=function(t,e){},e.applyMaterialVariantInstances=function(t,e){},t}(),SS=function(){function t(t){this.handlerType="container",this.glbContainerParser=new yS(t.graphicsDevice,t.assets,0),this.parsers={}}var e=t.prototype;return e._getUrlWithoutParams=function(t){return t.indexOf("?")>=0?t.split("?")[0]:t},e._getParser=function(t){var e=t?L.getExtension(this._getUrlWithoutParams(t)).toLowerCase().replace(".",""):null;return this.parsers[e]||this.glbContainerParser},e.load=function(t,e,i){"string"==typeof t&&(t={load:t,original:t}),this._getParser(t.original).load(t,e,i)},e.open=function(t,e,i){return this._getParser(t).open(t,e,i)},e.patch=function(t,e){},y(t,[{key:"maxRetries",get:function(){return this.glbContainerParser.maxRetries},set:function(t){for(var e in this.glbContainerParser.maxRetries=t,this.parsers)this.parsers.hasOwnProperty(e)&&(this.parsers[e].maxRetries=t)}}]),t}(),bS=function(){function t(t){this.handlerType="css",this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t}),_a.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?e("Error loading css resource: "+t.original+" ["+i+"]"):e(null,n)}))},e.open=function(t,e){return e},e.patch=function(t,e){},t}(),wS=function(){function t(t){this.handlerType="cubemap",this._device=t.graphicsDevice,this._registry=t.assets,this._loader=t.loader}var e=t.prototype;return e.load=function(t,e,i){this.loadAssets(i,e)},e.open=function(t,e,i){return i?i.resource:null},e.patch=function(t,e){this.loadAssets(t,(function(i,n){i&&(e.fire("error",t),e.fire("error:"+t.id,i,t),t.fire("error",t))}))},e.getAssetIds=function(t){var e=[];if(e[0]=t.file,(t.loadFaces||!t.file)&&t.data&&t.data.textures)for(var i=0;i<6;++i)e[i+1]=t.data.textures[i];else e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=null;return e},e.compareAssetIds=function(t,e){return t&&e?parseInt(t,10)===t||"string"==typeof t?t===e:t.url===e.url:null!==t==(null!==e)},e.update=function(t,e,i){var n,s,r,a=t.data||{},o=t._handlerState.assets,h=t._resources,l=[null,null,null,null,null,null,null],c=function(){return a.hasOwnProperty("type")?a.type:a.hasOwnProperty("rgbm")?a.rgbm?ii:ei:null};if(t.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])if((n=i[0].resource).cubemap)for(r=0;r<6;++r)l[r+1]=new Ls(this._device,{name:t.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});else n.type=si,n.addressU=1,n.addressV=1,n.mipmaps=!1,l[1]=n;var u=i.slice(1);if(t.loaded&&this.cmpArrays(u,o.slice(1)))l[0]=h[0]||null;else if(-1===u.indexOf(null)){var d,f=u.map((function(t){return t.resource})),p=[];for(s=0;s0,maxRetries:this.maxRetries},(function(i,s){if(i)e("Error loading font resource: "+t.original+" ["+i+"]");else{var r=CS(s);n._loadTextures(t.load.replace(".json",".png"),r,(function(t,i){t?e(t):e(null,{data:r,textures:i})}))}})):(i&&i.data&&(i.data=CS(i.data)),this._loadTextures(t.load,i&&i.data,e))},e._loadTextures=function(t,e,i){for(var n=e.info.maps.length,s=0,r=null,a=new Array(n),o=this._loader,h=function(e){var h=function(t,o){if(!r){if(t)return r=t,void i(t);o.upload(),a[e]=o,++s===n&&i(null,a)}};0===e?o.load(t,"texture",h):o.load(t.replace(".png",e+".png"),"texture",h)},l=0;l0,maxRetries:e},(function(e,n){if(e){var s="Error while loading scene JSON "+t.original;e.message?(s+=": "+e.message,e.stack&&(s+="\n"+e.stack)):s+=": "+e,i(s)}else i(e,n)}))},t}(),LS=function(){function t(t){this.handlerType="hierarchy",this._app=t,this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){IS.load(t,this.maxRetries,e)},e.open=function(t,e){this._app.systems.script.preloading=!0;var i=new RS(this._app,!1).parse(e);return this._app.systems.script.preloading=!1,i},t}(),DS=function(){function t(t){this.handlerType="html",this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t}),_a.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?e("Error loading html resource: "+t.original+" ["+i+"]"):e(null,n)}))},e.open=function(t,e){return e},e.patch=function(t,e){},t}(),OS=function(){function t(t){this.handlerType="json",this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};t.load.startsWith("blob:")&&(i.responseType=ma.ResponseType.JSON),_a.get(t.load,i,(function(i,n){i?e("Error loading JSON resource: "+t.original+" ["+i+"]"):e(null,n)}))},e.open=function(t,e){return e},e.patch=function(t,e){},t}(),kS=function(){function t(){this.removeInvalid=!0,this.valid=!0,this.enumValidators={occludeSpecular:this._createEnumValidator([0,1,2]),cull:this._createEnumValidator([se,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 e=t.prototype;return e.setInvalid=function(t,e){this.valid=!1,this.removeInvalid&&delete e[t]},e.validate=function(t){var e=tu,i=ru,n="path"===t.mappingFormat;for(var s in t){var r=e[s];if(r)if(r.startsWith("enum")){var a=r.split(":")[1];this.enumValidators[a]&&(this.enumValidators[a](t[s])||this.setInvalid(s,t))}else if("number"===r)"number"!=typeof t[s]&&this.setInvalid(s,t);else if("boolean"===r)"boolean"!=typeof t[s]&&this.setInvalid(s,t);else if("string"===r)"string"!=typeof t[s]&&this.setInvalid(s,t);else if("vec2"===r)t[s]instanceof Array&&2===t[s].length||this.setInvalid(s,t);else if("rgb"===r)t[s]instanceof Array&&3===t[s].length||this.setInvalid(s,t);else if("texture"===r)n?"string"!=typeof t[s]&&null!==t[s]&&(t[s]instanceof Ls||this.setInvalid(s,t)):"number"!=typeof t[s]&&null!==t[s]&&(t[s]instanceof Ls||this.setInvalid(s,t));else if("boundingbox"===r)t[s].center&&t[s].center instanceof Array&&3===t[s].center.length||this.setInvalid(s,t),t[s].halfExtents&&t[s].halfExtents instanceof Array&&3===t[s].halfExtents.length||this.setInvalid(s,t);else if("cubemap"===r)"number"!=typeof t[s]&&null!==t[s]&&void 0!==t[s]&&(t[s]instanceof Ls&&t[s].cubemap||this.setInvalid(s,t));else if("chunks"===r)for(var o=Object.keys(t[s]),h=0;h=0}},t}(),FS=function(){function t(){this._validator=null}var e=t.prototype;return e.parse=function(t){var e=this.migrate(t),i=this._validate(e),n=new lu;return this.initialize(n,i),n},e.initialize=function(t,e){for(var i in e.validated||(e=this._validate(e)),e.chunks&&(t.chunks=x({},e.chunks)),e){var n=tu[i],s=e[i];if("vec2"===n)t[i]=new Et(s[0],s[1]);else if("rgb"===n)t[i]=new vt(s[0],s[1],s[2]);else if("texture"===n)s instanceof Ls?t[i]=s:t[i]instanceof Ls&&"number"==typeof s&&s>0||(t[i]=null);else if("cubemap"===n)s instanceof Ls?t[i]=s:t[i]instanceof Ls&&"number"==typeof s&&s>0||(t[i]=null),"cubeMap"!==i||s||(t.prefilteredCubemaps=null);else if("boundingbox"===n){var r=new wt(s.center[0],s.center[1],s.center[2]),a=new wt(s.halfExtents[0],s.halfExtents[1],s.halfExtents[2]);t[i]=new Ht(r,a)}else t[i]=e[i]}t.update()},e.migrate=function(t){var e;void 0===t.shadingModel&&("blinn"===t.shader?t.shadingModel=1:t.shadingModel=0),t.shader&&delete t.shader,t.mapping_format&&(t.mappingFormat=t.mapping_format,delete t.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"],["clearCoatGlossiness","clearCoatGloss"]];for(e=0;e0,maxRetries:this.maxRetries},(function(i,n){i?e&&e("Error loading material: "+t.original+" ["+i+"]"):e&&(n._engine=!0,e(null,n))}))},e.open=function(t,e){var i=this._parser.parse(e);return e._engine&&(i._data=e,delete e._engine),i},e._createPlaceholders=function(){this._placeholderTextures={};var t={white:[255,255,255,255],gray:[128,128,128,255],black:[0,0,0,255],normal:[128,128,255,255]};for(var e in t)if(t.hasOwnProperty(e)){this._placeholderTextures[e]=new Ls(this._device,{width:2,height:2,format:7,name:"material_placeholder"});for(var i=this._placeholderTextures[e].lock(),n=0;n<4;n++)for(var s=0;s<4;s++)i[4*n+s]=t[e][s];this._placeholderTextures[e].unlock()}},e.patch=function(t,e){t.resource._data&&(t._data=t.resource._data,delete t.resource._data),t.data.name=t.name,t.resource.name=t.name,this._bindAndAssignAssets(t,e),t.off("unload",this._onAssetUnload,this),t.on("unload",this._onAssetUnload,this)},e._onAssetUnload=function(t){delete t.data.parameters,delete t.data.chunks,delete t.data.name},e._assignTexture=function(t,e,i){e.resource[t]=i},e._getPlaceholderTexture=function(t){this._placeholderTextures||this._createPlaceholders();var e=BS[t];return this._placeholderTextures[e]},e._assignPlaceholderTexture=function(t,e){e.resource[t]=this._getPlaceholderTexture(t)},e._onTextureLoad=function(t,e,i){this._assignTexture(t,e,i.resource),e.resource.update()},e._onTextureAdd=function(t,e,i){this._assets.load(i)},e._onTextureRemoveOrUnload=function(t,e,i){var n=e.resource;n&&e.resource[t]===i.resource&&(this._assignPlaceholderTexture(t,e),n.update())},e._assignCubemap=function(t,e,i){if(e.resource[t]=i[0],"cubeMap"===t){var n=i.slice(1);n.every((function(t){return t}))?e.resource.prefilteredCubemaps=n:n[0]&&(e.resource.envAtlas=n[0])}},e._onCubemapLoad=function(t,e,i){this._assignCubemap(t,e,i.resources),this._parser.initialize(e.resource,e.data)},e._onCubemapAdd=function(t,e,i){0===e.data.shadingModel&&(e.loadFaces=!0),this._assets.load(i)},e._onCubemapRemoveOrUnload=function(t,e,i){var n=e.resource;e.data.prefilteredCubeMap128===i.resources[1]&&(this._assignCubemap(t,e,[null,null,null,null,null,null,null]),n.update())},e._bindAndAssignAssets=function(t,e){var i,n,s,r=this._parser.migrate(t.data),a=t.resource,o="path"===r.mappingFormat,h=eu;for(i=0;i0){for(var c=i.blendIndices.data[4*h+l],u=!0,d=0;dn)return!1;for(var f=0;f=0;n--)if(l[n].boneNames.length>i){var f=l.splice(n,1)[0],p=[];for(s=0;s=0;r--)u[r].mesh===_.originalMesh&&(u.push({mesh:o,node:u[r].node}),e&&e.push({material:e[r].material,path:e[r].path}));for(s=0;s=0;r--)u[r].mesh===_.originalMesh&&(u.splice(r,1),e&&e.splice(r,1))}!function(t){for(var e=t.vertices,i=t.skins,n=t.meshes,s=t.meshInstances,r=0;r0&&GS(s,null,this._device.getBoneLimit());for(i=0;i0&&(h>65535&&this._device.extUintElement?(s=new vr(this._device,2,a),r=new Uint32Array(s.lock())):(s=new vr(this._device,1,a),r=new Uint16Array(s.lock()))),{buffer:s,data:r}},e._parseMeshes=function(t,e,i,n,s,r){for(var a=t.model,o=[],h=0,l=0;l0,maxRetries:this.maxRetries};(t.load.startsWith("blob:")||t.load.startsWith("data:"))&&(".glb"===L.getExtension(t.original).toLowerCase()?s.responseType=ma.ResponseType.ARRAY_BUFFER:s.responseType=ma.ResponseType.JSON),_a.get(t.load,s,(function(s,r){if(e)if(s)e("Error loading model: "+t.original+" ["+s+"]");else{for(var a=0;a0,maxRetries:this.maxRetries},(function(i,n){i?e("Error loading shader resource: "+t.original+" ["+i+"]"):e(null,n)}))},e.open=function(t,e){return e},e.patch=function(t,e){},t}();function ZS(t){this.resource&&(this.resource.atlas=t.resource)}function QS(t){this.registry.load(t)}var $S=function(){function t(t){this.handlerType="sprite",this._assets=t.assets,this._device=t.graphicsDevice,this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t}),".json"===L.getExtension(t.original)&&_a.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(t,i){t?e(t):e(null,i)}))},e.open=function(t,e){var i=new $d(this._device);return t&&(i.__data=e),i},e.patch=function(t,e){var i=t.resource;if(i.__data&&(t.data.pixelsPerUnit=i.__data.pixelsPerUnit,t.data.renderMode=i.__data.renderMode,t.data.frameKeys=i.__data.frameKeys,i.__data.textureAtlasAsset)){var n=e.getByUrl(i.__data.textureAtlasAsset);n?t.data.textureAtlasAsset=n.id:console.warn("Could not find textureatlas with url: "+i.__data.textureAtlasAsset)}i.startUpdate(),i.renderMode=t.data.renderMode,i.pixelsPerUnit=t.data.pixelsPerUnit,i.frameKeys=t.data.frameKeys,this._updateAtlas(t),i.endUpdate(),t.off("change",this._onAssetChange,this),t.on("change",this._onAssetChange,this)},e._updateAtlas=function(t){var e=t.resource;if(t.data.textureAtlasAsset){this._assets.off("load:"+t.data.textureAtlasAsset,ZS,t),this._assets.on("load:"+t.data.textureAtlasAsset,ZS,t);var i=this._assets.get(t.data.textureAtlasAsset);i&&i.resource?e.atlas=i.resource:i?this._assets.load(i):(this._assets.off("add:"+t.data.textureAtlasAsset,QS,t),this._assets.on("add:"+t.data.textureAtlasAsset,QS,t))}else e.atlas=null},e._onAssetChange=function(t,e,i,n){"data"===e&&i&&i.textureAtlasAsset&&n&&i.textureAtlasAsset!==n.textureAtlasAsset&&(this._assets.off("load:"+n.textureAtlasAsset,ZS,t),this._assets.off("add:"+n.textureAtlasAsset,QS,t))},t}(),JS=function(){function t(t,e){this._app=void 0,this._data=void 0,this._templateRoot=null,this._app=t,this._data=e}var e=t.prototype;return e.instantiate=function(){return this._templateRoot||this._parseTemplate(),this._templateRoot.clone()},e._parseTemplate=function(){var t=new RS(this._app,!0);this._templateRoot=t.parse(this._data)},t}(),tb=function(){function t(t){this.handlerType="template",this._app=t,this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};_a.get(t.load,i,(function(i,n){i?e("Error requesting template: "+t.original):e(i,n)}))},e.open=function(t,e){return new JS(this._app,e)},t}(),eb=function(){function t(t){this.handlerType="text",this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t}),_a.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?e("Error loading text resource: "+t.original+" ["+i+"]"):e(null,n)}))},e.open=function(t,e){return e},e.patch=function(t,e){},t}(),ib={repeat:0,clamp:1,mirror:2},nb={nearest:0,linear:1,nearest_mip_nearest:2,linear_mip_nearest:4,nearest_mip_linear:3,linear_mip_linear:5},sb=/^data\.frames\.(\d+)$/,rb=function(){function t(t){this.handlerType="textureatlas",this._loader=t.loader,this.maxRetries=0}var e=t.prototype;return e.load=function(t,e){"string"==typeof t&&(t={load:t,original:t});var i=this,n=this._loader.getHandler("texture");".json"===L.getExtension(t.original)?_a.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(n,s){if(n)e(n);else{var r=t.original.replace(".json",".png");i._loader.load(r,"texture",(function(t,i){t?e(t):e(null,{data:s,texture:i})}))}})):n.load(t,e)},e.open=function(t,e){var i=new Jd;if(e.texture&&e.data)i.texture=e.texture,i.__data=e.data;else{var n=this._loader.getHandler("texture").open(t,e);if(!n)return null;i.texture=n}return i},e.patch=function(t,e){if(t.resource){t.resource.__data&&(void 0!==t.resource.__data.minfilter&&(t.data.minfilter=t.resource.__data.minfilter),void 0!==t.resource.__data.magfilter&&(t.data.magfilter=t.resource.__data.magfilter),void 0!==t.resource.__data.addressu&&(t.data.addressu=t.resource.__data.addressu),void 0!==t.resource.__data.addressv&&(t.data.addressv=t.resource.__data.addressv),void 0!==t.resource.__data.mipmaps&&(t.data.mipmaps=t.resource.__data.mipmaps),void 0!==t.resource.__data.anisotropy&&(t.data.anisotropy=t.resource.__data.anisotropy),void 0!==t.resource.__data.rgbm&&(t.data.rgbm=!!t.resource.__data.rgbm),t.data.frames=t.resource.__data.frames,delete t.resource.__data);var i=t.resource.texture;if(i&&(i.name=t.name,t.data.hasOwnProperty("minfilter")&&i.minFilter!==nb[t.data.minfilter]&&(i.minFilter=nb[t.data.minfilter]),t.data.hasOwnProperty("magfilter")&&i.magFilter!==nb[t.data.magfilter]&&(i.magFilter=nb[t.data.magfilter]),t.data.hasOwnProperty("addressu")&&i.addressU!==ib[t.data.addressu]&&(i.addressU=ib[t.data.addressu]),t.data.hasOwnProperty("addressv")&&i.addressV!==ib[t.data.addressv]&&(i.addressV=ib[t.data.addressv]),t.data.hasOwnProperty("mipmaps")&&i.mipmaps!==t.data.mipmaps&&(i.mipmaps=t.data.mipmaps),t.data.hasOwnProperty("anisotropy")&&i.anisotropy!==t.data.anisotropy&&(i.anisotropy=t.data.anisotropy),t.data.hasOwnProperty("rgbm"))){var n=t.data.rgbm?ii:ei;i.type!==n&&(i.type=n)}t.resource.texture=i;var s={};for(var r in t.data.frames){var a=t.data.frames[r];s[r]={rect:new Pt(a.rect),pivot:new Et(a.pivot),border:new Pt(a.border)}}t.resource.frames=s,t.off("change",this._onAssetChange,this),t.on("change",this._onAssetChange,this)}},e._onAssetChange=function(t,e,i){var n;if("data"===e||"data.frames"===e){var s={};for(var r in i.frames)n=i.frames[r],s[r]={rect:new Pt(n.rect),pivot:new Et(n.pivot),border:new Pt(n.border)};t.resource.frames=s}else{var a=e.match(sb);if(a){var o=a[1];i?(t.resource.frames[o]?((n=t.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])):t.resource.frames[o]={rect:new Pt(i.rect),pivot:new Et(i.pivot),border:new Pt(i.border)},t.resource.fire("set:frame",o,t.resource.frames[o])):t.resource.frames[o]&&(delete t.resource.frames[o],t.resource.fire("remove:frame",o))}}},t}();function ab(){var t,e,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},v=21,g=22,y=23,x=8,S=10,b=26,w=27,T=28,A=29,C=30,E=7,M=3,P=5,R=function(t,e){switch(t){case n:return e.formats.etc1?v:g;case s:return y;case r:return x;case a:return S;case o:return b;case h:return w;case l:return T;case c:return A;case u:return C;case d:return E;case f:return M;case p:return P}},I=function(t){for(var e=function(t,e){var i=t*(2/255)-1,n=e*(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>3}return e},D=function(){return"undefined"!=typeof performance?performance.now():0},O=function(t,n,s){if(s){if(t.formats.astc)return"astc"}else if(n){if(t.formats.etc2)return"etc2"}else if(t.formats.etc1||t.formats.etc2)return"etc1";return function(e){for(var i=0;i0,maxRetries:t.maxRetries};if(t.glueUrl&&t.wasmUrl&&function(){try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){var t=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(t instanceof WebAssembly.Module)return new WebAssembly.Instance(t)instanceof WebAssembly.Instance}}catch(t){}return!1}()){var r=null,a=null;_a.get(t.glueUrl,s,(function(t,i){t?e(t):a?n(i,a):r=i}));var o=fetch(t.wasmUrl),h=function(){o.then((function(t){return t.arrayBuffer()})).then((function(t){return WebAssembly.compile(t)})).then((function(t){r?n(r,t):a=t})).catch((function(t){e(t,null)}))};WebAssembly.compileStreaming?WebAssembly.compileStreaming(o).then((function(t){r?n(r,t):a=t})).catch((function(t){h()})):h()}else _a.get(t.fallbackUrl,s,(function(t,i){t?e(t,null):n(i,null)}))},lb=function(){function t(){this.callbacks={},this.queue=[],this.clients=[]}var e=t.prototype;return e.enqueueJob=function(t,e,i,n){if(this.callbacks.hasOwnProperty(t))this.callbacks[t].push(i);else{this.callbacks[t]=[i];var s={url:t,data:e,options:n};this.clients.length>0?this.clients.shift().run(s):this.queue.push(s)}},e.enqueueClient=function(t){this.queue.length>0?t.run(this.queue.shift()):this.clients.push(t)},e.handleResponse=function(t,e,i){var n=this.callbacks[t];if(e)for(var s=0;s0&&++a<=o){var i=100*Math.pow(2,a);console.log("Error loading Texture from: '"+e+"' - Retrying in "+i+"ms...");var h=t.indexOf("?")>=0?"&":"?";r=setTimeout((function(){s.src=t+h+"retry="+Date.now(),r=null}),i)}else n("Error loading Texture from: '"+e+"'")},s.src=t},e._loadImageBitmap=function(t,e,i,n){var s=this,r={cache:!0,responseType:"blob",retry:this.maxRetries>0,maxRetries:this.maxRetries};_a.get(t,r,(function(t,e){t?n(t):s._loadImageBitmapFromBlob(e,n)}))},e._loadImageBitmapFromBlob=function(t,e){createImageBitmap(t,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then((function(t){return e(null,t)})).catch((function(t){return e(t)}))},t}(),wb=[1481919403,3140563232,169478669],Tb={33776:8,33778:9,33779:re,36196:pe,37492:22,37496:23,35840:ve,35841:me,35842:ge,35843:_e,32849:6,32856:7,35905:19,35907:20,35898:fe,34843:ae,34842:oe};for(var Ab=function(){function t(t){this.maxRetries=0}var e=t.prototype;return e.load=function(t,e,i){Vf.fetchArrayBuffer(t.load,e,i,this.maxRetries)},e.open=function(t,e,i,n){void 0===n&&(n={});var s=this.parse(e);if(!s)return null;var r=new Ls(i,x({name:t,addressU:s.cubemap?1:0,addressV:s.cubemap?1:0,width:s.width,height:s.height,format:s.format,cubemap:s.cubemap,levels:s.levels},n));return r.upload(),r},e.parse=function(t){var e=new Uint32Array(t);if(wb[0]!==e[0]||wb[1]!==e[1]||wb[2]!==e[2])return null;var i={endianness:e[3],glType:e[4],glTypeSize:e[5],glFormat:e[6],glInternalFormat:e[7],glBaseInternalFormat:e[8],pixelWidth:e[9],pixelHeight:e[10],pixelDepth:e[11],numberOfArrayElements:e[12],numberOfFaces:e[13],numberOfMipmapLevels:e[14],bytesOfKeyValueData:e[15]};if(i.pixelDepth>1)return null;if(0!==i.numberOfArrayElements)return null;var n=Tb[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=e[o++];h&&l.push([]);for(var d=h?l[c]:l,f=0;f<(h?6:1);++f)d.push((s=t,r=4*o,a=u,n===fe?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}},t}(),Cb=166,Eb=function(){function t(t,e){this.maxRetries=0,this.device=e}var e=t.prototype;return e.load=function(t,e,i){var n=this;Vf.fetchArrayBuffer(t.load,(function(s,r){s?e(s,r):n.parse(r,t,e,i)}),i,this.maxRetries)},e.open=function(t,e,i,n){void 0===n&&(n={});var s=new Ls(i,x({name:t,addressU:e.cubemap?1:0,addressV:e.cubemap?1:0,width:e.width,height:e.height,format:e.format,cubemap:e.cubemap,levels:e.levels},n));return s.upload(),s},e.parse=function(t,e,i,n){var s=new lt(t),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;l1},n));for(var w,T=128,A=d?6:1,C=c===f?8:16,E=0;E32767)return this._readPixelsFlat(t,e,i);var s=[0,0,0,0];if(t.readArray(s),2!==s[0]||2!==s[1]||0!=(128&s[2]))return t.skip(-4),this._readPixelsFlat(t,e,i);var r,a,o,h,l,c,u=new ArrayBuffer(e*i*4),d=new Uint8Array(u),f=n?0:4*e*(i-1);for(a=0;a128){if(r+(l-=128)>e)return null;for(c=t.readU8(),o=0;oe)return null;for(o=0;o=0?t.split("?")[0]:t},e._getParser=function(t){var e=L.getExtension(this._getUrlWithoutParams(t)).toLowerCase().replace(".","");return this.parsers[e]||this.imgParser},e._getTextureOptions=function(t){var e={};if(t){var i;(null==(i=t.name)?void 0:i.length)>0&&(e.name=t.name);var n=t.data;n.hasOwnProperty("minfilter")&&(e.minFilter=Ib[n.minfilter]),n.hasOwnProperty("magfilter")&&(e.magFilter=Ib[n.magfilter]),n.hasOwnProperty("addressu")&&(e.addressU=Rb[n.addressu]),n.hasOwnProperty("addressv")&&(e.addressV=Rb[n.addressv]),n.hasOwnProperty("mipmaps")&&(e.mipmaps=n.mipmaps),n.hasOwnProperty("anisotropy")&&(e.anisotropy=n.anisotropy),n.hasOwnProperty("flipY")&&(e.flipY=!!n.flipY),n.hasOwnProperty("type")?e.type=Lb[n.type]:n.hasOwnProperty("rgbm")&&n.rgbm?e.type=ii:t.file&&0!=(8&t.file.opt)&&(e.type=ri)}return e},e.load=function(t,e,i){"string"==typeof t&&(t={load:t,original:t}),this._getParser(t.original).load(t,e,i)},e.open=function(t,e,i){if(t){var n=this._getTextureOptions(i),s=this._getParser(t).open(t,e,this._device,n);return null===s?s=new Ls(this._device,{width:4,height:4,format:6}):(!function(t){var e=Math.log2(Math.max(t._width,t._height))+1;if(!(7!==t._format&&t._format!==le||t._volume||t._compressed||1===t._levels.length||t._levels.length===e||(i=t._cubemap?t._levels[0][0]:t._levels[0],i instanceof HTMLCanvasElement||i instanceof HTMLImageElement||i instanceof HTMLVideoElement))){for(var i,n=function(t,e,i){for(var n=Math.max(1,t>>1),s=Math.max(1,e>>1),r=new i.constructor(n*s*4),a=Math.floor(t/n),o=Math.floor(e/s),h=a*o,l=0;l>s-1),a=Math.max(1,t._height>>s-1);if(t._cubemap){for(var o=[],h=0;h<6;++h)o.push(n(r,a,t._levels[s-1][h]));t._levels.push(o)}else t._levels.push(n(r,a,t._levels[s-1]))}t._levelsUpdated=t._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0]}}(s),e.unswizzledGGGR&&(i.file.variants.basis.opt&=-9)),s}},e.patch=function(t,e){var i=t.resource;if(i)for(var n=this._getTextureOptions(t),s=0,r=Object.keys(n);sthis.views.length;){var a=this.viewsPool.pop();a||(a={viewport:new Pt,projMat:new Ft,viewMat:new Ft,viewOffMat:new Ft,viewInvMat:new Ft,viewInvOffMat:new Ft,projViewOffMat:new Ft,viewMat3:new At,position:new Float32Array(3),rotation:new Bt}),this.views.push(a)}for(;r0){var p=new Ft,m=this.views[0];p.copy(m.projMat);var _=p.data,v=2*Math.atan(1/_[5])*180/Math.PI,g=_[5]/_[0],y=_[14]/(_[10]+1),x=_[14]/(_[10]-1);this._camera.camera.setXrProperties({aspectRatio:g,farClip:y,fov:v,horizontalFov:!1,nearClip:x})}return this._camera.camera._node.setLocalPosition(this._localPosition),this._camera.camera._node.setLocalRotation(this._localRotation),this.input.update(t),this._type===Bb&&(this.hitTest.supported&&this.hitTest.update(t),this.lightEstimation.supported&&this.lightEstimation.update(t),this.depthSensing.supported&&this.depthSensing.update(t,n&&n.views[0]),this.imageTracking.supported&&this.imageTracking.update(t),this.anchors.supported&&this.anchors.update(t),this.planeDetection.supported&&this.planeDetection.update(t)),this.fire("update",t),!0},y(e,[{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}}]),e}(P),Tw=function(t){function e(e,i){var n;void 0===i&&(i={}),n=t.call(this,e)||this;var s=new up;return s.graphicsDevice=n.createDevice(e,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 Ta,s.lightmapper=Sp,s.batchManager=Eh,s.xr=ww,n.init(s),n}S(e,t);var i=e.prototype;return i.createDevice=function(t,e){return e.graphicsDeviceOptions||(e.graphicsDeviceOptions={}),G.browser&&navigator.xr&&(e.graphicsDeviceOptions.xrCompatible=!0),e.graphicsDeviceOptions.alpha=e.graphicsDeviceOptions.alpha||!1,new lr(t,e.graphicsDeviceOptions)},i.addComponentSystems=function(t){t.componentSystems=[Ig,L_,Cv,cm,Im,Zv,fg,Ny,Xy,bf.legacy?Yg:ex,Nm,gy,km,rg,Ug,vv,s_,hy,dy,Py,jv,Rv,Dy]},i.addResourceHandles=function(t){t.resourceHandlers=[ax,uS,dS,fS,jS,US,Ob,eb,OS,_S,YS,qS,wS,DS,bS,KS,LS,TS,ES,vS,rb,$S,tb,SS]},e}(hp),Aw=function(t){function e(e,i){var n;return(n=t.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=[],e.forEach((function(t){if(t instanceof Vf)t.registry||(t.registry=i),n._assets.add(t);else{var e=i.get(t);e?n._assets.add(e):n._waitForAsset(t)}})),n}S(e,t);var i=e.prototype;return i.destroy=function(){var t=this;this._registry.off("load",this._onLoad),this._registry.off("error",this._onError),this._waitingAssets.forEach((function(e){t._registry.off("add:"+e,this._onAddAsset)})),this.off("progress"),this.off("load")},i._assetHasDependencies=function(t){var e;return"model"===t.type&&(null==(e=t.file)?void 0:e.url)&&t.file.url&&t.file.url.match(/.json$/g)},i.load=function(t,e){var i=this;if(!this._loading){this._loading=!0,this._callback=t,this._scope=e,this._registry.on("load",this._onLoad,this),this._registry.on("error",this._onError,this);var n=!1;this._assets.forEach((function(t){t.loaded||(n=!0,i._assetHasDependencies(t)&&i._registry.loadFromUrl(t.file.url,t.type,(function(e,n){e?i._onError(e,t):i._onLoad(t)})),i._loadingAssets.add(t),i._registry.add(t))})),this._loadingAssets.forEach((function(t){i._assetHasDependencies(t)||i._registry.load(t)})),n||0!==this._waitingAssets.size||this._loadingComplete()}},i.ready=function(t,e){void 0===e&&(e=this),this._loaded?t.call(e,Array.from(this._assets)):this.once("load",(function(i){t.call(e,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(t){var e=this;this._loadingAssets.has(t)&&(this.fire("progress",t),this._loadingAssets.delete(t)),0===this._loadingAssets.size&&setTimeout((function(){e._loadingComplete(e._failed)}),0)},i._onError=function(t,e){var i=this;this._loadingAssets.has(e)&&(this._failed.push(e),this._loadingAssets.delete(e)),0===this._loadingAssets.size&&setTimeout((function(){i._loadingComplete(i._failed)}),0)},i._onAddAsset=function(t){this._waitingAssets.delete(t),this._assets.add(t),t.loaded||(this._loadingAssets.add(t),this._registry.load(t))},i._waitForAsset=function(t){this._waitingAssets.add(t),this._registry.once("add:"+t,this._onAddAsset,this)},e}(P),Cw=function(){function t(t,e,i,n){this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=i,this.texture=new Ls(t,{name:n,format:7,width:e,height:i,mipmaps:!0,minFilter:5,magFilter:1,addressU:1,addressV:1,levels:[this.canvas]}),this.ctx=this.canvas.getContext("2d",{alpha:!0})}var e=t.prototype;return e.destroy=function(){this.texture.destroy()},e.clear=function(t){var e=this.canvas,i=e.width,n=e.height;this.ctx.clearRect(0,0,i,n),this.ctx.fillStyle=t,this.ctx.fillRect(0,0,i,n)},t}(),Ew=function(t){function e(e,i){var n;return void 0===i&&(i={}),(n=t.call(this)||this).type="bitmap",n.app=e,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 vt(1,1,1),n.padding=i.padding||0,n.width=Math.min(4096,i.width||512),n.height=Math.min(4096,i.height||512),n.atlases=[],n.chars="",n.data={},n}S(e,t);var i=e.prototype;return i.createTextures=function(t){var e=this._normalizeCharsSet(t);if(e.length===this.chars.length){for(var i=0;i0&&this._renderAtlas(this.chars.concat(i))},i.destroy=function(){this.atlases.forEach((function(t){return t.destroy()})),this.chars=null,this.color=null,this.data=null,this.fontName=null,this.fontSize=null,this.glyphSize=null,this.intensity=null,this.atlases=null,this.type=null,this.fontWeight=null},i._colorToRgbString=function(t,e){var i=Math.round(255*t.r),n=Math.round(255*t.g),s=Math.round(255*t.b);return e?"rgba("+i+", "+n+", "+s+", "+t.a+")":"rgb("+i+", "+n+", "+s+")"},i.renderCharacter=function(t,e,i,n,s){t.fillStyle=s,t.fillText(e,i,n)},i._getAtlas=function(t){return t>=this.atlases.length&&(this.atlases[t]=new Cw(this.app.graphicsDevice,this.width,this.height,"font-atlas-"+this.fontName+"-"+t)),this.atlases[t]},i._renderAtlas=function(t){this.chars=t;var e=this.width,i=this.height,n=this._colorToRgbString(this.color,!1),s=this.color.a;this.color.a=1/255;var r=this._colorToRgbString(this.color,!0);this.color.a=s;var a=0,o=this._getAtlas(a++);o.clear(r),this.data=this._createJson(this.chars,this.fontName,e,i);for(var h=rt.getSymbols(this.chars.join("")),l=0,c=0,u={},d=0;dw&&(w=this.fontSize*this.fontSize/T,o.ctx.font=this.fontWeight+" "+w.toString()+"px "+this.fontName,T=this.fontSize),this.renderCharacter(o.ctx,S,g+_,y+v,n);var A=this.padding+(this.glyphSize-T)/2,C=-this.padding+u[S].descent-c,E=T;this._addChar(this.data,S,b,g,y,p,m,A,C,E,a-1,e,i),(g+=p)+p>e&&(g=0,(y+=m)+m>i&&((o=this._getAtlas(a++)).clear(r),y=0))}this.atlases.splice(a).forEach((function(t){return t.destroy()})),this.atlases.forEach((function(t){return t.texture.upload()})),this.fire("render")},i._createJson=function(t,e,i,n){return{version:3,intensity:this.intensity,info:{face:e,width:i,height:n,maps:[{width:i,height:n}]},chars:{}}},i._addChar=function(t,e,i,n,s,r,a,o,h,l,c,u,d){t.info.maps.length0&&(e.setCameraUniforms(i.camera,a),e.renderForward(i.camera,Mw,Pw,3,(function(e){var i=e.id;u[0]=(i>>16&255)/255,u[1]=(i>>8&255)/255,u[2]=(255&i)/255,u[3]=(i>>24&255)/255,c.setValue(u),t.setBlendState(Ui.NOBLEND)})),Mw.length=0)}}},e}(uo),Iw=new Set,Lw=function(){function t(t,e,i){this.renderTarget=null,this.mapping=new Map,t instanceof nn&&(t=vf()),this.renderer=t.renderer,this.device=t.graphicsDevice,this.renderPass=new Rw(this.device,t.renderer),this.width=0,this.height=0,this.resize(e,i)}var e=t.prototype;return e.getSelection=function(t,e,i,n){var s=this.device;if("object"==typeof t){var r=t;t=r.x,e=r.y,i=r.width,n=r.height}else e=this.renderTarget.height-(e+(n||1));t=Math.floor(t),e=Math.floor(e),i=Math.floor(Math.max(i||1,1)),n=Math.floor(Math.max(n||1,1)),s.setRenderTarget(this.renderTarget),s.updateBegin();var a=new Uint8Array(4*i*n);s.readPixels(t,e,i,n,a),s.updateEnd();for(var o=this.mapping,h=0;h0?h.wheelDelta=1:e.deltaY<0&&(h.wheelDelta=-1)),h}return S(e,t),e}(hT),cT=function(t){function e(e,i,n,s,r,a){var o;return(o=t.call(this,e,i,n)||this).touches=e.touches,o.changedTouches=e.changedTouches,o.x=s,o.y=r,o.touch=a,o}return S(e,t),e}(hT),uT=function(t){function e(e,i,n,s){var r;return(r=t.call(this,e,i,n)||this).inputSource=s,r}return S(e,t),e}(hT),dT=function(){function t(t,e){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=!e||!1!==e.useMouse,this._useTouch=!e||!1!==e.useTouch,this._useXr=!e||!1!==e.useXr,this._selectEventsAttached=!1,G.touch&&(this._clickedEntities={}),this.attach(t)}var e=t.prototype;return e.attach=function(t){this._attached&&(this._attached=!1,this.detach()),this._target=t,this._attached=!0;var e=!!G.passiveEvents&&{passive:!0};this._useMouse&&(window.addEventListener("mouseup",this._upHandler,e),window.addEventListener("mousedown",this._downHandler,e),window.addEventListener("mousemove",this._moveHandler,e),window.addEventListener("wheel",this._wheelHandler,e)),this._useTouch&&G.touch&&(this._target.addEventListener("touchstart",this._touchstartHandler,e),this._target.addEventListener("touchend",this._touchendHandler,!1),this._target.addEventListener("touchmove",this._touchmoveHandler,!1),this._target.addEventListener("touchcancel",this._touchcancelHandler,!1)),this.attachSelectEvents()},e.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))},e.detach=function(){if(this._attached){this._attached=!1;var t=!!G.passiveEvents&&{passive:!0};this._useMouse&&(window.removeEventListener("mouseup",this._upHandler,t),window.removeEventListener("mousedown",this._downHandler,t),window.removeEventListener("mousemove",this._moveHandler,t),window.removeEventListener("wheel",this._wheelHandler,t)),this._useTouch&&(this._target.removeEventListener("touchstart",this._touchstartHandler,t),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}},e.addElement=function(t){-1===this._elements.indexOf(t)&&this._elements.push(t)},e.removeElement=function(t){var e=this._elements.indexOf(t);-1!==e&&this._elements.splice(e,1)},e._handleUp=function(t){this._enabled&&(Zr.isPointerLocked()||(this._calcMouseCoords(t),this._onElementMouseEvent("mouseup",t)))},e._handleDown=function(t){this._enabled&&(Zr.isPointerLocked()||(this._calcMouseCoords(t),this._onElementMouseEvent("mousedown",t)))},e._handleMove=function(t){this._enabled&&(this._calcMouseCoords(t),this._onElementMouseEvent("mousemove",t),this._lastX=aw,this._lastY=ow)},e._handleWheel=function(t){this._enabled&&(this._calcMouseCoords(t),this._onElementMouseEvent("mousewheel",t))},e._determineTouchedElements=function(t){for(var e={},i=this.app.systems.camera.cameras,n=i.length-1;n>=0;n--){for(var s=i[n],r=0,a=t.changedTouches.length,o=0;o=0;d--){this._getTargetElementByCoords(e[d],u.x,u.y)===o&&(this._clickedEntities[o.entity.getGuid()]||(this._fireEvent("click",new cT(t,o,h,l,c,r)),this._clickedEntities[o.entity.getGuid()]=Date.now()))}this._fireEvent(t.type,new cT(t,o,h,l,c,r))}}}},e._handleTouchMove=function(t){if(t.preventDefault(),this._enabled)for(var e=this._determineTouchedElements(t),i=0,n=t.changedTouches.length;i=0&&(s=r[a],!(i=this._getTargetElementByCoords(s,aw,ow)));a--);if(this._hoveredElement=i,"mousemove"!==t&&"mouseup"!==t||!this._pressedElement?i&&(this._fireEvent(t,new lT(e,i,s,aw,ow,this._lastX,this._lastY)),"mousedown"===t&&(this._pressedElement=i)):this._fireEvent(t,new lT(e,this._pressedElement,s,aw,ow,this._lastX,this._lastY)),n!==this._hoveredElement&&(n&&this._fireEvent("mouseleave",new lT(e,n,s,aw,ow,this._lastX,this._lastY)),this._hoveredElement&&this._fireEvent("mouseenter",new lT(e,this._hoveredElement,s,aw,ow,this._lastX,this._lastY))),"mouseup"===t&&this._pressedElement){if(this._pressedElement===this._hoveredElement){var o=this._hoveredElement.entity.getGuid(),h=!this._clickedEntities;if(this._clickedEntities){var l=this._clickedEntities[o]||0;h=Date.now()-l>300,delete this._clickedEntities[o]}h&&this._fireEvent("click",new lT(e,this._hoveredElement,s,aw,ow,this._lastX,this._lastY))}this._pressedElement=null}},e._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)},e._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)},e._onXrUpdate=function(){if(this._enabled)for(var t=this.app.xr.input.inputSources,e=0;e=0&&(r=o[h],!(n=this._getTargetElementByRay(Nw,r)));h--);}e._elementEntity=n||null,n?(this._selectedElements[e.id]=n,s=n):delete this._selectedElements[e.id],a!==s&&(a&&this._fireEvent("selectleave",new uT(i,a,r,e)),s&&this._fireEvent("selectenter",new uT(i,s,r,e)));var l=this._selectedPressedElements[e.id];"selectmove"===t&&l&&this._fireEvent("selectmove",new uT(i,l,r,e)),"selectstart"===t&&(this._selectedPressedElements[e.id]=s,s&&this._fireEvent("selectstart",new uT(i,s,r,e))),!e.elementInput&&l&&(delete this._selectedPressedElements[e.id],a&&this._fireEvent("selectend",new uT(i,l,r,e))),"selectend"===t&&e.elementInput&&(delete this._selectedPressedElements[e.id],l&&this._fireEvent("selectend",new uT(i,l,r,e)),l&&l===a&&this._fireEvent("click",new uT(i,l,r,e)))},e._fireEvent=function(t,e){for(var i=e.element;i.fire(t,e),!e._stopPropagation&&i.entity.parent&&(i=i.entity.parent.element););},e._calcMouseCoords=function(t){var e=this._target.getBoundingClientRect(),i=Math.floor(e.left),n=Math.floor(e.top);aw=t.clientX-i,ow=t.clientY-n},e._calcTouchCoords=function(t){for(var e=0,i=0,n=t.target;!(n instanceof HTMLElement);)n=n.parentNode;var s=n;do{e+=s.offsetLeft-s.scrollLeft,i+=s.offsetTop-s.scrollTop,s=s.offsetParent}while(s);return{x:t.pageX-e,y:t.pageY-i}},e._sortElements=function(t,e){var i=this.app.scene.layers.sortTransparentLayers(t.layers,e.layers);return 0!==i?i:t.screen&&!e.screen?-1:!t.screen&&e.screen?1:t.screen||e.screen?t.screen.screen.screenSpace&&!e.screen.screen.screenSpace?-1:e.screen.screen.screenSpace&&!t.screen.screen.screenSpace?1:e.drawOrder-t.drawOrder:0},e._getTargetElementByCoords=function(t,e,i){var n=this._calculateRayScreen(e,i,t,Bw)?Bw:null,s=this._calculateRay3d(e,i,t,Uw)?Uw:null;return this._getTargetElement(t,n,s)},e._getTargetElementByRay=function(t,e){Bw.origin.copy(t.origin),Bw.direction.copy(t.direction),Bw.end.copy(Bw.direction).mulScalar(2*e.farClip).add(Bw.origin);var i=Bw,n=e.worldToScreen(i.origin,kw),s=this._calculateRayScreen(n.x,n.y,e,Uw)?Uw:null;return this._getTargetElement(e,s,i)},e._getTargetElement=function(t,e,i){var n=null,s=1/0;this._elements.sort(this._sortHandler);for(var r=0,a=this._elements.length;r=0){n=o;break}}else{if(!i)continue;var h=this._checkElement(i,o,!1);if(h>=0&&(h=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)},e._calculateRay3d=function(t,e,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=t,f=e;return t>=h&&t<=l&&e<=c&&f>=u&&(d=s*(d-h)/a,f=r*(f-u)/o,i.screenToWorld(d,f,i.nearClip,kw),i.screenToWorld(d,f,i.farClip,Fw),n.origin.copy(kw),n.direction.set(0,0,-1),n.end.copy(Fw),!0)},e._checkElement=function(e,i,n){if(i.maskedBy&&this._checkElement(e,i.maskedBy.element,n)<0)return-1;var s;s=n?t.calculateScaleToScreen(i):t.calculateScaleToWorld(i);var r=t.buildHitCorners(i,n?i.screenCorners:i.worldCorners,s);return function(t,e,i){zw.sub2(e,t),Vw.sub2(i[0],t),Gw.sub2(i[1],t),Hw.sub2(i[2],t),Xw.cross(Hw,zw);var n,s,r=Vw.dot(Xw);if(r>=0){if((n=-Gw.dot(Xw))<0)return-1;if((s=oT(zw,Gw,Vw))<0)return-1;var a=1/(n+r+s);jw.copy(i[0]).mulScalar(n*a),qw.copy(i[1]).mulScalar(r*a),Yw.copy(i[2]).mulScalar(s*a),Kw.copy(jw).add(qw).add(Yw)}else{if(Ww.sub2(i[3],t),(n=Ww.dot(Xw))<0)return-1;if((s=oT(zw,Vw,Ww))<0)return-1;var o=1/(n+(r=-r)+s);jw.copy(i[0]).mulScalar(n*o),qw.copy(i[3]).mulScalar(r*o),Yw.copy(i[2]).mulScalar(s*o),Kw.copy(jw).add(qw).add(Yw)}return zw.sub2(i[0],i[2]).lengthSq()<1e-8||zw.sub2(i[1],i[3]).lengthSq()<1e-8?-1:Kw.sub(t).lengthSq()}(e.origin,e.end,r)},t.buildHitCorners=function(t,e,i){var n=e;if(t.entity&&t.entity.button){var s=t.entity.button.hitPadding||aT;$w.copy(t.entity.up),Jw.copy($w).mulScalar(-1),eT.copy(t.entity.right),tT.copy(eT).mulScalar(-1),$w.mulScalar(s.w*i.y),Jw.mulScalar(s.y*i.y),eT.mulScalar(s.z*i.x),tT.mulScalar(s.x*i.x),iT.copy(n[0]).add(Jw).add(tT),nT.copy(n[1]).add(Jw).add(eT),sT.copy(n[2]).add($w).add(eT),rT.copy(n[3]).add($w).add(tT),n=[iT,nT,sT,rT]}if(i.x<0){var r=n[2].x,a=n[0].x;n[0].x=r,n[1].x=a,n[2].x=a,n[3].x=r}if(i.y<0){var o=n[2].y,h=n[0].y;n[0].y=o,n[1].y=o,n[2].y=h,n[3].y=h}if(i.z<0){var l=n[2].x,c=n[2].y,u=n[2].z;n[2].x=n[0].x,n[2].y=n[0].y,n[2].z=n[0].z,n[0].x=l,n[0].y=c,n[0].z=u}return n},t.calculateScaleToScreen=function(t){var e=t.entity,i=t.screen.screen.scale;for(Qw.set(i,i,i);e&&!e.screen;)Qw.mul(e.getLocalScale()),e=e.parent;return Qw},t.calculateScaleToWorld=function(t){var e=t.entity;for(Qw.set(1,1,1);e;)Qw.mul(e.getLocalScale()),e=e.parent;return Qw},y(t,[{key:"enabled",get:function(){return this._enabled},set:function(t){this._enabled=t}},{key:"app",get:function(){return this._app||vf()},set:function(t){this._app=t}}]),t}(),fT=new RegExp("^\\s*function(?:\\s|\\s*\\/\\*.*\\*\\/\\s*)+([^\\(\\s\\/]*)\\s*"),pT=function(t){function e(e){var i;return(i=t.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(e),i}S(e,t);var i=e.prototype;return i.initScriptType=function(t){var e=this.constructor;this.app=t.app,this.entity=t.entity,this._enabled="boolean"!=typeof t.enabled||t.enabled,this._enabledOld=this.enabled,this.__destroyed=!1,this.__attributes={},this.__attributesRaw=t.attributes||{},this.__scriptType=e,this.__executionOrder=-1},e.__getScriptName=function(t){if("function"==typeof t){if("name"in Function.prototype)return t.name;if(t===Function||t===Function.prototype.constructor)return"Function";var e=(""+t).match(fT);return e?e[1]:void 0}},i.__initializeAttributes=function(t){if(t||this.__attributesRaw){for(var e in this.__scriptType.attributes.index)this.__attributesRaw&&this.__attributesRaw.hasOwnProperty(e)?this[e]=this.__attributesRaw[e]:this.__attributes.hasOwnProperty(e)||(this.__scriptType.attributes.index[e].hasOwnProperty("default")?this[e]=this.__scriptType.attributes.index[e].default:this[e]=null);this.__attributesRaw=null}},e.extend=function(t){for(var e in t)t.hasOwnProperty(e)&&(this.prototype[e]=t[e])},y(e,[{key:"enabled",get:function(){return this._enabled&&!this._destroyed&&this.entity.script.enabled&&this.entity.enabled},set:function(t){this._enabled=!!t,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,Zy)),this._initialized&&!this._postInitialized&&this.enabled&&!this.entity.script._beingEnabled&&(this._postInitialized=!0,this.postInitialize&&this.entity.script._scriptMethod(this,Qy)))}}],[{key:"scriptName",get:function(){return this.__name}},{key:"attributes",get:function(){return this.hasOwnProperty("__attributes")||(this.__attributes=new Ky(this)),this.__attributes}}]),e}(P);pT.__name=null;var mT=new Set(["system","entity","create","destroy","swap","move","data","scripts","_scripts","_scriptsIndex","_scriptsData","enabled","_oldState","onEnable","onDisable","onPostStateChange","_onSetEnabled","_checkState","_onBeforeRemove","_onInitializeAttributes","_onInitialize","_onPostInitialize","_onUpdate","_onPostUpdate","_callbacks","_callbackActive","has","get","on","off","fire","once","hasEvent"]);function _T(t,e){if(bf.legacy)return null;if(mT.has(t))throw new Error("Script name '"+t+"' is reserved, please rename the script");var i=function(t){P.prototype.initEventHandler.call(this),pT.prototype.initScriptType.call(this,t)};return(i.prototype=Object.create(pT.prototype)).constructor=i,i.extend=pT.extend,i.attributes=new Ky(i),gT(i,t,e),i}var vT={};function gT(t,e,i){if(!t.legacy){if("function"!=typeof t)throw new Error("script class: '"+t+"' must be a constructor function (i.e. class).");if(!(t.prototype instanceof pT))throw new Error("script class: '"+pT.__getScriptName(t)+"' does not extend pc.ScriptType.");if(e=e||t.__name||pT.__getScriptName(t),mT.has(e))throw new Error("script name: '"+e+"' is reserved, please change script name");t.__name=e,(i?i.scripts:hp.getApplication().scripts).add(t),yf.push(t,t.legacy)}}Ky.reservedNames.forEach((function(t,e,i){vT[t]=1})),_T.reservedAttributes=vT;var yT={write:function(t){console.log(t)},open:function(){yT.write("Powered by PlayCanvas "+c+" "+u)},info:function(t){console.info("INFO: "+t)},debug:function(t){console.debug("DEBUG: "+t)},error:function(t){console.error("ERROR: "+t)},warning:function(t){console.warn("WARNING: "+t)},alert:function(t){function e(e){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}((function(t){yT.write("ALERT: "+t),alert(t)})),assert:function(t,e){!1===t&&yT.write("ASSERT: "+e)}};rt.endsWith=function(t,e){return t.endsWith(e)},rt.startsWith=function(t,e){return t.startsWith(e)};var xT=function(){function t(){this._isRunning=!1,this._a=0,this._b=0}var e=t.prototype;return e.start=function(){this._isRunning=!0,this._a=dt()},e.stop=function(){this._isRunning=!1,this._b=dt()},e.getMilliseconds=function(){return this._b-this._a},t}(),ST={now:dt,Timer:xT};Object.defineProperty(vt.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(vt.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}}),_t.INV_LOG2=Math.LOG2E,_t.intToBytes=_t.intToBytes32,_t.bytesToInt=_t.bytesToInt32,Object.defineProperty(Et.prototype,"data",{get:function(){return this._data||(this._data=new Float32Array(2)),this._data[0]=this.x,this._data[1]=this.y,this._data}}),Et.prototype.scale=Et.prototype.mulScalar,Object.defineProperty(wt.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}}),wt.prototype.scale=wt.prototype.mulScalar,Object.defineProperty(Pt.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}}),Pt.prototype.scale=Pt.prototype.mulScalar;var bT={Aabb:Ht,Sphere:jt,Plane:te};jt.prototype.intersectRay=jt.prototype.intersectsRay,qt.prototype.update=function(t,e){var i=new Ft;i.mul2(t,e),this.setFromMat4(i)};var wT=mi;function TT(t){this.name="UnsupportedBrowserError",this.message=t||""}function AT(t){this.name="ContextCreationError",this.message=t||""}TT.prototype=Error.prototype,AT.prototype=Error.prototype;var CT={begin:xo.begin,dummyFragmentCode:ir.dummyFragmentCode,end:xo.end,fogCode:xo.fogCode,gammaCode:xo.gammaCode,precisionCode:ir.precisionCode,skinCode:xo.skinCode,tonemapCode:xo.tonemapCode,versionCode:ir.versionCode},ET={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:se,CULLFACE_BACK:1,CULLFACE_FRONT:2,CULLFACE_FRONTANDBACK:3,ELEMENTTYPE_INT8:0,ELEMENTTYPE_UINT8:mi,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_RGB565:3,PIXELFORMAT_RGB8:6,PIXELFORMAT_RGBA8:7,PRIMITIVE_POINTS:0,PRIMITIVE_LINES:1,PRIMITIVE_LINELOOP:2,PRIMITIVE_LINESTRIP:3,PRIMITIVE_TRIANGLES:4,PRIMITIVE_TRISTRIP:be,PRIMITIVE_TRIFAN:6,SEMANTIC_POSITION:we,SEMANTIC_NORMAL:Te,SEMANTIC_COLOR:Me,SEMANTIC_TEXCOORD:Pe,SEMANTIC_TEXCOORD0:Re,SEMANTIC_TEXCOORD1:Ie,SEMANTIC_ATTR0:Ne,SEMANTIC_ATTR1:ze,SEMANTIC_ATTR2:Ve,SEMANTIC_ATTR3:Ge,TEXTURELOCK_READ:1,TEXTURELOCK_WRITE:2,drawQuadWithShader:Ro,programlib:CT,shaderChunks:_o,ContextCreationError:AT,Device:nn,IndexBuffer:vr,ProgramLibrary:uf,RenderTarget:rn,ScopeId:Hi,Shader:fs,ShaderInput:Fs,Texture:Ls,UnsupportedBrowserError:TT,VertexBuffer:ji,VertexFormat:Ji,VertexIterator:Lr},MT=new Pt;function PT(t,e,i,n,s){var r;if(s){var a=e?e.width:t.width,o=e?e.height:t.height;r=MT.set(s.x*a,s.y*o,s.z*a,s.w*o)}Ro(t,e,n,r)}var RT={createFullscreenQuad:function(t){return t.quadVertexBuffer},drawFullscreenQuad:PT,PostEffect:of,PostEffectQueue:ky};Object.defineProperty(_o,"transformSkinnedVS",{get:function(){return"#define SKIN\n"+_o.transformVS}});Object.keys({"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"}).forEach((function(t){Object.defineProperty(_o,t,{get:function(){return null},set:function(){}})})),Object.defineProperties(rn.prototype,{_glFrameBuffer:{get:function(){return this.impl._glFrameBuffer},set:function(t){}}}),Object.defineProperty(Ji,"defaultInstancingFormat",{get:function(){return Ji.getDefaultInstancingFormat(Ha.get())}}),Object.defineProperties(Ls.prototype,{rgbm:{get:function(){return this.type===ii},set:function(t){this.type=t?ii:ei}},swizzleGGGR:{get:function(){return this.type===ri},set:function(t){this.type=t?ri:ei}},_glTexture:{get:function(){return this.impl._glTexture}},autoMipmap:{get:function(){return this._mipmaps},set:function(t){this._mipmaps=t}}}),Object.defineProperty(nn.prototype,"webgl2",{get:function(){return this.isWebGL2}}),nn.prototype.getProgramLibrary=function(){return go(this)},nn.prototype.setProgramLibrary=function(t){yo(this,t)},nn.prototype.removeShaderFromCache=function(t){go(this).removeFromCache(t)},Ui.DEFAULT=Object.freeze(new Ui);var IT=new Ui,LT=new Ni;nn.prototype.setBlendFunction=function(t,e){var i=this.blendState;IT.copy(i),IT.setColorBlend(i.colorOp,t,e),IT.setAlphaBlend(i.alphaOp,t,e),this.setBlendState(IT)},nn.prototype.setBlendFunctionSeparate=function(t,e,i,n){var s=this.blendState;IT.copy(s),IT.setColorBlend(s.colorOp,t,e),IT.setAlphaBlend(s.alphaOp,i,n),this.setBlendState(IT)},nn.prototype.setBlendEquation=function(t){var e=this.blendState;IT.copy(e),IT.setColorBlend(t,e.colorSrcFactor,e.colorDstFactor),IT.setAlphaBlend(t,e.alphaSrcFactor,e.alphaDstFactor),this.setBlendState(IT)},nn.prototype.setBlendEquationSeparate=function(t,e){var i=this.blendState;IT.copy(i),IT.setColorBlend(t,i.colorSrcFactor,i.colorDstFactor),IT.setAlphaBlend(e,i.alphaSrcFactor,i.alphaDstFactor),this.setBlendState(IT)},nn.prototype.setColorWrite=function(t,e,i,n){var s=this.blendState;IT.copy(s),IT.setColorWrite(t,e,i,n),this.setBlendState(IT)},nn.prototype.getBlending=function(){return this.blendState.blend},nn.prototype.setBlending=function(t){IT.copy(this.blendState),IT.blend=t,this.setBlendState(IT)},nn.prototype.setDepthWrite=function(t){LT.copy(this.depthState),LT.write=t,this.setDepthState(LT)},nn.prototype.setDepthFunc=function(t){LT.copy(this.depthState),LT.func=t,this.setDepthState(LT)},nn.prototype.setDepthTest=function(t){LT.copy(this.depthState),LT.test=t,this.setDepthState(LT)},nn.prototype.getCullMode=function(){return this.cullMode};var DT=lu,OT=Hh,kT={partitionSkin:GS,procedural:{calculateTangents:$a,createMesh:Ja,createTorus:to,createCylinder:io,createCapsule:no,createCone:so,createSphere:ro,createPlane:ao,createBox:oo},BasicMaterial:Vo,ForwardRenderer:yu,GraphNode:hh,Material:zo,Mesh:qa,MeshInstance:yh,Model:Gu,ParticleEmitter:Nd,PhongMaterial:lu,Picker:Lw,Projection:{ORTHOGRAPHIC:1,PERSPECTIVE:0},Scene:Yd,Skin:Kd,SkinInstance:Xo};function FT(t,e){Object.defineProperty(lu.prototype,e,{get:function(){return this[t]},set:function(e){this[t]=e}})}function BT(t,e){"pass"!==t&&Object.defineProperty(Xc.prototype,t,{get:function(){return this.litOptions[e||t]},set:function(i){this.litOptions[e||t]=i}})}Object.defineProperty(Yd.prototype,"defaultMaterial",{get:function(){return Bo(vf().graphicsDevice)}}),Object.defineProperty(Ru.prototype,"_meshInstances",{get:function(){return null}}),Object.defineProperty(Yd.prototype,"drawCalls",{get:function(){return null}}),["128","64","32","16","8","4"].forEach((function(t,e){Object.defineProperty(Yd.prototype,"skyboxPrefiltered"+t,{get:function(){return this._prefilteredCubemaps[e]},set:function(t){this._prefilteredCubemaps[e]=t,this.updateShaders=!0}})})),Object.defineProperty(Yd.prototype,"models",{get:function(){return this._models||(this._models=[]),this._models}}),Object.defineProperty(Cu.prototype,"renderTarget",{set:function(t){this._renderTarget=t,this._dirtyCameras=!0},get:function(){return this._renderTarget}}),Yd.prototype._updateSkybox=function(t){this._updateSky(t)},Yd.prototype.addModel=function(t){if(!this.containsModel(t)){var e=this.layers.getLayerById(0);e&&(e.addMeshInstances(t.meshInstances),this.models.push(t))}},Yd.prototype.addShadowCaster=function(t){var e=this.layers.getLayerById(0);e&&e.addShadowCasters(t.meshInstances)},Yd.prototype.removeModel=function(t){var e=this.models.indexOf(t);if(-1!==e){var i=this.layers.getLayerById(0);if(!i)return;i.removeMeshInstances(t.meshInstances),this.models.splice(e,1)}},Yd.prototype.removeShadowCasters=function(t){var e=this.layers.getLayerById(0);e&&e.removeShadowCasters(t.meshInstances)},Yd.prototype.containsModel=function(t){return this.models.indexOf(t)>=0},Yd.prototype.getModels=function(t){return this.models},Object.defineProperty(Go.prototype,"model",{get:function(){return null}}),yu.prototype.renderComposition=function(t){vf().renderComposition(t)},yh.prototype.syncAabb=function(){},Hu.prototype.getTarget=function(t){return this.targets[t]},hh.prototype._dirtify=function(t){t?this._dirtifyLocal():this._dirtifyWorld()},hh.prototype.addLabel=function(t){this._labels[t]=!0},hh.prototype.getLabels=function(){return Object.keys(this._labels)},hh.prototype.hasLabel=function(t){return!!this._labels[t]},hh.prototype.removeLabel=function(t){delete this._labels[t]},hh.prototype.findByLabel=function(t,e){void 0===e&&(e=[]),this.hasLabel(t)&&e.push(this);for(var i=0;i=r.length?e(new Error("Failed to create a graphics device")):Promise.resolve(r[i++]()).then((function(e){e?t(e):n()})).catch((function(t){console.log(t),n()}))}()}))},t.createMesh=Ja,t.createPlane=ao,t.createScript=_T,t.createShader=So,t.createShaderFromCode=bo,t.createSphere=ro,t.createStyle=function(t){var e=document.createElement("style");return e.type="text/css",e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t)),e},t.createTorus=to,t.createURI=function(t){var e="";if((t.authority||t.scheme)&&(t.host||t.hostpath))throw new Error("Can't have 'scheme' or 'authority' and 'host' or 'hostpath' option");if(t.host&&t.hostpath)throw new Error("Can't have 'host' and 'hostpath' option");if(t.path&&t.hostpath)throw new Error("Can't have 'path' and 'hostpath' option");return t.scheme&&(e+=t.scheme+":"),t.authority&&(e+="//"+t.authority),t.host&&(e+=t.host),t.path&&(e+=t.path),t.hostpath&&(e+=t.hostpath),t.query&&(e+="?"+t.query),t.fragment&&(e+="#"+t.fragment),e},t.data={},t.dracoInitialize=function(t){null!=t&&t.lazyInit?ux=t:_x(t)},t.drawFullscreenQuad=PT,t.drawQuadWithShader=Ro,t.drawTexture=function(t,e,i,n,s,r){n=n||t.getCopyShader(),t.constantTexSource.setValue(e),Ro(t,i,n,s,r)},t.events=R,t.extend=p,t.getPixelFormatArrayType=Se,t.getReservedScriptNames=function(){return mT},t.getTouchTargetCoords=ua,t.gfx=ET,t.guid=I,t.http=_a,t.inherits=function(t,e){var i=function(){},n=function(i,n,s,r,a,o,h,l){e.call(this,i,n,s,r,a,o,h,l),t.call(this,i,n,s,r,a,o,h,l)};return n._super=e.prototype,i.prototype=e.prototype,n.prototype=new i,n},t.input=HT,t.isCompressedPixelFormat=xe,t.log=yT,t.makeArray=function(t){return Array.prototype.slice.call(t)},t.math=_t,t.now=dt,t.path=L,t.pixelFormatInfo=ye,t.platform=G,t.posteffect=RT,t.prefilterCubemap=function(t){},t.programlib=CT,t.registerScript=gT,t.reprojectTexture=Gc,t.revision=u,t.scene=kT,t.script=bf,t.semanticToLocation=Ri,t.shFromCubemap=function(t,e,i){if(7!==e.format)return null;if(!e._levels[0]||!e._levels[0][0])return null;var n=e.width;if(!e._levels[0][0].length){if(!(e._levels[0][0]instanceof HTMLImageElement))return null;for(var s=bo(t,_o.fullscreenQuadVS,_o.fullscreenQuadPS,"fsQuadSimple"),r=t.scope.resolve("source"),a=0;a<6;a++){var o=e._levels[0][a],h=new Ls(t,{name:"prefiltered-cube",cubemap:!1,type:ei,format:e.format,width:n,height:n,mipmaps:!1});h._levels[0]=o,h.upload();var l=new Ls(t,{name:"prefiltered-cube",cubemap:!1,type:ei,format:e.format,width:n,height:n,mipmaps:!1}),c=new rn({colorBuffer:l,depth:!1});r.setValue(h),t.setBlendState(Ui.NOBLEND),Ro(t,c,s);var u=t.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),e._levels[0][a]=d}}for(var f=[],p=0;p