!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).pc={})}(this,(function(e){"use strict";function t(e,t,i){e.prototype[t]||Object.defineProperty(e.prototype,t,{value:i,configurable:!0,enumerable:!1,writable:!0})}t(Array,"fill",(function(e){if(null==this)throw new TypeError("this is null or not defined");for(var t=Object(this),i=t.length>>>0,n=arguments[1],s=n>>0,r=s<0?Math.max(i+s,0):Math.min(s,i),a=arguments[2],o=void 0===a?i:a>>0,h=o<0?Math.max(i+o,0):Math.min(o,i);r>>0;if("function"!=typeof e)throw TypeError("predicate must be a function");for(var n=arguments[1],s=0;s>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");for(var n=arguments[1],s=0;s0)-(e<0)||+e}),void 0===Number.isFinite&&(Number.isFinite=function(e){return"number"==typeof e&&isFinite(e)}),"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var i=Object(e),n=1;nthis.length)&&(t=this.length),this.substring(t-e.length,t)===e})),t(String,"includes",(function(e,t){return"number"!=typeof t&&(t=0),!(t+e.length>this.length)&&-1!==this.indexOf(e,t)})),t(String,"startsWith",(function(e,t){var i=t>0?0|t:0;return this.substring(i,i+e.length)===e})),t(String,"trimEnd",(function(){return this.replace(new RegExp(/[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/.source+"$","g"),"")}));for(var i=0,n=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array];i0?r=r.slice(0,r.length-2):(a>0&&r.push(v.delimiter),r.push(n[a])));return s=r.join(""),t||s[0]!==v.delimiter||(s=s.slice(1)),i&&s[s.length-1]!==v.delimiter&&(s+=v.delimiter),s},split:function(e){var t=e.split(v.delimiter),i=t.slice(t.length-1)[0];return[t.slice(0,t.length-1).join(v.delimiter),i]},getBasename:function(e){return v.split(e)[1]},getDirectory:function(e){var t=e.split(v.delimiter);return t.slice(0,t.length-1).join(v.delimiter)},getExtension:function(e){var t=e.split("?")[0].split(".").pop();return t!==e?"."+t:""},isRelativePath:function(e){return"/"!==e.charAt(0)&&null===e.match(/:\/\//)},extractPath:function(e){var t="",i=e.split("/"),n=0;if(i.length>1)if(v.isRelativePath(e))if("."===i[0])for(n=0;n0),M="getGamepads"in navigator,C="undefined"!=typeof Worker;try{var R=Object.defineProperty({},"passive",{get:function(){return E=!0,!1}});window.addEventListener("testpassive",null,R),window.removeEventListener("testpassive",null,R)}catch(e){}}var I="undefined"!=typeof window?"browser":"node",L={environment:I,global:"browser"===I?window:global,browser:"browser"===I,desktop:y,mobile:x,ios:T,android:w,windows:b,xbox:S,gamepads:M,touch:A,workers:C,passiveEvents:E},D="abcdefghijklmnopqrstuvwxyz",k="ABCDEFGHIJKLMNOPQRSTUVWXYZ",O=55296,F=127462,B=127487,N=65024,U=65039;function z(e,t){void 0===t&&(t=0);var i=e.length;if(t<0||t>=i)return null;var n=e.charCodeAt(t);if(i>1&&n>=O&&n<=56319){var s=e.charCodeAt(t+1);if(s>=56320&&s<=57343)return{code:1024*(n-O)+s-56320+65536,long:!0}}return{code:n,long:!1}}function V(e,t,i){if(!e)return!1;var n=z(e);if(n){var s=n.code;return s>=t&&s<=i}return!1}function G(e,t){if(t===e.length-1)return 1;if(V(e[t],O,56319)){var i=e.substring(t,t+2),n=e.substring(t+2,t+4);return V(n,127995,127999)||V(i,F,B)&&V(n,F,B)?4:V(n,N,U)?3:2}return V(e[t+1],N,U)?2:1}var W,H,X,q={ASCII_LOWERCASE:D,ASCII_UPPERCASE:k,ASCII_LETTERS:"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",format:function(e){for(var t=1;t65535?[55296+(t>>10),t%1024+56320]:[e],n.push(String.fromCharCode.apply(null,i));return n.join("")}},j=function(){function e(){this._list=[],this._index={}}var t=e.prototype;return t.push=function(e,t){if(this._index[e])throw Error("Key already in index "+e);var i=this._list.push(t)-1;this._index[e]=i},t.has=function(e){return void 0!==this._index[e]},t.get=function(e){var t=this._index[e];return void 0!==t?this._list[t]:null},t.remove=function(e){var t=this._index[e];if(void 0!==t){for(e in this._list.splice(t,1),delete this._index[e],this._index){var i=this._index[e];i>t&&(this._index[e]=i-1)}return!0}return!1},t.list=function(){return this._list},t.clear=function(){for(var e in this._list.length=0,this._index)delete this._index[e]},e}(),Y=function(){function e(){}return e.loadScript=function(e,t){var i=document.createElement("script");i.setAttribute("src",e),i.onload=function(){t(null)},i.onerror=function(){t("Failed to load script='"+e+"'")},document.body.appendChild(i)},e.loadWasm=function(t,i,n){var s=e.wasmSupported()&&i.glueUrl&&i.wasmUrl?i.glueUrl:i.fallbackUrl;s?e.loadScript(s,(function(e){if(e)n(e,null);else{var s=window[t];window[t]=void 0,s({locateFile:function(){return i.wasmUrl},onAbort:function(){n("wasm module aborted.")}}).then((function(e){n(null,e)}))}})):n("No supported wasm modules found.",null)},e.getModule=function(t){return e.modules.hasOwnProperty(t)||(e.modules[t]={config:null,initializing:!1,instance:null,callbacks:[]}),e.modules[t]},e.initialize=function(t,i){if(!i.initializing){var n=i.config;(n.glueUrl||n.wasmUrl||n.fallbackUrl)&&(i.initializing=!0,e.loadWasm(t,n,(function(e,s){e?n.errorHandler?n.errorHandler(e):console.error("failed to initialize module="+t+" error="+e):(i.instance=s,i.callbacks.forEach((function(e){e(s)})))})))}},e}();Y.modules={},Y.wasmSupported=(W=function(){try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){var e=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(e instanceof WebAssembly.Module)return new WebAssembly.Instance(e)instanceof WebAssembly.Instance}}catch(e){}return!1},X=H={},function(){return X===H&&(X=W()),X});var K=function(){function e(){}return e.setConfig=function(e,t){var i=Y.getModule(e);i.config=t,i.callbacks.length>0&&Y.initialize(e,i)},e.getInstance=function(e,t){var i=Y.getModule(e);i.instance?t(i.instance):(i.callbacks.push(t),i.config&&Y.initialize(e,i))},e}();function Z(e,t){for(var i=0;ie.length)&&(t=e.length);for(var i=0,n=new Array(t);i=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var se=function(){function e(e){this.arraybuffer=e,this.dataView=new DataView(e),this.offset=0,this.stack=[]}var t=e.prototype;return t.reset=function(e){void 0===e&&(e=0),this.offset=e},t.skip=function(e){this.offset+=e},t.align=function(e){this.offset=this.offset+e-1&~(e-1)},t._inc=function(e){return this.offset+=e,this.offset-e},t.readChar=function(){return String.fromCharCode(this.dataView.getUint8(this.offset++))},t.readChars=function(e){for(var t="",i=0;i=e.byteLength);){var i=String.fromCharCode(this.readU8());if("\n"===i)break;t+=i}return t},$(e,[{key:"remainingBytes",get:function(){return this.dataView.byteLength-this.offset}}]),e}(),re=function(){function e(e){this.items=[],this.length=0,this.loopIndex=-1,this._sortBy=e.sortBy,this._sortHandler=this._doSort.bind(this)}var t=e.prototype;return t._binarySearch=function(e){for(var t,i,n=0,s=this.items.length-1,r=e[this._sortBy];n<=s;)t=Math.floor((n+s)/2),(i=this.items[t][this._sortBy])<=r?n=t+1:i>r&&(s=t-1);return n},t._doSort=function(e,t){var i=this._sortBy;return e[i]-t[i]},t.insert=function(e){var t=this._binarySearch(e);this.items.splice(t,0,e),this.length++,this.loopIndex>=t&&this.loopIndex++},t.append=function(e){this.items.push(e),this.length++},t.remove=function(e){var t=this.items.indexOf(e);t<0||(this.items.splice(t,1),this.length--,this.loopIndex>=t&&this.loopIndex--)},t.sort=function(){var e=this.loopIndex>=0?this.items[this.loopIndex]:null;this.items.sort(this._sortHandler),null!==e&&(this.loopIndex=this.items.indexOf(e))},e}(),ae=function(e){function t(t){var i;return(i=e.call(this)||this)._index={},i._list=[],i._parent=t,i}J(t,e);var i=t.prototype;return i.add=function(){var e=!1,t=this._processArguments(arguments,!0);if(!t.length)return e;for(var i=0;i=i?i:e<=t?t:e},intToBytes24:function(e){return[e>>16&255,e>>8&255,255&e]},intToBytes32:function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]},bytesToInt24:function(e,t,i){return e.length&&(i=e[2],t=e[1],e=e[0]),e<<16|t<<8|i},bytesToInt32:function(e,t,i,n){return e.length&&(n=e[3],i=e[2],t=e[1],e=e[0]),(e<<24|t<<16|i<<8|n)>>>0},lerp:function(e,t,i){return e+(t-e)*de.clamp(i,0,1)},lerpAngle:function(e,t,i){return t-e>180&&(t-=360),t-e<-180&&(t+=360),de.lerp(e,t,de.clamp(i,0,1))},powerOfTwo:function(e){return 0!==e&&!(e&e-1)},nextPowerOfTwo:function(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e},random:function(e,t){var i=t-e;return Math.random()*i+e},smoothstep:function(e,t,i){return i<=e?0:i>=t?1:(i=(i-e)/(t-e))*i*(3-2*i)},smootherstep:function(e,t,i){return i<=e?0:i>=t?1:(i=(i-e)/(t-e))*i*i*(i*(6*i-15)+10)},roundUp:function(e,t){return 0===t?e:Math.ceil(e/t)*t},between:function(e,t,i,n){var s=Math.min(t,i),r=Math.max(t,i);return n?e>=s&&e<=r:e>s&&e=0?e.ResponseType.ARRAY_BUFFER:".xml"===n?e.ResponseType.DOCUMENT:e.ResponseType.TEXT},t._isBinaryContentType=function(t){return[e.ContentType.MP4,e.ContentType.WAV,e.ContentType.OGG,e.ContentType.MP3,e.ContentType.BIN,e.ContentType.DDS,e.ContentType.BASIS,e.ContentType.GLB,e.ContentType.OPUS].indexOf(t)>=0},t._onReadyStateChange=function(e,t,i,n){if(4===n.readyState)switch(n.status){case 0:n.responseURL&&n.responseURL.startsWith("file:///")?this._onSuccess(e,t,i,n):this._onError(e,t,i,n);break;case 200:case 201:case 206:case 304:this._onSuccess(e,t,i,n);break;default:this._onError(e,t,i,n)}},t._onSuccess=function(t,i,n,s){var r,a,o=s.getResponseHeader("Content-Type");o&&(a=o.split(";")[0].trim());try{r=a===e.ContentType.JSON||i.split("?")[0].endsWith(".json")?JSON.parse(s.responseText):this._isBinaryContentType(a)||s.responseType===e.ResponseType.ARRAY_BUFFER||s.responseType===e.ResponseType.BLOB||s.responseType===e.ResponseType.JSON?s.response:s.responseType===e.ResponseType.DOCUMENT||a===e.ContentType.XML?s.responseXML:s.responseText,n.callback(null,r)}catch(e){n.callback(e)}},t._onError=function(t,i,n,s){var r=this;if(!n.retrying)if(n.retry&&n.retries7?t=de.intToBytes32(i):(t=de.intToBytes24(i))[3]=255,this.set(t[0]/255,t[1]/255,t[2]/255,t[3]/255),this},t.toString=function(e){var t="#"+((1<<24)+(Math.round(255*this.r)<<16)+(Math.round(255*this.g)<<8)+Math.round(255*this.b)).toString(16).slice(1);if(!0===e){var i=Math.round(255*this.a).toString(16);this.a<16/255?t+="0"+i:t+=i}return t},e}();me.BLACK=Object.freeze(new me(0,0,0,1)),me.BLUE=Object.freeze(new me(0,0,1,1)),me.CYAN=Object.freeze(new me(0,1,1,1)),me.GRAY=Object.freeze(new me(.5,.5,.5,1)),me.GREEN=Object.freeze(new me(0,1,0,1)),me.MAGENTA=Object.freeze(new me(1,0,1,1)),me.RED=Object.freeze(new me(1,0,0,1)),me.WHITE=Object.freeze(new me(1,1,1,1)),me.YELLOW=Object.freeze(new me(1,1,0,1));var _e=function(){function e(e,t){void 0===t&&(t=0),this._curve=e,this._left=-1/0,this._right=1/0,this._recip=0,this._p0=0,this._p1=0,this._m0=0,this._m1=0,this._reset(t)}var t=e.prototype;return t.evaluate=function(e,t){var i;void 0===t&&(t=!1),(t||e=this._right)&&this._reset(e);var n=this._curve.type;if(5===n)i=this._p0;else{var s=0===this._recip?0:(e-this._left)*this._recip;i=0===n?de.lerp(this._p0,this._p1,s):1===n?de.lerp(this._p0,this._p1,s*s*(3-2*s)):this._evaluateHermite(this._p0,this._p1,this._m0,this._m1,s)}return i},t._reset=function(e){var t=this._curve.keys,i=t.length;if(i)if(e=t[i-1][0])this._left=t[i-1][0],this._right=1/0,this._recip=0,this._p0=this._p1=t[i-1][1],this._m0=this._m1=0;else{for(var n=0;e>=t[n+1][0];)n++;this._left=t[n][0],this._right=t[n+1][0];var s=1/(this._right-this._left);this._recip=isFinite(s)?s:0,this._p0=t[n][1],this._p1=t[n+1][1],this._isHermite()&&this._calcTangents(t,n)}else this._left=-1/0,this._right=1/0,this._recip=0,this._p0=this._p1=this._m0=this._m1=0},t._isHermite=function(){return 2===this._curve.type||3===this._curve.type||4===this._curve.type},t._calcTangents=function(e,t){var i,n,s=e[t],r=e[t+1];if(i=0===t?[e[0][0]+(e[0][0]-e[1][0]),e[0][1]+(e[0][1]-e[1][1])]:e[t-1],n=t===e.length-2?[e[t+1][0]+(e[t+1][0]-e[t][0]),e[t+1][1]+(e[t+1][1]-e[t][1])]:e[t+2],4===this._curve.type){var a=2*(r[0]-s[0])/(r[0]-i[0]),o=2*(r[0]-s[0])/(n[0]-s[0]);this._m0=this._curve.tension*(isFinite(a)?a:0)*(r[1]-i[1]),this._m1=this._curve.tension*(isFinite(o)?o:0)*(n[1]-s[1])}else{var h=(r[0]-s[0])/(s[0]-i[0]),l=(r[0]-s[0])/(n[0]-r[0]),c=s[1]+(i[1]-s[1])*(isFinite(h)?h:0),u=r[1]+(n[1]-r[1])*(isFinite(l)?l:0),d=2===this._curve.type?.5:this._curve.tension;this._m0=d*(r[1]-c),this._m1=d*(u-s[1])}},t._evaluateHermite=function(e,t,i,n,s){var r=s*s,a=s+s,o=1-s,h=o*o;return e*((1+a)*h)+i*(s*h)+t*(r*(3-a))+n*(r*(s-1))},e}(),ge=function(){function e(e){if(this.keys=[],this.type=1,this.tension=.5,this._eval=new _e(this),e)for(var t=0;te);s++);var r=[e,t];return this.keys.splice(s,0,r),r},t.get=function(e){return this.keys[e]},t.sort=function(){this.keys.sort((function(e,t){return e[0]-t[0]}))},t.value=function(e){return this._eval.evaluate(e,!0)},t.closest=function(e){for(var t=this.keys,i=t.length,n=2,s=null,r=0;r=a))break;n=a,s=t[r]}return s},t.clone=function(){var e=new this.constructor;return e.keys=f(e.keys,this.keys),e.type=this.type,e.tension=this.tension,e},t.quantize=function(e){e=Math.max(e,2);var t=new Float32Array(e),i=1/(e-1);t[0]=this._eval.evaluate(0,!0);for(var n=1;n1)for(var e=0;e0){var t=1/Math.sqrt(e);this.x*=t,this.y*=t,this.z*=t}return this},t.floor=function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this},t.ceil=function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this},t.round=function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this},t.min=function(e){return e.xthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),this},t.project=function(e){var t=(this.x*e.x+this.y*e.y+this.z*e.z)/(e.x*e.x+e.y*e.y+e.z*e.z);return this.x=e.x*t,this.y=e.y*t,this.z=e.z*t,this},t.set=function(e,t,i){return this.x=e,this.y=t,this.z=i,this},t.sub=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this},t.sub2=function(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this},t.subScalar=function(e){return this.x-=e,this.y-=e,this.z-=e,this},t.toString=function(){return"["+this.x+", "+this.y+", "+this.z+"]"},e}();ye.ZERO=Object.freeze(new ye(0,0,0)),ye.ONE=Object.freeze(new ye(1,1,1)),ye.UP=Object.freeze(new ye(0,1,0)),ye.DOWN=Object.freeze(new ye(0,-1,0)),ye.RIGHT=Object.freeze(new ye(1,0,0)),ye.LEFT=Object.freeze(new ye(-1,0,0)),ye.FORWARD=Object.freeze(new ye(0,0,-1)),ye.BACK=Object.freeze(new ye(0,0,1));var xe=function(){function e(){var e=new Float32Array(9);e[0]=e[4]=e[8]=1,this.data=e}var t=e.prototype;return t.clone=function(){return(new(0,this.constructor)).copy(this)},t.copy=function(e){var t=e.data,i=this.data;return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[3],i[4]=t[4],i[5]=t[5],i[6]=t[6],i[7]=t[7],i[8]=t[8],this},t.set=function(e){var t=this.data;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],this},t.equals=function(e){var t=this.data,i=e.data;return t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]&&t[4]===i[4]&&t[5]===i[5]&&t[6]===i[6]&&t[7]===i[7]&&t[8]===i[8]},t.isIdentity=function(){var e=this.data;return 1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&1===e[4]&&0===e[5]&&0===e[6]&&0===e[7]&&1===e[8]},t.setIdentity=function(){var e=this.data;return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,this},t.toString=function(){return"["+this.data.join(", ")+"]"},t.transpose=function(){var e,t=this.data;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this},t.setFromMat4=function(e){var t=e.data,i=this.data;return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[4],i[4]=t[5],i[5]=t[6],i[6]=t[8],i[7]=t[9],i[8]=t[10],this},t.transformVector=function(e,t){void 0===t&&(t=new ye);var i=this.data,n=e.x,s=e.y,r=e.z;return t.x=n*i[0]+s*i[3]+r*i[6],t.y=n*i[1]+s*i[4]+r*i[7],t.z=n*i[2]+s*i[5]+r*i[8],t},e}();xe.IDENTITY=Object.freeze(new xe),xe.ZERO=Object.freeze((new xe).set([0,0,0,0,0,0,0,0,0]));var be=function(){function e(e,t){void 0===e&&(e=0),void 0===t&&(t=0),2===e.length?(this.x=e[0],this.y=e[1]):(this.x=e,this.y=t)}var t=e.prototype;return t.add=function(e){return this.x+=e.x,this.y+=e.y,this},t.add2=function(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this},t.addScalar=function(e){return this.x+=e,this.y+=e,this},t.clone=function(){return new(0,this.constructor)(this.x,this.y)},t.copy=function(e){return this.x=e.x,this.y=e.y,this},t.cross=function(e){return this.x*e.y-this.y*e.x},t.distance=function(e){var t=this.x-e.x,i=this.y-e.y;return Math.sqrt(t*t+i*i)},t.div=function(e){return this.x/=e.x,this.y/=e.y,this},t.div2=function(e,t){return this.x=e.x/t.x,this.y=e.y/t.y,this},t.divScalar=function(e){return this.x/=e,this.y/=e,this},t.dot=function(e){return this.x*e.x+this.y*e.y},t.equals=function(e){return this.x===e.x&&this.y===e.y},t.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},t.lengthSq=function(){return this.x*this.x+this.y*this.y},t.lerp=function(e,t,i){return this.x=e.x+i*(t.x-e.x),this.y=e.y+i*(t.y-e.y),this},t.mul=function(e){return this.x*=e.x,this.y*=e.y,this},t.mul2=function(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this},t.mulScalar=function(e){return this.x*=e,this.y*=e,this},t.normalize=function(){var e=this.x*this.x+this.y*this.y;if(e>0){var t=1/Math.sqrt(e);this.x*=t,this.y*=t}return this},t.floor=function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},t.ceil=function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},t.round=function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},t.min=function(e){return e.xthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),this},t.set=function(e,t){return this.x=e,this.y=t,this},t.sub=function(e){return this.x-=e.x,this.y-=e.y,this},t.sub2=function(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this},t.subScalar=function(e){return this.x-=e,this.y-=e,this},t.toString=function(){return"["+this.x+", "+this.y+"]"},e.angleRad=function(e,t){return Math.atan2(e.x*t.y-e.y*t.x,e.x*t.x+e.y*t.y)},e}();be.ZERO=Object.freeze(new be(0,0)),be.ONE=Object.freeze(new be(1,1)),be.UP=Object.freeze(new be(0,1)),be.DOWN=Object.freeze(new be(0,-1)),be.RIGHT=Object.freeze(new be(1,0)),be.LEFT=Object.freeze(new be(-1,0));var Se=function(){function e(e,t,i,n){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),4===e.length?(this.x=e[0],this.y=e[1],this.z=e[2],this.w=e[3]):(this.x=e,this.y=t,this.z=i,this.w=n)}var t=e.prototype;return t.add=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this},t.add2=function(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this},t.addScalar=function(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this},t.clone=function(){return new(0,this.constructor)(this.x,this.y,this.z,this.w)},t.copy=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},t.div=function(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this},t.div2=function(e,t){return this.x=e.x/t.x,this.y=e.y/t.y,this.z=e.z/t.z,this.w=e.w/t.w,this},t.divScalar=function(e){return this.x/=e,this.y/=e,this.z/=e,this.w/=e,this},t.dot=function(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w},t.equals=function(e){return this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},t.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.lengthSq=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},t.lerp=function(e,t,i){return this.x=e.x+i*(t.x-e.x),this.y=e.y+i*(t.y-e.y),this.z=e.z+i*(t.z-e.z),this.w=e.w+i*(t.w-e.w),this},t.mul=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this},t.mul2=function(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this.w=e.w*t.w,this},t.mulScalar=function(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},t.normalize=function(){var e=this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w;if(e>0){var t=1/Math.sqrt(e);this.x*=t,this.y*=t,this.z*=t,this.w*=t}return this},t.floor=function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this},t.ceil=function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this},t.round=function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this},t.min=function(e){return e.xthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this},t.set=function(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this},t.sub=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this},t.sub2=function(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this},t.subScalar=function(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this},t.toString=function(){return"["+this.x+", "+this.y+", "+this.z+", "+this.w+"]"},e}();Se.ZERO=Object.freeze(new Se(0,0,0,0)),Se.ONE=Object.freeze(new Se(1,1,1,1));var we=new be,Te=new ye,Ae=new ye,Me=new ye,Ce=new ye,Ee=function(){function e(){var e=new Float32Array(16);e[0]=e[5]=e[10]=e[15]=1,this.data=e}e._getPerspectiveHalfSize=function(e,t,i,n,s){s?(e.x=n*Math.tan(t*Math.PI/360),e.y=e.x/i):(e.y=n*Math.tan(t*Math.PI/360),e.x=e.y*i)};var t=e.prototype;return t.add2=function(e,t){var i=e.data,n=t.data,s=this.data;return s[0]=i[0]+n[0],s[1]=i[1]+n[1],s[2]=i[2]+n[2],s[3]=i[3]+n[3],s[4]=i[4]+n[4],s[5]=i[5]+n[5],s[6]=i[6]+n[6],s[7]=i[7]+n[7],s[8]=i[8]+n[8],s[9]=i[9]+n[9],s[10]=i[10]+n[10],s[11]=i[11]+n[11],s[12]=i[12]+n[12],s[13]=i[13]+n[13],s[14]=i[14]+n[14],s[15]=i[15]+n[15],this},t.add=function(e){return this.add2(this,e)},t.clone=function(){return(new(0,this.constructor)).copy(this)},t.copy=function(e){var t=e.data,i=this.data;return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[3],i[4]=t[4],i[5]=t[5],i[6]=t[6],i[7]=t[7],i[8]=t[8],i[9]=t[9],i[10]=t[10],i[11]=t[11],i[12]=t[12],i[13]=t[13],i[14]=t[14],i[15]=t[15],this},t.equals=function(e){var t=this.data,i=e.data;return t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]&&t[4]===i[4]&&t[5]===i[5]&&t[6]===i[6]&&t[7]===i[7]&&t[8]===i[8]&&t[9]===i[9]&&t[10]===i[10]&&t[11]===i[11]&&t[12]===i[12]&&t[13]===i[13]&&t[14]===i[14]&&t[15]===i[15]},t.isIdentity=function(){var e=this.data;return 1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]},t.mul2=function(e,t){var i,n,s,r,a=e.data,o=t.data,h=this.data,l=a[0],c=a[1],u=a[2],d=a[3],f=a[4],p=a[5],m=a[6],_=a[7],g=a[8],v=a[9],y=a[10],x=a[11],b=a[12],S=a[13],w=a[14],T=a[15];return i=o[0],n=o[1],s=o[2],r=o[3],h[0]=l*i+f*n+g*s+b*r,h[1]=c*i+p*n+v*s+S*r,h[2]=u*i+m*n+y*s+w*r,h[3]=d*i+_*n+x*s+T*r,i=o[4],n=o[5],s=o[6],r=o[7],h[4]=l*i+f*n+g*s+b*r,h[5]=c*i+p*n+v*s+S*r,h[6]=u*i+m*n+y*s+w*r,h[7]=d*i+_*n+x*s+T*r,i=o[8],n=o[9],s=o[10],r=o[11],h[8]=l*i+f*n+g*s+b*r,h[9]=c*i+p*n+v*s+S*r,h[10]=u*i+m*n+y*s+w*r,h[11]=d*i+_*n+x*s+T*r,i=o[12],n=o[13],s=o[14],r=o[15],h[12]=l*i+f*n+g*s+b*r,h[13]=c*i+p*n+v*s+S*r,h[14]=u*i+m*n+y*s+w*r,h[15]=d*i+_*n+x*s+T*r,this},t.mulAffine2=function(e,t){var i,n,s,r=e.data,a=t.data,o=this.data,h=r[0],l=r[1],c=r[2],u=r[4],d=r[5],f=r[6],p=r[8],m=r[9],_=r[10],g=r[12],v=r[13],y=r[14];return i=a[0],n=a[1],s=a[2],o[0]=h*i+u*n+p*s,o[1]=l*i+d*n+m*s,o[2]=c*i+f*n+_*s,o[3]=0,i=a[4],n=a[5],s=a[6],o[4]=h*i+u*n+p*s,o[5]=l*i+d*n+m*s,o[6]=c*i+f*n+_*s,o[7]=0,i=a[8],n=a[9],s=a[10],o[8]=h*i+u*n+p*s,o[9]=l*i+d*n+m*s,o[10]=c*i+f*n+_*s,o[11]=0,i=a[12],n=a[13],s=a[14],o[12]=h*i+u*n+p*s+g,o[13]=l*i+d*n+m*s+v,o[14]=c*i+f*n+_*s+y,o[15]=1,this},t.mul=function(e){return this.mul2(this,e)},t.transformPoint=function(e,t){void 0===t&&(t=new ye);var i=this.data,n=e.x,s=e.y,r=e.z;return t.x=n*i[0]+s*i[4]+r*i[8]+i[12],t.y=n*i[1]+s*i[5]+r*i[9]+i[13],t.z=n*i[2]+s*i[6]+r*i[10]+i[14],t},t.transformVector=function(e,t){void 0===t&&(t=new ye);var i=this.data,n=e.x,s=e.y,r=e.z;return t.x=n*i[0]+s*i[4]+r*i[8],t.y=n*i[1]+s*i[5]+r*i[9],t.z=n*i[2]+s*i[6]+r*i[10],t},t.transformVec4=function(e,t){void 0===t&&(t=new Se);var i=this.data,n=e.x,s=e.y,r=e.z,a=e.w;return t.x=n*i[0]+s*i[4]+r*i[8]+a*i[12],t.y=n*i[1]+s*i[5]+r*i[9]+a*i[13],t.z=n*i[2]+s*i[6]+r*i[10]+a*i[14],t.w=n*i[3]+s*i[7]+r*i[11]+a*i[15],t},t.setLookAt=function(e,t,i){Me.sub2(e,t).normalize(),Ae.copy(i).normalize(),Te.cross(Ae,Me).normalize(),Ae.cross(Me,Te);var n=this.data;return n[0]=Te.x,n[1]=Te.y,n[2]=Te.z,n[3]=0,n[4]=Ae.x,n[5]=Ae.y,n[6]=Ae.z,n[7]=0,n[8]=Me.x,n[9]=Me.y,n[10]=Me.z,n[11]=0,n[12]=e.x,n[13]=e.y,n[14]=e.z,n[15]=1,this},t.setFrustum=function(e,t,i,n,s,r){var a=2*s,o=t-e,h=n-i,l=r-s,c=this.data;return c[0]=a/o,c[1]=0,c[2]=0,c[3]=0,c[4]=0,c[5]=a/h,c[6]=0,c[7]=0,c[8]=(t+e)/o,c[9]=(n+i)/h,c[10]=(-r-s)/l,c[11]=-1,c[12]=0,c[13]=0,c[14]=-a*r/l,c[15]=0,this},t.setPerspective=function(t,i,n,s,r){return e._getPerspectiveHalfSize(we,t,i,n,r),this.setFrustum(-we.x,we.x,-we.y,we.y,n,s)},t.setOrtho=function(e,t,i,n,s,r){var a=this.data;return a[0]=2/(t-e),a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=2/(n-i),a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=-2/(r-s),a[11]=0,a[12]=-(t+e)/(t-e),a[13]=-(n+i)/(n-i),a[14]=-(r+s)/(r-s),a[15]=1,this},t.setFromAxisAngle=function(e,t){t*=de.DEG_TO_RAD;var i=e.x,n=e.y,s=e.z,r=Math.cos(t),a=Math.sin(t),o=1-r,h=o*i,l=o*n,c=this.data;return c[0]=h*i+r,c[1]=h*n+a*s,c[2]=h*s-a*n,c[3]=0,c[4]=h*n-a*s,c[5]=l*n+r,c[6]=l*s+a*i,c[7]=0,c[8]=h*s+a*n,c[9]=l*s-i*a,c[10]=o*s*s+r,c[11]=0,c[12]=0,c[13]=0,c[14]=0,c[15]=1,this},t.setTranslate=function(e,t,i){var n=this.data;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=e,n[13]=t,n[14]=i,n[15]=1,this},t.setScale=function(e,t,i){var n=this.data;return n[0]=e,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=t,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=i,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this},t.setViewport=function(e,t,i,n){var s=this.data;return s[0]=.5*i,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=.5*n,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=.5,s[11]=0,s[12]=e+.5*i,s[13]=t+.5*n,s[14]=.5,s[15]=1,this},t.invert=function(){var e=this.data,t=e[0],i=e[1],n=e[2],s=e[3],r=e[4],a=e[5],o=e[6],h=e[7],l=e[8],c=e[9],u=e[10],d=e[11],f=e[12],p=e[13],m=e[14],_=e[15],g=t*a-i*r,v=t*o-n*r,y=t*h-s*r,x=i*o-n*a,b=i*h-s*a,S=n*h-s*o,w=l*p-c*f,T=l*m-u*f,A=l*_-d*f,M=c*m-u*p,C=c*_-d*p,E=u*_-d*m,P=g*E-v*C+y*M+x*A-b*T+S*w;if(0===P)this.setIdentity();else{var R=1/P;e[0]=(a*E-o*C+h*M)*R,e[1]=(-i*E+n*C-s*M)*R,e[2]=(p*S-m*b+_*x)*R,e[3]=(-c*S+u*b-d*x)*R,e[4]=(-r*E+o*A-h*T)*R,e[5]=(t*E-n*A+s*T)*R,e[6]=(-f*S+m*y-_*v)*R,e[7]=(l*S-u*y+d*v)*R,e[8]=(r*C-a*A+h*w)*R,e[9]=(-t*C+i*A-s*w)*R,e[10]=(f*b-p*y+_*g)*R,e[11]=(-l*b+c*y-d*g)*R,e[12]=(-r*M+a*T-o*w)*R,e[13]=(t*M-i*T+n*w)*R,e[14]=(-f*x+p*v-m*g)*R,e[15]=(l*x-c*v+u*g)*R}return this},t.set=function(e){var t=this.data;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],this},t.setIdentity=function(){var e=this.data;return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},t.setTRS=function(e,t,i){var n=t.x,s=t.y,r=t.z,a=t.w,o=i.x,h=i.y,l=i.z,c=n+n,u=s+s,d=r+r,f=n*c,p=n*u,m=n*d,_=s*u,g=s*d,v=r*d,y=a*c,x=a*u,b=a*d,S=this.data;return S[0]=(1-(_+v))*o,S[1]=(p+b)*o,S[2]=(m-x)*o,S[3]=0,S[4]=(p-b)*h,S[5]=(1-(f+v))*h,S[6]=(g+y)*h,S[7]=0,S[8]=(m+x)*l,S[9]=(g-y)*l,S[10]=(1-(f+_))*l,S[11]=0,S[12]=e.x,S[13]=e.y,S[14]=e.z,S[15]=1,this},t.transpose=function(){var e,t=this.data;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this},t.invertTo3x3=function(e){var t=this.data,i=e.data,n=t[0],s=t[1],r=t[2],a=t[4],o=t[5],h=t[6],l=t[8],c=t[9],u=t[10],d=u*o-h*c,f=-u*s+r*c,p=h*s-r*o,m=-u*a+h*l,_=u*n-r*l,g=-h*n+r*a,v=c*a-o*l,y=-c*n+s*l,x=o*n-s*a,b=n*d+s*m+r*v;if(0===b)return this;var S=1/b;return i[0]=S*d,i[1]=S*f,i[2]=S*p,i[3]=S*m,i[4]=S*_,i[5]=S*g,i[6]=S*v,i[7]=S*y,i[8]=S*x,this},t.getTranslation=function(e){return void 0===e&&(e=new ye),e.set(this.data[12],this.data[13],this.data[14])},t.getX=function(e){return void 0===e&&(e=new ye),e.set(this.data[0],this.data[1],this.data[2])},t.getY=function(e){return void 0===e&&(e=new ye),e.set(this.data[4],this.data[5],this.data[6])},t.getZ=function(e){return void 0===e&&(e=new ye),e.set(this.data[8],this.data[9],this.data[10])},t.getScale=function(e){return void 0===e&&(e=new ye),this.getX(Te),this.getY(Ae),this.getZ(Me),e.set(Te.length(),Ae.length(),Me.length()),e},t.setFromEulerAngles=function(e,t,i){e*=de.DEG_TO_RAD,t*=de.DEG_TO_RAD,i*=de.DEG_TO_RAD;var n=Math.sin(-e),s=Math.cos(-e),r=Math.sin(-t),a=Math.cos(-t),o=Math.sin(-i),h=Math.cos(-i),l=this.data;return l[0]=a*h,l[1]=-a*o,l[2]=r,l[3]=0,l[4]=s*o+h*n*r,l[5]=s*h-n*r*o,l[6]=-a*n,l[7]=0,l[8]=n*o-s*h*r,l[9]=h*n+s*r*o,l[10]=s*a,l[11]=0,l[12]=0,l[13]=0,l[14]=0,l[15]=1,this},t.getEulerAngles=function(e){void 0===e&&(e=new ye),this.getScale(Ce);var t=Ce.x,i=Ce.y,n=Ce.z;if(0===t||0===i||0===n)return e.set(0,0,0);var s,r,a=this.data,o=Math.asin(-a[2]/t),h=.5*Math.PI;return o-h?(s=Math.atan2(a[6]/i,a[10]/n),r=Math.atan2(a[1]/t,a[0]/t)):(r=0,s=-Math.atan2(a[4]/i,a[5]/i)):(r=0,s=Math.atan2(a[4]/i,a[5]/i)),e.set(s,o,r).mulScalar(de.RAD_TO_DEG)},t.toString=function(){return"["+this.data.join(", ")+"]"},e}();Ee.IDENTITY=Object.freeze(new Ee),Ee.ZERO=Object.freeze((new Ee).set([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]));var Pe=function(){function e(e,t,i,n){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=1),4===e.length?(this.x=e[0],this.y=e[1],this.z=e[2],this.w=e[3]):(this.x=e,this.y=t,this.z=i,this.w=n)}var t=e.prototype;return t.clone=function(){return new(0,this.constructor)(this.x,this.y,this.z,this.w)},t.conjugate=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.copy=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},t.equals=function(e){return this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},t.getAxisAngle=function(e){var t=2*Math.acos(this.w),i=Math.sin(t/2);return 0!==i?(e.x=this.x/i,e.y=this.y/i,e.z=this.z/i,(e.x<0||e.y<0||e.z<0)&&(e.x*=-1,e.y*=-1,e.z*=-1,t*=-1)):(e.x=1,e.y=0,e.z=0),t*de.RAD_TO_DEG},t.getEulerAngles=function(e){var t,i,n;void 0===e&&(e=new ye);var s=this.x,r=this.y,a=this.z,o=this.w,h=2*(o*r-s*a);return h<=-.99999?(t=2*Math.atan2(s,o),i=-Math.PI/2,n=0):h>=.99999?(t=2*Math.atan2(s,o),i=Math.PI/2,n=0):(t=Math.atan2(2*(o*s+r*a),1-2*(s*s+r*r)),i=Math.asin(h),n=Math.atan2(2*(o*a+s*r),1-2*(r*r+a*a))),e.set(t,i,n).mulScalar(de.RAD_TO_DEG)},t.invert=function(){return this.conjugate().normalize()},t.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.lengthSq=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},t.mul=function(e){var t=this.x,i=this.y,n=this.z,s=this.w,r=e.x,a=e.y,o=e.z,h=e.w;return this.x=s*r+t*h+i*o-n*a,this.y=s*a+i*h+n*r-t*o,this.z=s*o+n*h+t*a-i*r,this.w=s*h-t*r-i*a-n*o,this},t.mul2=function(e,t){var i=e.x,n=e.y,s=e.z,r=e.w,a=t.x,o=t.y,h=t.z,l=t.w;return this.x=r*a+i*l+n*h-s*o,this.y=r*o+n*l+s*a-i*h,this.z=r*h+s*l+i*o-n*a,this.w=r*l-i*a-n*o-s*h,this},t.normalize=function(){var e=this.length();return 0===e?(this.x=this.y=this.z=0,this.w=1):(e=1/e,this.x*=e,this.y*=e,this.z*=e,this.w*=e),this},t.set=function(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this},t.setFromAxisAngle=function(e,t){t*=.5*de.DEG_TO_RAD;var i=Math.sin(t),n=Math.cos(t);return this.x=i*e.x,this.y=i*e.y,this.z=i*e.z,this.w=n,this},t.setFromEulerAngles=function(e,t,i){if(e instanceof ye){var n=e;e=n.x,t=n.y,i=n.z}var s=.5*de.DEG_TO_RAD;e*=s,t*=s,i*=s;var r=Math.sin(e),a=Math.cos(e),o=Math.sin(t),h=Math.cos(t),l=Math.sin(i),c=Math.cos(i);return this.x=r*h*c-a*o*l,this.y=a*o*c+r*h*l,this.z=a*h*l-r*o*c,this.w=a*h*c+r*o*l,this},t.setFromMat4=function(e){var t,i,n,s,r,a,o,h,l,c,u,d,f,p;if(t=(e=e.data)[0],i=e[1],n=e[2],s=e[4],r=e[5],a=e[6],o=e[8],h=e[9],l=e[10],0===(d=t*t+i*i+n*n))return this;if(d=1/Math.sqrt(d),0===(f=s*s+r*r+a*a))return this;if(f=1/Math.sqrt(f),0===(p=o*o+h*h+l*l))return this;i*=d,n*=d,s*=f,a*=f,o*=p=1/Math.sqrt(p),h*=p;var m=(t*=d)+(r*=f)+(l*=p);return m>=0?(c=Math.sqrt(m+1),this.w=.5*c,c=.5/c,this.x=(a-h)*c,this.y=(o-n)*c,this.z=(i-s)*c):t>r?t>l?(u=t-(r+l)+1,u=Math.sqrt(u),this.x=.5*u,u=.5/u,this.w=(a-h)*u,this.y=(i+s)*u,this.z=(n+o)*u):(u=l-(t+r)+1,u=Math.sqrt(u),this.z=.5*u,u=.5/u,this.w=(i-s)*u,this.x=(o+n)*u,this.y=(h+a)*u):r>l?(u=r-(l+t)+1,u=Math.sqrt(u),this.y=.5*u,u=.5/u,this.w=(o-n)*u,this.z=(a+h)*u,this.x=(s+i)*u):(u=l-(t+r)+1,u=Math.sqrt(u),this.z=.5*u,u=.5/u,this.w=(i-s)*u,this.x=(o+n)*u,this.y=(h+a)*u),this},t.slerp=function(e,t,i){var n=e.x,s=e.y,r=e.z,a=e.w,o=t.x,h=t.y,l=t.z,c=t.w,u=a*c+n*o+s*h+r*l;if(u<0&&(c=-c,o=-o,h=-h,l=-l,u=-u),Math.abs(u)>=1)return this.w=a,this.x=n,this.y=s,this.z=r,this;var d=Math.acos(u),f=Math.sqrt(1-u*u);if(Math.abs(f)<.001)return this.w=.5*a+.5*c,this.x=.5*n+.5*o,this.y=.5*s+.5*h,this.z=.5*r+.5*l,this;var p=Math.sin((1-i)*d)/f,m=Math.sin(i*d)/f;return this.w=a*p+c*m,this.x=n*p+o*m,this.y=s*p+h*m,this.z=r*p+l*m,this},t.transformVector=function(e,t){void 0===t&&(t=new ye);var i=e.x,n=e.y,s=e.z,r=this.x,a=this.y,o=this.z,h=this.w,l=h*i+a*s-o*n,c=h*n+o*i-r*s,u=h*s+r*n-a*i,d=-r*i-a*n-o*s;return t.x=l*h+d*-r+c*-o-u*-a,t.y=c*h+d*-a+u*-r-l*-o,t.z=u*h+d*-o+l*-a-c*-r,t},t.toString=function(){return"["+this.x+", "+this.y+", "+this.z+", "+this.w+"]"},e}();Pe.IDENTITY=Object.freeze(new Pe(0,0,0,1)),Pe.ZERO=Object.freeze(new Pe(0,0,0,0));var Re=new ye,Ie=new ye,Le=new ye,De=new ye,ke=new ye,Oe=function(){function e(e,t){void 0===e&&(e=new ye),void 0===t&&(t=new ye(.5,.5,.5)),this.center=e,this.halfExtents=t,this._min=new ye,this._max=new ye}var t=e.prototype;return t.add=function(e){var t=this.center,i=t.x,n=t.y,s=t.z,r=this.halfExtents,a=r.x,o=r.y,h=r.z,l=i-a,c=i+a,u=n-o,d=n+o,f=s-h,p=s+h,m=e.center,_=m.x,g=m.y,v=m.z,y=e.halfExtents,x=y.x,b=y.y,S=y.z,w=_-x,T=_+x,A=g-b,M=g+b,C=v-S,E=v+S;wc&&(c=T),Ad&&(d=M),Cp&&(p=E),t.x=.5*(l+c),t.y=.5*(u+d),t.z=.5*(f+p),r.x=.5*(c-l),r.y=.5*(d-u),r.z=.5*(p-f)},t.copy=function(e){this.center.copy(e.center),this.halfExtents.copy(e.halfExtents)},t.clone=function(){return new e(this.center.clone(),this.halfExtents.clone())},t.intersects=function(e){var t=this.getMax(),i=this.getMin(),n=e.getMax(),s=e.getMin();return i.x<=n.x&&t.x>=s.x&&i.y<=n.y&&t.y>=s.y&&i.z<=n.z&&t.z>=s.z},t._intersectsRay=function(e,t){var i=Re.copy(this.getMin()).sub(e.origin),n=Ie.copy(this.getMax()).sub(e.origin),s=e.direction;0===s.x?(i.x=i.x<0?-Number.MAX_VALUE:Number.MAX_VALUE,n.x=n.x<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.x/=s.x,n.x/=s.x),0===s.y?(i.y=i.y<0?-Number.MAX_VALUE:Number.MAX_VALUE,n.y=n.y<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.y/=s.y,n.y/=s.y),0===s.z?(i.z=i.z<0?-Number.MAX_VALUE:Number.MAX_VALUE,n.z=n.z<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.z/=s.z,n.z/=s.z);var r=Le.set(Math.min(i.x,n.x),Math.min(i.y,n.y),Math.min(i.z,n.z)),a=De.set(Math.max(i.x,n.x),Math.max(i.y,n.y),Math.max(i.z,n.z)),o=Math.min(Math.min(a.x,a.y),a.z),h=Math.max(Math.max(r.x,r.y),r.z),l=o>=h&&h>=0;return l&&t.copy(e.direction).mulScalar(h).add(e.origin),l},t._fastIntersectsRay=function(e){var t=Re,i=Ie,n=Le,s=De,r=ke,a=e.direction;return t.sub2(e.origin,this.center),s.set(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z)),n.mul2(t,a),!(s.x>this.halfExtents.x&&n.x>=0)&&(!(s.y>this.halfExtents.y&&n.y>=0)&&(!(s.z>this.halfExtents.z&&n.z>=0)&&(r.set(Math.abs(a.x),Math.abs(a.y),Math.abs(a.z)),i.cross(a,t),i.set(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z)),!(i.x>this.halfExtents.y*r.z+this.halfExtents.z*r.y)&&(!(i.y>this.halfExtents.x*r.z+this.halfExtents.z*r.x)&&!(i.z>this.halfExtents.x*r.y+this.halfExtents.y*r.x)))))},t.intersectsRay=function(e,t){return t?this._intersectsRay(e,t):this._fastIntersectsRay(e)},t.setMinMax=function(e,t){this.center.add2(t,e).mulScalar(.5),this.halfExtents.sub2(t,e).mulScalar(.5)},t.getMin=function(){return this._min.copy(this.center).sub(this.halfExtents)},t.getMax=function(){return this._max.copy(this.center).add(this.halfExtents)},t.containsPoint=function(e){var t=this.getMin(),i=this.getMax();return!(e.xi.x||e.yi.y||e.zi.z)},t.setFromTransformedAabb=function(e,t,i){void 0===i&&(i=!1);var n=e.center,s=e.halfExtents,r=t.data,a=r[0],o=r[4],h=r[8],l=r[1],c=r[5],u=r[9],d=r[2],f=r[6],p=r[10];if(i){var m=a*a+o*o+h*h;if(m>0){var _=1/Math.sqrt(m);a*=_,o*=_,h*=_}if((m=l*l+c*c+u*u)>0){var g=1/Math.sqrt(m);l*=g,c*=g,u*=g}if((m=d*d+f*f+p*p)>0){var v=1/Math.sqrt(m);d*=v,f*=v,p*=v}}this.center.set(r[12]+a*n.x+o*n.y+h*n.z,r[13]+l*n.x+c*n.y+u*n.z,r[14]+d*n.x+f*n.y+p*n.z),this.halfExtents.set(Math.abs(a)*s.x+Math.abs(o)*s.y+Math.abs(h)*s.z,Math.abs(l)*s.x+Math.abs(c)*s.y+Math.abs(u)*s.z,Math.abs(d)*s.x+Math.abs(f)*s.y+Math.abs(p)*s.z)},e.computeMinMax=function(e,t,i,n){if(void 0===n&&(n=e.length/3),n>0){t.set(e[0],e[1],e[2]),i.set(e[0],e[1],e[2]);for(var s=1;si.x&&(i.x=r),a>i.y&&(i.y=a),o>i.z&&(i.z=o)}}},t.compute=function(t,i){e.computeMinMax(t,Re,Ie,i),this.setMinMax(Re,Ie)},t.intersectsBoundingSphere=function(e){return this._distanceToBoundingSphereSq(e)<=e.radius*e.radius},t._distanceToBoundingSphereSq=function(e){for(var t=this.getMin(),i=this.getMax(),n=0,s=["x","y","z"],r=0;r<3;++r){var a=0,o=e.center[s[r]],h=t[s[r]],l=i[s[r]],c=0;ol&&(a+=(c=o-l)*c),n+=a}return n},t._expand=function(e,t){Re.add2(this.getMin(),e),Ie.add2(this.getMax(),t),this.setMinMax(Re,Ie)},e}(),Fe=new ye,Be=new ye,Ne=function(){function e(e,t){void 0===e&&(e=new ye),void 0===t&&(t=.5),this.center=e,this.radius=t}var t=e.prototype;return t.containsPoint=function(e){var t=Fe.sub2(e,this.center).lengthSq(),i=this.radius;return t0&&n>0)return!1;var r=n*n-s;if(r<0)return!1;var a=Math.abs(-n-Math.sqrt(r));return t&&t.copy(e.direction).mulScalar(a).add(e.origin),!0},t.intersectsBoundingSphere=function(e){Fe.sub2(e.center,this.center);var t=e.radius+this.radius;return Fe.lengthSq()<=t*t},e}(),Ue="none",ze="linear",Ve={0:"PCF3",1:"VSM8",2:"VSM16",3:"VSM32",4:"PCF5",5:"PCF1"},Ge=128,We=256,He=1024,Xe=2048,qe=4096,je=8192,Ye="forward",Ke="depth",Ze="pick",$e="shadow",Qe=[new ye,new ye,new ye,new ye,new ye,new ye,new ye,new ye],Je=function(){function e(){this.planes=[];for(var e=0;e<6;e++)this.planes[e]=[]}var t=e.prototype;return t.setFromMat4=function(e){var t,i=e.data,n=this.planes;(t=n[0])[0]=i[3]-i[0],t[1]=i[7]-i[4],t[2]=i[11]-i[8],t[3]=i[15]-i[12];var s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s,(t=n[1])[0]=i[3]+i[0],t[1]=i[7]+i[4],t[2]=i[11]+i[8],t[3]=i[15]+i[12],s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s,(t=n[2])[0]=i[3]+i[1],t[1]=i[7]+i[5],t[2]=i[11]+i[9],t[3]=i[15]+i[13],s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s,(t=n[3])[0]=i[3]-i[1],t[1]=i[7]-i[5],t[2]=i[11]-i[9],t[3]=i[15]-i[13],s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s,(t=n[4])[0]=i[3]-i[2],t[1]=i[7]-i[6],t[2]=i[11]-i[10],t[3]=i[15]-i[14],s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s,(t=n[5])[0]=i[3]+i[2],t[1]=i[7]+i[6],t[2]=i[11]+i[10],t[3]=i[15]+i[14],s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s},t.containsPoint=function(e){var t,i;for(t=0;t<6;t++)if((i=this.planes[t])[0]*e.x+i[1]*e.y+i[2]*e.z+i[3]<=0)return!1;return!0},t.containsSphere=function(e){var t,i,n,s=0,r=e.radius,a=e.center,o=a.x,h=a.y,l=a.z,c=this.planes;for(i=0;i<6;i++){if((t=(n=c[i])[0]*o+n[1]*h+n[2]*l+n[3])<=-r)return 0;t>r&&s++}return 6===s?2:1},e.getPoints=function(e,t,i){t=t||e._nearClip,i=i||e._farClip;var n=e._fov*Math.PI/180,s=0===e._projection?Math.tan(n/2)*t:e._orthoHeight,r=s*e._aspectRatio,a=Qe;return a[0].x=r,a[0].y=-s,a[0].z=-t,a[1].x=r,a[1].y=s,a[1].z=-t,a[2].x=-r,a[2].y=s,a[2].z=-t,a[3].x=-r,a[3].y=-s,a[3].z=-t,0===e._projection&&(r=(s=Math.tan(n/2)*i)*e._aspectRatio),a[4].x=r,a[4].y=-s,a[4].z=-i,a[5].x=r,a[5].y=s,a[5].z=-i,a[6].x=-r,a[6].y=s,a[6].z=-i,a[7].x=-r,a[7].y=-s,a[7].z=-i,a},e}(),et=function(){function e(e,t){void 0===e&&(e=new ye),void 0===t&&(t=new ye(0,0,-1)),this.origin=e,this.direction=t}return e.prototype.set=function(e,t){return this.origin.copy(e),this.direction.copy(t),this},e}(),tt=new et,it=new ye,nt=new Ne,st=new Ee,rt=function(){function e(e,t){void 0===e&&(e=new Ee),void 0===t&&(t=new ye(.5,.5,.5)),this.halfExtents=t,this._modelTransform=e.clone().invert(),this._worldTransform=e.clone(),this._aabb=new Oe(new ye,this.halfExtents)}var t=e.prototype;return t.intersectsRay=function(e,t){if(this._modelTransform.transformPoint(e.origin,tt.origin),this._modelTransform.transformVector(e.direction,tt.direction),t){var i=this._aabb._intersectsRay(tt,t);return st.copy(this._modelTransform).invert().transformPoint(t,t),i}return this._aabb._fastIntersectsRay(tt)},t.containsPoint=function(e){return this._modelTransform.transformPoint(e,it),this._aabb.containsPoint(it)},t.intersectsBoundingSphere=function(e){return this._modelTransform.transformPoint(e.center,nt.center),nt.radius=e.radius,!!this._aabb.intersectsBoundingSphere(nt)},$(e,[{key:"worldTransform",get:function(){return this._worldTransform},set:function(e){this._worldTransform.copy(e),this._modelTransform.copy(e).invert()}}]),e}(),at=new ye,ot=function(){function e(e,t){void 0===e&&(e=new ye),void 0===t&&(t=new ye(0,0,1)),this.point=e,this.normal=t}var t=e.prototype;return t.intersectsLine=function(e,t,i){var n=-this.normal.dot(this.point),s=this.normal.dot(e)+n,r=s/(s-(this.normal.dot(t)+n)),a=r>=0&&r<=1;return a&&i&&i.lerp(e,t,r),a},t.intersectsRay=function(e,t){var i=at.sub2(this.point,e.origin),n=this.normal.dot(i)/this.normal.dot(e.direction),s=n>=0;return s&&t&&t.copy(e.direction).mulScalar(n).add(e.origin),s},e}(),ht=10,lt=11,ct=12,ut=13,dt=14,ft=16,pt=17,mt=21,_t=24,gt=25,vt="POSITION",yt="NORMAL",xt="TANGENT",bt="BLENDWEIGHT",St="BLENDINDICES",wt="COLOR",Tt="TEXCOORD",At="TEXCOORD0",Mt="TEXCOORD1",Ct="TEXCOORD2",Et="TEXCOORD3",Pt="TEXCOORD4",Rt="TEXCOORD5",It="TEXCOORD6",Lt="TEXCOORD7",Dt="ATTR",kt="ATTR0",Ot="ATTR1",Ft="ATTR2",Bt="ATTR3",Nt="ATTR4",Ut="ATTR5",zt="ATTR6",Vt="ATTR7",Gt="ATTR8",Wt="ATTR9",Ht="ATTR10",Xt="ATTR11",qt="ATTR12",jt="ATTR13",Yt="ATTR14",Kt="ATTR15",Zt="default",$t="rgbm",Qt="rgbe",Jt="rgbp",ei="swizzleGGGR",ti="2d",ii="float",ni="unfilterable-float",si="none",ri="cube",ai="equirect",oi="octahedral",hi=["bool","int","float","vec2","vec3","vec4","ivec2","ivec3","ivec4","bec2","bec3","bec4","mat2","mat3","mat4","sampler2D","samplerCube","","sampler2DShadow","samplerCubeShadow","sampler3D","","",""],li="webgl",ci="webgpu",ui="default",di=["view","mesh"],fi=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array],pi=[1,1,2,2,4,4,4],mi={Int8Array:0,Uint8Array:1,Int16Array:2,Uint16Array:3,Int32Array:4,Uint32Array:5,Float32Array:6},_i=[Uint8Array,Uint16Array,Uint32Array],gi=[1,2,4],vi={POSITION:0,NORMAL:1,BLENDWEIGHT:2,BLENDINDICES:3,COLOR:4,TEXCOORD0:5,TEXCOORD1:6,TEXCOORD2:7,TEXCOORD3:8,TEXCOORD4:9,TEXCOORD5:10,TEXCOORD6:11,TEXCOORD7:12,TANGENT:13,ATTR0:0,ATTR1:1,ATTR2:2,ATTR3:3,ATTR4:4,ATTR5:5,ATTR6:6,ATTR7:7,ATTR8:8,ATTR9:9,ATTR10:10,ATTR11:11,ATTR12:12,ATTR13:13,ATTR14:14,ATTR15:15},yi="1.55",xi="1.57",bi=0,Si=function(){function e(e,t,i,n,s){void 0===n&&(n=0),this.device=e,this.format=t,this.numVertices=i,this.usage=n,this.id=bi++,this.impl=e.createVertexBufferImpl(this,t),this.instancing=!1,this.numBytes=t.verticesByteSize?t.verticesByteSize:t.size*i,this.adjustVramSizeTracking(e._vram,this.numBytes),s?this.setData(s):this.storage=new ArrayBuffer(this.numBytes),this.device.buffers.push(this)}var t=e.prototype;return t.destroy=function(){var e=this.device,t=e.buffers.indexOf(this);-1!==t&&e.buffers.splice(t,1),this.impl.initialized&&(this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this.storage.byteLength))},t.adjustVramSizeTracking=function(e,t){e.vb+=t},t.loseContext=function(){this.impl.loseContext()},t.getFormat=function(){return this.format},t.getUsage=function(){return this.usage},t.getNumVertices=function(){return this.numVertices},t.lock=function(){return this.storage},t.unlock=function(){this.impl.unlock(this)},t.setData=function(e){return e.byteLength===this.numBytes&&(this.storage=e,this.unlock(),!0)},e}();function wi(e){for(var t=0,i=0,n=e.length;i<=|&+-]/g,Ni=function(){function e(){}return e.run=function(e){return e=(e=e.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm,"$1")).split(/\r?\n/).map((function(e){return e.trimEnd()})).join("\n"),null!==(e=this._preprocess(e))&&(e=(e=e.split(/\r?\n/).map((function(e){return""===e.trim()?"":e})).join("\n")).replace(/(\n\n){3,}/gm,"\n\n")),e},e._preprocess=function(t){for(var i,n=t,s=[],r=!1,a=new Map;null!==(i=Pi.exec(t));){var o=i[1];switch(o){case"define":Ri.lastIndex=i.index;var h=Ri.exec(t);r||(r=null===h);var l=h[1];Oi.lastIndex=h.index;var c=Oi.exec(l)[1],u=l.substring(c.length).trim();""===u&&(u="true"),e._keep(s)&&a.set(c,u),Pi.lastIndex=h.index+h[0].length;break;case"undef":Li.lastIndex=i.index;var d=Li.exec(t),f=d[1].trim();e._keep(s)&&a.delete(f),Pi.lastIndex=d.index+d[0].length;break;case"extension":Ii.lastIndex=i.index;var p=Ii.exec(t);if(r||(r=null===p),p){var m=p[1];e._keep(s)&&a.set(m,"true")}Pi.lastIndex=p.index+p[0].length;break;case"ifdef":case"ifndef":case"if":Di.lastIndex=i.index;var _=Di.exec(t),g=_[2],v=e.evaluate(g,a);r||(r=v.error);var y=v.result;"ifndef"===o&&(y=!y),s.push({anyKeep:y,keep:y,start:i.index,end:Di.lastIndex}),Pi.lastIndex=_.index+_[0].length;break;case"endif":case"else":case"elif":ki.lastIndex=i.index;var x=ki.exec(t),b=s.pop(),S=b.keep?t.substring(b.end,i.index):"";t=t.substring(0,b.start)+S+t.substring(ki.lastIndex),Pi.lastIndex=b.start+S.length;var w=x[1];if("else"===w||"elif"===w){var T=!1;if(!b.anyKeep)if("else"===w)T=!b.keep;else{var A=e.evaluate(x[2],a);T=A.result,r||(r=A.error)}s.push({anyKeep:b.anyKeep||T,keep:T,start:Pi.lastIndex,end:Pi.lastIndex})}}}return r?(console.warn("Failed to preprocess shader: ",{source:n}),n):t},e._keep=function(e){for(var t=0;t shadowZ ? 1.0 : 0.0;\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\n float getShadowOmniClusteredPCF3(sampler2D shadowMap, vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 dir) {\n\n float shadowTextureResolution = shadowParams.x;\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);\n\n // pcf3\n float shadowZ = length(dir) * shadowParams.w + shadowParams.z;\n dShadowCoord = vec3(uv, shadowZ);\n return getShadowPCF3x3(shadowMap, shadowParams.xyz);\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\n // we don't have PCF5 implementation for webgl1, use PCF3\n float getShadowOmniClusteredPCF5(sampler2D shadowMap, vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 dir) {\n\n float shadowTextureResolution = shadowParams.x;\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);\n\n // pcf3\n float shadowZ = length(dir) * shadowParams.w + shadowParams.z;\n dShadowCoord = vec3(uv, shadowZ);\n return getShadowPCF3x3(shadowMap, shadowParams.xyz);\n }\n\n #endif\n\n#endif\n\n\n// Clustered Spot Sampling using atlas\n\n#ifdef GL2\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\n float getShadowSpotClusteredPCF1(sampler2DShadow shadowMap, vec4 shadowParams) {\n return texture(shadowMap, dShadowCoord);\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\n float getShadowSpotClusteredPCF3(sampler2DShadow shadowMap, vec4 shadowParams) {\n return getShadowSpotPCF3x3(shadowMap, shadowParams);\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\n float getShadowSpotClusteredPCF5(sampler2DShadow shadowMap, vec4 shadowParams) {\n return getShadowPCF5x5(shadowMap, shadowParams.xyz);\n }\n #endif\n\n#else\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\n float getShadowSpotClusteredPCF1(sampler2D shadowMap, vec4 shadowParams) {\n\n float depth = unpackFloat(texture2D(shadowMap, dShadowCoord.xy));\n\n return depth > dShadowCoord.z ? 1.0 : 0.0;\n\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\n float getShadowSpotClusteredPCF3(sampler2D shadowMap, vec4 shadowParams) {\n return getShadowSpotPCF3x3(shadowMap, shadowParams);\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\n // we don't have PCF5 implementation for webgl1, use PCF3\n float getShadowSpotClusteredPCF5(sampler2D shadowMap, vec4 shadowParams) {\n return getShadowSpotPCF3x3(shadowMap, shadowParams);\n }\n\n #endif\n\n#endif\n",clusteredLightUtilsPS:"\n// Converts unnormalized direction vector to a cubemap face index [0..5] and uv coordinates within the face in [0..1] range.\n// Additionally offset to a tile in atlas within 3x3 subdivision is provided\nvec2 getCubemapFaceCoordinates(const vec3 dir, out float faceIndex, out vec2 tileOffset)\n{\n vec3 vAbs = abs(dir);\n float ma;\n vec2 uv;\n if (vAbs.z >= vAbs.x && vAbs.z >= vAbs.y) { // front / back\n\n faceIndex = dir.z < 0.0 ? 5.0 : 4.0;\n ma = 0.5 / vAbs.z;\n uv = vec2(dir.z < 0.0 ? -dir.x : dir.x, -dir.y);\n\n tileOffset.x = 2.0;\n tileOffset.y = dir.z < 0.0 ? 1.0 : 0.0;\n\n } else if(vAbs.y >= vAbs.x) { // top index 2, bottom index 3\n\n faceIndex = dir.y < 0.0 ? 3.0 : 2.0;\n ma = 0.5 / vAbs.y;\n uv = vec2(dir.x, dir.y < 0.0 ? -dir.z : dir.z);\n\n tileOffset.x = 1.0;\n tileOffset.y = dir.y < 0.0 ? 1.0 : 0.0;\n\n } else { // left / right\n\n faceIndex = dir.x < 0.0 ? 1.0 : 0.0;\n ma = 0.5 / vAbs.x;\n uv = vec2(dir.x < 0.0 ? dir.z : -dir.z, -dir.y);\n\n tileOffset.x = 0.0;\n tileOffset.y = dir.x < 0.0 ? 1.0 : 0.0;\n\n }\n return uv * ma + 0.5;\n}\n\n// converts unnormalized direction vector to a texture coordinate for a cubemap face stored within texture atlas described by the viewport\nvec2 getCubemapAtlasCoordinates(const vec3 omniAtlasViewport, float shadowEdgePixels, float shadowTextureResolution, const vec3 dir) {\n\n float faceIndex;\n vec2 tileOffset;\n vec2 uv = getCubemapFaceCoordinates(dir, faceIndex, tileOffset);\n\n // move uv coordinates inwards inside to compensate for larger fov when rendering shadow into atlas\n float atlasFaceSize = omniAtlasViewport.z;\n float tileSize = shadowTextureResolution * atlasFaceSize;\n float offset = shadowEdgePixels / tileSize;\n uv = uv * vec2(1.0 - offset * 2.0) + vec2(offset * 1.0);\n\n // scale uv coordinates to cube face area within the viewport\n uv *= atlasFaceSize;\n\n // offset into face of the atlas (3x3 grid)\n uv += tileOffset * atlasFaceSize;\n\n // offset into the atlas viewport\n uv += omniAtlasViewport.xy;\n\n return uv;\n}\n",clusteredLightPS:"\nuniform sampler2D clusterWorldTexture;\nuniform sampler2D lightsTexture8;\nuniform highp sampler2D lightsTextureFloat;\n\n// complex ifdef expression are not supported, handle it here\n// defined(CLUSTER_COOKIES) || defined(CLUSTER_SHADOWS)\n#if defined(CLUSTER_COOKIES)\n #define CLUSTER_COOKIES_OR_SHADOWS\n#endif\n#if defined(CLUSTER_SHADOWS)\n #define CLUSTER_COOKIES_OR_SHADOWS\n#endif\n\n#ifdef CLUSTER_SHADOWS\n #ifdef GL2\n // TODO: when VSM shadow is supported, it needs to use sampler2D in webgl2\n uniform sampler2DShadow shadowAtlasTexture;\n #else\n uniform sampler2D shadowAtlasTexture;\n #endif\n#endif\n\n#ifdef CLUSTER_COOKIES\n uniform sampler2D cookieAtlasTexture;\n#endif\n\nuniform float clusterPixelsPerCell;\nuniform vec3 clusterCellsCountByBoundsSize;\nuniform vec4 lightsTextureInvSize;\nuniform vec3 clusterTextureSize;\nuniform vec3 clusterBoundsMin;\nuniform vec3 clusterBoundsDelta;\nuniform vec3 clusterCellsDot;\nuniform vec3 clusterCellsMax;\nuniform vec2 clusterCompressionLimit0;\nuniform vec2 shadowAtlasParams;\n\n// structure storing light properties of a clustered light\nstruct ClusterLightData {\n\n // v coordinate to look up the light textures\n float lightV;\n\n // type of the light (spot or omni)\n float type;\n\n // area light shape\n float shape;\n\n // area light sizes / orientation\n vec3 halfWidth;\n vec3 halfHeight;\n\n // light follow mode\n float falloffMode;\n\n // 0.0 if the light doesn't cast shadows\n float shadowIntensity;\n\n // shadow bias values\n float shadowBias;\n float shadowNormalBias;\n\n // world space position\n vec3 position;\n\n // world space direction (spot light only)\n vec3 direction;\n\n // range of the light\n float range;\n\n // spot light inner and outer angle cosine\n float innerConeAngleCos;\n float outerConeAngleCos;\n\n // color\n vec3 color;\n\n // atlas viewport for omni light shadow and cookie (.xy is offset to the viewport slot, .z is size of the face in the atlas)\n vec3 omniAtlasViewport;\n\n // 1.0 if the light has a cookie texture\n float cookie;\n\n // 1.0 if cookie texture is rgb, otherwise it is using a single channel selectable by cookieChannelMask\n float cookieRgb;\n\n // intensity of the cookie\n float cookieIntensity;\n\n // channel mask - one of the channels has 1, the others are 0\n vec4 cookieChannelMask;\n\n // light mask\n float mask;\n};\n\n// Note: on some devices (tested on Pixel 3A XL), this matrix when stored inside the light struct has lower precision compared to\n// when stored outside, so we store it outside to avoid spot shadow flickering. This might need to be done to other / all members\n// of the structure if further similar issues are observed.\n\n// shadow (spot light only) / cookie projection matrix\nmat4 lightProjectionMatrix;\n\n// macros for light properties\n#define isClusteredLightCastShadow(light) ( light.shadowIntensity > 0.0 )\n#define isClusteredLightCookie(light) (light.cookie > 0.5 )\n#define isClusteredLightCookieRgb(light) (light.cookieRgb > 0.5 )\n#define isClusteredLightSpot(light) ( light.type > 0.5 )\n#define isClusteredLightFalloffLinear(light) ( light.falloffMode < 0.5 )\n\n// macros to test light shape\n// Note: Following functions need to be called serially in listed order as they do not test both '>' and '<'\n#define isClusteredLightArea(light) ( light.shape > 0.1 )\n#define isClusteredLightRect(light) ( light.shape < 0.3 )\n#define isClusteredLightDisk(light) ( light.shape < 0.6 )\n\n// macro to test light mask (mesh accepts dynamic vs lightmapped lights)\n#ifdef CLUSTER_MESH_DYNAMIC_LIGHTS\n // accept lights marked as dynamic or both dynamic and lightmapped\n #define acceptLightMask(light) ( light.mask < 0.75)\n#else\n // accept lights marked as lightmapped or both dynamic and lightmapped\n #define acceptLightMask(light) ( light.mask > 0.25)\n#endif\n\nvec4 decodeClusterLowRange4Vec4(vec4 d0, vec4 d1, vec4 d2, vec4 d3) {\n return vec4(\n bytes2floatRange4(d0, -2.0, 2.0),\n bytes2floatRange4(d1, -2.0, 2.0),\n bytes2floatRange4(d2, -2.0, 2.0),\n bytes2floatRange4(d3, -2.0, 2.0)\n );\n}\n\n// use LOD sampling if supported to sample data textures as it has better chance of getting skipped inside dynamic branches\n#ifdef SUPPORTS_TEXLOD\n #define textureData(texture, uv) texture2DLodEXT(texture, uv, 0.0)\n#else\n #define textureData(texture, uv) texture2D(texture, uv)\n#endif\n\nvec4 sampleLightsTexture8(const ClusterLightData clusterLightData, float index) {\n return textureData(lightsTexture8, vec2(index * lightsTextureInvSize.z, clusterLightData.lightV));\n}\n\nvec4 sampleLightTextureF(const ClusterLightData clusterLightData, float index) {\n return textureData(lightsTextureFloat, vec2(index * lightsTextureInvSize.x, clusterLightData.lightV));\n}\n\nvoid decodeClusterLightCore(inout ClusterLightData clusterLightData, float lightIndex) {\n\n // read omni light properties\n clusterLightData.lightV = (lightIndex + 0.5) * lightsTextureInvSize.w;\n\n // shared data from 8bit texture\n vec4 lightInfo = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_FLAGS);\n clusterLightData.type = lightInfo.x;\n clusterLightData.shape = lightInfo.y;\n clusterLightData.falloffMode = lightInfo.z;\n clusterLightData.shadowIntensity = lightInfo.w;\n\n // color\n vec4 colorA = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COLOR_A);\n vec4 colorB = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COLOR_B);\n clusterLightData.color = vec3(bytes2float2(colorA.xy), bytes2float2(colorA.zw), bytes2float2(colorB.xy)) * clusterCompressionLimit0.y;\n\n // cookie\n clusterLightData.cookie = colorB.z;\n\n // light mask\n clusterLightData.mask = colorB.w;\n\n #ifdef CLUSTER_TEXTURE_FLOAT\n\n vec4 lightPosRange = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_POSITION_RANGE);\n clusterLightData.position = lightPosRange.xyz;\n clusterLightData.range = lightPosRange.w;\n\n // spot light direction\n vec4 lightDir_Unused = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_SPOT_DIRECTION);\n clusterLightData.direction = lightDir_Unused.xyz;\n\n #else // 8bit\n\n vec4 encPosX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_POSITION_X);\n vec4 encPosY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_POSITION_Y);\n vec4 encPosZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_POSITION_Z);\n clusterLightData.position = vec3(bytes2float4(encPosX), bytes2float4(encPosY), bytes2float4(encPosZ)) * clusterBoundsDelta + clusterBoundsMin;\n\n vec4 encRange = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_RANGE);\n clusterLightData.range = bytes2float4(encRange) * clusterCompressionLimit0.x;\n\n // spot light direction\n vec4 encDirX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_DIRECTION_X);\n vec4 encDirY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_DIRECTION_Y);\n vec4 encDirZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_DIRECTION_Z);\n clusterLightData.direction = vec3(bytes2float4(encDirX), bytes2float4(encDirY), bytes2float4(encDirZ)) * 2.0 - 1.0;\n\n #endif\n}\n\nvoid decodeClusterLightSpot(inout ClusterLightData clusterLightData) {\n\n // spot light cos angles\n vec4 coneAngle = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_ANGLES);\n clusterLightData.innerConeAngleCos = bytes2float2(coneAngle.xy) * 2.0 - 1.0;\n clusterLightData.outerConeAngleCos = bytes2float2(coneAngle.zw) * 2.0 - 1.0;\n}\n\nvoid decodeClusterLightOmniAtlasViewport(inout ClusterLightData clusterLightData) {\n #ifdef CLUSTER_TEXTURE_FLOAT\n clusterLightData.omniAtlasViewport = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_0).xyz;\n #else\n vec4 viewportA = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_ATLAS_VIEWPORT_A);\n vec4 viewportB = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_ATLAS_VIEWPORT_B);\n clusterLightData.omniAtlasViewport = vec3(bytes2float2(viewportA.xy), bytes2float2(viewportA.zw), bytes2float2(viewportB.xy));\n #endif\n}\n\nvoid decodeClusterLightAreaData(inout ClusterLightData clusterLightData) {\n #ifdef CLUSTER_TEXTURE_FLOAT\n clusterLightData.halfWidth = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_AREA_DATA_WIDTH).xyz;\n clusterLightData.halfHeight = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_AREA_DATA_HEIGHT).xyz;\n #else\n vec4 areaWidthX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_WIDTH_X);\n vec4 areaWidthY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_WIDTH_Y);\n vec4 areaWidthZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_WIDTH_Z);\n clusterLightData.halfWidth = vec3(mantissaExponent2Float(areaWidthX), mantissaExponent2Float(areaWidthY), mantissaExponent2Float(areaWidthZ));\n\n vec4 areaHeightX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_HEIGHT_X);\n vec4 areaHeightY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_HEIGHT_Y);\n vec4 areaHeightZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_HEIGHT_Z);\n clusterLightData.halfHeight = vec3(mantissaExponent2Float(areaHeightX), mantissaExponent2Float(areaHeightY), mantissaExponent2Float(areaHeightZ));\n #endif\n}\n\nvoid decodeClusterLightProjectionMatrixData(inout ClusterLightData clusterLightData) {\n \n // shadow matrix\n #ifdef CLUSTER_TEXTURE_FLOAT\n vec4 m0 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_0);\n vec4 m1 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_1);\n vec4 m2 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_2);\n vec4 m3 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_3);\n #else\n vec4 m00 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_00);\n vec4 m01 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_01);\n vec4 m02 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_02);\n vec4 m03 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_03);\n vec4 m0 = decodeClusterLowRange4Vec4(m00, m01, m02, m03);\n\n vec4 m10 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_10);\n vec4 m11 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_11);\n vec4 m12 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_12);\n vec4 m13 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_13);\n vec4 m1 = decodeClusterLowRange4Vec4(m10, m11, m12, m13);\n\n vec4 m20 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_20);\n vec4 m21 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_21);\n vec4 m22 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_22);\n vec4 m23 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_23);\n vec4 m2 = decodeClusterLowRange4Vec4(m20, m21, m22, m23);\n\n vec4 m30 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_30);\n vec4 m31 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_31);\n vec4 m32 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_32);\n vec4 m33 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_33);\n vec4 m3 = vec4(mantissaExponent2Float(m30), mantissaExponent2Float(m31), mantissaExponent2Float(m32), mantissaExponent2Float(m33));\n #endif\n \n lightProjectionMatrix = mat4(m0, m1, m2, m3);\n}\n\nvoid decodeClusterLightShadowData(inout ClusterLightData clusterLightData) {\n \n // shadow biases\n vec4 biases = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SHADOW_BIAS);\n clusterLightData.shadowBias = bytes2floatRange2(biases.xy, -1.0, 20.0),\n clusterLightData.shadowNormalBias = bytes2float2(biases.zw);\n}\n\nvoid decodeClusterLightCookieData(inout ClusterLightData clusterLightData) {\n\n vec4 cookieA = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COOKIE_A);\n clusterLightData.cookieIntensity = cookieA.x;\n clusterLightData.cookieRgb = cookieA.y;\n\n clusterLightData.cookieChannelMask = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COOKIE_B);\n}\n\nvoid evaluateLight(ClusterLightData light) {\n\n dAtten3 = vec3(1.0);\n\n // evaluate omni part of the light\n getLightDirPoint(light.position);\n\n #ifdef CLUSTER_AREALIGHTS\n\n // distance attenuation\n if (isClusteredLightArea(light)) { // area light\n\n // area lights\n decodeClusterLightAreaData(light);\n\n // handle light shape\n if (isClusteredLightRect(light)) {\n calcRectLightValues(light.position, light.halfWidth, light.halfHeight);\n } else if (isClusteredLightDisk(light)) {\n calcDiskLightValues(light.position, light.halfWidth, light.halfHeight);\n } else { // sphere\n calcSphereLightValues(light.position, light.halfWidth, light.halfHeight);\n }\n\n dAtten = getFalloffWindow(light.range);\n\n } else\n\n #endif\n\n { // punctual light\n\n if (isClusteredLightFalloffLinear(light))\n dAtten = getFalloffLinear(light.range);\n else\n dAtten = getFalloffInvSquared(light.range);\n }\n\n if (dAtten > 0.00001) {\n\n #ifdef CLUSTER_AREALIGHTS\n\n if (isClusteredLightArea(light)) { // area light\n\n // handle light shape\n if (isClusteredLightRect(light)) {\n dAttenD = getRectLightDiffuse() * 16.0;\n } else if (isClusteredLightDisk(light)) {\n dAttenD = getDiskLightDiffuse() * 16.0;\n } else { // sphere\n dAttenD = getSphereLightDiffuse() * 16.0;\n }\n\n } else\n\n #endif\n\n {\n dAtten *= getLightDiffuse();\n }\n\n // spot light falloff\n if (isClusteredLightSpot(light)) {\n decodeClusterLightSpot(light);\n dAtten *= getSpotEffect(light.direction, light.innerConeAngleCos, light.outerConeAngleCos);\n }\n\n #if defined(CLUSTER_COOKIES_OR_SHADOWS)\n\n if (dAtten > 0.00001) {\n\n // shadow / cookie\n if (isClusteredLightCastShadow(light) || isClusteredLightCookie(light)) {\n\n // shared shadow / cookie data depends on light type\n if (isClusteredLightSpot(light)) {\n decodeClusterLightProjectionMatrixData(light);\n } else {\n decodeClusterLightOmniAtlasViewport(light);\n }\n\n float shadowTextureResolution = shadowAtlasParams.x;\n float shadowEdgePixels = shadowAtlasParams.y;\n\n #ifdef CLUSTER_COOKIES\n\n // cookie\n if (isClusteredLightCookie(light)) {\n decodeClusterLightCookieData(light);\n\n if (isClusteredLightSpot(light)) {\n dAtten3 = getCookie2DClustered(cookieAtlasTexture, lightProjectionMatrix, vPositionW, light.cookieIntensity, isClusteredLightCookieRgb(light), light.cookieChannelMask);\n } else {\n dAtten3 = getCookieCubeClustered(cookieAtlasTexture, dLightDirW, light.cookieIntensity, isClusteredLightCookieRgb(light), light.cookieChannelMask, shadowTextureResolution, shadowEdgePixels, light.omniAtlasViewport);\n }\n }\n\n #endif\n\n #ifdef CLUSTER_SHADOWS\n\n // shadow\n if (isClusteredLightCastShadow(light)) {\n decodeClusterLightShadowData(light);\n\n vec4 shadowParams = vec4(shadowTextureResolution, light.shadowNormalBias, light.shadowBias, 1.0 / light.range);\n\n if (isClusteredLightSpot(light)) {\n\n // spot shadow\n getShadowCoordPerspZbufferNormalOffset(lightProjectionMatrix, shadowParams);\n \n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n float shadow = getShadowSpotClusteredPCF1(shadowAtlasTexture, shadowParams);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF3)\n float shadow = getShadowSpotClusteredPCF3(shadowAtlasTexture, shadowParams);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF5)\n float shadow = getShadowSpotClusteredPCF5(shadowAtlasTexture, shadowParams);\n #endif\n dAtten *= mix(1.0, shadow, light.shadowIntensity);\n\n } else {\n\n // omni shadow\n normalOffsetPointShadow(shadowParams); // normalBias adjusted for distance\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n float shadow = getShadowOmniClusteredPCF1(shadowAtlasTexture, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dLightDirW);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF3)\n float shadow = getShadowOmniClusteredPCF3(shadowAtlasTexture, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dLightDirW);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF5)\n float shadow = getShadowOmniClusteredPCF5(shadowAtlasTexture, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dLightDirW);\n #endif\n dAtten *= mix(1.0, shadow, light.shadowIntensity);\n }\n }\n\n #endif\n }\n }\n\n #endif\n\n // diffuse / specular / clearcoat\n #ifdef CLUSTER_AREALIGHTS\n\n if (isClusteredLightArea(light)) { // area light\n\n // area light diffuse\n {\n vec3 areaDiffuse = (dAttenD * dAtten) * light.color * dAtten3;\n\n #if defined(LIT_SPECULAR)\n #if defined(LIT_CONSERVE_ENERGY)\n areaDiffuse = mix(areaDiffuse, vec3(0), dLTCSpecFres);\n #endif\n #endif\n\n // area light diffuse - it does not mix diffuse lighting into specular attenuation\n dDiffuseLight += areaDiffuse;\n }\n\n // specular and clear coat are material settings and get included by a define based on the material\n #ifdef LIT_SPECULAR\n\n // area light specular\n float areaLightSpecular;\n\n if (isClusteredLightRect(light)) {\n areaLightSpecular = getRectLightSpecular();\n } else if (isClusteredLightDisk(light)) {\n areaLightSpecular = getDiskLightSpecular();\n } else { // sphere\n areaLightSpecular = getSphereLightSpecular();\n }\n\n dSpecularLight += dLTCSpecFres * areaLightSpecular * dAtten * light.color * dAtten3;\n\n #ifdef LIT_CLEARCOAT\n\n // area light specular clear coat\n float areaLightSpecularCC;\n\n if (isClusteredLightRect(light)) {\n areaLightSpecularCC = getRectLightSpecularCC();\n } else if (isClusteredLightDisk(light)) {\n areaLightSpecularCC = getDiskLightSpecularCC();\n } else { // sphere\n areaLightSpecularCC = getSphereLightSpecularCC();\n }\n\n ccSpecularLight += ccLTCSpecFres * areaLightSpecularCC * dAtten * light.color * dAtten3;\n\n #endif\n\n #endif\n\n } else\n\n #endif\n\n { // punctual light\n\n // punctual light diffuse\n {\n vec3 punctualDiffuse = dAtten * light.color * dAtten3;\n\n #if defined(CLUSTER_AREALIGHTS)\n #if defined(LIT_SPECULAR)\n #if defined(LIT_CONSERVE_ENERGY)\n punctualDiffuse = mix(punctualDiffuse, vec3(0), dSpecularity);\n #endif\n #endif\n #endif\n\n dDiffuseLight += punctualDiffuse;\n }\n \n // specular and clear coat are material settings and get included by a define based on the material\n #ifdef LIT_SPECULAR\n\n vec3 halfDir = normalize(-dLightDirNormW + dViewDirW);\n \n // specular\n #ifdef LIT_SPECULAR_FRESNEL\n dSpecularLight += getLightSpecular(halfDir) * dAtten * light.color * dAtten3 * getFresnel(dot(dViewDirW, halfDir), dSpecularity);\n #else\n dSpecularLight += getLightSpecular(halfDir) * dAtten * light.color * dAtten3 * dSpecularity;\n #endif\n\n #ifdef LIT_CLEARCOAT\n #ifdef LIT_SPECULAR_FRESNEL\n ccSpecularLight += getLightSpecularCC(halfDir) * dAtten * light.color * dAtten3 * getFresnelCC(dot(dViewDirW, halfDir));\n #else\n ccSpecularLight += getLightSpecularCC(halfDir) * dAtten * light.color * dAtten3;\n #endif\n #endif\n\n #ifdef LIT_SHEEN\n sSpecularLight += getLightSpecularSheen(halfDir) * dAtten * light.color * dAtten3;\n #endif\n\n #endif\n }\n }\n}\n\nvoid evaluateClusterLight(float lightIndex) {\n\n // decode core light data from textures\n ClusterLightData clusterLightData;\n decodeClusterLightCore(clusterLightData, lightIndex);\n\n // evaluate light if it uses accepted light mask\n if (acceptLightMask(clusterLightData))\n evaluateLight(clusterLightData);\n}\n\nvoid addClusteredLights() {\n // world space position to 3d integer cell cordinates in the cluster structure\n vec3 cellCoords = floor((vPositionW - clusterBoundsMin) * clusterCellsCountByBoundsSize);\n\n // no lighting when cell coordinate is out of range\n if (!(any(lessThan(cellCoords, vec3(0.0))) || any(greaterThanEqual(cellCoords, clusterCellsMax)))) {\n\n // cell index (mapping from 3d cell coordinates to linear memory)\n float cellIndex = dot(clusterCellsDot, cellCoords);\n\n // convert cell index to uv coordinates\n float clusterV = floor(cellIndex * clusterTextureSize.y);\n float clusterU = cellIndex - (clusterV * clusterTextureSize.x);\n clusterV = (clusterV + 0.5) * clusterTextureSize.z;\n\n // loop over maximum possible number of supported light cells\n const float maxLightCells = 256.0 / 4.0; // 8 bit index, each stores 4 lights\n for (float lightCellIndex = 0.5; lightCellIndex < maxLightCells; lightCellIndex++) {\n\n vec4 lightIndices = textureData(clusterWorldTexture, vec2(clusterTextureSize.y * (clusterU + lightCellIndex), clusterV));\n vec4 indices = lightIndices * 255.0;\n\n // evaluate up to 4 lights. This is written using a loop instead of manually unrolling to keep shader compile time smaller\n for (int i = 0; i < 4; i++) {\n \n if (indices.x <= 0.0)\n return;\n\n evaluateClusterLight(indices.x); \n indices = indices.yzwx;\n }\n\n // end of the cell array\n if (lightCellIndex > clusterPixelsPerCell) {\n break;\n }\n }\n }\n}\n",combinePS:"\nvec3 combineColor() {\n vec3 ret = vec3(0);\n#ifdef LIT_OLD_AMBIENT\n ret += (dDiffuseLight - light_globalAmbient) * dAlbedo + material_ambient * light_globalAmbient;\n#else\n ret += dAlbedo * dDiffuseLight;\n#endif\n#ifdef LIT_SPECULAR\n ret += dSpecularLight;\n#endif\n#ifdef LIT_REFLECTIONS\n ret += dReflection.rgb * dReflection.a;\n#endif\n\n#ifdef LIT_SHEEN\n float sheenScaling = 1.0 - max(max(sSpecularity.r, sSpecularity.g), sSpecularity.b) * 0.157;\n ret = ret * sheenScaling + (sSpecularLight + sReflection.rgb) * sSpecularity;\n#endif\n#ifdef LIT_CLEARCOAT\n float clearCoatScaling = 1.0 - ccFresnel * ccSpecularity;\n ret = ret * clearCoatScaling + (ccSpecularLight + ccReflection.rgb) * ccSpecularity;\n#endif\n\n return ret;\n}\n",cookiePS:"\n// light cookie functionality for non-clustered lights\nvec4 getCookie2D(sampler2D tex, mat4 transform, float intensity) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n return mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);\n}\n\nvec4 getCookie2DClip(sampler2D tex, mat4 transform, float intensity) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n if (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0);\n return mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);\n}\n\nvec4 getCookie2DXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n projPos.xy += cookieOffset;\n vec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);\n return mix(vec4(1.0), texture2D(tex, uv), intensity);\n}\n\nvec4 getCookie2DClipXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n projPos.xy += cookieOffset;\n if (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0);\n vec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);\n return mix(vec4(1.0), texture2D(tex, uv), intensity);\n}\n\nvec4 getCookieCube(samplerCube tex, mat4 transform, float intensity) {\n return mix(vec4(1.0), textureCube(tex, dLightDirNormW * mat3(transform)), intensity);\n}\n",cubeMapProjectBoxPS:"\nuniform vec3 envBoxMin, envBoxMax;\n\nvec3 cubeMapProject(vec3 nrdir) {\n nrdir = cubeMapRotate(nrdir);\n\n vec3 rbmax = (envBoxMax - vPositionW) / nrdir;\n vec3 rbmin = (envBoxMin - vPositionW) / nrdir;\n\n vec3 rbminmax;\n rbminmax.x = nrdir.x>0.0? rbmax.x : rbmin.x;\n rbminmax.y = nrdir.y>0.0? rbmax.y : rbmin.y;\n rbminmax.z = nrdir.z>0.0? rbmax.z : rbmin.z;\n\n float fa = min(min(rbminmax.x, rbminmax.y), rbminmax.z);\n\n vec3 posonbox = vPositionW + nrdir * fa;\n vec3 envBoxPos = (envBoxMin + envBoxMax) * 0.5;\n return normalize(posonbox - envBoxPos);\n}\n",cubeMapProjectNonePS:"\nvec3 cubeMapProject(vec3 dir) {\n return cubeMapRotate(dir);\n}\n",cubeMapRotatePS:"\n#ifdef CUBEMAP_ROTATION\nuniform mat3 cubeMapRotationMatrix;\n#endif\n\nvec3 cubeMapRotate(vec3 refDir) {\n#ifdef CUBEMAP_ROTATION\n return refDir * cubeMapRotationMatrix;\n#else\n return refDir;\n#endif\n}\n",detailModesPS:"\nvec3 detailMode_mul(vec3 c1, vec3 c2) {\n return c1 * c2;\n}\n\nvec3 detailMode_add(vec3 c1, vec3 c2) {\n return c1 + c2;\n}\n\n// https://en.wikipedia.org/wiki/Blend_modes#Screen\nvec3 detailMode_screen(vec3 c1, vec3 c2) {\n return 1.0 - (1.0 - c1)*(1.0 - c2);\n}\n\n// https://en.wikipedia.org/wiki/Blend_modes#Overlay\nvec3 detailMode_overlay(vec3 c1, vec3 c2) {\n return mix(1.0 - 2.0*(1.0 - c1)*(1.0 - c2), 2.0*c1*c2, step(c1, vec3(0.5)));\n}\n\nvec3 detailMode_min(vec3 c1, vec3 c2) {\n return min(c1, c2);\n}\n\nvec3 detailMode_max(vec3 c1, vec3 c2) {\n return max(c1, c2);\n}\n",diffusePS:"\n#ifdef MAPCOLOR\nuniform vec3 material_diffuse;\n#endif\n\nvoid getAlbedo() {\n dAlbedo = vec3(1.0);\n\n#ifdef MAPCOLOR\n dAlbedo *= material_diffuse.rgb;\n#endif\n\n#ifdef MAPTEXTURE\n vec3 albedoBase = $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n dAlbedo *= addAlbedoDetail(albedoBase);\n#endif\n\n#ifdef MAPVERTEX\n dAlbedo *= gammaCorrectInput(saturate(vVertexColor.$VC));\n#endif\n}\n",diffuseDetailMapPS:"\nvec3 addAlbedoDetail(vec3 albedo) {\n#ifdef MAPTEXTURE\n vec3 albedoDetail = $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n return detailMode_$DETAILMODE(albedo, albedoDetail);\n#else\n return albedo;\n#endif\n}\n",decodePS:Vi,emissivePS:"\n#ifdef MAPCOLOR\nuniform vec3 material_emissive;\n#endif\n\n#ifdef MAPFLOAT\nuniform float material_emissiveIntensity;\n#endif\n\nvoid getEmission() {\n dEmission = vec3(1.0);\n\n #ifdef MAPFLOAT\n dEmission *= material_emissiveIntensity;\n #endif\n\n #ifdef MAPCOLOR\n dEmission *= material_emissive;\n #endif\n\n #ifdef MAPTEXTURE\n dEmission *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n #endif\n\n #ifdef MAPVERTEX\n dEmission *= gammaCorrectInput(saturate(vVertexColor.$VC));\n #endif\n}\n",encodePS:Gi,endPS:"\n gl_FragColor.rgb = combineColor();\n\n gl_FragColor.rgb += dEmission;\n gl_FragColor.rgb = addFog(gl_FragColor.rgb);\n\n #ifndef HDR\n gl_FragColor.rgb = toneMap(gl_FragColor.rgb);\n gl_FragColor.rgb = gammaCorrectOutput(gl_FragColor.rgb);\n #endif\n",endVS:"\n",envAtlasPS:"\n// the envAtlas is fixed at 512 pixels. every equirect is generated with 1 pixel boundary.\nconst float atlasSize = 512.0;\nconst float seamSize = 1.0 / atlasSize;\n\n// map a normalized equirect UV to the given rectangle (taking 1 pixel seam into account).\nvec2 mapUv(vec2 uv, vec4 rect) {\n return vec2(mix(rect.x + seamSize, rect.x + rect.z - seamSize, uv.x),\n mix(rect.y + seamSize, rect.y + rect.w - seamSize, uv.y));\n}\n\n// map a normalized equirect UV and roughness level to the correct atlas rect.\nvec2 mapRoughnessUv(vec2 uv, float level) {\n float t = 1.0 / exp2(level);\n return mapUv(uv, vec4(0, 1.0 - t, t, t * 0.5));\n}\n\n// map shiny level UV\nvec2 mapShinyUv(vec2 uv, float level) {\n float t = 1.0 / exp2(level);\n return mapUv(uv, vec4(1.0 - t, 1.0 - t, t, t * 0.5));\n}\n",envConstPS:"\nvec3 processEnvironment(vec3 color) {\n return color;\n}\n",envMultiplyPS:"\nuniform float skyboxIntensity;\n\nvec3 processEnvironment(vec3 color) {\n return color * skyboxIntensity;\n}\n",extensionPS:"\n",extensionVS:"\n",falloffInvSquaredPS:"\nfloat getFalloffWindow(float lightRadius) {\n float sqrDist = dot(dLightDirW, dLightDirW);\n float invRadius = 1.0 / lightRadius;\n return square( saturate( 1.0 - square( sqrDist * square(invRadius) ) ) );\n}\n\nfloat getFalloffInvSquared(float lightRadius) {\n float sqrDist = dot(dLightDirW, dLightDirW);\n float falloff = 1.0 / (sqrDist + 1.0);\n float invRadius = 1.0 / lightRadius;\n\n falloff *= 16.0;\n falloff *= square( saturate( 1.0 - square( sqrDist * square(invRadius) ) ) );\n\n return falloff;\n}\n",falloffLinearPS:"\nfloat getFalloffLinear(float lightRadius) {\n float d = length(dLightDirW);\n return max(((lightRadius - d) / lightRadius), 0.0);\n}\n",fixCubemapSeamsNonePS:"\nvec3 fixSeams(vec3 vec, float mipmapIndex) {\n return vec;\n}\n\nvec3 fixSeams(vec3 vec) {\n return vec;\n}\n\nvec3 fixSeamsStatic(vec3 vec, float invRecMipSize) {\n return vec;\n}\n\nvec3 calcSeam(vec3 vec) {\n return vec3(0);\n}\n\nvec3 applySeam(vec3 vec, vec3 seam, float scale) {\n return vec;\n}\n",fixCubemapSeamsStretchPS:"\nvec3 fixSeams(vec3 vec, float mipmapIndex) {\n vec3 avec = abs(vec);\n float scale = 1.0 - exp2(mipmapIndex) / 128.0;\n float M = max(max(avec.x, avec.y), avec.z);\n if (avec.x != M) vec.x *= scale;\n if (avec.y != M) vec.y *= scale;\n if (avec.z != M) vec.z *= scale;\n return vec;\n}\n\nvec3 fixSeams(vec3 vec) {\n vec3 avec = abs(vec);\n float scale = 1.0 - 1.0 / 128.0;\n float M = max(max(avec.x, avec.y), avec.z);\n if (avec.x != M) vec.x *= scale;\n if (avec.y != M) vec.y *= scale;\n if (avec.z != M) vec.z *= scale;\n return vec;\n}\n\nvec3 fixSeamsStatic(vec3 vec, float invRecMipSize) {\n vec3 avec = abs(vec);\n float scale = invRecMipSize;\n float M = max(max(avec.x, avec.y), avec.z);\n if (avec.x != M) vec.x *= scale;\n if (avec.y != M) vec.y *= scale;\n if (avec.z != M) vec.z *= scale;\n return vec;\n}\n\nvec3 calcSeam(vec3 vec) {\n vec3 avec = abs(vec);\n float M = max(avec.x, max(avec.y, avec.z));\n return vec3(avec.x != M ? 1.0 : 0.0,\n avec.y != M ? 1.0 : 0.0,\n avec.z != M ? 1.0 : 0.0);\n}\n\nvec3 applySeam(vec3 vec, vec3 seam, float scale) {\n return vec * (seam * -scale + vec3(1.0));\n}\n",floatUnpackingPS:"\n// float unpacking functionality, complimentary to float-packing.js\nfloat bytes2float2(vec2 data) {\n return dot(data, vec2(1.0, 1.0 / 255.0));\n}\n\nfloat bytes2float3(vec3 data) {\n return dot(data, vec3(1.0, 1.0 / 255.0, 1.0 / 65025.0));\n}\n\nfloat bytes2float4(vec4 data) {\n return dot(data, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n}\n\nfloat bytes2floatRange2(vec2 data, float min, float max) {\n return mix(min, max, bytes2float2(data));\n}\n\nfloat bytes2floatRange3(vec3 data, float min, float max) {\n return mix(min, max, bytes2float3(data));\n}\n\nfloat bytes2floatRange4(vec4 data, float min, float max) {\n return mix(min, max, bytes2float4(data));\n}\n\nfloat mantissaExponent2Float(vec4 pack)\n{\n float value = bytes2floatRange3(pack.xyz, -1.0, 1.0);\n float exponent = floor(pack.w * 255.0 - 127.0);\n return value * exp2(exponent);\n}\n",fogExpPS:"\nuniform vec3 fog_color;\nuniform float fog_density;\nfloat dBlendModeFogFactor = 1.0;\n\nvec3 addFog(vec3 color) {\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n float fogFactor = exp(-depth * fog_density);\n fogFactor = clamp(fogFactor, 0.0, 1.0);\n return mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogExp2PS:"\nuniform vec3 fog_color;\nuniform float fog_density;\nfloat dBlendModeFogFactor = 1.0;\n\nvec3 addFog(vec3 color) {\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n float fogFactor = exp(-depth * depth * fog_density * fog_density);\n fogFactor = clamp(fogFactor, 0.0, 1.0);\n return mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogLinearPS:"\nuniform vec3 fog_color;\nuniform float fog_start;\nuniform float fog_end;\nfloat dBlendModeFogFactor = 1.0;\n\nvec3 addFog(vec3 color) {\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n float fogFactor = (fog_end - depth) / (fog_end - fog_start);\n fogFactor = clamp(fogFactor, 0.0, 1.0);\n return mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogNonePS:"\nfloat dBlendModeFogFactor = 1.0;\n\nvec3 addFog(vec3 color) {\n return color;\n}\n",fresnelSchlickPS:"\n// Schlick's approximation\nvec3 getFresnel(float cosTheta, vec3 f0) {\n float fresnel = pow(1.0 - max(cosTheta, 0.0), 5.0);\n float glossSq = dGlossiness * dGlossiness;\n vec3 ret = f0 + (max(vec3(glossSq), f0) - f0) * fresnel;\n #ifdef LIT_IRIDESCENCE\n return mix(ret, dIridescenceFresnel, vec3(dIridescence));\n #else\n return ret;\n #endif \n}\n\nfloat getFresnelCC(float cosTheta) {\n float fresnel = pow(1.0 - max(cosTheta, 0.0), 5.0);\n return 0.04 + (1.0 - 0.04) * fresnel;\n}\n",fullscreenQuadPS:"\nvarying vec2 vUv0;\n\nuniform sampler2D source;\n\nvoid main(void) {\n gl_FragColor = texture2D(source, vUv0);\n}\n",fullscreenQuadVS:"\nattribute vec2 vertex_position;\n\nvarying vec2 vUv0;\n\nvoid main(void)\n{\n gl_Position = vec4(vertex_position, 0.5, 1.0);\n vUv0 = vertex_position.xy*0.5+0.5;\n}\n",gamma1_0PS:"\nfloat gammaCorrectInput(float color) {\n return color;\n}\n\nvec3 gammaCorrectInput(vec3 color) {\n return color;\n}\n\nvec4 gammaCorrectInput(vec4 color) {\n return color;\n}\n\nvec3 gammaCorrectOutput(vec3 color) {\n return color;\n}\n",gamma2_2PS:"\nfloat gammaCorrectInput(float color) {\n return decodeGamma(color);\n}\n\nvec3 gammaCorrectInput(vec3 color) {\n return decodeGamma(color);\n}\n\nvec4 gammaCorrectInput(vec4 color) {\n return vec4(decodeGamma(color.xyz), color.w);\n}\n\nvec3 gammaCorrectOutput(vec3 color) {\n#ifdef HDR\n return color;\n#else\n return pow(color + 0.0000001, vec3(1.0 / 2.2));\n#endif\n}\n",gles2PS:"\n#define texture2DBias texture2D\n",gles3PS:"\n#define varying in\nout highp vec4 pc_fragColor;\n#define gl_FragColor pc_fragColor\n#define texture2D texture\n#define texture2DBias texture\n#define textureCube texture\n#define texture2DProj textureProj\n#define texture2DLodEXT textureLod\n#define texture2DProjLodEXT textureProjLod\n#define textureCubeLodEXT textureLod\n#define texture2DGradEXT textureGrad\n#define texture2DProjGradEXT textureProjGrad\n#define textureCubeGradEXT textureGrad\n#define GL2\n#define SUPPORTS_TEXLOD\n",gles3VS:"\n#define attribute in\n#define varying out\n#define texture2D texture\n#define GL2\n#define VERTEXSHADER\n",glossPS:"\n#ifdef MAPFLOAT\nuniform float material_shininess;\n#endif\n\nvoid getGlossiness() {\n dGlossiness = 1.0;\n\n #ifdef MAPFLOAT\n dGlossiness *= material_shininess;\n #endif\n\n #ifdef MAPTEXTURE\n dGlossiness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n dGlossiness *= saturate(vVertexColor.$VC);\n #endif\n\n dGlossiness += 0.0000001;\n}\n",iridescenceDiffractionPS:"\nuniform float material_iridescenceRefractionIndex;\n\n#ifndef PI\n#define PI 3.14159265\n#endif\n\nfloat iridescence_iorToFresnel(float transmittedIor, float incidentIor) {\n return pow((transmittedIor - incidentIor) / (transmittedIor + incidentIor), 2.0);\n}\n\nvec3 iridescence_iorToFresnel(vec3 transmittedIor, float incidentIor) {\n return pow((transmittedIor - vec3(incidentIor)) / (transmittedIor + vec3(incidentIor)), vec3(2.0));\n}\n\nvec3 iridescence_fresnelToIor(vec3 f0) {\n vec3 sqrtF0 = sqrt(f0);\n return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0);\n}\n\nvec3 iridescence_sensitivity(float opd, vec3 shift) {\n float phase = 2.0 * PI * opd * 1.0e-9;\n const vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13);\n const vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06);\n const vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09);\n\n vec3 xyz = val * sqrt(2.0 * PI * var) * cos(pos * phase + shift) * exp(-pow(phase, 2.0) * var);\n xyz.x += 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift[0]) * exp(-4.5282e+09 * pow(phase, 2.0));\n xyz /= vec3(1.0685e-07);\n\n const mat3 XYZ_TO_REC709 = mat3(\n 3.2404542, -0.9692660, 0.0556434,\n -1.5371385, 1.8760108, -0.2040259,\n -0.4985314, 0.0415560, 1.0572252\n );\n\n return XYZ_TO_REC709 * xyz;\n}\n\nfloat iridescence_fresnel(float cosTheta, float f0) {\n float x = clamp(1.0 - cosTheta, 0.0, 1.0);\n float x2 = x * x;\n float x5 = x * x2 * x2;\n return f0 + (1.0 - f0) * x5;\n} \n\nvec3 iridescence_fresnel(float cosTheta, vec3 f0) {\n float x = clamp(1.0 - cosTheta, 0.0, 1.0);\n float x2 = x * x;\n float x5 = x * x2 * x2; \n return f0 + (vec3(1.0) - f0) * x5;\n}\n\nvec3 calcIridescence(float outsideIor, float cosTheta, vec3 base_f0) {\n\n float iridescenceIor = mix(outsideIor, material_iridescenceRefractionIndex, smoothstep(0.0, 0.03, dIridescenceThickness));\n float sinTheta2Sq = pow(outsideIor / iridescenceIor, 2.0) * (1.0 - pow(cosTheta, 2.0));\n float cosTheta2Sq = 1.0 - sinTheta2Sq;\n\n if (cosTheta2Sq < 0.0) {\n return vec3(1.0);\n }\n\n float cosTheta2 = sqrt(cosTheta2Sq);\n\n float r0 = iridescence_iorToFresnel(iridescenceIor, outsideIor);\n float r12 = iridescence_fresnel(cosTheta, r0);\n float r21 = r12;\n float t121 = 1.0 - r12;\n\n float phi12 = iridescenceIor < outsideIor ? PI : 0.0;\n float phi21 = PI - phi12;\n\n vec3 baseIor = iridescence_fresnelToIor(base_f0 + vec3(0.0001));\n vec3 r1 = iridescence_iorToFresnel(baseIor, iridescenceIor);\n vec3 r23 = iridescence_fresnel(cosTheta2, r1);\n\n vec3 phi23 = vec3(0.0);\n if (baseIor[0] < iridescenceIor) phi23[0] = PI;\n if (baseIor[1] < iridescenceIor) phi23[1] = PI;\n if (baseIor[2] < iridescenceIor) phi23[2] = PI;\n float opd = 2.0 * iridescenceIor * dIridescenceThickness * cosTheta2;\n vec3 phi = vec3(phi21) + phi23; \n\n vec3 r123Sq = clamp(r12 * r23, 1e-5, 0.9999);\n vec3 r123 = sqrt(r123Sq);\n vec3 rs = pow(t121, 2.0) * r23 / (1.0 - r123Sq);\n\n vec3 c0 = r12 + rs;\n vec3 i = c0;\n\n vec3 cm = rs - t121;\n for (int m = 1; m <= 2; m++) {\n cm *= r123;\n vec3 sm = 2.0 * iridescence_sensitivity(float(m) * opd, float(m) * phi);\n i += cm * sm;\n }\n return max(i, vec3(0.0));\n}\n\nvoid getIridescence(float cosTheta) {\n dIridescenceFresnel = calcIridescence(1.0, cosTheta, dSpecularity);\n}\n",iridescencePS:"\n#ifdef MAPFLOAT\nuniform float material_iridescence;\n#endif\n\nvoid getIridescence() {\n float iridescence = 1.0;\n\n #ifdef MAPFLOAT\n iridescence *= material_iridescence;\n #endif\n\n #ifdef MAPTEXTURE\n iridescence *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n dIridescence = iridescence; \n}\n",iridescenceThicknessPS:"\nuniform float material_iridescenceThicknessMax;\n\n#ifdef MAPTEXTURE\nuniform float material_iridescenceThicknessMin;\n#endif\n\nvoid getIridescenceThickness() {\n\n #ifdef MAPTEXTURE\n float blend = texture2DBias($SAMPLER, $UV, textureBias).$CH;\n float iridescenceThickness = mix(material_iridescenceThicknessMin, material_iridescenceThicknessMax, blend);\n #else\n float iridescenceThickness = material_iridescenceThicknessMax;\n #endif\n\n dIridescenceThickness = iridescenceThickness; \n}\n",instancingVS:"\nattribute vec4 instance_line1;\nattribute vec4 instance_line2;\nattribute vec4 instance_line3;\nattribute vec4 instance_line4;\n",lightDiffuseLambertPS:"\nfloat getLightDiffuse() {\n return max(dot(dNormalW, -dLightDirNormW), 0.0);\n}\n",lightDirPointPS:"\nvoid getLightDirPoint(vec3 lightPosW) {\n dLightDirW = vPositionW - lightPosW;\n dLightDirNormW = normalize(dLightDirW);\n dLightPosW = lightPosW;\n}\n",lightmapAddPS:"\nvoid addLightMap() {\n dDiffuseLight += dLightmap;\n}\n",lightmapDirAddPS:"\nvoid addLightMap() {\n if (dot(dLightmapDir, dLightmapDir) < 0.0001) {\n dDiffuseLight += dLightmap;\n } else {\n dLightDirNormW = dLightmapDir;\n\n float vlight = saturate(dot(dLightDirNormW, -dVertexNormalW));\n float flight = saturate(dot(dLightDirNormW, -dNormalW));\n float nlight = (flight / max(vlight, 0.01)) * 0.5;\n\n dDiffuseLight += dLightmap * nlight * 2.0;\n\n vec3 halfDirW = normalize(-dLightmapDir + dViewDirW);\n vec3 specularLight = dLightmap * getLightSpecular(halfDirW);\n\n #ifdef LIT_SPECULAR_FRESNEL\n specularLight *= getFresnel(dot(dViewDirW, halfDirW), dSpecularity);\n #endif\n\n dSpecularLight += specularLight;\n }\n}\n",lightmapDirPS:"\nuniform sampler2D texture_lightMap;\nuniform sampler2D texture_dirLightMap;\n\nvoid getLightMap() {\n dLightmap = $DECODE(texture2DBias(texture_lightMap, $UV, textureBias)).$CH;\n\n vec3 dir = texture2DBias(texture_dirLightMap, $UV, textureBias).xyz * 2.0 - 1.0;\n float dirDot = dot(dir, dir);\n dLightmapDir = (dirDot > 0.001) ? dir / sqrt(dirDot) : vec3(0.0);\n}\n",lightmapSinglePS:"\nvoid getLightMap() {\n dLightmap = vec3(1.0);\n\n #ifdef MAPTEXTURE\n dLightmap *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n #endif\n\n #ifdef MAPVERTEX\n dLightmap *= saturate(vVertexColor.$VC);\n #endif\n}\n",lightSpecularAnisoGGXPS:"\n// Anisotropic GGX\nfloat calcLightSpecular(float tGlossiness, vec3 tNormalW, vec3 h) {\n float PI = 3.141592653589793;\n float roughness = max((1.0 - tGlossiness) * (1.0 - tGlossiness), 0.001);\n float anisotropy = material_anisotropy * roughness;\n \n float at = max((roughness + anisotropy), roughness / 4.0);\n float ab = max((roughness - anisotropy), roughness / 4.0);\n\n float NoH = dot(tNormalW, h);\n float ToH = dot(dTBN[0], h);\n float BoH = dot(dTBN[1], h);\n\n float a2 = at * ab;\n vec3 v = vec3(ab * ToH, at * BoH, a2 * NoH);\n float v2 = dot(v, v);\n float w2 = a2 / v2;\n float D = a2 * w2 * w2 * (1.0 / PI);\n\n float ToV = dot(dTBN[0], dViewDirW);\n float BoV = dot(dTBN[1], dViewDirW);\n float ToL = dot(dTBN[0], -dLightDirNormW);\n float BoL = dot(dTBN[1], -dLightDirNormW);\n float NoV = dot(tNormalW, dViewDirW);\n float NoL = dot(tNormalW, -dLightDirNormW);\n\n float lambdaV = NoL * length(vec3(at * ToV, ab * BoV, NoV));\n float lambdaL = NoV * length(vec3(at * ToL, ab * BoL, NoL));\n float G = 0.5 / (lambdaV + lambdaL);\n\n return D * G;\n}\n\nfloat getLightSpecular(vec3 h) {\n return calcLightSpecular(dGlossiness, dNormalW, h);\n}\n\n#ifdef LIT_CLEARCOAT\nfloat getLightSpecularCC(vec3 h) {\n return calcLightSpecular(ccGlossiness, ccNormalW, h);\n}\n#endif\n",lightSpecularBlinnPS:"\n// Energy-conserving (hopefully) Blinn-Phong\nfloat calcLightSpecular(float tGlossiness, vec3 tNormalW, vec3 h) {\n float nh = max( dot( h, tNormalW ), 0.0 );\n\n float specPow = exp2(tGlossiness * 11.0); // glossiness is linear, power is not; 0 - 2048\n\n // Hack: On Mac OS X, calling pow with zero for the exponent generates hideous artifacts so bias up a little\n specPow = max(specPow, 0.0001);\n\n return pow(nh, specPow) * (specPow + 2.0) / 8.0;\n}\n\nfloat getLightSpecular(vec3 h) {\n return calcLightSpecular(dGlossiness, dNormalW, h);\n}\n\n#ifdef LIT_CLEARCOAT\nfloat getLightSpecularCC(vec3 h) {\n return calcLightSpecular(ccGlossiness, ccNormalW, h);\n}\n#endif\n",lightSpecularPhongPS:"\nfloat calcLightSpecular(float tGlossiness, vec3 tReflDirW, vec3 h) {\n float specPow = tGlossiness;\n\n // Hack: On Mac OS X, calling pow with zero for the exponent generates hideous artifacts so bias up a little\n return pow(max(dot(tReflDirW, -dLightDirNormW), 0.0), specPow + 0.0001);\n}\n\nfloat getLightSpecular(vec3 h) {\n return calcLightSpecular(dGlossiness, dReflDirW, h);\n}\n\n#ifdef LIT_CLEARCOAT\nfloat getLightSpecularCC(vec3 h) {\n return calcLightSpecular(ccGlossiness, ccReflDirW,h );\n}\n#endif\n",lightSheenPS:"\n\nfloat sheenD(vec3 normal, vec3 h, float roughness) {\n float invR = 1.0 / (roughness * roughness);\n float cos2h = max(dot(normal, h), 0.0);\n cos2h *= cos2h;\n float sin2h = max(1.0 - cos2h, 0.0078125);\n return (2.0 + invR) * pow(sin2h, invR * 0.5) / (2.0 * PI);\n}\n\nfloat sheenV(vec3 normal, vec3 view, vec3 light) {\n float NoV = max(dot(normal, view), 0.000001);\n float NoL = max(dot(normal, light), 0.000001);\n return 1.0 / (4.0 * (NoL + NoV - NoL * NoV));\n}\n\nfloat getLightSpecularSheen(vec3 h) {\n float D = sheenD(dNormalW, h, sGlossiness);\n float V = sheenV(dNormalW, dViewDirW, -dLightDirNormW);\n return D * V;\n}\n",ltc:'\n// Real-Time Polygonal-Light Shading with Linearly Transformed Cosines\n// by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt\n// code: https://github.com/selfshadow/ltc_code/\n\nmat3 transposeMat3( const in mat3 m ) {\n mat3 tmp;\n tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n return tmp;\n}\n\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n const float LUT_SIZE = 64.0;\n const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n const float LUT_BIAS = 0.5 / LUT_SIZE;\n float dotNV = saturate( dot( N, V ) );\n // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )\n vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n uv = uv * LUT_SCALE + LUT_BIAS;\n return uv;\n}\n\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n // Real-Time Area Lighting: a Journey from Research to Production (p.102)\n // An approximation of the form factor of a horizon-clipped rectangle.\n float l = length( f );\n return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\n\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n float x = dot( v1, v2 );\n float y = abs( x );\n // rational polynomial approximation to theta / sin( theta ) / 2PI\n float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n float b = 3.4175940 + ( 4.1616724 + y ) * y;\n float v = a / b;\n float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n return cross( v1, v2 ) * theta_sintheta;\n}\n\nstruct Coords {\n vec3 coord0;\n vec3 coord1;\n vec3 coord2;\n vec3 coord3;\n};\n\nfloat LTC_EvaluateRect( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in Coords rectCoords) {\n // bail if point is on back side of plane of light\n // assumes ccw winding order of light vertices\n vec3 v1 = rectCoords.coord1 - rectCoords.coord0;\n vec3 v2 = rectCoords.coord3 - rectCoords.coord0;\n \n vec3 lightNormal = cross( v1, v2 );\n // if( dot( lightNormal, P - rectCoords.coord0 ) < 0.0 ) return 0.0;\n float factor = sign(-dot( lightNormal, P - rectCoords.coord0 ));\n\n // construct orthonormal basis around N\n vec3 T1, T2;\n T1 = normalize( V - N * dot( V, N ) );\n T2 = factor * cross( N, T1 ); // negated from paper; possibly due to a different handedness of world coordinate system\n // compute transform\n mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n // transform rect\n vec3 coords[ 4 ];\n coords[ 0 ] = mat * ( rectCoords.coord0 - P );\n coords[ 1 ] = mat * ( rectCoords.coord1 - P );\n coords[ 2 ] = mat * ( rectCoords.coord2 - P );\n coords[ 3 ] = mat * ( rectCoords.coord3 - P );\n // project rect onto sphere\n coords[ 0 ] = normalize( coords[ 0 ] );\n coords[ 1 ] = normalize( coords[ 1 ] );\n coords[ 2 ] = normalize( coords[ 2 ] );\n coords[ 3 ] = normalize( coords[ 3 ] );\n // calculate vector form factor\n vec3 vectorFormFactor = vec3( 0.0 );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n // adjust for horizon clipping\n float result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\n return result;\n}\n\nCoords dLTCCoords;\nCoords getLTCLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){\n Coords coords;\n coords.coord0 = lightPos + halfWidth - halfHeight;\n coords.coord1 = lightPos - halfWidth - halfHeight;\n coords.coord2 = lightPos - halfWidth + halfHeight;\n coords.coord3 = lightPos + halfWidth + halfHeight;\n return coords;\n}\n\nfloat dSphereRadius;\nCoords getSphereLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){\n // used for simple sphere light falloff\n // also, the code only handles a spherical light, it cannot be non-uniformly scaled in world space, and so we enforce it here\n dSphereRadius = max(length(halfWidth), length(halfHeight));\n\n // Billboard the 2d light quad to reflection vector, as it\'s used for specular. This allows us to use disk math for the sphere.\n vec3 f = reflect(normalize(lightPos - view_position), vNormalW);\n vec3 w = normalize(cross(f, halfHeight));\n vec3 h = normalize(cross(f, w));\n\n return getLTCLightCoords(lightPos, w * dSphereRadius, h * dSphereRadius);\n}\n\n// used for LTC LUT texture lookup\nvec2 dLTCUV;\n#ifdef LIT_CLEARCOAT\nvec2 ccLTCUV;\n#endif\nvec2 getLTCLightUV(float tGlossiness, vec3 tNormalW)\n{\n float roughness = max((1.0 - tGlossiness) * (1.0 - tGlossiness), 0.001);\n return LTC_Uv( tNormalW, dViewDirW, roughness );\n}\n\n//used for energy conservation and to modulate specular\nvec3 dLTCSpecFres;\n#ifdef LIT_CLEARCOAT\nvec3 ccLTCSpecFres;\n#endif\nvec3 getLTCLightSpecFres(vec2 uv, vec3 tSpecularity)\n{\n vec4 t2 = texture2D( areaLightsLutTex2, uv );\n\n #ifdef AREA_R8_G8_B8_A8_LUTS\n t2 *= vec4(0.693103,1,1,1);\n t2 += vec4(0.306897,0,0,0);\n #endif\n\n return tSpecularity * t2.x + ( vec3( 1.0 ) - tSpecularity) * t2.y;\n}\n\nvoid calcLTCLightValues()\n{\n dLTCUV = getLTCLightUV(dGlossiness, dNormalW);\n dLTCSpecFres = getLTCLightSpecFres(dLTCUV, dSpecularity); \n\n#ifdef LIT_CLEARCOAT\n ccLTCUV = getLTCLightUV(ccGlossiness, ccNormalW);\n ccLTCSpecFres = getLTCLightSpecFres(ccLTCUV, vec3(ccSpecularity));\n#endif\n}\n\nvoid calcRectLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n dLTCCoords = getLTCLightCoords(lightPos, halfWidth, halfHeight);\n}\nvoid calcDiskLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n calcRectLightValues(lightPos, halfWidth, halfHeight);\n}\nvoid calcSphereLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n dLTCCoords = getSphereLightCoords(lightPos, halfWidth, halfHeight);\n}\n\n// An extended version of the implementation from\n// "How to solve a cubic equation, revisited"\n// http://momentsingraphics.de/?p=105\nvec3 SolveCubic(vec4 Coefficient)\n{\n float pi = 3.14159;\n // Normalize the polynomial\n Coefficient.xyz /= Coefficient.w;\n // Divide middle coefficients by three\n Coefficient.yz /= 3.0;\n\n float A = Coefficient.w;\n float B = Coefficient.z;\n float C = Coefficient.y;\n float D = Coefficient.x;\n\n // Compute the Hessian and the discriminant\n vec3 Delta = vec3(\n -Coefficient.z * Coefficient.z + Coefficient.y,\n -Coefficient.y * Coefficient.z + Coefficient.x,\n dot(vec2(Coefficient.z, -Coefficient.y), Coefficient.xy)\n );\n\n float Discriminant = dot(vec2(4.0 * Delta.x, -Delta.y), Delta.zy);\n\n vec3 RootsA, RootsD;\n\n vec2 xlc, xsc;\n\n // Algorithm A\n {\n float A_a = 1.0;\n float C_a = Delta.x;\n float D_a = -2.0 * B * Delta.x + Delta.y;\n\n // Take the cubic root of a normalized complex number\n float Theta = atan(sqrt(Discriminant), -D_a) / 3.0;\n\n float x_1a = 2.0 * sqrt(-C_a) * cos(Theta);\n float x_3a = 2.0 * sqrt(-C_a) * cos(Theta + (2.0 / 3.0) * pi);\n\n float xl;\n if ((x_1a + x_3a) > 2.0 * B)\n xl = x_1a;\n else\n xl = x_3a;\n\n xlc = vec2(xl - B, A);\n }\n\n // Algorithm D\n {\n float A_d = D;\n float C_d = Delta.z;\n float D_d = -D * Delta.y + 2.0 * C * Delta.z;\n\n // Take the cubic root of a normalized complex number\n float Theta = atan(D * sqrt(Discriminant), -D_d) / 3.0;\n\n float x_1d = 2.0 * sqrt(-C_d) * cos(Theta);\n float x_3d = 2.0 * sqrt(-C_d) * cos(Theta + (2.0 / 3.0) * pi);\n\n float xs;\n if (x_1d + x_3d < 2.0 * C)\n xs = x_1d;\n else\n xs = x_3d;\n\n xsc = vec2(-D, xs + C);\n }\n\n float E = xlc.y * xsc.y;\n float F = -xlc.x * xsc.y - xlc.y * xsc.x;\n float G = xlc.x * xsc.x;\n\n vec2 xmc = vec2(C * F - B * G, -B * F + C * E);\n\n vec3 Root = vec3(xsc.x / xsc.y, xmc.x / xmc.y, xlc.x / xlc.y);\n\n if (Root.x < Root.y && Root.x < Root.z)\n Root.xyz = Root.yxz;\n else if (Root.z < Root.x && Root.z < Root.y)\n Root.xyz = Root.xzy;\n\n return Root;\n}\n\nfloat LTC_EvaluateDisk(vec3 N, vec3 V, vec3 P, mat3 Minv, Coords points)\n{\n // construct orthonormal basis around N\n vec3 T1, T2;\n T1 = normalize(V - N * dot(V, N));\n T2 = cross(N, T1);\n\n // rotate area light in (T1, T2, N) basis\n //mat3 R = transpose(mat3(T1, T2, N));\n mat3 R = transposeMat3( mat3( T1, T2, N ) );\n // polygon (allocate 5 vertices for clipping)\n vec3 L_[ 3 ];\n L_[ 0 ] = R * ( points.coord0 - P );\n L_[ 1 ] = R * ( points.coord1 - P );\n L_[ 2 ] = R * ( points.coord2 - P );\n\n vec3 Lo_i = vec3(0);\n\n // init ellipse\n vec3 C = 0.5 * (L_[0] + L_[2]);\n vec3 V1 = 0.5 * (L_[1] - L_[2]);\n vec3 V2 = 0.5 * (L_[1] - L_[0]);\n\n C = Minv * C;\n V1 = Minv * V1;\n V2 = Minv * V2;\n\n //if(dot(cross(V1, V2), C) > 0.0)\n // return 0.0;\n\n // compute eigenvectors of ellipse\n float a, b;\n float d11 = dot(V1, V1);\n float d22 = dot(V2, V2);\n float d12 = dot(V1, V2);\n if (abs(d12) / sqrt(d11 * d22) > 0.0001)\n {\n float tr = d11 + d22;\n float det = -d12 * d12 + d11 * d22;\n\n // use sqrt matrix to solve for eigenvalues\n det = sqrt(det);\n float u = 0.5 * sqrt(tr - 2.0 * det);\n float v = 0.5 * sqrt(tr + 2.0 * det);\n float e_max = (u + v) * (u + v);\n float e_min = (u - v) * (u - v);\n\n vec3 V1_, V2_;\n\n if (d11 > d22)\n {\n V1_ = d12 * V1 + (e_max - d11) * V2;\n V2_ = d12 * V1 + (e_min - d11) * V2;\n }\n else\n {\n V1_ = d12*V2 + (e_max - d22)*V1;\n V2_ = d12*V2 + (e_min - d22)*V1;\n }\n\n a = 1.0 / e_max;\n b = 1.0 / e_min;\n V1 = normalize(V1_);\n V2 = normalize(V2_);\n }\n else\n {\n a = 1.0 / dot(V1, V1);\n b = 1.0 / dot(V2, V2);\n V1 *= sqrt(a);\n V2 *= sqrt(b);\n }\n\n vec3 V3 = cross(V1, V2);\n if (dot(C, V3) < 0.0)\n V3 *= -1.0;\n\n float L = dot(V3, C);\n float x0 = dot(V1, C) / L;\n float y0 = dot(V2, C) / L;\n\n float E1 = inversesqrt(a);\n float E2 = inversesqrt(b);\n\n a *= L * L;\n b *= L * L;\n\n float c0 = a * b;\n float c1 = a * b * (1.0 + x0 * x0 + y0 * y0) - a - b;\n float c2 = 1.0 - a * (1.0 + x0 * x0) - b * (1.0 + y0 * y0);\n float c3 = 1.0;\n\n vec3 roots = SolveCubic(vec4(c0, c1, c2, c3));\n float e1 = roots.x;\n float e2 = roots.y;\n float e3 = roots.z;\n\n vec3 avgDir = vec3(a * x0 / (a - e2), b * y0 / (b - e2), 1.0);\n\n mat3 rotate = mat3(V1, V2, V3);\n\n avgDir = rotate * avgDir;\n avgDir = normalize(avgDir);\n\n float L1 = sqrt(-e2 / e3);\n float L2 = sqrt(-e2 / e1);\n\n float formFactor = L1 * L2 * inversesqrt((1.0 + L1 * L1) * (1.0 + L2 * L2));\n \n const float LUT_SIZE = 64.0;\n const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n const float LUT_BIAS = 0.5 / LUT_SIZE;\n\n // use tabulated horizon-clipped sphere\n vec2 uv = vec2(avgDir.z * 0.5 + 0.5, formFactor);\n uv = uv*LUT_SCALE + LUT_BIAS;\n\n float scale = texture2D( areaLightsLutTex2, uv ).w;\n\n return formFactor*scale;\n}\n\nfloat getRectLightDiffuse() {\n return LTC_EvaluateRect( dNormalW, dViewDirW, vPositionW, mat3( 1.0 ), dLTCCoords );\n}\n\nfloat getDiskLightDiffuse() {\n return LTC_EvaluateDisk( dNormalW, dViewDirW, vPositionW, mat3( 1.0 ), dLTCCoords );\n}\n\nfloat getSphereLightDiffuse() {\n // NB: this could be improved further with distance based wrap lighting\n float falloff = dSphereRadius / (dot(dLightDirW, dLightDirW) + dSphereRadius);\n return getLightDiffuse()*falloff;\n}\n\nmat3 getLTCLightInvMat(vec2 uv)\n{\n vec4 t1 = texture2D( areaLightsLutTex1, uv );\n\n #ifdef AREA_R8_G8_B8_A8_LUTS\n t1 *= vec4(1.001, 0.3239, 0.60437568, 1.0);\n t1 += vec4(0.0, -0.2976, -0.01381, 0.0);\n #endif\n\n return mat3(\n vec3( t1.x, 0, t1.y ),\n vec3( 0, 1, 0 ),\n vec3( t1.z, 0, t1.w )\n );\n}\n\nfloat calcRectLightSpecular(vec3 tNormalW, vec2 uv) {\n mat3 mInv = getLTCLightInvMat(uv);\n return LTC_EvaluateRect( tNormalW, dViewDirW, vPositionW, mInv, dLTCCoords );\n}\n\nfloat getRectLightSpecular() {\n return calcRectLightSpecular(dNormalW, dLTCUV);\n}\n\n#ifdef LIT_CLEARCOAT\nfloat getRectLightSpecularCC() {\n return calcRectLightSpecular(ccNormalW, ccLTCUV);\n}\n#endif\n\nfloat calcDiskLightSpecular(vec3 tNormalW, vec2 uv) {\n mat3 mInv = getLTCLightInvMat(uv);\n return LTC_EvaluateDisk( tNormalW, dViewDirW, vPositionW, mInv, dLTCCoords );\n}\n\nfloat getDiskLightSpecular() {\n return calcDiskLightSpecular(dNormalW, dLTCUV);\n}\n\n#ifdef LIT_CLEARCOAT\nfloat getDiskLightSpecularCC() {\n return calcDiskLightSpecular(ccNormalW, ccLTCUV);\n}\n#endif\n\nfloat getSphereLightSpecular() {\n return calcDiskLightSpecular(dNormalW, dLTCUV);\n}\n\n#ifdef LIT_CLEARCOAT\nfloat getSphereLightSpecularCC() {\n return calcDiskLightSpecular(ccNormalW, ccLTCUV);\n}\n#endif\n',metalnessPS:"\n#ifdef MAPFLOAT\nuniform float material_metalness;\n#endif\n\nvoid getMetalness() {\n float metalness = 1.0;\n\n #ifdef MAPFLOAT\n metalness *= material_metalness;\n #endif\n\n #ifdef MAPTEXTURE\n metalness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n metalness *= saturate(vVertexColor.$VC);\n #endif\n\n dMetalness = metalness;\n}\n",metalnessModulatePS:"\n\nuniform float material_f0;\n\nvoid getMetalnessModulate() {\n vec3 dielectricF0 = material_f0 * dSpecularity;\n dSpecularity = mix(dielectricF0, dAlbedo, dMetalness);\n dAlbedo *= 1.0 - dMetalness;\n}\n",msdfPS:"\nuniform sampler2D texture_msdfMap;\n\n#ifdef GL_OES_standard_derivatives\n#define USE_FWIDTH\n#endif\n\n#ifdef GL2\n#define USE_FWIDTH\n#endif\n\nfloat median(float r, float g, float b) {\n return max(min(r, g), min(max(r, g), b));\n}\n\nfloat map (float min, float max, float v) {\n return (v - min) / (max - min);\n}\n\nuniform float font_sdfIntensity; // intensity is used to boost the value read from the SDF, 0 is no boost, 1.0 is max boost\nuniform float font_pxrange; // the number of pixels between inside and outside the font in SDF\nuniform float font_textureWidth; // the width of the texture atlas\n\n#ifdef UNIFORM_TEXT_PARAMETERS\nuniform vec4 outline_color;\nuniform float outline_thickness;\nuniform vec4 shadow_color;\nuniform vec2 shadow_offset;\n#else\nvarying vec4 outline_color;\nvarying float outline_thickness;\nvarying vec4 shadow_color;\nvarying vec2 shadow_offset;\n#endif\n\nvec4 applyMsdf(vec4 color) {\n // sample the field\n vec3 tsample = texture2D(texture_msdfMap, vUv0).rgb;\n vec2 uvShdw = vUv0 - shadow_offset;\n vec3 ssample = texture2D(texture_msdfMap, uvShdw).rgb;\n // get the signed distance value\n float sigDist = median(tsample.r, tsample.g, tsample.b);\n float sigDistShdw = median(ssample.r, ssample.g, ssample.b);\n\n // smoothing limit - smaller value makes for sharper but more aliased text, especially on angles\n // too large value (0.5) creates a dark glow around the letters\n float smoothingMax = 0.2;\n\n #ifdef USE_FWIDTH\n // smoothing depends on size of texture on screen\n vec2 w = fwidth(vUv0);\n float smoothing = clamp(w.x * font_textureWidth / font_pxrange, 0.0, smoothingMax);\n #else\n float font_size = 16.0; // TODO fix this\n // smoothing gets smaller as the font size gets bigger\n // don't have fwidth we can approximate from font size, this doesn't account for scaling\n // so a big font scaled down will be wrong...\n float smoothing = clamp(font_pxrange / font_size, 0.0, smoothingMax);\n #endif\n\n float mapMin = 0.05;\n float mapMax = clamp(1.0 - font_sdfIntensity, mapMin, 1.0);\n\n // remap to a smaller range (used on smaller font sizes)\n float sigDistInner = map(mapMin, mapMax, sigDist);\n float sigDistOutline = map(mapMin, mapMax, sigDist + outline_thickness);\n sigDistShdw = map(mapMin, mapMax, sigDistShdw + outline_thickness);\n\n float center = 0.5;\n // calculate smoothing and use to generate opacity\n float inside = smoothstep(center-smoothing, center+smoothing, sigDistInner);\n float outline = smoothstep(center-smoothing, center+smoothing, sigDistOutline);\n float shadow = smoothstep(center-smoothing, center+smoothing, sigDistShdw);\n\n vec4 tcolor = (outline > inside) ? outline * vec4(outline_color.a * outline_color.rgb, outline_color.a) : vec4(0.0);\n tcolor = mix(tcolor, color, inside);\n\n vec4 scolor = (shadow > outline) ? shadow * vec4(shadow_color.a * shadow_color.rgb, shadow_color.a) : tcolor;\n tcolor = mix(scolor, tcolor, outline);\n \n return tcolor;\n}\n",msdfVS:"\nattribute vec3 vertex_outlineParameters;\nattribute vec3 vertex_shadowParameters;\n\nvarying vec4 outline_color;\nvarying float outline_thickness;\nvarying vec4 shadow_color;\nvarying vec2 shadow_offset;\n\nvoid unpackMsdfParams() {\n vec3 little = mod(vertex_outlineParameters, 256.);\n vec3 big = (vertex_outlineParameters - little) / 256.;\n\n outline_color.rb = little.xy / 255.;\n outline_color.ga = big.xy / 255.;\n\n // _outlineThicknessScale === 0.2\n outline_thickness = little.z / 255. * 0.2;\n\n little = mod(vertex_shadowParameters, 256.);\n big = (vertex_shadowParameters - little) / 256.;\n\n shadow_color.rb = little.xy / 255.;\n shadow_color.ga = big.xy / 255.;\n\n // vec2(little.z, big.z) / 127. - 1. remaps shadow offset from [0, 254] to [-1, 1]\n // _shadowOffsetScale === 0.005\n shadow_offset = (vec2(little.z, big.z) / 127. - 1.) * 0.005;\n}\n",normalVS:"\n#ifdef MORPHING_TEXTURE_BASED_NORMAL\nuniform highp sampler2D morphNormalTex;\n#endif\n\nvec3 getNormal() {\n #ifdef SKIN\n dNormalMatrix = mat3(dModelMatrix[0].xyz, dModelMatrix[1].xyz, dModelMatrix[2].xyz);\n #elif defined(INSTANCING)\n dNormalMatrix = mat3(instance_line1.xyz, instance_line2.xyz, instance_line3.xyz);\n #else\n dNormalMatrix = matrix_normal;\n #endif\n\n vec3 tempNormal = vertex_normal;\n\n #ifdef MORPHING\n #ifdef MORPHING_NRM03\n tempNormal += morph_weights_a[0] * morph_nrm0;\n tempNormal += morph_weights_a[1] * morph_nrm1;\n tempNormal += morph_weights_a[2] * morph_nrm2;\n tempNormal += morph_weights_a[3] * morph_nrm3;\n #endif\n #ifdef MORPHING_NRM47\n tempNormal += morph_weights_b[0] * morph_nrm4;\n tempNormal += morph_weights_b[1] * morph_nrm5;\n tempNormal += morph_weights_b[2] * morph_nrm6;\n tempNormal += morph_weights_b[3] * morph_nrm7;\n #endif\n #endif\n\n #ifdef MORPHING_TEXTURE_BASED_NORMAL\n // apply morph offset from texture\n vec2 morphUV = getTextureMorphCoords();\n vec3 morphNormal = texture2D(morphNormalTex, morphUV).xyz;\n tempNormal += morphNormal;\n #endif\n\n return normalize(dNormalMatrix * tempNormal);\n}\n",normalDetailMapPS:"\n#ifdef MAPTEXTURE\nuniform float material_normalDetailMapBumpiness;\n\nvec3 blendNormals(vec3 n1, vec3 n2) {\n // https://blog.selfshadow.com/publications/blending-in-detail/#detail-oriented\n n1 += vec3(0, 0, 1);\n n2 *= vec3(-1, -1, 1);\n return n1 * dot(n1, n2) / n1.z - n2;\n}\n#endif\n\nvec3 addNormalDetail(vec3 normalMap) {\n#ifdef MAPTEXTURE\n vec3 normalDetailMap = unpackNormal(texture2DBias($SAMPLER, $UV, textureBias));\n normalDetailMap = mix(vec3(0.0, 0.0, 1.0), normalDetailMap, material_normalDetailMapBumpiness);\n return blendNormals(normalMap, normalDetailMap);\n#else\n return normalMap;\n#endif\n}\n",normalInstancedVS:"\nvec3 getNormal() {\n dNormalMatrix = mat3(instance_line1.xyz, instance_line2.xyz, instance_line3.xyz);\n return normalize(dNormalMatrix * vertex_normal);\n}\n",normalMapPS:"\n#ifdef MAPTEXTURE\nuniform float material_bumpiness;\n#endif\n\nvoid getNormal() {\n#ifdef MAPTEXTURE\n vec3 normalMap = unpackNormal(texture2DBias($SAMPLER, $UV, textureBias));\n normalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, material_bumpiness);\n dNormalW = normalize(dTBN * addNormalDetail(normalMap));\n#else\n dNormalW = dVertexNormalW;\n#endif\n}\n",normalSkinnedVS:"\nvec3 getNormal() {\n dNormalMatrix = mat3(dModelMatrix[0].xyz, dModelMatrix[1].xyz, dModelMatrix[2].xyz);\n return normalize(dNormalMatrix * vertex_normal);\n}\n",normalXYPS:"\nvec3 unpackNormal(vec4 nmap) {\n vec3 normal;\n normal.xy = nmap.wy * 2.0 - 1.0;\n normal.z = sqrt(1.0 - saturate(dot(normal.xy, normal.xy)));\n return normal;\n}\n",normalXYZPS:"\nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\n",opacityPS:"\n#ifdef MAPFLOAT\nuniform float material_opacity;\n#endif\n\nvoid getOpacity() {\n dAlpha = 1.0;\n\n #ifdef MAPFLOAT\n dAlpha *= material_opacity;\n #endif\n\n #ifdef MAPTEXTURE\n dAlpha *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n dAlpha *= clamp(vVertexColor.$VC, 0.0, 1.0);\n #endif\n}\n",outputAlphaPS:"\ngl_FragColor.a = dAlpha;\n",outputAlphaOpaquePS:"\n gl_FragColor.a = 1.0;\n",outputAlphaPremulPS:"\ngl_FragColor.rgb *= dAlpha;\ngl_FragColor.a = dAlpha;\n",outputTex2DPS:"\nvarying vec2 vUv0;\n\nuniform sampler2D source;\n\nvoid main(void) {\n gl_FragColor = texture2D(source, vUv0);\n}\n",packDepthPS:"\n// Packing a float in GLSL with multiplication and mod\n// http://blog.gradientstudios.com/2012/08/23/shadow-map-improvement\nvec4 packFloat(float depth) {\n const vec4 bit_shift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);\n\n // combination of mod and multiplication and division works better\n vec4 res = mod(depth * bit_shift * vec4(255), vec4(256) ) / vec4(255);\n res -= res.xxyz * bit_mask;\n return res;\n}\n",sheenPS:"\n\n#ifdef MAPCOLOR\nuniform vec3 material_sheen;\n#endif\n\nvoid getSheen() {\n vec3 sheenColor = vec3(1, 1, 1);\n\n #ifdef MAPCOLOR\n sheenColor *= material_sheen;\n #endif\n\n #ifdef MAPTEXTURE\n sheenColor *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n #endif\n\n #ifdef MAPVERTEX\n sheenColor *= saturate(vVertexColor.$VC);\n #endif\n\n sSpecularity = sheenColor;\n}\n",sheenGlossPS:"\n#ifdef MAPFLOAT\nuniform float material_sheenGlossiness;\n#endif\n\nvoid getSheenGlossiness() {\n float sheenGlossiness = 1.0;\n\n #ifdef MAPFLOAT\n sheenGlossiness *= material_sheenGlossiness;\n #endif\n\n #ifdef MAPTEXTURE\n sheenGlossiness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n sheenGlossiness *= saturate(vVertexColor.$VC);\n #endif\n\n sheenGlossiness += 0.0000001;\n sGlossiness = sheenGlossiness;\n}\n",parallaxPS:"\nuniform float material_heightMapFactor;\n\nvoid getParallax() {\n float parallaxScale = material_heightMapFactor;\n\n float height = texture2DBias($SAMPLER, $UV, textureBias).$CH;\n height = height * parallaxScale - parallaxScale*0.5;\n vec3 viewDirT = dViewDirW * dTBN;\n\n viewDirT.z += 0.42;\n dUvOffset = height * (viewDirT.xy / viewDirT.z);\n}\n",particlePS:"\nvarying vec4 texCoordsAlphaLife;\n\nuniform sampler2D colorMap;\nuniform sampler2D colorParam;\nuniform float graphSampleSize;\nuniform float graphNumSamples;\n\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n#endif\n\nuniform float softening;\nuniform float colorMult;\n\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n const vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n float depth = dot(rgbaDepth, bitShift);\n return depth;\n}\n#endif\n\nvoid main(void) {\n vec4 tex = gammaCorrectInput(texture2D(colorMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y)));\n vec4 ramp = gammaCorrectInput(texture2D(colorParam, vec2(texCoordsAlphaLife.w, 0.0)));\n ramp.rgb *= colorMult;\n\n ramp.a += texCoordsAlphaLife.z;\n\n vec3 rgb = tex.rgb * ramp.rgb;\n float a = tex.a * ramp.a;\n",particleVS:"\nvec3 unpack3NFloats(float src) {\n float r = fract(src);\n float g = fract(src * 256.0);\n float b = fract(src * 65536.0);\n return vec3(r, g, b);\n}\n\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n\nvec4 tex1Dlod_lerp(highp sampler2D tex, vec2 tc) {\n return mix( texture2D(tex,tc), texture2D(tex,tc + graphSampleSize), fract(tc.x*graphNumSamples) );\n}\n\nvec4 tex1Dlod_lerp(highp sampler2D tex, vec2 tc, out vec3 w) {\n vec4 a = texture2D(tex,tc);\n vec4 b = texture2D(tex,tc + graphSampleSize);\n float c = fract(tc.x*graphNumSamples);\n\n vec3 unpackedA = unpack3NFloats(a.w);\n vec3 unpackedB = unpack3NFloats(b.w);\n w = mix(unpackedA, unpackedB, c);\n\n return mix(a, b, c);\n}\n\nvec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix) {\n float c = cos(pRotation);\n float s = sin(pRotation);\n\n mat2 m = mat2(c, -s, s, c);\n rotMatrix = m;\n\n return m * quadXY;\n}\n\nvec3 billboard(vec3 InstanceCoords, vec2 quadXY) {\n #ifdef SCREEN_SPACE\n vec3 pos = vec3(-1, 0, 0) * quadXY.x + vec3(0, -1, 0) * quadXY.y;\n #else\n vec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;\n #endif\n\n return pos;\n}\n\nvec3 customFace(vec3 InstanceCoords, vec2 quadXY) {\n vec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;\n return pos;\n}\n\nvec2 safeNormalize(vec2 v) {\n float l = length(v);\n return (l > 1e-06) ? v / l : v;\n}\n\nvoid main(void) {\n vec3 meshLocalPos = particle_vertexData.xyz;\n float id = floor(particle_vertexData.w);\n\n float rndFactor = fract(sin(id + 1.0 + seed));\n vec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));\n\n float uv = id / numParticlesPot;\n readInput(uv);\n\n#ifdef LOCAL_SPACE\n inVel = mat3(matrix_model) * inVel;\n#endif\n vec2 velocityV = safeNormalize((mat3(matrix_view) * inVel).xy); // should be removed by compiler if align/stretch is not used\n\n float particleLifetime = lifetime;\n\n if (inLife <= 0.0 || inLife > particleLifetime || !inShow) meshLocalPos = vec3(0.0);\n vec2 quadXY = meshLocalPos.xy;\n float nlife = clamp(inLife / particleLifetime, 0.0, 1.0);\n\n vec3 paramDiv;\n vec4 params = tex1Dlod_lerp(internalTex2, vec2(nlife, 0), paramDiv);\n float scale = params.y;\n float scaleDiv = paramDiv.x;\n float alphaDiv = paramDiv.z;\n\n scale += (scaleDiv * 2.0 - 1.0) * scaleDivMult * fract(rndFactor*10000.0);\n\n#ifndef USE_MESH\n texCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);\n#else\n texCoordsAlphaLife = vec4(particle_uv, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);\n#endif\n\n vec3 particlePos = inPos;\n vec3 particlePosMoved = vec3(0.0);\n\n mat2 rotMatrix;\n",particleAnimFrameClampVS:"\n float animFrame = min(floor(texCoordsAlphaLife.w * animTexParams.y) + animTexParams.x, animTexParams.z);\n",particleAnimFrameLoopVS:"\n float animFrame = floor(mod(texCoordsAlphaLife.w * animTexParams.y + animTexParams.x, animTexParams.z + 1.0));\n",particleAnimTexVS:"\n float animationIndex;\n\n if (animTexIndexParams.y == 1.0) {\n animationIndex = floor((animTexParams.w + 1.0) * rndFactor3.z) * (animTexParams.z + 1.0);\n } else {\n animationIndex = animTexIndexParams.x * (animTexParams.z + 1.0);\n }\n\n float atlasX = (animationIndex + animFrame) * animTexTilesParams.x;\n float atlasY = 1.0 - floor(atlasX + 1.0) * animTexTilesParams.y;\n atlasX = fract(atlasX);\n\n texCoordsAlphaLife.xy *= animTexTilesParams.xy;\n texCoordsAlphaLife.xy += vec2(atlasX, atlasY);\n",particleInputFloatPS:"\nvoid readInput(float uv) {\n vec4 tex = texture2D(particleTexIN, vec2(uv, 0.25));\n vec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.75));\n\n inPos = tex.xyz;\n inVel = tex2.xyz;\n inAngle = (tex.w < 0.0? -tex.w : tex.w) - 1000.0;\n inShow = tex.w >= 0.0;\n inLife = tex2.w;\n}\n",particleInputRgba8PS:"\n//RG=X, BA=Y\n//RG=Z, BA=A\n//RGB=V, A=visMode\n//RGBA=life\n\n#define PI2 6.283185307179586\n\nuniform vec3 inBoundsSize;\nuniform vec3 inBoundsCenter;\n\nuniform float maxVel;\n\nfloat decodeFloatRG(vec2 rg) {\n return rg.y*(1.0/255.0) + rg.x;\n}\n\nfloat decodeFloatRGBA( vec4 rgba ) {\n return dot( rgba, vec4(1.0, 1.0/255.0, 1.0/65025.0, 1.0/160581375.0) );\n}\n\nvoid readInput(float uv) {\n vec4 tex0 = texture2D(particleTexIN, vec2(uv, 0.125));\n vec4 tex1 = texture2D(particleTexIN, vec2(uv, 0.375));\n vec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.625));\n vec4 tex3 = texture2D(particleTexIN, vec2(uv, 0.875));\n\n inPos = vec3(decodeFloatRG(tex0.rg), decodeFloatRG(tex0.ba), decodeFloatRG(tex1.rg));\n inPos = (inPos - vec3(0.5)) * inBoundsSize + inBoundsCenter;\n\n inVel = tex2.xyz;\n inVel = (inVel - vec3(0.5)) * maxVel;\n\n inAngle = decodeFloatRG(tex1.ba) * PI2;\n inShow = tex2.a > 0.5;\n\n inLife = decodeFloatRGBA(tex3);\n float maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));\n float maxPosLife = lifetime+1.0;\n inLife = inLife * (maxNegLife + maxPosLife) - maxNegLife;\n}\n",particleOutputFloatPS:"\nvoid writeOutput() {\n if (gl_FragCoord.y<1.0) {\n gl_FragColor = vec4(outPos, (outAngle + 1000.0) * visMode);\n } else {\n gl_FragColor = vec4(outVel, outLife);\n }\n}\n",particleOutputRgba8PS:"\nuniform vec3 outBoundsMul;\nuniform vec3 outBoundsAdd;\n\nvec2 encodeFloatRG( float v ) {\n vec2 enc = vec2(1.0, 255.0) * v;\n enc = fract(enc);\n enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n return enc;\n}\n\nvec4 encodeFloatRGBA( float v ) {\n vec4 enc = vec4(1.0, 255.0, 65025.0, 160581375.0) * v;\n enc = fract(enc);\n enc -= enc.yzww * vec4(1.0/255.0,1.0/255.0,1.0/255.0,0.0);\n return enc;\n}\n\nvoid writeOutput() {\n outPos = outPos * outBoundsMul + outBoundsAdd;\n outAngle = fract(outAngle / PI2);\n\n outVel = (outVel / maxVel) + vec3(0.5); // TODO: mul\n\n float maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));\n float maxPosLife = lifetime+1.0;\n outLife = (outLife + maxNegLife) / (maxNegLife + maxPosLife);\n\n if (gl_FragCoord.y < 1.0) {\n gl_FragColor = vec4(encodeFloatRG(outPos.x), encodeFloatRG(outPos.y));\n } else if (gl_FragCoord.y < 2.0) {\n gl_FragColor = vec4(encodeFloatRG(outPos.z), encodeFloatRG(outAngle));\n } else if (gl_FragCoord.y < 3.0) {\n gl_FragColor = vec4(outVel, visMode*0.5+0.5);\n } else {\n gl_FragColor = encodeFloatRGBA(outLife);\n }\n}\n",particleUpdaterAABBPS:"\nuniform mat3 spawnBounds;\nuniform vec3 spawnPosInnerRatio;\n\nvec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {\n vec3 pos = inBounds - vec3(0.5);\n\n vec3 posAbs = abs(pos);\n vec3 maxPos = vec3(max(posAbs.x, max(posAbs.y, posAbs.z)));\n\n vec3 edge = maxPos + (vec3(0.5) - maxPos) * spawnPosInnerRatio;\n\n pos.x = edge.x * (maxPos.x == posAbs.x ? sign(pos.x) : 2.0 * pos.x);\n pos.y = edge.y * (maxPos.y == posAbs.y ? sign(pos.y) : 2.0 * pos.y);\n pos.z = edge.z * (maxPos.z == posAbs.z ? sign(pos.z) : 2.0 * pos.z);\n\n#ifndef LOCAL_SPACE\n return emitterPos + spawnBounds * pos;\n#else\n return spawnBounds * pos;\n#endif\n}\n\nvoid addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {\n localVelocity -= vec3(0, 0, initialVelocity);\n}\n",particleUpdaterEndPS:"\n writeOutput();\n}\n",particleUpdaterInitPS:"\nvarying vec2 vUv0;\n\nuniform highp sampler2D particleTexIN;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\nuniform highp sampler2D internalTex3;\n\nuniform mat3 emitterMatrix, emitterMatrixInv;\nuniform vec3 emitterScale;\n\nuniform vec3 emitterPos, frameRandom, localVelocityDivMult, velocityDivMult;\nuniform float delta, rate, rateDiv, lifetime, numParticles, rotSpeedDivMult, radialSpeedDivMult, seed;\nuniform float startAngle, startAngle2;\nuniform float initialVelocity;\n\nuniform float graphSampleSize;\nuniform float graphNumSamples;\n\nvec3 inPos;\nvec3 inVel;\nfloat inAngle;\nbool inShow;\nfloat inLife;\nfloat visMode;\n\nvec3 outPos;\nvec3 outVel;\nfloat outAngle;\nbool outShow;\nfloat outLife;\n",particleUpdaterNoRespawnPS:"\n if (outLife >= lifetime) {\n outLife -= max(lifetime, (numParticles - 1.0) * particleRate);\n visMode = -1.0;\n }\n",particleUpdaterOnStopPS:"\n visMode = outLife < 0.0? -1.0: visMode;\n",particleUpdaterRespawnPS:"\n if (outLife >= lifetime) {\n outLife -= max(lifetime, (numParticles - 1.0) * particleRate);\n visMode = 1.0;\n }\n visMode = outLife < 0.0? 1.0: visMode;\n",particleUpdaterSpherePS:"\nuniform float spawnBoundsSphere;\nuniform float spawnBoundsSphereInnerRatio;\n\nvec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {\n float rnd4 = fract(rndFactor * 1000.0);\n vec3 norm = normalize(inBounds.xyz - vec3(0.5));\n float r = rnd4 * (1.0 - spawnBoundsSphereInnerRatio) + spawnBoundsSphereInnerRatio;\n#ifndef LOCAL_SPACE\n return emitterPos + norm * r * spawnBoundsSphere;\n#else\n return norm * r * spawnBoundsSphere;\n#endif\n}\n\nvoid addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {\n localVelocity += normalize(inBounds - vec3(0.5)) * initialVelocity;\n}\n",particleUpdaterStartPS:"\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n\nvec3 unpack3NFloats(float src) {\n float r = fract(src);\n float g = fract(src * 256.0);\n float b = fract(src * 65536.0);\n return vec3(r, g, b);\n}\n\nvec3 tex1Dlod_lerp(highp sampler2D tex, vec2 tc, out vec3 w) {\n vec4 a = texture2D(tex, tc);\n vec4 b = texture2D(tex, tc + graphSampleSize);\n float c = fract(tc.x * graphNumSamples);\n\n vec3 unpackedA = unpack3NFloats(a.w);\n vec3 unpackedB = unpack3NFloats(b.w);\n w = mix(unpackedA, unpackedB, c);\n\n return mix(a.xyz, b.xyz, c);\n}\n\n#define HASHSCALE4 vec4(1031, .1030, .0973, .1099)\nvec4 hash41(float p) {\n vec4 p4 = fract(vec4(p) * HASHSCALE4);\n p4 += dot(p4, p4.wzxy+19.19);\n return fract(vec4((p4.x + p4.y)*p4.z, (p4.x + p4.z)*p4.y, (p4.y + p4.z)*p4.w, (p4.z + p4.w)*p4.x));\n}\n\nvoid main(void) {\n if (gl_FragCoord.x > numParticles) discard;\n\n readInput(vUv0.x);\n visMode = inShow? 1.0 : -1.0;\n\n vec4 rndFactor = hash41(gl_FragCoord.x + seed);\n\n float particleRate = rate + rateDiv * rndFactor.x;\n\n outLife = inLife + delta;\n float nlife = clamp(outLife / lifetime, 0.0, 1.0);\n\n vec3 localVelocityDiv;\n vec3 velocityDiv;\n vec3 paramDiv;\n vec3 localVelocity = tex1Dlod_lerp(internalTex0, vec2(nlife, 0), localVelocityDiv);\n vec3 velocity = tex1Dlod_lerp(internalTex1, vec2(nlife, 0), velocityDiv);\n vec3 params = tex1Dlod_lerp(internalTex2, vec2(nlife, 0), paramDiv);\n float rotSpeed = params.x;\n float rotSpeedDiv = paramDiv.y;\n\n vec3 radialParams = tex1Dlod_lerp(internalTex3, vec2(nlife, 0), paramDiv);\n float radialSpeed = radialParams.x;\n float radialSpeedDiv = radialParams.y;\n\n bool respawn = inLife <= 0.0 || outLife >= lifetime;\n inPos = respawn ? calcSpawnPosition(rndFactor.xyz, rndFactor.x) : inPos;\n inAngle = respawn ? mix(startAngle, startAngle2, rndFactor.x) : inAngle;\n\n#ifndef LOCAL_SPACE\n vec3 radialVel = inPos - emitterPos;\n#else\n vec3 radialVel = inPos;\n#endif\n radialVel = (dot(radialVel, radialVel) > 1.0E-8) ? radialSpeed * normalize(radialVel) : vec3(0.0);\n radialVel += (radialSpeedDiv * vec3(2.0) - vec3(1.0)) * radialSpeedDivMult * rndFactor.xyz;\n\n localVelocity += (localVelocityDiv * vec3(2.0) - vec3(1.0)) * localVelocityDivMult * rndFactor.xyz;\n velocity += (velocityDiv * vec3(2.0) - vec3(1.0)) * velocityDivMult * rndFactor.xyz;\n rotSpeed += (rotSpeedDiv * 2.0 - 1.0) * rotSpeedDivMult * rndFactor.y;\n\n addInitialVelocity(localVelocity, rndFactor.xyz);\n\n#ifndef LOCAL_SPACE\n outVel = emitterMatrix * localVelocity + (radialVel + velocity) * emitterScale;\n#else\n outVel = (localVelocity + radialVel) / emitterScale + emitterMatrixInv * velocity;\n#endif\n\n outPos = inPos + outVel * delta;\n outAngle = inAngle + rotSpeed * delta;\n",particle_billboardVS:"\n quadXY = rotate(quadXY, inAngle, rotMatrix);\n vec3 localPos = billboard(particlePos, quadXY);\n",particle_blendAddPS:"\n dBlendModeFogFactor = 0.0;\n rgb *= saturate(gammaCorrectInput(max(a, 0.0)));\n if ((rgb.r + rgb.g + rgb.b) < 0.000001) discard;\n",particle_blendMultiplyPS:"\n rgb = mix(vec3(1.0), rgb, vec3(a));\n if (rgb.r + rgb.g + rgb.b > 2.99) discard;\n",particle_blendNormalPS:"\n if (a < 0.01) discard;\n",particle_cpuVS:"\nattribute vec4 particle_vertexData; // XYZ = world pos, W = life\nattribute vec4 particle_vertexData2; // X = angle, Y = scale, Z = alpha, W = velocity.x\nattribute vec4 particle_vertexData3; // XYZ = particle local pos, W = velocity.y\nattribute float particle_vertexData4; // particle id\n#ifndef USE_MESH\n#define VDATA5TYPE vec2\n#else\n#define VDATA5TYPE vec4\n#endif\nattribute VDATA5TYPE particle_vertexData5; // VDATA4TYPE depends on useMesh property. Start with X = velocity.z, Y = particle ID and for mesh particles proceeds with Z = mesh UV.x, W = mesh UV.y\n\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\n\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n\nuniform mat3 matrix_normal;\nuniform mat4 matrix_viewInverse;\n\nuniform float numParticles;\nuniform float lifetime;\nuniform float stretch;\nuniform float seed;\nuniform vec3 wrapBounds, emitterScale, faceTangent, faceBinorm;\nuniform sampler2D texLifeAndSourcePosOUT;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\nuniform vec3 emitterPos;\n\nvarying vec4 texCoordsAlphaLife;\n\nvec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix)\n{\n float c = cos(pRotation);\n float s = sin(pRotation);\n //vec4 rotationMatrix = vec4(c, -s, s, c);\n\n mat2 m = mat2(c, -s, s, c);\n rotMatrix = m;\n\n return m * quadXY;\n}\n\nvec3 billboard(vec3 InstanceCoords, vec2 quadXY)\n{\n vec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;\n return pos;\n}\n\nvec3 customFace(vec3 InstanceCoords, vec2 quadXY)\n{\n vec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;\n return pos;\n}\n\nvoid main(void)\n{\n vec3 particlePos = particle_vertexData.xyz;\n vec3 inPos = particlePos;\n vec3 vertPos = particle_vertexData3.xyz;\n vec3 inVel = vec3(particle_vertexData2.w, particle_vertexData3.w, particle_vertexData5.x);\n\n float id = floor(particle_vertexData4);\n float rndFactor = fract(sin(id + 1.0 + seed));\n vec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));\n\n#ifdef LOCAL_SPACE\n inVel = mat3(matrix_model) * inVel;\n#endif\n vec2 velocityV = normalize((mat3(matrix_view) * inVel).xy); // should be removed by compiler if align/stretch is not used\n\n vec2 quadXY = vertPos.xy;\n\n#ifdef USE_MESH\n texCoordsAlphaLife = vec4(particle_vertexData5.zw, particle_vertexData2.z, particle_vertexData.w);\n#else\n texCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, particle_vertexData2.z, particle_vertexData.w);\n#endif\n mat2 rotMatrix;\n\n float inAngle = particle_vertexData2.x;\n vec3 particlePosMoved = vec3(0.0);\n vec3 meshLocalPos = particle_vertexData3.xyz;\n",particle_cpu_endVS:"\n localPos *= particle_vertexData2.y * emitterScale;\n localPos += particlePos;\n\n gl_Position = matrix_viewProjection * vec4(localPos, 1.0);\n",particle_customFaceVS:"\n quadXY = rotate(quadXY, inAngle, rotMatrix);\n vec3 localPos = customFace(particlePos, quadXY);\n",particle_endPS:"\n rgb = addFog(rgb);\n rgb = toneMap(rgb);\n rgb = gammaCorrectOutput(rgb);\n gl_FragColor = vec4(rgb, a);\n}\n",particle_endVS:"\n localPos *= scale * emitterScale;\n localPos += particlePos;\n\n #ifdef SCREEN_SPACE\n gl_Position = vec4(localPos.x, localPos.y, 0.0, 1.0);\n #else\n gl_Position = matrix_viewProjection * vec4(localPos.xyz, 1.0);\n #endif\n",particle_halflambertPS:"\n vec3 negNormal = normal*0.5+0.5;\n vec3 posNormal = -normal*0.5+0.5;\n negNormal *= negNormal;\n posNormal *= posNormal;\n",particle_initVS:"\nattribute vec4 particle_vertexData; // XYZ = particle position, W = particle ID + random factor\n#ifdef USE_MESH\nattribute vec2 particle_uv; // mesh UV\n#endif\n\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\nuniform mat3 matrix_normal;\nuniform mat4 matrix_viewInverse;\n\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n\nuniform float numParticles, numParticlesPot;\nuniform float graphSampleSize;\nuniform float graphNumSamples;\nuniform float stretch;\nuniform vec3 wrapBounds;\nuniform vec3 emitterScale, emitterPos, faceTangent, faceBinorm;\nuniform float rate, rateDiv, lifetime, deltaRandomnessStatic, scaleDivMult, alphaDivMult, seed, delta;\nuniform sampler2D particleTexOUT, particleTexIN;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\n\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n#endif\n\nvarying vec4 texCoordsAlphaLife;\n\nvec3 inPos;\nvec3 inVel;\nfloat inAngle;\nbool inShow;\nfloat inLife;\n",particle_lambertPS:"\n vec3 negNormal = max(normal, vec3(0.0));\n vec3 posNormal = max(-normal, vec3(0.0));\n",particle_lightingPS:"\n vec3 light = negNormal.x*lightCube[0] + posNormal.x*lightCube[1] +\n negNormal.y*lightCube[2] + posNormal.y*lightCube[3] +\n negNormal.z*lightCube[4] + posNormal.z*lightCube[5];\n\n rgb *= light;\n",particle_localShiftVS:"\n particlePos = (matrix_model * vec4(particlePos, 1.0)).xyz;\n",particle_meshVS:"\n vec3 localPos = meshLocalPos;\n localPos.xy = rotate(localPos.xy, inAngle, rotMatrix);\n localPos.yz = rotate(localPos.yz, inAngle, rotMatrix);\n\n billboard(particlePos, quadXY);\n",particle_normalVS:"\n Normal = normalize(localPos + matrix_viewInverse[2].xyz);\n",particle_normalMapPS:"\n vec3 normalMap = normalize(texture2D(normalMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y)).xyz * 2.0 - 1.0);\n vec3 normal = ParticleMat * normalMap;\n",particle_pointAlongVS:"\n inAngle = atan(velocityV.x, velocityV.y); // not the fastest way, but easier to plug in; TODO: create rot matrix right from vectors\n\n",particle_softPS:"\n float depth = getLinearScreenDepth();\n float particleDepth = vDepth;\n float depthDiff = saturate(abs(particleDepth - depth) * softening);\n a *= depthDiff;\n",particle_softVS:"\n vDepth = getLinearDepth(localPos);\n",particle_stretchVS:"\n vec3 moveDir = inVel * stretch;\n vec3 posPrev = particlePos - moveDir;\n posPrev += particlePosMoved;\n\n vec2 centerToVertexV = normalize((mat3(matrix_view) * localPos).xy);\n\n float interpolation = dot(-velocityV, centerToVertexV) * 0.5 + 0.5;\n\n particlePos = mix(particlePos, posPrev, interpolation);\n",particle_TBNVS:"\n mat3 rot3 = mat3(rotMatrix[0][0], rotMatrix[0][1], 0.0, rotMatrix[1][0], rotMatrix[1][1], 0.0, 0.0, 0.0, 1.0);\n ParticleMat = mat3(-matrix_viewInverse[0].xyz, -matrix_viewInverse[1].xyz, matrix_viewInverse[2].xyz) * rot3;\n",particle_wrapVS:"\n vec3 origParticlePos = particlePos;\n particlePos -= matrix_model[3].xyz;\n particlePos = mod(particlePos, wrapBounds) - wrapBounds * 0.5;\n particlePos += matrix_model[3].xyz;\n particlePosMoved = particlePos - origParticlePos;\n",precisionTestPS:"\nvoid main(void) {\n gl_FragColor = vec4(2147483648.0);\n}\n",precisionTest2PS:"\nuniform sampler2D source;\n\nvec4 packFloat(float depth) {\n const vec4 bit_shift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);\n\n vec4 res = mod(depth * bit_shift * vec4(255), vec4(256) ) / vec4(255);\n res -= res.xxyz * bit_mask;\n return res;\n}\n\nvoid main(void) {\n float c = texture2D(source, vec2(0.0)).r;\n float diff = abs(c - 2147483648.0) / 2147483648.0;\n gl_FragColor = packFloat(diff);\n}\n",reflDirPS:"\nvoid getReflDir() {\n dReflDirW = normalize(-reflect(dViewDirW, dNormalW));\n}\n",reflDirAnisoPS:"\nvoid getReflDir() {\n float roughness = sqrt(1.0 - min(dGlossiness, 1.0));\n float anisotropy = material_anisotropy * roughness;\n vec3 anisotropicDirection = anisotropy >= 0.0 ? dTBN[1] : dTBN[0];\n vec3 anisotropicTangent = cross(anisotropicDirection, dViewDirW);\n vec3 anisotropicNormal = cross(anisotropicTangent, anisotropicDirection);\n vec3 bentNormal = normalize(mix(normalize(dNormalW), normalize(anisotropicNormal), anisotropy));\n dReflDirW = reflect(-dViewDirW, bentNormal);\n}\n",reflectionCCPS:"\n#ifdef LIT_CLEARCOAT\nvoid addReflectionCC() {\n ccReflection += calcReflection(ccReflDirW, ccGlossiness);\n}\n#endif\n",reflectionCubePS:"\nuniform samplerCube texture_cubeMap;\nuniform float material_reflectivity;\n\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n vec3 lookupVec = fixSeams(cubeMapProject(tReflDirW));\n lookupVec.x *= -1.0;\n return $DECODE(textureCube(texture_cubeMap, lookupVec));\n}\n\nvoid addReflection() { \n dReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionEnvHQPS:"\n#ifndef ENV_ATLAS\n#define ENV_ATLAS\nuniform sampler2D texture_envAtlas;\n#endif\nuniform samplerCube texture_cubeMap;\nuniform float material_reflectivity;\n\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n vec3 dir = cubeMapProject(tReflDirW) * vec3(-1.0, 1.0, 1.0);\n vec2 uv = toSphericalUv(dir);\n\n // calculate roughness level\n float level = saturate(1.0 - tGlossiness) * 5.0;\n float ilevel = floor(level);\n float flevel = level - ilevel;\n\n vec3 sharp = $DECODE(textureCube(texture_cubeMap, fixSeams(dir)));\n vec3 roughA = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel)));\n vec3 roughB = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0)));\n\n return processEnvironment(mix(sharp, mix(roughA, roughB, flevel), min(level, 1.0)));\n}\n\nvoid addReflection() { \n dReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionEnvPS:"\n#ifndef ENV_ATLAS\n#define ENV_ATLAS\nuniform sampler2D texture_envAtlas;\n#endif\nuniform float material_reflectivity;\n\n// calculate mip level for shiny reflection given equirect coords uv.\nfloat shinyMipLevel(vec2 uv) {\n vec2 dx = dFdx(uv);\n vec2 dy = dFdy(uv);\n\n // calculate second dF at 180 degrees\n vec2 uv2 = vec2(fract(uv.x + 0.5), uv.y);\n vec2 dx2 = dFdx(uv2);\n vec2 dy2 = dFdy(uv2);\n\n // calculate min of both sets of dF to handle discontinuity at the azim edge\n float maxd = min(max(dot(dx, dx), dot(dy, dy)), max(dot(dx2, dx2), dot(dy2, dy2)));\n\n return clamp(0.5 * log2(maxd) - 1.0 + textureBias, 0.0, 5.0);\n}\n\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n vec3 dir = cubeMapProject(tReflDirW) * vec3(-1.0, 1.0, 1.0);\n vec2 uv = toSphericalUv(dir);\n\n // calculate roughness level\n float level = saturate(1.0 - tGlossiness) * 5.0;\n float ilevel = floor(level);\n\n // accessing the shiny (top level) reflection - perform manual mipmap lookup\n float level2 = shinyMipLevel(uv * atlasSize);\n float ilevel2 = floor(level2);\n\n vec2 uv0, uv1;\n float weight;\n if (ilevel == 0.0) {\n uv0 = mapShinyUv(uv, ilevel2);\n uv1 = mapShinyUv(uv, ilevel2 + 1.0);\n weight = level2 - ilevel2;\n } else {\n // accessing rough reflection - just sample the same part twice\n uv0 = uv1 = mapRoughnessUv(uv, ilevel);\n weight = 0.0;\n }\n\n vec3 linearA = $DECODE(texture2D(texture_envAtlas, uv0));\n vec3 linearB = $DECODE(texture2D(texture_envAtlas, uv1));\n vec3 linear0 = mix(linearA, linearB, weight);\n vec3 linear1 = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0)));\n\n return processEnvironment(mix(linear0, linear1, level - ilevel));\n}\n\nvoid addReflection() { \n dReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionSpherePS:"\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nuniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\n\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n vec3 reflDirV = (mat3(matrix_view) * tReflDirW).xyz;\n\n float m = 2.0 * sqrt( dot(reflDirV.xy, reflDirV.xy) + (reflDirV.z+1.0)*(reflDirV.z+1.0) );\n vec2 sphereMapUv = reflDirV.xy / m + 0.5;\n\n return $DECODE(texture2D(texture_sphereMap, sphereMapUv));\n}\n\nvoid addReflection() { \n dReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionSphereLowPS:"\nuniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\n\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n vec3 reflDirV = vNormalV;\n\n vec2 sphereMapUv = reflDirV.xy * 0.5 + 0.5;\n return $DECODE(texture2D(texture_sphereMap, sphereMapUv));\n}\n\nvoid addReflection() { \n dReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionSheenPS:"\n\nvoid addReflectionSheen() {\n float NoV = dot(dNormalW, dViewDirW);\n float alphaG = sGlossiness * sGlossiness;\n\n // Avoid using a LUT and approximate the values analytically\n float a = sGlossiness < 0.25 ? -339.2 * alphaG + 161.4 * sGlossiness - 25.9 : -8.48 * alphaG + 14.3 * sGlossiness - 9.95;\n float b = sGlossiness < 0.25 ? 44.0 * alphaG - 23.7 * sGlossiness + 3.26 : 1.97 * alphaG - 3.27 * sGlossiness + 0.72;\n float DG = exp( a * NoV + b ) + ( sGlossiness < 0.25 ? 0.0 : 0.1 * ( sGlossiness - 0.25 ) );\n sReflection += calcReflection(dNormalW, 0.0) * saturate(DG);\n}\n",refractionCubePS:"\nuniform float material_refractionIndex;\n\nvec3 refract2(vec3 viewVec, vec3 Normal, float IOR) {\n float vn = dot(viewVec, Normal);\n float k = 1.0 - IOR * IOR * (1.0 - vn * vn);\n vec3 refrVec = IOR * viewVec - (IOR * vn + sqrt(k)) * Normal;\n return refrVec;\n}\n\nvoid addRefraction() {\n // use same reflection code with refraction vector\n vec3 tmpDir = dReflDirW;\n vec4 tmpRefl = dReflection;\n dReflDirW = refract2(-dViewDirW, dNormalW, material_refractionIndex);\n dReflection = vec4(0);\n addReflection();\n dDiffuseLight = mix(dDiffuseLight, dReflection.rgb * dAlbedo, dTransmission);\n dReflection = tmpRefl;\n dReflDirW = tmpDir;\n}\n",refractionDynamicPS:"\nuniform float material_refractionIndex;\nuniform float material_invAttenuationDistance;\nuniform vec3 material_attenuation;\n\nvec3 refract2(vec3 viewVec, vec3 Normal, float IOR) {\n float vn = dot(viewVec, Normal);\n float k = 1.0 - IOR * IOR * (1.0 - vn * vn);\n vec3 refrVec = IOR * viewVec - (IOR * vn + sqrt(k)) * Normal;\n return refrVec;\n}\n\nvoid addRefraction() {\n\n // Extract scale from the model transform\n vec3 modelScale;\n modelScale.x = length(vec3(matrix_model[0].xyz));\n modelScale.y = length(vec3(matrix_model[1].xyz));\n modelScale.z = length(vec3(matrix_model[2].xyz));\n\n // Calculate the refraction vector, scaled by the thickness and scale of the object\n vec3 refractionVector = normalize(refract(-dViewDirW, dNormalW, material_refractionIndex)) * dThickness * modelScale;\n\n // The refraction point is the entry point + vector to exit point\n vec4 pointOfRefraction = vec4(vPositionW + refractionVector, 1.0);\n\n // Project to texture space so we can sample it\n vec4 projectionPoint = matrix_viewProjection * pointOfRefraction;\n vec2 uv = projectionPoint.xy / projectionPoint.ww;\n uv += vec2(1.0);\n uv *= vec2(0.5);\n\n #ifdef GL2\n // Use IOR and roughness to select mip\n float iorToRoughness = (1.0 - dGlossiness) * clamp((1.0 / material_refractionIndex) * 2.0 - 2.0, 0.0, 1.0);\n float refractionLod = log2(uScreenSize.x) * iorToRoughness;\n vec3 refraction = texture2DLodEXT(uSceneColorMap, uv, refractionLod).rgb;\n #else\n vec3 refraction = texture2D(uSceneColorMap, uv).rgb;\n #endif\n\n // Transmittance is our final refraction color\n vec3 transmittance;\n if (material_invAttenuationDistance != 0.0)\n {\n vec3 attenuation = -log(material_attenuation) * material_invAttenuationDistance;\n transmittance = exp(-attenuation * length(refractionVector));\n }\n else\n {\n transmittance = refraction;\n }\n\n // Apply fresnel effect on refraction\n vec3 fresnel = vec3(1.0) - getFresnel(dot(dViewDirW, dNormalW), dSpecularity);\n dDiffuseLight = mix(dDiffuseLight, refraction * transmittance * fresnel, dTransmission);\n}\n",reprojectPS:'\n// This shader requires the following #DEFINEs:\n//\n// PROCESS_FUNC - must be one of reproject, prefilter\n// DECODE_FUNC - must be one of decodeRGBM, decodeRGBE, decodeGamma or decodeLinear\n// ENCODE_FUNC - must be one of encodeRGBM, encodeRGBE, encideGamma or encodeLinear\n// SOURCE_FUNC - must be one of sampleCubemap, sampleEquirect, sampleOctahedral\n// TARGET_FUNC - must be one of getDirectionCubemap, getDirectionEquirect, getDirectionOctahedral\n//\n// When filtering:\n// NUM_SAMPLES - number of samples\n// NUM_SAMPLES_SQRT - sqrt of number of samples\n//\n// SUPPORTS_TEXLOD - whether supports texlod is supported\n\nvarying vec2 vUv0;\n\n// source\nuniform sampler2D sourceTex;\nuniform samplerCube sourceCube;\n\n// samples\nuniform sampler2D samplesTex;\nuniform vec2 samplesTexInverseSize;\n\n// params:\n// x - target cubemap face 0..6\n// y - specular power (when prefiltering)\n// z - source cubemap seam scale (0 to disable)\n// w - target cubemap size for seam calc (0 to disable)\nuniform vec4 params;\n\n// params2:\n// x - target image total pixels\n// y - source cubemap size\nuniform vec2 params2;\n\nfloat targetFace() { return params.x; }\nfloat specularPower() { return params.y; }\nfloat sourceCubeSeamScale() { return params.z; }\nfloat targetCubeSeamScale() { return params.w; }\n\nfloat targetTotalPixels() { return params2.x; }\nfloat sourceTotalPixels() { return params2.y; }\n\nfloat PI = 3.141592653589793;\n\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n\n\nvec3 decodeLinear(vec4 raw) {\n return raw.rgb;\n}\n\nfloat decodeGamma(float raw) {\n return pow(raw, 2.2);\n}\n\nvec3 decodeGamma(vec3 raw) {\n return pow(raw, vec3(2.2));\n}\n\nvec3 decodeGamma(vec4 raw) {\n return pow(raw.xyz, vec3(2.2));\n}\n\nvec3 decodeRGBM(vec4 raw) {\n vec3 color = (8.0 * raw.a) * raw.rgb;\n return color * color;\n}\n\nvec3 decodeRGBP(vec4 raw) {\n vec3 color = raw.rgb * (-raw.a * 7.0 + 8.0);\n return color * color;\n}\n\nvec3 decodeRGBE(vec4 raw) {\n if (raw.a == 0.0) {\n return vec3(0.0, 0.0, 0.0);\n } else {\n return raw.xyz * pow(2.0, raw.w * 255.0 - 128.0);\n }\n}\n\nvec4 passThrough(vec4 raw) {\n return raw;\n}\n\n\nvec4 encodeLinear(vec3 source) {\n return vec4(source, 1.0);\n}\n\nvec4 encodeGamma(vec3 source) {\n return vec4(pow(source + 0.0000001, vec3(1.0 / 2.2)), 1.0);\n}\n\nvec4 encodeRGBM(vec3 source) { // modified RGBM\n vec4 result;\n result.rgb = pow(source.rgb, vec3(0.5));\n result.rgb *= 1.0 / 8.0;\n\n result.a = saturate( max( max( result.r, result.g ), max( result.b, 1.0 / 255.0 ) ) );\n result.a = ceil(result.a * 255.0) / 255.0;\n\n result.rgb /= result.a;\n return result;\n}\n\nvec4 encodeRGBP(vec3 source) {\n // convert incoming linear to gamma(ish)\n vec3 gamma = pow(source, vec3(0.5));\n\n // calculate the maximum component clamped to 1..8\n float maxVal = min(8.0, max(1.0, max(gamma.x, max(gamma.y, gamma.z))));\n\n // calculate storage factor\n float v = 1.0 - ((maxVal - 1.0) / 7.0);\n\n // round the value for storage in 8bit channel\n v = ceil(v * 255.0) / 255.0;\n\n return vec4(gamma / (-v * 7.0 + 8.0), v); \n}\n\nvec4 encodeRGBE(vec3 source) {\n float maxVal = max(source.x, max(source.y, source.z));\n if (maxVal < 1e-32) {\n return vec4(0, 0, 0, 0);\n } else {\n float e = ceil(log2(maxVal));\n return vec4(source / pow(2.0, e), (e + 128.0) / 255.0);\n }\n}\n\n\n//-- supported projections\n\nvec3 modifySeams(vec3 dir, float scale) {\n vec3 adir = abs(dir);\n float M = max(max(adir.x, adir.y), adir.z);\n return dir / M * vec3(\n adir.x == M ? 1.0 : scale,\n adir.y == M ? 1.0 : scale,\n adir.z == M ? 1.0 : scale\n );\n}\n\nvec2 toSpherical(vec3 dir) {\n return vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y));\n}\n\nvec3 fromSpherical(vec2 uv) {\n return vec3(cos(uv.y) * sin(uv.x),\n sin(uv.y),\n cos(uv.y) * cos(uv.x));\n}\n\nvec3 getDirectionEquirect() {\n return fromSpherical((vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0) * vec2(PI, PI * 0.5));\n}\n\nvec4 sampleEquirect(vec2 sph) {\n vec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;\n return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n}\n\nvec4 sampleEquirect(vec3 dir) {\n return sampleEquirect(toSpherical(dir));\n}\n\nvec4 sampleCubemap(vec3 dir) {\n return textureCube(sourceCube, modifySeams(dir, 1.0 - sourceCubeSeamScale()));\n}\n\nvec4 sampleCubemap(vec2 sph) {\n return sampleCubemap(fromSpherical(sph));\n}\n\nvec4 sampleEquirect(vec2 sph, float mipLevel) {\n vec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;\n#ifdef SUPPORTS_TEXLOD\n return texture2DLodEXT(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);\n#else\n return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n#endif\n}\n\nvec4 sampleEquirect(vec3 dir, float mipLevel) {\n return sampleEquirect(toSpherical(dir), mipLevel);\n}\n\nvec4 sampleCubemap(vec3 dir, float mipLevel) {\n#ifdef SUPPORTS_TEXLOD\n return textureCubeLodEXT(sourceCube, modifySeams(dir, 1.0 - exp2(mipLevel) * sourceCubeSeamScale()), mipLevel);\n#else\n return textureCube(sourceCube, modifySeams(dir, 1.0 - exp2(mipLevel) * sourceCubeSeamScale()));\n#endif\n}\n\nvec4 sampleCubemap(vec2 sph, float mipLevel) {\n return sampleCubemap(fromSpherical(sph), mipLevel);\n}\n\n// octahedral code, based on http://jcgt.org/published/0003/02/01\n// "Survey of Efficient Representations for Independent Unit Vectors" by Cigolle, Donow, Evangelakos, Mara, McGuire, Meyer\n\nfloat signNotZero(float k){\n return(k >= 0.0) ? 1.0 : -1.0;\n}\n\nvec2 signNotZero(vec2 v) {\n return vec2(signNotZero(v.x), signNotZero(v.y));\n}\n\n// Returns a unit vector. Argument o is an octahedral vector packed via octEncode, on the [-1, +1] square\nvec3 octDecode(vec2 o) {\n vec3 v = vec3(o.x, 1.0 - abs(o.x) - abs(o.y), o.y);\n if (v.y < 0.0) {\n v.xz = (1.0 - abs(v.zx)) * signNotZero(v.xz);\n }\n return normalize(v);\n}\n\nvec3 getDirectionOctahedral() {\n return octDecode(vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0);\n}\n\n// Assumes that v is a unit vector. The result is an octahedral vector on the [-1, +1] square\nvec2 octEncode(in vec3 v) {\n float l1norm = abs(v.x) + abs(v.y) + abs(v.z);\n vec2 result = v.xz * (1.0 / l1norm);\n if (v.y < 0.0) {\n result = (1.0 - abs(result.yx)) * signNotZero(result.xy);\n }\n return result;\n}\n\nvec4 sampleOctahedral(vec3 dir) {\n vec2 uv = octEncode(dir) * 0.5 + 0.5;\n return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n}\n\nvec4 sampleOctahedral(vec2 sph) {\n return sampleOctahedral(fromSpherical(sph));\n}\n\nvec4 sampleOctahedral(vec3 dir, float mipLevel) {\n vec2 uv = octEncode(dir) * 0.5 + 0.5;\n#ifdef SUPPORTS_TEXLOD\n return texture2DLodEXT(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);\n#else\n return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n#endif\n}\n\nvec4 sampleOctahedral(vec2 sph, float mipLevel) {\n return sampleOctahedral(fromSpherical(sph), mipLevel);\n}\n\n/////////////////////////////////////////////////////////////////////\n\nvec3 getDirectionCubemap() {\n vec2 st = vUv0 * 2.0 - 1.0;\n float face = targetFace();\n\n vec3 vec;\n if (face == 0.0) {\n vec = vec3(1, -st.y, -st.x);\n } else if (face == 1.0) {\n vec = vec3(-1, -st.y, st.x);\n } else if (face == 2.0) {\n vec = vec3(st.x, 1, st.y);\n } else if (face == 3.0) {\n vec = vec3(st.x, -1, -st.y);\n } else if (face == 4.0) {\n vec = vec3(st.x, -st.y, 1);\n } else {\n vec = vec3(-st.x, -st.y, -1);\n }\n\n return normalize(modifySeams(vec, 1.0 / (1.0 - targetCubeSeamScale())));\n}\n\nmat3 matrixFromVector(vec3 n) { // frisvad\n float a = 1.0 / (1.0 + n.z);\n float b = -n.x * n.y * a;\n vec3 b1 = vec3(1.0 - n.x * n.x * a, b, -n.x);\n vec3 b2 = vec3(b, 1.0 - n.y * n.y * a, -n.y);\n return mat3(b1, b2, n);\n}\n\nmat3 matrixFromVectorSlow(vec3 n) {\n vec3 up = (1.0 - abs(n.y) <= 0.0000001) ? vec3(0.0, 0.0, n.y > 0.0 ? 1.0 : -1.0) : vec3(0.0, 1.0, 0.0);\n vec3 x = normalize(cross(up, n));\n vec3 y = cross(n, x);\n return mat3(x, y, n);\n}\n\nvec4 reproject() {\n if (NUM_SAMPLES <= 1) {\n // single sample\n return ENCODE_FUNC(DECODE_FUNC(SOURCE_FUNC(TARGET_FUNC())));\n } else {\n // multi sample\n vec3 t = TARGET_FUNC();\n vec3 tu = dFdx(t);\n vec3 tv = dFdy(t);\n\n vec3 result = vec3(0.0);\n for (float u = 0.0; u < NUM_SAMPLES_SQRT; ++u) {\n for (float v = 0.0; v < NUM_SAMPLES_SQRT; ++v) {\n result += DECODE_FUNC(SOURCE_FUNC(normalize(t +\n tu * (u / NUM_SAMPLES_SQRT - 0.5) +\n tv * (v / NUM_SAMPLES_SQRT - 0.5))));\n }\n }\n return ENCODE_FUNC(result / (NUM_SAMPLES_SQRT * NUM_SAMPLES_SQRT));\n }\n}\n\nvec4 unpackFloat = vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0);\n\nvoid unpackSample(int i, out vec3 L, out float mipLevel) {\n float u = (float(i * 4) + 0.5) * samplesTexInverseSize.x;\n float v = (floor(u) + 0.5) * samplesTexInverseSize.y;\n\n vec4 raw;\n raw.x = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n raw.y = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n raw.z = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n raw.w = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat);\n\n L.xyz = raw.xyz * 2.0 - 1.0;\n mipLevel = raw.w * 8.0;\n}\n\n// convolve an environment given pre-generated samples\nvec4 prefilterSamples() {\n // construct vector space given target direction\n mat3 vecSpace = matrixFromVectorSlow(TARGET_FUNC());\n\n vec3 L;\n float mipLevel;\n\n vec3 result = vec3(0.0);\n float totalWeight = 0.0;\n for (int i = 0; i < NUM_SAMPLES; ++i) {\n unpackSample(i, L, mipLevel);\n result += DECODE_FUNC(SOURCE_FUNC(vecSpace * L, mipLevel)) * L.z;\n totalWeight += L.z;\n }\n\n return ENCODE_FUNC(result / totalWeight);\n}\n\n// unweighted version of prefilterSamples\nvec4 prefilterSamplesUnweighted() {\n // construct vector space given target direction\n mat3 vecSpace = matrixFromVectorSlow(TARGET_FUNC());\n\n vec3 L;\n float mipLevel;\n\n vec3 result = vec3(0.0);\n float totalWeight = 0.0;\n for (int i = 0; i < NUM_SAMPLES; ++i) {\n unpackSample(i, L, mipLevel);\n result += DECODE_FUNC(SOURCE_FUNC(vecSpace * L, mipLevel));\n }\n\n return ENCODE_FUNC(result / float(NUM_SAMPLES));\n}\n\nvoid main(void) {\n gl_FragColor = PROCESS_FUNC();\n}\n',screenDepthPS:"\nuniform highp sampler2D uSceneDepthMap;\n\n#ifndef SCREENSIZE\n#define SCREENSIZE\nuniform vec4 uScreenSize;\n#endif\n\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n\n\n\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params; // 1 / camera_far, camera_far, camera_near, is_ortho\n#endif\n\n#ifdef GL2\nfloat linearizeDepth(float z) {\n if (camera_params.w == 0.0)\n return (camera_params.z * camera_params.y) / (camera_params.y + z * (camera_params.z - camera_params.y));\n else\n return camera_params.z + z * (camera_params.y - camera_params.z);\n}\n#else\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n const vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n return dot(rgbaDepth, bitShift);\n}\n#endif\n#endif\n\n// Retrieves rendered linear camera depth by UV\nfloat getLinearScreenDepth(vec2 uv) {\n #ifdef GL2\n return linearizeDepth(texture2D(uSceneDepthMap, uv).r);\n #else\n return unpackFloat(texture2D(uSceneDepthMap, uv)) * camera_params.y;\n #endif\n}\n\n#ifndef VERTEXSHADER\n// Retrieves rendered linear camera depth under the current pixel\nfloat getLinearScreenDepth() {\n vec2 uv = gl_FragCoord.xy * uScreenSize.zw;\n return getLinearScreenDepth(uv);\n}\n#endif\n\n// Generates linear camera depth for the given world position\nfloat getLinearDepth(vec3 pos) {\n return -(matrix_view * vec4(pos, 1.0)).z;\n}\n",shadowCascadesPS:"\nconst float maxCascades = 4.0;\n\n// shadow matrix for selected cascade\nmat4 cascadeShadowMat;\n\n// function which selects a shadow projection matrix based on cascade distances \nvoid getShadowCascadeMatrix(mat4 shadowMatrixPalette[4], float shadowCascadeDistances[4], float shadowCascadeCount) {\n\n // depth in 0 .. far plane range\n float depth = 1.0 / gl_FragCoord.w;\n\n // find cascade index based on the depth (loop as there is no per component vec compare operator in webgl)\n float cascadeIndex = 0.0;\n for (float i = 0.0; i < maxCascades; i++) {\n if (depth < shadowCascadeDistances[int(i)]) {\n cascadeIndex = i;\n break;\n }\n }\n\n // limit to actual number of used cascades\n cascadeIndex = min(cascadeIndex, shadowCascadeCount - 1.0);\n\n // pick shadow matrix\n #ifdef GL2\n cascadeShadowMat = shadowMatrixPalette[int(cascadeIndex)];\n #else\n // webgl 1 does not allow non-cost index array lookup\n if (cascadeIndex == 0.0) {\n cascadeShadowMat = shadowMatrixPalette[0];\n }\n else if (cascadeIndex == 1.0) {\n cascadeShadowMat = shadowMatrixPalette[1];\n }\n else if (cascadeIndex == 2.0) {\n cascadeShadowMat = shadowMatrixPalette[2];\n }\n else {\n cascadeShadowMat = shadowMatrixPalette[3];\n }\n #endif\n}\n\nvoid fadeShadow(float shadowCascadeDistances[4]) { \n\n // if the pixel is past the shadow distance, remove shadow\n // this enforces straight line instead of corner of shadow which moves when camera rotates \n float depth = 1.0 / gl_FragCoord.w;\n if (depth > shadowCascadeDistances[int(maxCascades - 1.0)]) {\n dShadowCoord.z = -9999999.0;\n }\n}\n",shadowCommonPS:"\nvoid normalOffsetPointShadow(vec4 shadowParams) {\n float distScale = length(dLightDirW);\n vec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0) * distScale; //0.02\n vec3 dir = wPos - dLightPosW;\n dLightDirW = dir;\n}\n",shadowCoordPS:"\nvoid _getShadowCoordOrtho(mat4 shadowMatrix, vec3 shadowParams, vec3 wPos) {\n dShadowCoord = (shadowMatrix * vec4(wPos, 1.0)).xyz;\n dShadowCoord.z = saturate(dShadowCoord.z) - 0.0001;\n\n #ifdef SHADOWBIAS\n dShadowCoord.z += getShadowBias(shadowParams.x, shadowParams.z);\n #endif\n}\n\nvoid _getShadowCoordPersp(mat4 shadowMatrix, vec4 shadowParams, vec3 wPos) {\n vec4 projPos = shadowMatrix * vec4(wPos, 1.0);\n projPos.xy /= projPos.w;\n dShadowCoord.xy = projPos.xy;\n dShadowCoord.z = length(dLightDirW) * shadowParams.w;\n\n #ifdef SHADOWBIAS\n dShadowCoord.z += getShadowBias(shadowParams.x, shadowParams.z);\n #endif\n}\n\nvoid getShadowCoordOrtho(mat4 shadowMatrix, vec3 shadowParams) {\n _getShadowCoordOrtho(shadowMatrix, shadowParams, vPositionW);\n}\n\nvoid getShadowCoordPersp(mat4 shadowMatrix, vec4 shadowParams) {\n _getShadowCoordPersp(shadowMatrix, shadowParams, vPositionW);\n}\n\nvoid getShadowCoordPerspNormalOffset(mat4 shadowMatrix, vec4 shadowParams) {\n float distScale = abs(dot(vPositionW - dLightPosW, dLightDirNormW)); // fov?\n vec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0) * distScale;\n\n _getShadowCoordPersp(shadowMatrix, shadowParams, wPos);\n}\n\nvoid getShadowCoordOrthoNormalOffset(mat4 shadowMatrix, vec3 shadowParams) {\n vec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0); //0.08\n\n _getShadowCoordOrtho(shadowMatrix, shadowParams, wPos);\n}\n",shadowCoordPerspZbufferPS:"\nvoid _getShadowCoordPerspZbuffer(mat4 shadowMatrix, vec4 shadowParams, vec3 wPos) {\n vec4 projPos = shadowMatrix * vec4(wPos, 1.0);\n projPos.xyz /= projPos.w;\n dShadowCoord = projPos.xyz;\n // depth bias is already applied on render\n}\n\nvoid getShadowCoordPerspZbufferNormalOffset(mat4 shadowMatrix, vec4 shadowParams) {\n vec3 wPos = vPositionW + dVertexNormalW * shadowParams.y;\n _getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, wPos);\n}\n\nvoid getShadowCoordPerspZbuffer(mat4 shadowMatrix, vec4 shadowParams) {\n _getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, vPositionW);\n}\n",shadowEVSMPS:"\nfloat VSM$(sampler2D tex, vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n vec3 moments = texture2D(tex, texCoords).xyz;\n return calculateEVSM(moments, Z, vsmBias, exponent);\n}\n\nfloat getShadowVSM$(sampler2D shadowMap, vec3 shadowParams, float exponent) {\n return VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, dShadowCoord.z, shadowParams.y, exponent);\n}\n\nfloat getShadowSpotVSM$(sampler2D shadowMap, vec4 shadowParams, float exponent) {\n return VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, length(dLightDirW) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);\n}\n",shadowEVSMnPS:"\nfloat VSM$(sampler2D tex, vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n float pixelSize = 1.0 / resolution;\n texCoords -= vec2(pixelSize);\n vec3 s00 = texture2D(tex, texCoords).xyz;\n vec3 s10 = texture2D(tex, texCoords + vec2(pixelSize, 0)).xyz;\n vec3 s01 = texture2D(tex, texCoords + vec2(0, pixelSize)).xyz;\n vec3 s11 = texture2D(tex, texCoords + vec2(pixelSize)).xyz;\n vec2 fr = fract(texCoords * resolution);\n vec3 h0 = mix(s00, s10, fr.x);\n vec3 h1 = mix(s01, s11, fr.x);\n vec3 moments = mix(h0, h1, fr.y);\n return calculateEVSM(moments, Z, vsmBias, exponent);\n}\n\nfloat getShadowVSM$(sampler2D shadowMap, vec3 shadowParams, float exponent) {\n return VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, dShadowCoord.z, shadowParams.y, exponent);\n}\n\nfloat getShadowSpotVSM$(sampler2D shadowMap, vec4 shadowParams, float exponent) {\n return VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, length(dLightDirW) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);\n}\n",shadowStandardPS:"\nvec3 lessThan2(vec3 a, vec3 b) {\n return clamp((b - a)*1000.0, 0.0, 1.0); // softer version\n}\n\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n const vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n return dot(rgbaDepth, bitShift);\n}\n#endif\n\n// ----- Direct/Spot Sampling -----\n\n#ifdef GL2\nfloat _getShadowPCF3x3(sampler2DShadow shadowMap, vec3 shadowParams) {\n float z = dShadowCoord.z;\n vec2 uv = dShadowCoord.xy * shadowParams.x; // 1 unit - 1 texel\n float shadowMapSizeInv = 1.0 / shadowParams.x;\n vec2 base_uv = floor(uv + 0.5);\n float s = (uv.x + 0.5 - base_uv.x);\n float t = (uv.y + 0.5 - base_uv.y);\n base_uv -= vec2(0.5);\n base_uv *= shadowMapSizeInv;\n\n float sum = 0.0;\n\n float uw0 = (3.0 - 2.0 * s);\n float uw1 = (1.0 + 2.0 * s);\n\n float u0 = (2.0 - s) / uw0 - 1.0;\n float u1 = s / uw1 + 1.0;\n\n float vw0 = (3.0 - 2.0 * t);\n float vw1 = (1.0 + 2.0 * t);\n\n float v0 = (2.0 - t) / vw0 - 1.0;\n float v1 = t / vw1 + 1.0;\n\n u0 = u0 * shadowMapSizeInv + base_uv.x;\n v0 = v0 * shadowMapSizeInv + base_uv.y;\n\n u1 = u1 * shadowMapSizeInv + base_uv.x;\n v1 = v1 * shadowMapSizeInv + base_uv.y;\n\n sum += uw0 * vw0 * texture(shadowMap, vec3(u0, v0, z));\n sum += uw1 * vw0 * texture(shadowMap, vec3(u1, v0, z));\n sum += uw0 * vw1 * texture(shadowMap, vec3(u0, v1, z));\n sum += uw1 * vw1 * texture(shadowMap, vec3(u1, v1, z));\n\n sum *= 1.0f / 16.0;\n return sum;\n}\n\nfloat getShadowPCF3x3(sampler2DShadow shadowMap, vec3 shadowParams) {\n return _getShadowPCF3x3(shadowMap, shadowParams);\n}\n\nfloat getShadowSpotPCF3x3(sampler2DShadow shadowMap, vec4 shadowParams) {\n return _getShadowPCF3x3(shadowMap, shadowParams.xyz);\n}\n#else\nfloat _xgetShadowPCF3x3(mat3 depthKernel, sampler2D shadowMap, vec3 shadowParams) {\n mat3 shadowKernel;\n vec3 shadowCoord = dShadowCoord;\n vec3 shadowZ = vec3(shadowCoord.z);\n shadowKernel[0] = vec3(greaterThan(depthKernel[0], shadowZ));\n shadowKernel[1] = vec3(greaterThan(depthKernel[1], shadowZ));\n shadowKernel[2] = vec3(greaterThan(depthKernel[2], shadowZ));\n\n vec2 fractionalCoord = fract( shadowCoord.xy * shadowParams.x );\n\n shadowKernel[0] = mix(shadowKernel[0], shadowKernel[1], fractionalCoord.x);\n shadowKernel[1] = mix(shadowKernel[1], shadowKernel[2], fractionalCoord.x);\n\n vec4 shadowValues;\n shadowValues.x = mix(shadowKernel[0][0], shadowKernel[0][1], fractionalCoord.y);\n shadowValues.y = mix(shadowKernel[0][1], shadowKernel[0][2], fractionalCoord.y);\n shadowValues.z = mix(shadowKernel[1][0], shadowKernel[1][1], fractionalCoord.y);\n shadowValues.w = mix(shadowKernel[1][1], shadowKernel[1][2], fractionalCoord.y);\n\n return dot( shadowValues, vec4( 1.0 ) ) * 0.25;\n}\n\nfloat _getShadowPCF3x3(sampler2D shadowMap, vec3 shadowParams) {\n vec3 shadowCoord = dShadowCoord;\n\n float xoffset = 1.0 / shadowParams.x; // 1/shadow map width\n float dx0 = -xoffset;\n float dx1 = xoffset;\n\n mat3 depthKernel;\n depthKernel[0][0] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx0, dx0)));\n depthKernel[0][1] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx0, 0.0)));\n depthKernel[0][2] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx0, dx1)));\n depthKernel[1][0] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(0.0, dx0)));\n depthKernel[1][1] = unpackFloat(texture2D(shadowMap, shadowCoord.xy));\n depthKernel[1][2] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(0.0, dx1)));\n depthKernel[2][0] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx1, dx0)));\n depthKernel[2][1] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx1, 0.0)));\n depthKernel[2][2] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx1, dx1)));\n\n return _xgetShadowPCF3x3(depthKernel, shadowMap, shadowParams);\n}\n\nfloat getShadowPCF3x3(sampler2D shadowMap, vec3 shadowParams) {\n return _getShadowPCF3x3(shadowMap, shadowParams);\n}\n\nfloat getShadowSpotPCF3x3(sampler2D shadowMap, vec4 shadowParams) {\n return _getShadowPCF3x3(shadowMap, shadowParams.xyz);\n}\n#endif\n\n\n// ----- Omni Sampling -----\n\nfloat _getShadowPoint(samplerCube shadowMap, vec4 shadowParams, vec3 dir) {\n\n vec3 tc = normalize(dir);\n vec3 tcAbs = abs(tc);\n\n vec4 dirX = vec4(1,0,0, tc.x);\n vec4 dirY = vec4(0,1,0, tc.y);\n float majorAxisLength = tc.z;\n if ((tcAbs.x > tcAbs.y) && (tcAbs.x > tcAbs.z)) {\n dirX = vec4(0,0,1, tc.z);\n dirY = vec4(0,1,0, tc.y);\n majorAxisLength = tc.x;\n } else if ((tcAbs.y > tcAbs.x) && (tcAbs.y > tcAbs.z)) {\n dirX = vec4(1,0,0, tc.x);\n dirY = vec4(0,0,1, tc.z);\n majorAxisLength = tc.y;\n }\n\n float shadowParamsInFaceSpace = ((1.0/shadowParams.x) * 2.0) * abs(majorAxisLength);\n\n vec3 xoffset = (dirX.xyz * shadowParamsInFaceSpace);\n vec3 yoffset = (dirY.xyz * shadowParamsInFaceSpace);\n vec3 dx0 = -xoffset;\n vec3 dy0 = -yoffset;\n vec3 dx1 = xoffset;\n vec3 dy1 = yoffset;\n\n mat3 shadowKernel;\n mat3 depthKernel;\n\n depthKernel[0][0] = unpackFloat(textureCube(shadowMap, tc + dx0 + dy0));\n depthKernel[0][1] = unpackFloat(textureCube(shadowMap, tc + dx0));\n depthKernel[0][2] = unpackFloat(textureCube(shadowMap, tc + dx0 + dy1));\n depthKernel[1][0] = unpackFloat(textureCube(shadowMap, tc + dy0));\n depthKernel[1][1] = unpackFloat(textureCube(shadowMap, tc));\n depthKernel[1][2] = unpackFloat(textureCube(shadowMap, tc + dy1));\n depthKernel[2][0] = unpackFloat(textureCube(shadowMap, tc + dx1 + dy0));\n depthKernel[2][1] = unpackFloat(textureCube(shadowMap, tc + dx1));\n depthKernel[2][2] = unpackFloat(textureCube(shadowMap, tc + dx1 + dy1));\n\n vec3 shadowZ = vec3(length(dir) * shadowParams.w + shadowParams.z);\n\n shadowKernel[0] = vec3(lessThan2(depthKernel[0], shadowZ));\n shadowKernel[1] = vec3(lessThan2(depthKernel[1], shadowZ));\n shadowKernel[2] = vec3(lessThan2(depthKernel[2], shadowZ));\n\n vec2 uv = (vec2(dirX.w, dirY.w) / abs(majorAxisLength)) * 0.5;\n\n vec2 fractionalCoord = fract( uv * shadowParams.x );\n\n shadowKernel[0] = mix(shadowKernel[0], shadowKernel[1], fractionalCoord.x);\n shadowKernel[1] = mix(shadowKernel[1], shadowKernel[2], fractionalCoord.x);\n\n vec4 shadowValues;\n shadowValues.x = mix(shadowKernel[0][0], shadowKernel[0][1], fractionalCoord.y);\n shadowValues.y = mix(shadowKernel[0][1], shadowKernel[0][2], fractionalCoord.y);\n shadowValues.z = mix(shadowKernel[1][0], shadowKernel[1][1], fractionalCoord.y);\n shadowValues.w = mix(shadowKernel[1][1], shadowKernel[1][2], fractionalCoord.y);\n\n return 1.0 - dot( shadowValues, vec4( 1.0 ) ) * 0.25;\n}\n\nfloat getShadowPointPCF3x3(samplerCube shadowMap, vec4 shadowParams) {\n return _getShadowPoint(shadowMap, shadowParams, dLightDirW);\n}\n",shadowStandardGL2PS:"\nfloat _getShadowPCF5x5(sampler2DShadow shadowMap, vec3 shadowParams) {\n // http://the-witness.net/news/2013/09/shadow-mapping-summary-part-1/\n\n float z = dShadowCoord.z;\n vec2 uv = dShadowCoord.xy * shadowParams.x; // 1 unit - 1 texel\n float shadowMapSizeInv = 1.0 / shadowParams.x;\n vec2 base_uv = floor(uv + 0.5);\n float s = (uv.x + 0.5 - base_uv.x);\n float t = (uv.y + 0.5 - base_uv.y);\n base_uv -= vec2(0.5);\n base_uv *= shadowMapSizeInv;\n\n\n float uw0 = (4.0 - 3.0 * s);\n float uw1 = 7.0;\n float uw2 = (1.0 + 3.0 * s);\n\n float u0 = (3.0 - 2.0 * s) / uw0 - 2.0;\n float u1 = (3.0 + s) / uw1;\n float u2 = s / uw2 + 2.0;\n\n float vw0 = (4.0 - 3.0 * t);\n float vw1 = 7.0;\n float vw2 = (1.0 + 3.0 * t);\n\n float v0 = (3.0 - 2.0 * t) / vw0 - 2.0;\n float v1 = (3.0 + t) / vw1;\n float v2 = t / vw2 + 2.0;\n\n float sum = 0.0;\n\n u0 = u0 * shadowMapSizeInv + base_uv.x;\n v0 = v0 * shadowMapSizeInv + base_uv.y;\n\n u1 = u1 * shadowMapSizeInv + base_uv.x;\n v1 = v1 * shadowMapSizeInv + base_uv.y;\n\n u2 = u2 * shadowMapSizeInv + base_uv.x;\n v2 = v2 * shadowMapSizeInv + base_uv.y;\n\n sum += uw0 * vw0 * texture(shadowMap, vec3(u0, v0, z));\n sum += uw1 * vw0 * texture(shadowMap, vec3(u1, v0, z));\n sum += uw2 * vw0 * texture(shadowMap, vec3(u2, v0, z));\n\n sum += uw0 * vw1 * texture(shadowMap, vec3(u0, v1, z));\n sum += uw1 * vw1 * texture(shadowMap, vec3(u1, v1, z));\n sum += uw2 * vw1 * texture(shadowMap, vec3(u2, v1, z));\n\n sum += uw0 * vw2 * texture(shadowMap, vec3(u0, v2, z));\n sum += uw1 * vw2 * texture(shadowMap, vec3(u1, v2, z));\n sum += uw2 * vw2 * texture(shadowMap, vec3(u2, v2, z));\n\n sum *= 1.0f / 144.0;\n\n sum = gammaCorrectInput(sum); // gives softer gradient\n sum = saturate(sum);\n\n return sum;\n}\n\nfloat getShadowPCF5x5(sampler2DShadow shadowMap, vec3 shadowParams) {\n return _getShadowPCF5x5(shadowMap, shadowParams);\n}\n\nfloat getShadowSpotPCF5x5(sampler2DShadow shadowMap, vec4 shadowParams) {\n return _getShadowPCF5x5(shadowMap, shadowParams.xyz);\n}\n",shadowVSM8PS:"\nfloat calculateVSM8(vec3 moments, float Z, float vsmBias) {\n float VSMBias = vsmBias;//0.01 * 0.25;\n float depthScale = VSMBias * Z;\n float minVariance1 = depthScale * depthScale;\n return chebyshevUpperBound(moments.xy, Z, minVariance1, 0.1);\n}\n\nfloat decodeFloatRG(vec2 rg) {\n return rg.y*(1.0/255.0) + rg.x;\n}\n\nfloat VSM8(sampler2D tex, vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n vec4 c = texture2D(tex, texCoords);\n vec3 moments = vec3(decodeFloatRG(c.xy), decodeFloatRG(c.zw), 0.0);\n return calculateVSM8(moments, Z, vsmBias);\n}\n\nfloat getShadowVSM8(sampler2D shadowMap, vec3 shadowParams, float exponent) {\n return VSM8(shadowMap, dShadowCoord.xy, shadowParams.x, dShadowCoord.z, shadowParams.y, 0.0);\n}\n\nfloat getShadowSpotVSM8(sampler2D shadowMap, vec4 shadowParams, float exponent) {\n return VSM8(shadowMap, dShadowCoord.xy, shadowParams.x, length(dLightDirW) * shadowParams.w + shadowParams.z, shadowParams.y, 0.0);\n}\n",shadowVSM_commonPS:"\nfloat linstep(float a, float b, float v) {\n return saturate((v - a) / (b - a));\n}\n\nfloat reduceLightBleeding(float pMax, float amount) {\n // Remove the [0, amount] tail and linearly rescale (amount, 1].\n return linstep(amount, 1.0, pMax);\n}\n\nfloat chebyshevUpperBound(vec2 moments, float mean, float minVariance, float lightBleedingReduction) {\n // Compute variance\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, minVariance);\n\n // Compute probabilistic upper bound\n float d = mean - moments.x;\n float pMax = variance / (variance + (d * d));\n\n pMax = reduceLightBleeding(pMax, lightBleedingReduction);\n\n // One-tailed Chebyshev\n return (mean <= moments.x ? 1.0 : pMax);\n}\n\nfloat calculateEVSM(vec3 moments, float Z, float vsmBias, float exponent) {\n Z = 2.0 * Z - 1.0;\n float warpedDepth = exp(exponent * Z);\n\n moments.xy += vec2(warpedDepth, warpedDepth*warpedDepth) * (1.0 - moments.z);\n\n float VSMBias = vsmBias;//0.01 * 0.25;\n float depthScale = VSMBias * exponent * warpedDepth;\n float minVariance1 = depthScale * depthScale;\n return chebyshevUpperBound(moments.xy, warpedDepth, minVariance1, 0.1);\n}\n",skinBatchConstVS:"\nattribute float vertex_boneIndices;\n\nuniform vec4 matrix_pose[BONE_LIMIT * 3];\n\nmat4 getBoneMatrix(const in float i) {\n // read 4x3 matrix\n vec4 v1 = matrix_pose[int(3.0 * i)];\n vec4 v2 = matrix_pose[int(3.0 * i + 1.0)];\n vec4 v3 = matrix_pose[int(3.0 * i + 2.0)];\n\n // transpose to 4x4 matrix\n return mat4(\n v1.x, v2.x, v3.x, 0,\n v1.y, v2.y, v3.y, 0,\n v1.z, v2.z, v3.z, 0,\n v1.w, v2.w, v3.w, 1\n );\n}\n",skinBatchTexVS:"\nattribute float vertex_boneIndices;\n\nuniform highp sampler2D texture_poseMap;\nuniform vec4 texture_poseMapSize;\n\nmat4 getBoneMatrix(const in float i) {\n float j = i * 3.0;\n float dx = texture_poseMapSize.z;\n float dy = texture_poseMapSize.w;\n\n float y = floor(j * dx);\n float x = j - (y * texture_poseMapSize.x);\n y = dy * (y + 0.5);\n\n // read elements of 4x3 matrix\n vec4 v1 = texture2D(texture_poseMap, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(texture_poseMap, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(texture_poseMap, vec2(dx * (x + 2.5), y));\n\n // transpose to 4x4 matrix\n return mat4(\n v1.x, v2.x, v3.x, 0,\n v1.y, v2.y, v3.y, 0,\n v1.z, v2.z, v3.z, 0,\n v1.w, v2.w, v3.w, 1\n );\n}\n",skinConstVS:"\nattribute vec4 vertex_boneWeights;\nattribute vec4 vertex_boneIndices;\n\nuniform vec4 matrix_pose[BONE_LIMIT * 3];\n\nvoid getBoneMatrix(const in float i, out vec4 v1, out vec4 v2, out vec4 v3) {\n // read 4x3 matrix\n v1 = matrix_pose[int(3.0 * i)];\n v2 = matrix_pose[int(3.0 * i + 1.0)];\n v3 = matrix_pose[int(3.0 * i + 2.0)];\n}\n\nmat4 getSkinMatrix(const in vec4 indices, const in vec4 weights) {\n // get 4 bone matrices\n vec4 a1, a2, a3;\n getBoneMatrix(indices.x, a1, a2, a3);\n\n vec4 b1, b2, b3;\n getBoneMatrix(indices.y, b1, b2, b3);\n\n vec4 c1, c2, c3;\n getBoneMatrix(indices.z, c1, c2, c3);\n\n vec4 d1, d2, d3;\n getBoneMatrix(indices.w, d1, d2, d3);\n\n // multiply them by weights and add up to get final 4x3 matrix\n vec4 v1 = a1 * weights.x + b1 * weights.y + c1 * weights.z + d1 * weights.w;\n vec4 v2 = a2 * weights.x + b2 * weights.y + c2 * weights.z + d2 * weights.w;\n vec4 v3 = a3 * weights.x + b3 * weights.y + c3 * weights.z + d3 * weights.w;\n\n // add up weights\n float one = dot(weights, vec4(1.0));\n\n // transpose to 4x4 matrix\n return mat4(\n v1.x, v2.x, v3.x, 0,\n v1.y, v2.y, v3.y, 0,\n v1.z, v2.z, v3.z, 0,\n v1.w, v2.w, v3.w, one\n );\n}\n",skinTexVS:"\nattribute vec4 vertex_boneWeights;\nattribute vec4 vertex_boneIndices;\n\nuniform highp sampler2D texture_poseMap;\nuniform vec4 texture_poseMapSize;\n\nvoid getBoneMatrix(const in float i, out vec4 v1, out vec4 v2, out vec4 v3) {\n float j = i * 3.0;\n float dx = texture_poseMapSize.z;\n float dy = texture_poseMapSize.w;\n \n float y = floor(j * dx);\n float x = j - (y * texture_poseMapSize.x);\n y = dy * (y + 0.5);\n\n // read elements of 4x3 matrix\n v1 = texture2D(texture_poseMap, vec2(dx * (x + 0.5), y));\n v2 = texture2D(texture_poseMap, vec2(dx * (x + 1.5), y));\n v3 = texture2D(texture_poseMap, vec2(dx * (x + 2.5), y));\n}\n\nmat4 getSkinMatrix(const in vec4 indices, const in vec4 weights) {\n // get 4 bone matrices\n vec4 a1, a2, a3;\n getBoneMatrix(indices.x, a1, a2, a3);\n\n vec4 b1, b2, b3;\n getBoneMatrix(indices.y, b1, b2, b3);\n\n vec4 c1, c2, c3;\n getBoneMatrix(indices.z, c1, c2, c3);\n\n vec4 d1, d2, d3;\n getBoneMatrix(indices.w, d1, d2, d3);\n\n // multiply them by weights and add up to get final 4x3 matrix\n vec4 v1 = a1 * weights.x + b1 * weights.y + c1 * weights.z + d1 * weights.w;\n vec4 v2 = a2 * weights.x + b2 * weights.y + c2 * weights.z + d2 * weights.w;\n vec4 v3 = a3 * weights.x + b3 * weights.y + c3 * weights.z + d3 * weights.w;\n\n // add up weights\n float one = dot(weights, vec4(1.0));\n\n // transpose to 4x4 matrix\n return mat4(\n v1.x, v2.x, v3.x, 0,\n v1.y, v2.y, v3.y, 0,\n v1.z, v2.z, v3.z, 0,\n v1.w, v2.w, v3.w, one\n );\n}\n",skyboxEnvPS:"\nvarying vec3 vViewDir;\n\nuniform sampler2D texture_envAtlas;\nuniform float mipLevel;\n\nvoid main(void) {\n vec3 dir = vViewDir * vec3(-1.0, 1.0, 1.0);\n vec2 uv = toSphericalUv(normalize(dir));\n\n vec3 linear = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, mipLevel)));\n\n gl_FragColor = vec4(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0);\n}\n",skyboxHDRPS:"\nvarying vec3 vViewDir;\n\nuniform samplerCube texture_cubeMap;\n\nvoid main(void) {\n vec3 dir=vViewDir;\n dir.x *= -1.0;\n\n vec3 linear = $DECODE(textureCube(texture_cubeMap, fixSeamsStatic(dir, $FIXCONST)));\n\n gl_FragColor = vec4(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0);\n}\n",skyboxVS:"\nattribute vec3 aPosition;\n\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n\nuniform mat4 matrix_projectionSkybox;\nuniform mat3 cubeMapRotationMatrix;\n\nvarying vec3 vViewDir;\n\nvoid main(void) {\n mat4 view = matrix_view;\n view[3][0] = view[3][1] = view[3][2] = 0.0;\n gl_Position = matrix_projectionSkybox * view * vec4(aPosition, 1.0);\n\n // Force skybox to far Z, regardless of the clip planes on the camera\n // Subtract a tiny fudge factor to ensure floating point errors don't\n // still push pixels beyond far Z. See:\n // http://www.opengl.org/discussion_boards/showthread.php/171867-skybox-problem\n\n gl_Position.z = gl_Position.w - 0.00001;\n vViewDir = aPosition * cubeMapRotationMatrix;\n}\n",specularPS:"\n\n#ifdef MAPCOLOR\nuniform vec3 material_specular;\n#endif\n\nvoid getSpecularity() {\n vec3 specularColor = vec3(1,1,1);\n\n #ifdef MAPCOLOR\n specularColor *= material_specular;\n #endif\n\n #ifdef MAPTEXTURE\n specularColor *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n #endif\n\n #ifdef MAPVERTEX\n specularColor *= saturate(vVertexColor.$VC);\n #endif\n\n dSpecularity = specularColor;\n}\n",sphericalPS:"\n// equirectangular helper functions\nconst float PI = 3.141592653589793;\n\nvec2 toSpherical(vec3 dir) {\n return vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y));\n}\n\nvec2 toSphericalUv(vec3 dir) {\n vec2 uv = toSpherical(dir) / vec2(PI * 2.0, PI) + 0.5;\n return vec2(uv.x, 1.0 - uv.y);\n}\n",specularityFactorPS:"\n\n#ifdef MAPFLOAT\nuniform float material_specularityFactor;\n#endif\n\nvoid getSpecularityFactor() {\n float specularityFactor = 1.0;\n\n #ifdef MAPFLOAT\n specularityFactor *= material_specularityFactor;\n #endif\n\n #ifdef MAPTEXTURE\n specularityFactor *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n specularityFactor *= saturate(vVertexColor.$VC);\n #endif\n\n dSpecularityFactor = specularityFactor;\n}\n",spotPS:"\nfloat getSpotEffect(vec3 lightSpotDirW, float lightInnerConeAngle, float lightOuterConeAngle) {\n float cosAngle = dot(dLightDirNormW, lightSpotDirW);\n return smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle);\n}\n",startPS:"\nvoid main(void) {\n dReflection = vec4(0);\n\n #ifdef LIT_CLEARCOAT\n ccSpecularLight = vec3(0);\n ccReflection = vec3(0);\n #endif\n",startVS:"\nvoid main(void) {\n gl_Position = getPosition();\n",startNineSlicedPS:"\n nineSlicedUv = vUv0;\n nineSlicedUv.y = 1.0 - nineSlicedUv.y;\n\n",startNineSlicedTiledPS:"\n vec2 tileMask = step(vMask, vec2(0.99999));\n vec2 tileSize = 0.5 * (innerOffset.xy + innerOffset.zw);\n vec2 tileScale = vec2(1.0) / (vec2(1.0) - tileSize);\n vec2 clampedUv = mix(innerOffset.xy * 0.5, vec2(1.0) - innerOffset.zw * 0.5, fract((vTiledUv - tileSize) * tileScale));\n clampedUv = clampedUv * atlasRect.zw + atlasRect.xy;\n nineSlicedUv = vUv0 * tileMask + clampedUv * (vec2(1.0) - tileMask);\n nineSlicedUv.y = 1.0 - nineSlicedUv.y;\n \n",storeEVSMPS:"\nfloat exponent = VSM_EXPONENT;\n\ndepth = 2.0 * depth - 1.0;\ndepth = exp(exponent * depth);\ngl_FragColor = vec4(depth, depth*depth, 1.0, 1.0);\n",tangentBinormalVS:"\nvec3 getTangent() {\n return normalize(dNormalMatrix * vertex_tangent.xyz);\n}\n\nvec3 getBinormal() {\n return cross(vNormalW, vTangentW) * vertex_tangent.w;\n}\n\nvec3 getObjectSpaceUp() {\n return normalize(dNormalMatrix * vec3(0, 1, 0));\n}\n",TBNPS:"\nvoid getTBN() {\n dTBN = mat3(normalize(dTangentW), normalize(dBinormalW), normalize(dVertexNormalW));\n}\n",TBNderivativePS:"\nuniform float tbnBasis;\n\n// http://www.thetenthplanet.de/archives/1180\nvoid getTBN() {\n vec2 uv = $UV;\n\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx( vPositionW );\n vec3 dp2 = dFdy( vPositionW );\n vec2 duv1 = dFdx( uv );\n vec2 duv2 = dFdy( uv );\n\n // solve the linear system\n vec3 dp2perp = cross( dp2, dVertexNormalW );\n vec3 dp1perp = cross( dVertexNormalW, dp1 );\n vec3 T = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 B = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame\n float denom = max( dot(T,T), dot(B,B) );\n float invmax = (denom == 0.0) ? 0.0 : tbnBasis / sqrt( denom );\n dTBN = mat3(T * invmax, -B * invmax, dVertexNormalW );\n}\n",TBNfastPS:"\nvoid getTBN() {\n dTBN = mat3(dTangentW, dBinormalW, dVertexNormalW);\n}\n",TBNObjectSpacePS:"\nvoid getTBN() {\n\n vec3 B = cross(dVertexNormalW, vObjectSpaceUpW);\n vec3 T = cross(dVertexNormalW, B);\n\n if (dot(B,B)==0.0) // deal with case when vObjectSpaceUpW dVertexNormalW are parallel\n {\n float major=max(max(dVertexNormalW.x, dVertexNormalW.y),dVertexNormalW.z);\n\n if (dVertexNormalW.x==major)\n {\n B=cross(dVertexNormalW, vec3(0,1,0));\n T=cross(dVertexNormalW, B);\n }\n else if (dVertexNormalW.y==major)\n {\n B=cross(dVertexNormalW, vec3(0,0,1));\n T=cross(dVertexNormalW, B);\n }\n else if (dVertexNormalW.z==major)\n {\n B=cross(dVertexNormalW, vec3(1,0,0));\n T=cross(dVertexNormalW, B);\n }\n }\n\n dTBN = mat3(normalize(T), normalize(B), normalize(dVertexNormalW));\n}\n",textureSamplePS:"\nvec4 texture2DSRGB(sampler2D tex, vec2 uv) {\n return gammaCorrectInput(texture2D(tex, uv));\n}\n\nvec4 texture2DSRGB(sampler2D tex, vec2 uv, float bias) {\n return gammaCorrectInput(texture2D(tex, uv, bias));\n}\n\nvec3 texture2DRGBM(sampler2D tex, vec2 uv) {\n return decodeRGBM(texture2D(tex, uv));\n}\n\nvec3 texture2DRGBM(sampler2D tex, vec2 uv, float bias) {\n return decodeRGBM(texture2D(tex, uv, bias));\n}\n\nvec3 texture2DRGBE(sampler2D tex, vec2 uv) {\n return decodeRGBM(texture2D(tex, uv));\n}\n\nvec3 texture2DRGBE(sampler2D tex, vec2 uv, float bias) {\n return decodeRGBM(texture2D(tex, uv, bias));\n}\n",thicknessPS:"\n#ifdef MAPFLOAT\nuniform float material_thickness;\n#endif\n\nvoid getThickness() {\n dThickness = 1.0;\n\n #ifdef MAPFLOAT\n dThickness *= material_thickness;\n #endif\n\n #ifdef MAPTEXTURE\n dThickness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n dThickness *= saturate(vVertexColor.$VC);\n #endif\n}\n",tonemappingAcesPS:"\nuniform float exposure;\n\nvec3 toneMap(vec3 color) {\n float tA = 2.51;\n float tB = 0.03;\n float tC = 2.43;\n float tD = 0.59;\n float tE = 0.14;\n vec3 x = color * exposure;\n return (x*(tA*x+tB))/(x*(tC*x+tD)+tE);\n}\n",tonemappingAces2PS:"\nuniform float exposure;\n\n// ACES approximation by Stephen Hill\n\n// sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT\nconst mat3 ACESInputMat = mat3(\n 0.59719, 0.35458, 0.04823,\n 0.07600, 0.90834, 0.01566,\n 0.02840, 0.13383, 0.83777\n);\n\n// ODT_SAT => XYZ => D60_2_D65 => sRGB\nconst mat3 ACESOutputMat = mat3(\n 1.60475, -0.53108, -0.07367,\n -0.10208, 1.10813, -0.00605,\n -0.00327, -0.07276, 1.07602\n);\n\nvec3 RRTAndODTFit(vec3 v) {\n vec3 a = v * (v + 0.0245786) - 0.000090537;\n vec3 b = v * (0.983729 * v + 0.4329510) + 0.238081;\n return a / b;\n}\n\nvec3 toneMap(vec3 color) {\n color *= exposure;\n color = color * ACESInputMat;\n\n // Apply RRT and ODT\n color = RRTAndODTFit(color);\n color = color * ACESOutputMat;\n\n // Clamp to [0, 1]\n color = clamp(color, 0.0, 1.0);\n\n return color;\n}\n",tonemappingFilmicPS:"\nconst float A = 0.15;\nconst float B = 0.50;\nconst float C = 0.10;\nconst float D = 0.20;\nconst float E = 0.02;\nconst float F = 0.30;\nconst float W = 11.2;\n\nuniform float exposure;\n\nvec3 uncharted2Tonemap(vec3 x) {\n return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\n}\n\nvec3 toneMap(vec3 color) {\n color = uncharted2Tonemap(color * exposure);\n vec3 whiteScale = 1.0 / uncharted2Tonemap(vec3(W,W,W));\n color = color * whiteScale;\n\n return color;\n}\n",tonemappingHejlPS:"\nuniform float exposure;\n\nvec3 toneMap(vec3 color) {\n color *= exposure;\n const float A = 0.22, B = 0.3, C = .1, D = 0.2, E = .01, F = 0.3;\n const float Scl = 1.25;\n\n vec3 h = max( vec3(0.0), color - vec3(0.004) );\n return (h*((Scl*A)*h+Scl*vec3(C*B,C*B,C*B))+Scl*vec3(D*E,D*E,D*E)) / (h*(A*h+vec3(B,B,B))+vec3(D*F,D*F,D*F)) - Scl*vec3(E/F,E/F,E/F);\n}\n",tonemappingLinearPS:"\nuniform float exposure;\n\nvec3 toneMap(vec3 color) {\n return color * exposure;\n}\n",tonemappingNonePS:"\nvec3 toneMap(vec3 color) {\n return color;\n}\n",transformVS:"\n#ifdef PIXELSNAP\nuniform vec4 uScreenSize;\n#endif\n\n#ifdef SCREENSPACE\nuniform float projectionFlipY;\n#endif\n\n#ifdef MORPHING\nuniform vec4 morph_weights_a;\nuniform vec4 morph_weights_b;\n#endif\n\n#ifdef MORPHING_TEXTURE_BASED\nuniform vec4 morph_tex_params;\n\nvec2 getTextureMorphCoords() {\n float vertexId = morph_vertex_id;\n vec2 textureSize = morph_tex_params.xy;\n vec2 invTextureSize = morph_tex_params.zw;\n\n // turn vertexId into int grid coordinates\n float morphGridV = floor(vertexId * invTextureSize.x);\n float morphGridU = vertexId - (morphGridV * textureSize.x);\n\n // convert grid coordinates to uv coordinates with half pixel offset\n return (vec2(morphGridU, morphGridV) * invTextureSize) + (0.5 * invTextureSize);\n}\n#endif\n\n#ifdef MORPHING_TEXTURE_BASED_POSITION\nuniform highp sampler2D morphPositionTex;\n#endif\n\nmat4 getModelMatrix() {\n #ifdef DYNAMICBATCH\n return getBoneMatrix(vertex_boneIndices);\n #elif defined(SKIN)\n return matrix_model * getSkinMatrix(vertex_boneIndices, vertex_boneWeights);\n #elif defined(INSTANCING)\n return mat4(instance_line1, instance_line2, instance_line3, instance_line4);\n #else\n return matrix_model;\n #endif\n}\n\nvec4 getPosition() {\n dModelMatrix = getModelMatrix();\n vec3 localPos = vertex_position;\n\n #ifdef NINESLICED\n // outer and inner vertices are at the same position, scale both\n localPos.xz *= outerScale;\n\n // offset inner vertices inside\n // (original vertices must be in [-1;1] range)\n vec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0));\n vec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0));\n localPos.xz += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;\n\n vTiledUv = (localPos.xz - outerScale + innerOffset.xy) * -0.5 + 1.0; // uv = local pos - inner corner\n\n localPos.xz *= -0.5; // move from -1;1 to -0.5;0.5\n localPos = localPos.xzy;\n #endif\n\n #ifdef MORPHING\n #ifdef MORPHING_POS03\n localPos.xyz += morph_weights_a[0] * morph_pos0;\n localPos.xyz += morph_weights_a[1] * morph_pos1;\n localPos.xyz += morph_weights_a[2] * morph_pos2;\n localPos.xyz += morph_weights_a[3] * morph_pos3;\n #endif // MORPHING_POS03\n #ifdef MORPHING_POS47\n localPos.xyz += morph_weights_b[0] * morph_pos4;\n localPos.xyz += morph_weights_b[1] * morph_pos5;\n localPos.xyz += morph_weights_b[2] * morph_pos6;\n localPos.xyz += morph_weights_b[3] * morph_pos7;\n #endif // MORPHING_POS47\n #endif // MORPHING\n\n #ifdef MORPHING_TEXTURE_BASED_POSITION\n // apply morph offset from texture\n vec2 morphUV = getTextureMorphCoords();\n vec3 morphPos = texture2D(morphPositionTex, morphUV).xyz;\n localPos += morphPos;\n #endif\n\n vec4 posW = dModelMatrix * vec4(localPos, 1.0);\n #ifdef SCREENSPACE\n posW.zw = vec2(0.0, 1.0);\n #endif\n dPositionW = posW.xyz;\n\n vec4 screenPos;\n #ifdef UV1LAYOUT\n screenPos = vec4(vertex_texCoord1.xy * 2.0 - 1.0, 0.5, 1);\n #else\n #ifdef SCREENSPACE\n screenPos = posW;\n screenPos.y *= projectionFlipY;\n #else\n screenPos = matrix_viewProjection * posW;\n #endif\n\n #ifdef PIXELSNAP\n // snap vertex to a pixel boundary\n screenPos.xy = (screenPos.xy * 0.5) + 0.5;\n screenPos.xy *= uScreenSize.xy;\n screenPos.xy = floor(screenPos.xy);\n screenPos.xy *= uScreenSize.zw;\n screenPos.xy = (screenPos.xy * 2.0) - 1.0;\n #endif\n #endif\n\n return screenPos;\n}\n\nvec3 getWorldPosition() {\n return dPositionW;\n}\n",transformDeclVS:"\nattribute vec3 vertex_position;\n\nuniform mat4 matrix_model;\nuniform mat4 matrix_viewProjection;\n\nvec3 dPositionW;\nmat4 dModelMatrix;\n",transmissionPS:"\n\n#ifdef MAPFLOAT\nuniform float material_refraction;\n#endif\n\nvoid getRefraction() {\n float refraction = 1.0;\n\n #ifdef MAPFLOAT\n refraction = material_refraction;\n #endif\n\n #ifdef MAPTEXTURE\n refraction *= gammaCorrectInput(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n #endif\n\n #ifdef MAPVERTEX\n refraction *= saturate(vVertexColor.$VC);\n #endif\n\n dTransmission = refraction;\n}\n",uv0VS:"\n#ifdef NINESLICED\nvec2 getUv0() {\n vec2 uv = vertex_position.xz;\n\n // offset inner vertices inside\n // (original vertices must be in [-1;1] range)\n vec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0));\n vec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0));\n uv += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;\n\n uv = uv * -0.5 + 0.5;\n uv = uv * atlasRect.zw + atlasRect.xy;\n\n vMask = vertex_texCoord0.xy;\n\n return uv;\n}\n#else\nvec2 getUv0() {\n return vertex_texCoord0;\n}\n#endif\n",uv1VS:"\nvec2 getUv1() {\n return vertex_texCoord1;\n}\n",viewDirPS:"\nvoid getViewDir() {\n dViewDirW = normalize(view_position - vPositionW);\n}\n",viewNormalVS:"\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n\nvec3 getViewNormal() {\n return mat3(matrix_view) * vNormalW;\n}\n",webgpuPS:"\n\nlayout(location = 0) out highp vec4 pc_fragColor;\n#define gl_FragColor pc_fragColor\n\n#define texture2D(res, uv) texture(sampler2D(res, res ## _sampler), uv)\n#define texture2DBias(res, uv, bias) texture(sampler2D(res, res ## _sampler), uv, bias)\n#define texture2DLodEXT(res, uv, lod) textureLod(sampler2D(res, res ## _sampler), uv, lod)\n\n// TODO: implement other texture sampling macros\n// #define textureCube texture\n// #define texture2DProj textureProj\n// #define texture2DProjLodEXT textureProjLod\n// #define textureCubeLodEXT textureLod\n// #define texture2DGradEXT textureGrad\n// #define texture2DProjGradEXT textureProjGrad\n// #define textureCubeGradEXT textureGrad\n#define GL2\n#define SUPPORTS_TEXLOD\n",webgpuVS:"\n#define texture2D(res, uv) texture(sampler2D(res, res ## _sampler), uv)\n\n#define GL2\n#define VERTEXSHADER\n"},Hi=function(){function e(){}return e.getType=function(e){switch(e){case 0:case 1:return Ye;case 2:return Ke;case 3:return Ze;default:return e>=4&&e<22?$e:Ye}},e.isForward=function(e){return this.getType(e)===Ye},e.isShadow=function(e){return this.getType(e)===$e},e.toLightType=function(e){var t=e-4;return Math.floor(t/6)},e.toShadowType=function(e){var t=e-4;return t-6*Math.floor(t/6)},e.getShadow=function(e,t){return 4+(t+6*e)},e.getPassShaderDefine=function(t){return 3===t?"#define PICK_PASS\n":2===t?"#define DEPTH_PASS\n":e.isShadow(t)?"#define SHADOW_PASS\n":""},e}();function Xi(e,t){return t||(t=Wi),1===e||2===e?t.gamma2_2PS?t.gamma2_2PS:Wi.gamma2_2PS:3===e?"#define HDR\n"+(t.gamma2_2PS?t.gamma2_2PS:Wi.gamma2_2PS):t.gamma1_0PS?t.gamma1_0PS:Wi.gamma1_0PS}function qi(e,t){return t||(t=Wi),1===e?t.tonemappingFilmicPS?t.tonemappingFilmicPS:Wi.tonemappingFilmicPS:0===e?t.tonemappingLinearPS?t.tonemappingLinearPS:Wi.tonemappingLinearPS:2===e?t.tonemappingHejlPS?t.tonemappingHejlPS:Wi.tonemappingHejlPS:3===e?t.tonemappingAcesPS?t.tonemappingAcesPS:Wi.tonemappingAcesPS:4===e?t.tonemappingAces2PS?t.tonemappingAces2PS:Wi.tonemappingAces2PS:t.tonemapingNonePS?t.tonemapingNonePS:Wi.tonemappingNonePS}function ji(e,t){return t||(t=Wi),"linear"===e?t.fogLinearPS?t.fogLinearPS:Wi.fogLinearPS:"exp"===e?t.fogExpPS?t.fogExpPS:Wi.fogExpPS:"exp2"===e?t.fogExp2PS?t.fogExp2PS:Wi.fogExp2PS:t.fogNonePS?t.fogNonePS:Wi.fogNonePS}function Yi(e,t){return t||(t=Wi),e.supportsBoneTextures?t.skinTexVS:"#define BONE_LIMIT "+e.getBoneLimit()+"\n"+t.skinConstVS}function Ki(e,t,i){var n="";if(e.deviceType===li){t&&"highp"!==t&&"mediump"!==t&&"lowp"!==t&&(t=null),t&&("highp"===t&&"highp"!==e.maxPrecision&&(t="mediump"),"mediump"===t&&"lowp"===e.maxPrecision&&(t="lowp"));var s=t||e.precision;n="precision "+s+" float;\n",i&&e.webgl2&&(n+="precision "+s+" sampler2DShadow;\n")}return n}function Zi(e){return e.deviceType===ci?"#version 450\n":e.webgl2?"#version 300 es\n":""}function $i(e){return"#define SHADER_NAME "+e+"\n"}function Qi(e,t,i,n){var s=Zi(e);return e.deviceType===ci?s+=Wi.webgpuVS:(n&&(s+=n+"\n"),e.webgl2&&(s+=Wi.gles3VS)),s+=$i(t),s+=Hi.getPassShaderDefine(i)}function Ji(e,t,i,n,s){var r=Zi(e);return e.deviceType===ci?r+=Wi.webgpuPS:(n&&(r+=n+"\n"),e.webgl2?r+=Wi.gles3PS:(e.extStandardDerivatives&&(r+="#extension GL_OES_standard_derivatives : enable\n"),e.extTextureLod&&(r+="#extension GL_EXT_shader_texture_lod : enable\n",r+="#define SUPPORTS_TEXLOD\n"),r+=Wi.gles2PS)),r+=Ki(e,s,!0),r+=$i(t),r+=Hi.getPassShaderDefine(i)}function en(){return"void main(void) {gl_FragColor = vec4(0.0);}"}function tn(){return"void main(void)\n{\n"}function nn(){return"}\n"}var sn={vertex_position:vt,vertex_normal:yt,vertex_tangent:xt,vertex_texCoord0:At,vertex_texCoord1:Mt,vertex_texCoord2:Ct,vertex_texCoord3:Et,vertex_texCoord4:Pt,vertex_texCoord5:Rt,vertex_texCoord6:It,vertex_texCoord7:Lt,vertex_color:wt,vertex_boneIndices:St,vertex_boneWeights:bt};function rn(e){for(var t={},i=0,n=e.indexOf("attribute");n>=0&&!(n>0&&"/"===e[n-1]);){var s=e.indexOf(";",n),r=e.lastIndexOf(" ",s),a=e.substring(r+1,s),o=sn[a];void 0!==o?t[a]=o:(t[a]="ATTR"+i,i++),n=e.indexOf("attribute",n+1)}return t}function an(e,t,i,n){void 0===n&&(n=!1);var s=Wi[t],r=Ki(e)+"\n"+Wi[i],a=rn(s);return e.deviceType===ci?(s=Zi(e)+Wi.webgpuVS+s,r=Zi(e)+Wi.webgpuPS+r):e.webgl2&&(s=Zi(e)+Wi.gles3VS+s,r=Zi(e)+Wi.gles3PS+r),new zi(e,{attributes:a,vshader:s,fshader:r,useTransformFeedback:n,name:t+"_"+i})}function on(e,t,i,n,s,r){void 0===s&&(s=!1),void 0===r&&(r="");var a=e.programLib._cache,o=a[n];if(void 0!==o)return o;i=Ki(e)+"\n"+(i||"void main(void) {gl_FragColor = vec4(0.0);}");var h=rn(t);return e.deviceType===ci?(t=Zi(e)+Wi.webgpuVS+t,i=Zi(e)+Wi.webgpuPS+i):e.webgl2&&(t=Zi(e)+Wi.gles3VS+t,i=Zi(e)+Wi.gles3PS+i),a[n]=new zi(e,{name:n,attributes:h,vshader:t,fshader:r+i,useTransformFeedback:s}),a[n]}Wi.collectAttribs=rn,Wi.createShader=an,Wi.createShaderFromCode=on;var hn=function(){function e(){this.globalId=0,this.revision=0}var t=e.prototype;return t.equals=function(e){return this.globalId===e.globalId&&this.revision===e.revision},t.copy=function(e){this.globalId=e.globalId,this.revision=e.revision},t.reset=function(){this.globalId=0,this.revision=0},e}(),ln=0,cn=function(){function e(){ln++,this.version=new hn,this.version.globalId=ln}return e.prototype.increment=function(){this.version.revision++},e}(),un=function(){function e(e){this.name=e,this.value=null,this.versionObject=new cn}var t=e.prototype;return t.toJSON=function(e){},t.setValue=function(e){this.value=e,this.versionObject.increment()},t.getValue=function(){return this.value},e}(),dn=function(){function e(e){this.name=e,this.variables=new Map}var t=e.prototype;return t.resolve=function(e){return this.variables.has(e)||this.variables.set(e,new un(e)),this.variables.get(e)},t.removeValue=function(e){for(var t in this.variables){var i=this.variables[t];i.value===e&&(i.value=null)}},e}(),fn={linear:"decodeLinear",srgb:"decodeGamma",rgbm:"decodeRGBM",rgbe:"decodeRGBE",rgbp:"decodeRGBP"},pn={linear:"encodeLinear",srgb:"encodeGamma",rgbm:"encodeRGBM",rgbe:"encodeRGBE",rgbp:"encodeRGBP"},mn=function(){function e(){}return e.decodeFunc=function(e){return fn[e]||"decodeGamma"},e.encodeFunc=function(e){return pn[e]||"encodeGamma"},e}(),_n=1/255,gn=new Float32Array(1),vn=new Int32Array(gn.buffer),yn=function(){function e(){}return e.float2Half=function(e){gn[0]=e;var t=vn[0],i=t>>16&32768,n=t>>12&2047,s=t>>23&255;return s<103?i:s>142?(i|=31744,i|=(255===s?0:1)&&8388607&t):s<113?i|=((n|=2048)>>114-s)+(n>>113-s&1):(i|=s-112<<10|n>>1,i+=1&n)},e.float2Bytes=function(e,t,i,n){var s=255*e%1;if(t[i+0]=Math.round(255*(e%1-_n*s)),n>1){var r=65025*e%1;if(t[i+1]=Math.round(255*(s-_n*r)),n>2){var a=16581375*e%1;t[i+2]=Math.round(255*(r-_n*a)),n>3&&(t[i+3]=Math.round(255*a))}}},e.float2BytesRange=function(t,i,n,s,r,a){t=de.clamp((t-s)/(r-s),0,1),e.float2Bytes(t,i,n,a)},e.float2MantissaExponent=function(t,i,n,s){var r=Math.floor(Math.log2(Math.abs(t)))+1;t/=Math.pow(2,r),e.float2BytesRange(t,i,n,-1,1,s-1),i[n+s-1]=Math.round(r+127)},e}(),xn=null,bn=null,Sn=0,wn=function(){function e(e,t){this.id=Sn++,this.device=e,this.name=null,this._width=4,this._height=4,this._depth=1,this._format=7,this.type=Zt,this.projection=si,this._cubemap=!1,this._volume=!1,this.fixCubemapSeams=!1,this._flipY=!1,this._premultiplyAlpha=!1,this._isRenderTarget=!1,this._mipmaps=!0,this._minFilter=5,this._magFilter=1,this._anisotropy=1,this._addressU=0,this._addressV=0,this._addressW=0,this._compareOnRead=!1,this._compareFunc=1,void 0!==t&&(void 0!==t.name&&(this.name=t.name),this._width=void 0!==t.width?t.width:this._width,this._height=void 0!==t.height?t.height:this._height,this._format=void 0!==t.format?t.format:this._format,t.hasOwnProperty("type")?this.type=t.type:t.hasOwnProperty("rgbm")?this.type=t.rgbm?$t:Zt:t.hasOwnProperty("swizzleGGGR")&&(this.type=t.swizzleGGGR?ei:Zt),void 0!==t.mipmaps?this._mipmaps=t.mipmaps:this._mipmaps=void 0!==t.autoMipmap?t.autoMipmap:this._mipmaps,this._levels=t.levels,this._cubemap=void 0!==t.cubemap?t.cubemap:this._cubemap,this.fixCubemapSeams=void 0!==t.fixCubemapSeams?t.fixCubemapSeams:this.fixCubemapSeams,this._cubemap?this.projection=ri:t.projection&&t.projection!==ri&&(this.projection=t.projection),this._minFilter=void 0!==t.minFilter?t.minFilter:this._minFilter,this._magFilter=void 0!==t.magFilter?t.magFilter:this._magFilter,this._anisotropy=void 0!==t.anisotropy?t.anisotropy:this._anisotropy,this._addressU=void 0!==t.addressU?t.addressU:this._addressU,this._addressV=void 0!==t.addressV?t.addressV:this._addressV,this._compareOnRead=void 0!==t.compareOnRead?t.compareOnRead:this._compareOnRead,this._compareFunc=void 0!==t._compareFunc?t._compareFunc:this._compareFunc,this._flipY=void 0!==t.flipY?t.flipY:this._flipY,this._premultiplyAlpha=void 0!==t.premultiplyAlpha?t.premultiplyAlpha:this._premultiplyAlpha,e.webgl2&&(this._depth=void 0!==t.depth?t.depth:this._depth,this._volume=void 0!==t.volume?t.volume:this._volume,this._addressW=void 0!==t.addressW?t.addressW:this._addressW)),this._compressed=8===this._format||9===this._format||this._format===ht||this._format>=mt,this._invalid=!1,this._lockedLevel=-1,this._levels||(this._levels=this._cubemap?[[null,null,null,null,null,null]]:[null]),this.dirtyAll(),this._gpuSize=0,this.impl=e.createTextureImpl(this),e.textures.push(this)}var t=e.prototype;return t.destroy=function(){if(this.device){var e=this.device,t=e.textures.indexOf(this);-1!==t&&e.textures.splice(t,1),e.scope.removeValue(this),this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this._gpuSize),this._levels=null,this.device=null}},t.loseContext=function(){this.impl.loseContext(),this.dirtyAll()},t.adjustVramSizeTracking=function(e,t){e.tex+=t},e.calcGpuSize=function(e,t,i,n,s,r){xn||((xn=[])[0]=1,xn[1]=1,xn[2]=2,xn[3]=2,xn[4]=2,xn[5]=2,xn[6]=4,xn[7]=4,xn[11]=8,xn[12]=8,xn[13]=16,xn[14]=16,xn[15]=4,xn[16]=4,xn[17]=4,xn[18]=4,xn[19]=4,xn[20]=4),bn||((bn=[])[21]=8,bn[22]=8,bn[24]=8,bn[25]=8,bn[26]=8,bn[27]=8,bn[8]=8,bn[29]=8,bn[23]=16,bn[9]=16,bn[10]=16,bn[28]=16,bn[30]=16);for(var a=xn.hasOwnProperty(n)?xn[n]:0,o=bn.hasOwnProperty(n)?bn[n]:0,h=0;;){if(a>0)h+=e*t*i*a;else{var l=Math.floor((e+3)/4),c=Math.floor((t+3)/4),u=Math.floor((i+3)/4);n!==_t&&n!==gt||(l=Math.max(Math.floor(l/2),1)),h+=l*c*u*o}if(!s||1===e&&1===t&&1===i)break;e=Math.max(Math.floor(e/2),1),t=Math.max(Math.floor(t/2),1),i=Math.max(Math.floor(i/2),1)}return h*(r?6:1)},t.dirtyAll=function(){this._levelsUpdated=this._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0],this._needsUpload=!0,this._needsMipmapsUpload=this._mipmaps,this._mipmapsUploaded=!1,this._parameterFlags=255},t.lock=function(e){if(void 0===e&&(e={}),void 0===e.level&&(e.level=0),void 0===e.face&&(e.face=0),void 0===e.mode&&(e.mode=2),this._lockedLevel=e.level,null===this._levels[e.level])switch(this._format){case 0:case 1:this._levels[e.level]=new Uint8Array(this._width*this._height*this._depth);break;case 2:this._levels[e.level]=new Uint8Array(this._width*this._height*this._depth*2);break;case 3:case 4:case 5:this._levels[e.level]=new Uint16Array(this._width*this._height*this._depth);break;case 6:this._levels[e.level]=new Uint8Array(this._width*this._height*this._depth*3);break;case 7:this._levels[e.level]=new Uint8Array(this._width*this._height*this._depth*4);break;case 8:this._levels[e.level]=new Uint8Array(Math.floor((this._width+3)/4)*Math.floor((this._height+3)/4)*8*this._depth);break;case 9:case ht:this._levels[e.level]=new Uint8Array(Math.floor((this._width+3)/4)*Math.floor((this._height+3)/4)*16*this._depth);break;case lt:this._levels[e.level]=new Uint16Array(this._width*this._height*this._depth*3);break;case ut:this._levels[e.level]=new Float32Array(this._width*this._height*this._depth*3);break;case ct:this._levels[e.level]=new Uint16Array(this._width*this._height*this._depth*4);break;case dt:this._levels[e.level]=new Float32Array(this._width*this._height*this._depth*4)}return this._levels[e.level]},t.setSource=function(e,t){void 0===t&&(t=0);var i,n,s=!1;if(this._cubemap){if(e[0]){i=e[0].width||0,n=e[0].height||0;for(var r=0;r<6;r++){var a=e[r];if(!a||a.width!==i||a.height!==n||!this.device._isBrowserInterface(a)){s=!0;break}}}else s=!0;if(!s)for(var o=0;o<6;o++)this._levels[t][o]!==e[o]&&(this._levelsUpdated[t][o]=!0)}else this.device._isBrowserInterface(e)||(s=!0),s||(e!==this._levels[t]&&(this._levelsUpdated[t]=!0),i=e.width,n=e.height);if(s)if(this._width=4,this._height=4,this._cubemap)for(var h=0;h<6;h++)this._levels[t][h]=null,this._levelsUpdated[t][h]=!0;else this._levels[t]=null,this._levelsUpdated[t]=!0;else 0===t&&(this._width=i,this._height=n),this._levels[t]=e;this._invalid===s&&s||(this._invalid=s,this.upload())},t.getSource=function(e){return void 0===e&&(e=0),this._levels[e]},t.unlock=function(){this._lockedLevel,this.upload(),this._lockedLevel=-1},t.upload=function(){this._needsUpload=!0,this._needsMipmapsUpload=this._mipmaps},t.getDds=function(){for(var e=128,t=0;this._levels[t];){if(this.cubemap)for(var i=0;i<6;i++){if(!this._levels[t][i])return;var n=this._levels[t][i].length;if(!n)return;e+=n}else{var s=this._levels[t].length;if(!s)return;e+=s}e+=this._levels[t].length,t++}var r=new ArrayBuffer(e),a=new Uint32Array(r,0,32),o=528391;this._levels.length>1&&(o|=131072);var h=4096;this._levels.length>1&&(h|=4194304),(this._levels.length>1||this.cubemap)&&(h|=8);var l=this.cubemap?65024:0;a[0]=542327876,a[1]=124,a[2]=o,a[3]=this.height,a[4]=this.width,a[5]=this.width*this.height*4,a[6]=0,a[7]=this._levels.length;for(var c=0;c<11;c++)a[8+c]=0;a[19]=32,a[20]=65,a[21]=0,a[22]=32,a[23]=16711680,a[24]=65280,a[25]=255,a[26]=4278190080,a[27]=h,a[28]=l,a[29]=0,a[30]=0,a[31]=0;var u=128;if(this.cubemap)for(var d=0;d<6;d++)for(var f=0;f=0?e.insertChild(this,t):e.addChild(this))},i.setLocalEulerAngles=function(e,t,i){this.localRotation.setFromEulerAngles(e,t,i),this._dirtyLocal||this._dirtifyLocal()},i.setLocalPosition=function(e,t,i){e instanceof ye?this.localPosition.copy(e):this.localPosition.set(e,t,i),this._dirtyLocal||this._dirtifyLocal()},i.setLocalRotation=function(e,t,i,n){e instanceof Pe?this.localRotation.copy(e):this.localRotation.set(e,t,i,n),this._dirtyLocal||this._dirtifyLocal()},i.setLocalScale=function(e,t,i){e instanceof ye?this.localScale.copy(e):this.localScale.set(e,t,i),this._dirtyLocal||this._dirtifyLocal()},i._dirtifyLocal=function(){this._dirtyLocal||(this._dirtyLocal=!0,this._dirtyWorld||this._dirtifyWorld())},i._unfreezeParentToRoot=function(){for(var e=this._parent;e;)e._frozen=!1,e=e._parent},i._dirtifyWorld=function(){this._dirtyWorld||this._unfreezeParentToRoot(),this._dirtifyWorldInternal()},i._dirtifyWorldInternal=function(){if(!this._dirtyWorld){this._frozen=!1,this._dirtyWorld=!0;for(var e=0;e8?e.FORMAT_FLOAT:e.FORMAT_8BIT,e.initShaderDefines()},e.createTexture=function(e,t,i,n,s){return new wn(e,{name:s,width:t,height:i,mipmaps:!1,format:n,addressU:1,addressV:1,type:Zt,magFilter:0,minFilter:0,anisotropy:1})};var t=e.prototype;return t.destroy=function(){this.lightsTexture8&&(this.lightsTexture8.destroy(),this.lightsTexture8=null),this.lightsTextureFloat&&(this.lightsTextureFloat.destroy(),this.lightsTextureFloat=null)},t.setCompressionRanges=function(e,t){this.invMaxColorValue=1/t,this.invMaxAttenuation=1/e},t.setBounds=function(e,t){this.boundsMin.copy(e),this.boundsDelta.copy(t)},t.uploadTextures=function(){this.lightsTextureFloat&&(this.lightsTextureFloat.lock().set(this.lightsFloat),this.lightsTextureFloat.unlock()),this.lightsTexture8.lock().set(this.lights8),this.lightsTexture8.unlock()},t.updateUniforms=function(){this._lightsTexture8Id.setValue(this.lightsTexture8),e.lightTextureFormat===e.FORMAT_FLOAT&&this._lightsTextureFloatId.setValue(this.lightsTextureFloat),this._lightsTextureInvSizeId.setValue(this._lightsTextureInvSizeData)},t.getSpotDirection=function(e,t){t._node.getWorldTransform().getY(e).mulScalar(-1),e.normalize()},t.getLightAreaSizes=function(e){var t=e._node.getWorldTransform();return t.transformVector($n,Kn),Zn[0]=Kn.x,Zn[1]=Kn.y,Zn[2]=Kn.z,t.transformVector(Qn,Kn),Zn[3]=Kn.x,Zn[4]=Kn.y,Zn[5]=Kn.z,Zn},t.addLightDataFlags=function(e,t,i,n,s,r){e[t+0]=n?255:0,e[t+1]=64*i._shape,e[t+2]=255*i._falloffMode,e[t+3]=s?255*r:0},t.addLightDataColor=function(e,t,i,n,s){var r=this.invMaxColorValue,a=n?i._linearFinalColor:i._finalColor;yn.float2Bytes(a[0]*r,e,t+0,2),yn.float2Bytes(a[1]*r,e,t+2,2),yn.float2Bytes(a[2]*r,e,t+4,2),e[t+6]=s?255:0;var o=!!(1&i.mask),h=!!(2&i.mask);e[t+7]=o&&h?127:h?255:0},t.addLightDataSpotAngles=function(e,t,i){yn.float2Bytes(.499999*i._innerConeAngleCos+.5,e,t+0,2),yn.float2Bytes(.499999*i._outerConeAngleCos+.5,e,t+2,2)},t.addLightDataShadowBias=function(e,t,i){var n=i.getRenderData(null,0),s=i._getUniformBiasValues(n);yn.float2BytesRange(s.bias,e,t,-1,20,2),yn.float2Bytes(s.normalBias,e,t+2,2)},t.addLightDataPositionRange=function(e,t,i,n){var s=Kn.sub2(n,this.boundsMin).div(this.boundsDelta);yn.float2Bytes(s.x,e,t+0,4),yn.float2Bytes(s.y,e,t+4,4),yn.float2Bytes(s.z,e,t+8,4),yn.float2Bytes(i.attenuationEnd*this.invMaxAttenuation,e,t+12,4)},t.addLightDataSpotDirection=function(e,t,i){this.getSpotDirection(Kn,i),yn.float2Bytes(.499999*Kn.x+.5,e,t+0,4),yn.float2Bytes(.499999*Kn.y+.5,e,t+4,4),yn.float2Bytes(.499999*Kn.z+.5,e,t+8,4)},t.addLightDataLightProjMatrix=function(e,t,i){for(var n=i.data,s=0;s<12;s++)yn.float2BytesRange(n[s],e,t+4*s,-2,2,4);for(var r=12;r<16;r++)yn.float2MantissaExponent(n[r],e,t+4*r,4)},t.addLightDataCookies=function(e,t,i){var n="rgb"===i._cookieChannel;if(e[t+0]=Math.floor(255*i.cookieIntensity),e[t+1]=n?255:0,!n){var s=i._cookieChannel;e[t+4]="rrr"===s?255:0,e[t+5]="ggg"===s?255:0,e[t+6]="bbb"===s?255:0,e[t+7]="aaa"===s?255:0}},t.addLightAtlasViewport=function(e,t,i){yn.float2Bytes(i.x,e,t+0,2),yn.float2Bytes(i.y,e,t+2,2),yn.float2Bytes(i.z/3,e,t+4,2)},t.addLightAreaSizes=function(e,t,i){for(var n=this.getLightAreaSizes(i),s=0;s<6;s++)yn.float2MantissaExponent(n[s],e,t+4*s,4)},t.addLightData=function(t,i,n){var s=2===t._type,r=t.atlasViewportAllocated,a=this.cookiesEnabled&&!!t._cookie&&r,o=this.areaLightsEnabled&&0!==t.shape,h=this.shadowsEnabled&&t.castShadows&&r,l=t._node.getPosition(),c=null,u=null;s?h?c=t.getRenderData(null,0).shadowMatrix:a&&(c=Yn.evalSpotCookieMatrix(t)):(h||a)&&(u=t.atlasViewport);var d=this.lights8,f=i*this.lightsTexture8.width*4;if(this.addLightDataFlags(d,f+4*Jn.FLAGS,t,s,h,t.shadowIntensity),this.addLightDataColor(d,f+4*Jn.COLOR_A,t,n,a),s&&this.addLightDataSpotAngles(d,f+4*Jn.SPOT_ANGLES,t),t.castShadows&&this.addLightDataShadowBias(d,f+4*Jn.SHADOW_BIAS,t),a&&this.addLightDataCookies(d,f+4*Jn.COOKIE_A,t),e.lightTextureFormat===e.FORMAT_FLOAT){var p=this.lightsFloat,m=i*this.lightsTextureFloat.width*4;if(p[m+4*es.POSITION_RANGE+0]=l.x,p[m+4*es.POSITION_RANGE+1]=l.y,p[m+4*es.POSITION_RANGE+2]=l.z,p[m+4*es.POSITION_RANGE+3]=t.attenuationEnd,s&&(this.getSpotDirection(Kn,t),p[m+4*es.SPOT_DIRECTION+0]=Kn.x,p[m+4*es.SPOT_DIRECTION+1]=Kn.y,p[m+4*es.SPOT_DIRECTION+2]=Kn.z),c)for(var _=c.data,g=0;g<16;g++)p[m+4*es.PROJ_MAT_0+g]=_[g];if(u&&(p[m+4*es.ATLAS_VIEWPORT+0]=u.x,p[m+4*es.ATLAS_VIEWPORT+1]=u.y,p[m+4*es.ATLAS_VIEWPORT+2]=u.z/3),o){var v=this.getLightAreaSizes(t);p[m+4*es.AREA_DATA_WIDTH+0]=v[0],p[m+4*es.AREA_DATA_WIDTH+1]=v[1],p[m+4*es.AREA_DATA_WIDTH+2]=v[2],p[m+4*es.AREA_DATA_HEIGHT+0]=v[3],p[m+4*es.AREA_DATA_HEIGHT+1]=v[4],p[m+4*es.AREA_DATA_HEIGHT+2]=v[5]}}else this.addLightDataPositionRange(d,f+4*Jn.POSITION_X,t,l),s&&this.addLightDataSpotDirection(d,f+4*Jn.SPOT_DIRECTION_X,t),c&&this.addLightDataLightProjMatrix(d,f+4*Jn.PROJ_MAT_00,c),u&&this.addLightAtlasViewport(d,f+4*Jn.ATLAS_VIEWPORT_A,u),o&&this.addLightAreaSizes(d,f+4*Jn.AREA_DATA_WIDTH_X,t)},e}();ts.FORMAT_FLOAT=0,ts.FORMAT_8BIT=1,ts.lightTextureFormat=ts.FORMAT_8BIT,ts.shaderDefines="";var is={vertex_normal:yt,vertex_tangent:xt,vertex_texCoord0:At,vertex_texCoord1:Mt,vertex_color:wt,vertex_boneWeights:bt,vertex_boneIndices:St},ns={vVertexColor:"vec4",vPositionW:"vec3",vNormalV:"vec3",vNormalW:"vec3",vTangentW:"vec3",vBinormalW:"vec3",vObjectSpaceUpW:"vec3",vUv0:"vec2",vUv1:"vec2"},ss=function(){function e(e,t){if(this.device=e,this.options=t,this.attributes={vertex_position:vt},t.chunks){this.chunks={};var i=t.chunks;for(var n in Wi)if(i.hasOwnProperty(n)){var s=i[n];for(var r in is)is.hasOwnProperty(r)&&s.indexOf(r)>=0&&(this.attributes[r]=is[r]);this.chunks[n]=s}else this.chunks[n]=Wi[n]}else this.chunks=Wi;this.lighting=t.lights.length>0||!!t.dirLightMap||!!t.clusteredLightingEnabled,this.reflections=!!t.reflectionSource,t.useSpecular||(t.specularMap=t.glossMap=null),this.shadowPass=Hi.isShadow(t.pass),this.needsNormal=this.lighting||this.reflections||t.useSpecular||t.ambientSH||t.heightMap||t.enableGGXSpecular||t.clusteredLightingEnabled&&!this.shadowPass||t.clearCoatNormalMap,this.needsSceneColor=t.useDynamicRefraction,this.needsScreenSize=t.useDynamicRefraction,this.needsTransforms=t.useDynamicRefraction,this.varyings="",this.vshader=null,this.frontendDecl=null,this.frontendCode=null,this.frontendFunc=null,this.lightingUv=null,this.defines=[],this.fshader=null}var t=e.prototype;return t._vsAddBaseCode=function(e,t,i){return e+=t.baseVS,1!==i.nineSlicedMode&&2!==i.nineSlicedMode||(e+=t.baseNineSlicedVS),e},t._vsAddTransformCode=function(e,t,i,n){return e+=this.chunks.transformVS},t._setMapTransform=function(e,t,i,n){var s=i+100*n;if(!e[3][s]){var r="texture_"+t+"MapTransform";e[0]+="uniform vec3 "+r+"0;\n",e[0]+="uniform vec3 "+r+"1;\n",e[1]+="varying vec2 vUV"+n+"_"+i+";\n",e[2]+=" vUV"+n+"_"+i+" = vec2(dot(vec3(uv"+n+", 1), "+r+"0), dot(vec3(uv"+n+", 1), "+r+"1));\n",e[3][s]=!0}return e},t._fsGetBaseCode=function(){var e=this.options,t=this.chunks,i=this.chunks.basePS;return 1===e.nineSlicedMode?i+=t.baseNineSlicedPS:2===e.nineSlicedMode&&(i+=t.baseNineSlicedTiledPS),i},t._fsGetStartCode=function(e,t,i,n){var s=i.startPS;return 1===n.nineSlicedMode?s+=i.startNineSlicedPS:2===n.nineSlicedMode&&(s+=i.startNineSlicedTiledPS),s},t._directionalShadowMapProjection=function(e,t,i,n,s){var r="";return e.numCascades>1&&(r+="getShadowCascadeMatrix(light"+n+"_shadowMatrixPalette, light"+n+"_shadowCascadeDistances, light"+n+"_shadowCascadeCount);\n",t="(cascadeShadowMat, "+i+");\n"),r+=s+t,r+="fadeShadow(light"+n+"_shadowCascadeDistances);\n"},t._nonPointShadowMapProjection=function(e,t,i,n,s){var r="("+i+", "+n+");\n";return!t._normalOffsetBias||t._isVsm?2===t._type?t._isPcf&&(e.webgl2||e.extStandardDerivatives)?" getShadowCoordPerspZbuffer"+r:" getShadowCoordPersp"+r:this._directionalShadowMapProjection(t,r,n,s,"getShadowCoordOrtho"):2===t._type?t._isPcf&&(e.webgl2||e.extStandardDerivatives)?" getShadowCoordPerspZbufferNormalOffset"+r:" getShadowCoordPerspNormalOffset"+r:this._directionalShadowMapProjection(t,r,n,s,"getShadowCoordOrthoNormalOffset")},t._getLightSourceShapeString=function(e){switch(e){case 1:return"Rect";case 2:return"Disk";case 3:return"Sphere";default:return""}},t.generateVertexShader=function(e,t,i){var n=this,s=this.device,r=this.options,a=this.chunks,o="",h="";o=this._vsAddBaseCode(o,a,r),h+=" vPositionW = getWorldPosition();\n",2===this.options.pass&&(o+="varying float vDepth;\n",o+="#ifndef VIEWMATRIX\n",o+="#define VIEWMATRIX\n",o+="uniform mat4 matrix_view;\n",o+="#endif\n",o+="#ifndef CAMERAPLANES\n",o+="#define CAMERAPLANES\n",o+="uniform vec4 camera_params;\n\n",o+="#endif\n",h+=" vDepth = -(matrix_view * vec4(vPositionW,1.0)).z * camera_params.x;\n"),this.options.useInstancing&&(this.attributes.instance_line1=qt,this.attributes.instance_line2=jt,this.attributes.instance_line3=Yt,this.attributes.instance_line4=Kt,o+=a.instancingVS),this.needsNormal&&(this.attributes.vertex_normal=yt,h+=" vNormalW = getNormal();\n","sphereMap"===r.reflectionSource&&s.fragmentUniformsCount<=16&&(o+=a.viewNormalVS,h+=" vNormalV = getViewNormal();\n"),r.hasTangents&&(r.heightMap||r.normalMap||r.enableGGXSpecular)?(this.attributes.vertex_tangent=xt,o+=a.tangentBinormalVS,h+=" vTangentW = getTangent();\n",h+=" vBinormalW = getBinormal();\n"):r.enableGGXSpecular&&(o+=a.tangentBinormalVS,h+=" vObjectSpaceUpW = getObjectSpaceUp();\n"));for(var l=0;l<2;l++)e[l]&&(this.attributes["vertex_texCoord"+l]="TEXCOORD"+l,o+=a["uv"+l+"VS"],h+=" vec2 uv"+l+" = getUv"+l+"();\n"),t[l]&&(h+=" vUv"+l+" = uv"+l+";\n");var c=[o,this.varyings,h,[]];i.forEach((function(e){n._setMapTransform(c,e.name,e.id,e.uv)})),o=c[0],this.varyings=c[1],h=c[2],r.vertexColors&&(this.attributes.vertex_color=wt,h+=" vVertexColor = vertex_color;\n"),r.msdf&&r.msdfTextAttribute&&(this.attributes.vertex_outlineParameters=Gt,this.attributes.vertex_shadowParameters=Wt,h+=" unpackMsdfParams();\n",o+=a.msdfVS),(r.useMorphPosition||r.useMorphNormal)&&(r.useMorphTextureBased?(o+="#define MORPHING_TEXTURE_BASED\n",r.useMorphPosition&&(o+="#define MORPHING_TEXTURE_BASED_POSITION\n"),r.useMorphNormal&&(o+="#define MORPHING_TEXTURE_BASED_NORMAL\n"),this.attributes.morph_vertex_id=Kt,o+="attribute float morph_vertex_id;\n"):(o+="#define MORPHING\n",r.useMorphPosition?(this.attributes.morph_pos0=Gt,this.attributes.morph_pos1=Wt,this.attributes.morph_pos2=Ht,this.attributes.morph_pos3=Xt,o+="#define MORPHING_POS03\n",o+="attribute vec3 morph_pos0;\n",o+="attribute vec3 morph_pos1;\n",o+="attribute vec3 morph_pos2;\n",o+="attribute vec3 morph_pos3;\n"):r.useMorphNormal&&(this.attributes.morph_nrm0=Gt,this.attributes.morph_nrm1=Wt,this.attributes.morph_nrm2=Ht,this.attributes.morph_nrm3=Xt,o+="#define MORPHING_NRM03\n",o+="attribute vec3 morph_nrm0;\n",o+="attribute vec3 morph_nrm1;\n",o+="attribute vec3 morph_nrm2;\n",o+="attribute vec3 morph_nrm3;\n"),r.useMorphNormal?(this.attributes.morph_nrm4=qt,this.attributes.morph_nrm5=jt,this.attributes.morph_nrm6=Yt,this.attributes.morph_nrm7=Kt,o+="#define MORPHING_NRM47\n",o+="attribute vec3 morph_nrm4;\n",o+="attribute vec3 morph_nrm5;\n",o+="attribute vec3 morph_nrm6;\n",o+="attribute vec3 morph_nrm7;\n"):(this.attributes.morph_pos4=qt,this.attributes.morph_pos5=jt,this.attributes.morph_pos6=Yt,this.attributes.morph_pos7=Kt,o+="#define MORPHING_POS47\n",o+="attribute vec3 morph_pos4;\n",o+="attribute vec3 morph_pos5;\n",o+="attribute vec3 morph_pos6;\n",o+="attribute vec3 morph_pos7;\n"))),r.skin?(this.attributes.vertex_boneWeights=bt,this.attributes.vertex_boneIndices=St,o+=Yi(s,a),o+="#define SKIN\n"):r.useInstancing&&(o+="#define INSTANCING\n"),r.screenSpace&&(o+="#define SCREENSPACE\n"),r.pixelSnap&&(o+="#define PIXELSNAP\n"),o=this._vsAddTransformCode(o,s,a,r),this.needsNormal&&(o+=a.normalVS),o+="\n",o+=a.startVS,o+=h,o+=a.endVS,o+="}",Object.keys(ns).forEach((function(e){o.indexOf(e)>=0&&(n.varyings+="varying "+ns[e]+" "+e+";\n")}));var u=Qi(s,"LitShader",this.options.pass,a.extensionVS);this.vshader=u+this.varyings+o},t._fsGetBeginCode=function(){for(var e=this.device,t=this.chunks,i=this.options.forceFragmentPrecision,n=Ji(e,"LitShader",this.options.pass,t.extensionPS,i),s=0;s0&&this.defines.push("LIT_SPECULAR_FRESNEL"),t.conserveEnergy&&this.defines.push("LIT_CONSERVE_ENERGY"),t.sheen&&this.defines.push("LIT_SHEEN"),t.iridescence&&this.defines.push("LIT_IRIDESCENCE"));var s=[],r=0,a=!1,o=!1,h=!1,l=t.lights.some((function(e){return e._shape&&0!==e._shape}));t.clusteredLightingEnabled&&t.clusteredLightingAreaLightsEnabled&&(l=!0);var c="highp";7===e.areaLightLutFormat&&(n+="#define AREA_R8_G8_B8_A8_LUTS\n",c="lowp"),(l||t.clusteredLightingEnabled)&&(n+="#define AREA_LIGHTS\n",n+="uniform "+c+" sampler2D areaLightsLutTex1;\n",n+="uniform "+c+" sampler2D areaLightsLutTex2;\n");for(var u=0;u0?i.cubeMapProjectBoxPS:i.cubeMapProjectNonePS,n+=t.skyboxIntensity?i.envMultiplyPS:i.envConstPS),(this.lighting&&t.useSpecular||this.reflections)&&(t.useMetalness&&(n+=i.metalnessModulatePS),2===t.fresnelModel&&(n+=i.fresnelSchlickPS),t.iridescence&&(n+=i.iridescenceDiffractionPS));var m=t.aoMap||t.aoVertexColor;if(m)switch(n+=i.aoDiffuseOccPS,t.occludeSpecular){case 1:n+=t.occludeSpecularFloat?i.aoSpecOccSimplePS:i.aoSpecOccConstSimplePS;break;case 2:n+=t.occludeSpecularFloat?i.aoSpecOccPS:i.aoSpecOccConstPS}if("envAtlasHQ"===t.reflectionSource)n+=t.fixSeams?i.fixCubemapSeamsStretchPS:i.fixCubemapSeamsNonePS,n+=i.envAtlasPS,n+=i.reflectionEnvHQPS.replace(/\$DECODE/g,mn.decodeFunc(t.reflectionEncoding));else if("envAtlas"===t.reflectionSource)n+=i.envAtlasPS,n+=i.reflectionEnvPS.replace(/\$DECODE/g,mn.decodeFunc(t.reflectionEncoding));else if("cubeMap"===t.reflectionSource)n+=t.fixSeams?i.fixCubemapSeamsStretchPS:i.fixCubemapSeamsNonePS,n+=i.reflectionCubePS.replace(/\$DECODE/g,mn.decodeFunc(t.reflectionEncoding));else if("sphereMap"===t.reflectionSource){n+=(e.fragmentUniformsCount>16?i.reflectionSpherePS:i.reflectionSphereLowPS).replace(/\$DECODE/g,mn.decodeFunc(t.reflectionEncoding))}this.reflections&&(t.clearCoat&&(n+=i.reflectionCCPS),t.sheen&&(n+=i.reflectionSheenPS)),t.refraction&&(t.useDynamicRefraction?n+=i.refractionDynamicPS:this.reflections&&(n+=i.refractionCubePS)),t.sheen&&(n+=i.lightSheenPS),t.clusteredLightingEnabled&&(n+=i.clusteredLightUtilsPS,t.clusteredLightingCookiesEnabled&&(n+=i.clusteredLightCookiesPS),t.clusteredLightingShadowsEnabled&&!t.noShadow&&(s[0]=!0,s[4]=!0),h=!0),(r>0||t.clusteredLightingEnabled)&&(a&&(n+=i.shadowCascadesPS),s[0]&&(n+=i.shadowStandardPS),s[4]&&e.webgl2&&(n+=i.shadowStandardGL2PS),o&&(n+=i.shadowVSM_commonPS,s[1]&&(n+=i.shadowVSM8PS),s[2]&&(n+=e.extTextureHalfFloatLinear?i.shadowEVSMPS.replace(/\$/g,"16"):i.shadowEVSMnPS.replace(/\$/g,"16")),s[3]&&(n+=e.extTextureFloatLinear?i.shadowEVSMPS.replace(/\$/g,"32"):i.shadowEVSMnPS.replace(/\$/g,"32"))),e.webgl2||e.extStandardDerivatives||(n+=i.biasConstPS),n+=i.shadowCoordPS+i.shadowCommonPS,h&&(n+=i.shadowCoordPerspZbufferPS)),t.enableGGXSpecular&&(n+="uniform float material_anisotropy;\n"),this.lighting&&(n+=i.lightDiffuseLambertPS,(l||t.clusteredLightingEnabled)&&(n+=i.ltc)),n+="\n";var _=!1;t.useSpecular&&(this.lighting&&(n+=0===t.shadingModel?i.lightSpecularPhongPS:t.enableGGXSpecular?i.lightSpecularAnisoGGXPS:i.lightSpecularBlinnPS),t.fresnelModel||this.reflections||t.diffuseMap||(n+=" uniform vec3 material_ambient;\n",n+="#define LIT_OLD_AMBIENT",_=!0)),n+=i.combinePS,(t.lightMap||t.lightVertexColor)&&(n+=t.useSpecular&&t.dirLightMap?i.lightmapDirAddPS:i.lightmapAddPS);var g=!t.lightMap&&!t.lightVertexColor||t.lightMapWithoutAmbient;g&&("ambientSH"===t.ambientSource?n+=i.ambientSHPS:"envAtlas"===t.ambientSource?("envAtlas"!==t.reflectionSource&&"envAtlasHQ"!==t.reflectionSource&&(n+=i.envAtlasPS),n+=i.ambientEnvPS.replace(/\$DECODE/g,mn.decodeFunc(t.ambientEncoding))):n+=i.ambientConstantPS),t.ambientTint&&!_&&(n+="uniform vec3 material_ambient;\n"),t.msdf&&(t.msdfTextAttribute||(n+="\n#define UNIFORM_TEXT_PARAMETERS"),n+=i.msdfPS),this.needsNormal&&(n+=i.viewDirPS,t.useSpecular&&(n+=t.enableGGXSpecular?i.reflDirAnisoPS:i.reflDirPS));var v,y=!1,x=!1,b=!1,S=!1,w=!1;if(t.clusteredLightingEnabled&&this.lighting&&(S=!0,y=!0,x=!0,w=!0,n+=i.floatUnpackingPS,t.lightMaskDynamic&&(n+="\n#define CLUSTER_MESH_DYNAMIC_LIGHTS"),t.clusteredLightingCookiesEnabled&&(n+="\n#define CLUSTER_COOKIES"),t.clusteredLightingShadowsEnabled&&!t.noShadow&&(n+="\n#define CLUSTER_SHADOWS",n+="\n#define CLUSTER_SHADOW_TYPE_"+Ve[t.clusteredLightingShadowType]),t.clusteredLightingAreaLightsEnabled&&(n+="\n#define CLUSTER_AREALIGHTS"),n+=ts.shaderDefines,t.clusteredLightingShadowsEnabled&&!t.noShadow&&(n+=i.clusteredLightShadowsPS),n+=i.clusteredLightPS),t.twoSidedLighting&&(n+="uniform float twoSidedLightingNegScaleFactor;\n"),n+=this._fsGetStartCode(n,e,i,t),this.needsNormal&&(t.twoSidedLighting?n+=" dVertexNormalW = normalize(gl_FrontFacing ? vNormalW * twoSidedLightingNegScaleFactor : -vNormalW * twoSidedLightingNegScaleFactor);\n":n+=" dVertexNormalW = normalize(vNormalW);\n",(t.heightMap||t.normalMap)&&t.hasTangents&&(t.twoSidedLighting?(n+=" dTangentW = gl_FrontFacing ? vTangentW * twoSidedLightingNegScaleFactor : -vTangentW * twoSidedLightingNegScaleFactor;\n",n+=" dBinormalW = gl_FrontFacing ? vBinormalW * twoSidedLightingNegScaleFactor : -vBinormalW * twoSidedLightingNegScaleFactor;\n"):(n+=" dTangentW = vTangentW;\n",n+=" dBinormalW = vBinormalW;\n")),n+=" getViewDir();\n",p&&(n+=" getTBN();\n")),n+=this.frontendFunc,this.needsNormal&&(t.useSpecular&&(n+=" getReflDir();\n"),t.clearCoat&&(n+=" ccReflDirW = normalize(-reflect(dViewDirW, ccNormalW));\n")),(this.lighting&&t.useSpecular||this.reflections)&&(t.useMetalness&&(n+=" getMetalnessModulate();\n"),t.iridescence&&(n+=" getIridescence(saturate(dot(dViewDirW, dNormalW)));\n")),g&&(n+=" addAmbient();\n",t.separateAmbient&&(n+="\n vec3 dAmbientLight = dDiffuseLight;\n dDiffuseLight = vec3(0);\n ")),t.ambientTint&&!_&&(n+=" dDiffuseLight *= material_ambient;\n"),m&&!t.occludeDirect&&(n+=" occludeDiffuse();\n"),(t.lightMap||t.lightVertexColor)&&(n+=" addLightMap();\n"),this.lighting||this.reflections){this.reflections&&(t.clearCoat&&(n+=" addReflectionCC();\n",t.fresnelModel>0?(n+=" ccFresnel = getFresnelCC(dot(dViewDirW, ccNormalW));\n",n+=" ccReflection.rgb *= ccFresnel;\n"):n+=" ccFresnel = 0.0;\n"),t.useSpecularityFactor&&(n+=" ccReflection.rgb *= dSpecularityFactor;\n"),t.sheen&&(n+=" addReflectionSheen();\n"),n+=" addReflection();\n",t.fresnelModel>0?n+=" dReflection.rgb *= getFresnel(dot(dViewDirW, dNormalW), dSpecularity);\n":n+=" dReflection.rgb *= dSpecularity;\n",t.useSpecularityFactor&&(n+=" dReflection.rgb *= dSpecularityFactor;\n")),l&&(n+=" dSpecularLight *= dSpecularity;\n",t.useSpecular&&(n+=" calcLTCLightValues();\n"));for(var T=0;T 0.00001) {\n",2===M&&(v&&!A._cookieFalloff||(n+=" dAtten *= getSpotEffect(light"+T+"_direction, light"+T+"_innerConeAngle, light"+T+"_outerConeAngle);\n",S=!0))),n+=0!==C?0===M?" dAttenD = getLightDiffuse();\n":" dAttenD = get"+E+"LightDiffuse() * 16.0;\n":" dAtten *= getLightDiffuse();\n",A.castShadows&&!t.noShadow){var P=null,R=void 0;if(1===A._shadowType?(P="VSM8",R="0.0"):2===A._shadowType?(P="VSM16",R="5.54"):3===A._shadowType?(P="VSM32",R=e.textureFloatHighPrecision?"15.0":"5.54"):P=4===A._shadowType?"PCF5x5":"PCF3x3",null!==P)if(1===M){var I="(light"+T+"_shadowMap, light"+T+"_shadowParams);\n";A._normalOffsetBias&&(n+=" normalOffsetPointShadow(light"+T+"_shadowParams);\n"),n+=" float shadow"+T+" = getShadowPoint"+P+I,n+=" dAtten *= mix(1.0, shadow"+T+", light"+T+"_shadowIntensity);\n"}else{var L="light"+T+"_shadowMatrix",D="light"+T+"_shadowParams";n+=this._nonPointShadowMapProjection(e,t.lights[T],L,D,T),2===M&&(P="Spot"+P),n+=" float shadow"+T+" = getShadow"+P+"(light"+T+"_shadowMap, light"+T+"_shadowParams"+(A._isVsm?", "+R:"")+");\n",n+=" dAtten *= mix(1.0, shadow"+T+", light"+T+"_shadowIntensity);\n"}}if(0!==C?t.conserveEnergy&&t.useSpecular?n+=" dDiffuseLight += mix((dAttenD * dAtten) * light"+T+"_color"+(v?" * dAtten3":"")+", vec3(0), dLTCSpecFres);\n":n+=" dDiffuseLight += (dAttenD * dAtten) * light"+T+"_color"+(v?" * dAtten3":"")+";\n":l&&t.conserveEnergy&&t.useSpecular?n+=" dDiffuseLight += mix(dAtten * light"+T+"_color"+(v?" * dAtten3":"")+", vec3(0), dSpecularity);\n":n+=" dDiffuseLight += dAtten * light"+T+"_color"+(v?" * dAtten3":"")+";\n",t.useSpecular&&(n+=" dHalfDirW = normalize(-dLightDirNormW + dViewDirW);\n"),0!==C)t.clearCoat&&(n+=" ccSpecularLight += ccLTCSpecFres * get"+E+"LightSpecularCC() * dAtten * light"+T+"_color"+(v?" * dAtten3":"")+";\n"),t.useSpecular&&(n+=" dSpecularLight += dLTCSpecFres * get"+E+"LightSpecular() * dAtten * light"+T+"_color"+(v?" * dAtten3":"")+";\n");else{var k=!1;0===M&&t.fresnelModel>0&&(k=!0),t.clearCoat&&(n+=" ccSpecularLight += getLightSpecularCC(dHalfDirW) * dAtten * light"+T+"_color",n+=v?" * dAtten3":"",n+=k?" * getFresnelCC(dot(dViewDirW, dHalfDirW))":"",n+=";\n"),t.sheen&&(n+=" sSpecularLight += getLightSpecularSheen(dHalfDirW) * dAtten * light"+T+"_color",n+=v?" * dAtten3":"",n+=";\n"),t.useSpecular&&(n+=" dSpecularLight += getLightSpecular(dHalfDirW) * dAtten * light"+T+"_color",n+=v?" * dAtten3":"",n+=k?" * getFresnel(dot(dViewDirW, dHalfDirW), dSpecularity)":"",n+=";\n")}0!==M&&(n+=" }\n"),n+="\n"}}t.clusteredLightingEnabled&&this.lighting&&(x=!0,b=!0,y=!0,n+=" addClusteredLights();\n"),l&&(t.clearCoat&&(n+=" ccSpecularity = 1.0;\n"),t.useSpecular&&(n+=" dSpecularity = vec3(1);\n")),t.refraction&&(n+=" addRefraction();\n")}n+="\n",m&&(t.occludeDirect&&(n+=" occludeDiffuse();\n"),1!==t.occludeSpecular&&2!==t.occludeSpecular||(n+=" occludeSpecular();\n")),t.useSpecularityFactor&&(n+=" dSpecularLight *= dSpecularityFactor;\n"),!1===t.opacityFadesSpecular&&(2!==t.blendType&&4!==t.blendType||(n+="float specLum = dot((dSpecularLight + dReflection.rgb * dReflection.a), vec3( 0.2126, 0.7152, 0.0722 ));\n",n+="#ifdef LIT_CLEARCOAT\n specLum += dot(ccSpecularLight * ccSpecularity + ccReflection.rgb * ccSpecularity, vec3( 0.2126, 0.7152, 0.0722 ));\n#endif\n",n+="dAlpha = clamp(dAlpha + gammaCorrectInput(specLum), 0.0, 1.0);\n"),n+="dAlpha *= material_alphaFade;\n"),n+=i.endPS,2===t.blendType||6===t.blendType||t.alphaToCoverage?n+=i.outputAlphaPS:4===t.blendType?n+=i.outputAlphaPremulPS:n+=i.outputAlphaOpaquePS,t.msdf&&(n+=" gl_FragColor = applyMsdf(gl_FragColor);\n"),n+="\n",n+="}\n",y&&(n=i.lightDirPointPS+n),x&&(n=i.falloffLinearPS+n),b&&(n=i.falloffInvSquaredPS+n),S&&(n=i.spotPS+n),w&&!t.clusteredLightingEnabled&&(n=i.cookiePS+n);var O="";return n.includes("dReflection")&&(O+="vec4 dReflection;\n"),n.includes("dTBN")&&(O+="mat3 dTBN;\n"),n.includes("dVertexNormalW")&&(O+="vec3 dVertexNormalW;\n"),n.includes("dTangentW")&&(O+="vec3 dTangentW;\n"),n.includes("dBinormalW")&&(O+="vec3 dBinormalW;\n"),n.includes("dViewDirW")&&(O+="vec3 dViewDirW;\n"),n.includes("dReflDirW")&&(O+="vec3 dReflDirW;\n"),n.includes("dHalfDirW")&&(O+="vec3 dHalfDirW;\n"),n.includes("dDiffuseLight")&&(O+="vec3 dDiffuseLight;\n"),n.includes("dSpecularLight")&&(O+="vec3 dSpecularLight;\n"),n.includes("dLightDirNormW")&&(O+="vec3 dLightDirNormW;\n"),n.includes("dLightDirW")&&(O+="vec3 dLightDirW;\n"),n.includes("dLightPosW")&&(O+="vec3 dLightPosW;\n"),n.includes("dShadowCoord")&&(O+="vec3 dShadowCoord;\n"),n.includes("dAtten")&&(O+="float dAtten;\n"),n.includes("dAttenD")&&(O+="float dAttenD;\n"),n.includes("dAtten3")&&(O+="vec3 dAtten3;\n"),n.includes("dMsdf")&&(O+="vec4 dMsdf;\n"),n.includes("ccFresnel")&&(O+="float ccFresnel;\n"),n.includes("ccReflection")&&(O+="vec3 ccReflection;\n"),n.includes("ccReflDirW")&&(O+="vec3 ccReflDirW;\n"),n.includes("ccSpecularLight")&&(O+="vec3 ccSpecularLight;\n"),n.includes("ccSpecularityNoFres")&&(O+="float ccSpecularityNoFres;\n"),n.includes("sSpecularLight")&&(O+="vec3 sSpecularLight;\n"),n.includes("sReflection")&&(O+="vec3 sReflection;\n"),this._fsGetBeginCode()+this.varyings+this._fsGetBaseCode()+(t.detailModes?i.detailModesPS:"")+O+this.frontendDecl+n},t.generateFragmentShader=function(e,t,i,n){var s=this.options;this.frontendDecl=e,this.frontendCode=t,this.frontendFunc=i,this.lightingUv=n,3===s.pass?this.fshader=this._fsGetPickPassCode():2===s.pass?this.fshader=this._fsGetDepthPassCode():this.shadowPass?this.fshader=this._fsGetShadowPassCode():s.customFragmentShader?this.fshader=this._fsGetBeginCode()+s.customFragmentShader:this.fshader=this._fsGetLitPassCode()},t.getDefinition=function(){var e={attributes:this.attributes,vshader:this.vshader,fshader:this.fshader};return Hi.isForward(this.options.pass)&&(e.tag=1),e},e}(),rs=function(){function e(){this.code=""}var t=e.prototype;return t.append=function(){for(var e=this,t=arguments.length,i=new Array(t),n=0;n0){if(i[e]t.length){for(var n=t,s=n.charAt(n.length-1),r=i[e]-n.length,a=0;a0&&(p.append("float ccSpecularity;"),p.append("float ccGlossiness;"),p.append("vec3 ccNormalW;"),m.append(this._addMap("clearCoat","clearCoatPS",t,i.chunks,a)),m.append(this._addMap("clearCoatGloss","clearCoatGlossPS",t,i.chunks,a)),m.append(this._addMap("clearCoatNormal","clearCoatNormalPS",t,i.chunks,a)),_.append("getClearCoat();"),_.append("getClearCoatGlossiness();"),_.append("getClearCoatNormal();")),t.lightMap||t.lightVertexColor){var y=t.dirLightMap&&t.useSpecular,x=y?"lightmapDirPS":"lightmapSinglePS";p.append("vec3 dLightmap;"),y&&p.append("vec3 dLightmapDir;"),m.append(this._addMap("light",x,t,i.chunks,a,t.lightMapEncoding)),_.append("getLightMap();")}-1===m.code.indexOf("texture2DSRGB")&&-1===m.code.indexOf("texture2DRGBM")&&-1===m.code.indexOf("texture2DRGBE")||m.prepend(i.chunks.textureSamplePS)}else t.alphaTest&&(p.append("float dAlpha;"),m.append(this._addMap("opacity","opacityPS",t,i.chunks,a)),m.append(i.chunks.alphaTestPS),_.append("getOpacity();"),_.append("alphaTest(dAlpha);"));for(var b in a)p.append("uniform sampler2D "+a[b]+";");return _.code="\n"+_.code.split("\n").map((function(e){return" "+e})).join("\n")+"\n\n",i.generateFragmentShader(p.code,m.code,_.code,g),i.getDefinition()}},hs=2.399963229728653,ls=function(e,t,i){var n=t*hs,s=Math.sqrt(t)/Math.sqrt(i);e.x=s*Math.cos(n),e.y=s*Math.sin(n)},cs=function(e,t,i,n,s){void 0===n&&(n=0),void 0===s&&(s=1),n=1-2*n,s=1-2*s;var r=de.lerp(n,s,t/i),a=Math.sqrt(1-r*r),o=hs*t;e.x=Math.cos(o)*a,e.y=r,e.z=Math.sin(o)*a},us=function(e){var t=(e<<16|e>>>16)>>>0;return 2.3283064365386963e-10*(t=((16711935&(t=((252645135&(t=((858993459&(t=((1431655765&t)<<1|(2863311530&t)>>>1)>>>0))<<2|(3435973836&t)>>>2)>>>0))<<4|(4042322160&t)>>>4)>>>0))<<8|(4278255360&t)>>>8)>>>0)},ds=function(e){switch(e){case ri:return"Cubemap";case oi:return"Octahedral";default:return"Equirect"}},fs=function(e,t,i){if(e<=0)t[i+0]=0,t[i+1]=0,t[i+2]=0,t[i+3]=0;else if(e>=1)t[i+0]=255,t[i+1]=0,t[i+2]=0,t[i+3]=0;else{var n=1*e%1,s=255*e%1,r=65025*e%1,a=16581375*e%1;n-=s/255,s-=r/255,r-=a/255,t[i+0]=Math.min(255,Math.floor(256*n)),t[i+1]=Math.min(255,Math.floor(256*s)),t[i+2]=Math.min(255,Math.floor(256*r)),t[i+3]=Math.min(255,Math.floor(256*a))}},ps=function(e,t,i,n){var s=2*i*Math.PI,r=Math.pow(1-t,1/(n+1)),a=Math.sqrt(1-r*r);e.set(Math.cos(s)*a,Math.sin(s)*a,r).normalize()},ms=function(e,t,i){var n=2*i*Math.PI,s=Math.sqrt(1-t),r=Math.sqrt(t);e.set(Math.cos(n)*r,Math.sin(n)*r,s).normalize()},_s=function(e,t,i,n){var s=2*i*Math.PI,r=Math.sqrt((1-t)/(1+(n*n-1)*t)),a=Math.sqrt(1-r*r);e.set(Math.cos(s)*a,Math.sin(s)*a,r).normalize()},gs=function(e,t){var i=e*t,n=t/(1-e*e+i*i);return n*n*(1/Math.PI)},vs={16:{2:26,8:20,32:17,128:16,512:16},32:{2:53,8:40,32:34,128:32,512:32},128:{2:214,8:163,32:139,128:130,512:128},1024:{2:1722,8:1310,32:1114,128:1041,512:1025}},ys=function(e,t,i){for(var n=i/e,s=1-Math.log2(t)/11,r=s*s,a=new ye,o=new ye,h=new ye(0,0,1),l=[],c=function(e,t){var i=vs[e];return i&&i[t]||e}(e,t),u=0;u0){var f=gs(Math.min(1,d),r)/4+.001,p=.5*Math.log2(n/f);l.push(o.x,o.y,o.z,p)}}for(;l.length<4*e;)l.push(0,0,0,0);return l},xs=function(e,t,i){var n=function(e){for(var t=e.length,i=Math.min(t,512),n=Math.ceil(t/i),s=new Uint8Array(i*n*4),r=0,a=0;a>2*h),rect:r,seamPixels:s}),r.y+=r.w,r.z=Math.max(1,Math.floor(.5*r.z)),r.w=Math.max(1,Math.floor(.5*r.w));return r.set(128*s,384*s,64*s,32*s),Ps(e,n,{numSamples:(null==t?void 0:t.numAmbientSamples)||2048,distribution:"lambert",rect:r,seamPixels:s}),n},e.generatePrefilteredAtlas=function(e,t){for(var i=e[0].device,n=e[0].format,s=e[0].type,r=(null==t?void 0:t.target)||new wn(i,{name:"envPrefilteredAtlas",width:(null==t?void 0:t.size)||512,height:(null==t?void 0:t.size)||512,format:n,type:s,projection:ai,addressU:1,addressV:1,mipmaps:!1}),a=r.width/512,o=new Se(0,0,512*a,256*a),h=Is(512),l=0;l0,e.forceFragmentPrecision=i.forceFragmentPrecision||"",e.chunks=i.chunks||"",e.blendType=i.blendType,e.forceUv1=i.forceUv1,e.separateAmbient=!1,e.screenSpace=n&&0!=(n&We),e.skin=n&&0!=(2&n),e.useInstancing=n&&0!=(32&n),e.useMorphPosition=n&&0!=(n&He),e.useMorphNormal=n&&0!=(n&Xe),e.useMorphTextureBased=n&&0!=(n&qe),e.nineSlicedMode=i.nineSlicedMode||0,t.clusteredLightingEnabled&&i.useLighting?(e.clusteredLightingEnabled=!0,e.clusteredLightingCookiesEnabled=t.lighting.cookiesEnabled,e.clusteredLightingShadowsEnabled=t.lighting.shadowsEnabled,e.clusteredLightingShadowType=t.lighting.shadowType,e.clusteredLightingAreaLightsEnabled=t.lighting.areaLightsEnabled):(e.clusteredLightingEnabled=!1,e.clusteredLightingCookiesEnabled=!1,e.clusteredLightingShadowsEnabled=!1,e.clusteredLightingAreaLightsEnabled=!1)},t._updateUVOptions=function(e,t,i,n){var s=!1,r=!1,a=!1;i&&(s=0!=(4&i),r=0!=(8&i),a=0!=(16&i)),e.vertexColors=!1,this._mapXForms=[];var o={};for(var h in as)this._updateTexOptions(e,t,h,s,r,a,n,o);this._mapXForms=null},t._updateMinOptions=function(e,t){e.opacityTint=1!==t.opacity&&3!==t.blendType,e.lights=[]},t._updateMaterialOptions=function(e,t){var i,n,s,r,a,o=(t.diffuseTint||!t.diffuseMap&&!t.diffuseVertexColor)&&Us(t.diffuse),h=!!(t.useMetalness||t.specularMap||t.sphereMap||t.cubeMap||(a=t.specular,0!==a.r||0!==a.g||0!==a.b)||t.specularityFactor>0&&t.useMetalness||t.enableGGXSpecular||t.clearCoat>0),l=!t.useMetalness||t.useMetalnessSpecularColor,c=h&&(t.specularTint||!t.specularMap&&!t.specularVertexColor)&&Us(t.specular),u=h&&t.useMetalnessSpecularColor&&(t.specularityFactorTint||t.specularityFactor<1&&!t.specularityFactorMap),d=!t.emissiveMap||Us(t.emissive)&&t.emissiveTint,f=1!==t.emissiveIntensity,p=!!t.normalMap&&(t.normalMap.format===ht||t.normalMap.type===ei);e.opacityTint=1!==t.opacity&&3!==t.blendType?1:0,e.blendMapsWithColors=!0,e.ambientTint=t.ambientTint,e.diffuseTint=o?2:0,e.specularTint=c?2:0,e.specularityFactorTint=u?1:0,e.useSpecularityFactor=(u||!!t.specularityFactorMap)&&t.useMetalnessSpecularColor,e.useSpecularColor=l,e.metalnessTint=t.useMetalness&&t.metalness<1?1:0,e.glossTint=1,e.emissiveTint=(d?2:0)+(f?1:0),e.alphaToCoverage=t.alphaToCoverage,e.normalizeNormalMap=t.normalizeNormalMap,e.ambientSH=!!t.ambientSH,e.useSpecular=h,e.diffuseEncoding=null==(i=t.diffuseMap)?void 0:i.encoding,e.diffuseDetailEncoding=null==(n=t.diffuseDetailMap)?void 0:n.encoding,e.emissiveEncoding=null==(s=t.emissiveMap)?void 0:s.encoding,e.lightMapEncoding=null==(r=t.lightMap)?void 0:r.encoding,e.conserveEnergy=t.conserveEnergy,e.opacityFadesSpecular=t.opacityFadesSpecular,e.alphaFade=t.alphaFade,e.occludeSpecular=t.occludeSpecular,e.occludeSpecularFloat=1!==t.occludeSpecularIntensity,e.occludeDirect=t.occludeDirect,e.shadingModel=t.shadingModel,e.fresnelModel=t.fresnelModel,e.packedNormal=p,e.fastTbn=t.fastTbn,e.cubeMapProjection=t.cubeMapProjection,e.customFragmentShader=t.customFragmentShader,e.refraction=(t.refraction||!!t.refractionMap)&&(t.useDynamicRefraction||!!e.reflectionSource),e.useDynamicRefraction=t.useDynamicRefraction,e.refractionIndexTint=t.refractionIndex!==1/1.5?1:0,e.thicknessTint=t.useDynamicRefraction&&1!==t.thickness?1:0,e.useMetalness=t.useMetalness,e.specularEncoding=t.specularEncoding||"linear",e.sheenEncoding=t.sheenEncoding||"linear",e.enableGGXSpecular=t.enableGGXSpecular,e.msdf=!!t.msdfMap,e.msdfTextAttribute=!!t.msdfTextAttribute,e.twoSidedLighting=t.twoSidedLighting,e.pixelSnap=t.pixelSnap,e.aoMapUv=t.aoUvSet,e.diffuseDetail=!!t.diffuseMap,e.normalDetail=!!t.normalMap,e.diffuseDetailMode=t.diffuseDetailMode,e.detailModes=!!e.diffuseDetail,e.clearCoat=!!t.clearCoat,e.clearCoatTint=1!==t.clearCoat?1:0,e.clearCoatGlossiness=!!t.clearCoatGlossiness,e.clearCoatGlossTint=1!==t.clearCoatGlossiness?1:0,e.iridescence=t.useIridescence&&0!==t.iridescence,e.iridescenceTint=1!==t.iridescence?1:0,e.sheen=t.useSheen,e.sheenTint=t.useSheen&&Us(t.sheen)?2:0,e.sheenGlossinessTint=1},t._updateEnvOptions=function(e,t,i){e.fog=t.useFog?i.fog:"none",e.gamma=t.useGammaTonemap?i.gammaCorrection:0,e.toneMap=t.useGammaTonemap?i.toneMapping:-1,e.fixSeams=!!t.cubeMap&&t.cubeMap.fixCubemapSeams;var n=0===t.shadingModel,s=!1;if(t.envAtlas&&t.cubeMap&&!n?(e.reflectionSource="envAtlasHQ",e.reflectionEncoding=t.envAtlas.encoding):t.envAtlas&&!n?(e.reflectionSource="envAtlas",e.reflectionEncoding=t.envAtlas.encoding):t.cubeMap?(e.reflectionSource="cubeMap",e.reflectionEncoding=t.cubeMap.encoding):t.sphereMap?(e.reflectionSource="sphereMap",e.reflectionEncoding=t.sphereMap.encoding):t.useSkybox&&i.envAtlas&&i.skybox&&!n?(e.reflectionSource="envAtlasHQ",e.reflectionEncoding=i.envAtlas.encoding,s=!0):t.useSkybox&&i.envAtlas&&!n?(e.reflectionSource="envAtlas",e.reflectionEncoding=i.envAtlas.encoding,s=!0):t.useSkybox&&i.skybox?(e.reflectionSource="cubeMap",e.reflectionEncoding=i.skybox.encoding,s=!0):(e.reflectionSource=null,e.reflectionEncoding=null),t.ambientSH&&!n)e.ambientSource="ambientSH",e.ambientEncoding=null;else{var r=t.envAtlas||(t.useSkybox&&i.envAtlas?i.envAtlas:null);r&&!n?(e.ambientSource="envAtlas",e.ambientEncoding=r.encoding):(e.ambientSource="constant",e.ambientEncoding=null)}e.skyboxIntensity=s&&(1!==i.skyboxIntensity||i.physicalUnits),e.useCubeMapRotation=s&&i.skyboxRotation&&!i.skyboxRotation.equals(Pe.IDENTITY)},t._updateLightOptions=function(e,t,i,n,s){if(e.lightMap=!1,e.lightMapChannel="",e.lightMapUv=0,e.lightMapTransform=0,e.lightMapWithoutAmbient=!1,e.dirLightMap=!1,i&&(e.noShadow=0!=(1&i),0!=(64&i)&&(e.lightMapEncoding="rgbm",e.lightMap=!0,e.lightMapChannel="rgb",e.lightMapUv=1,e.lightMapTransform=0,e.lightMapWithoutAmbient=!t.lightMap,0!=(i&Ge)&&(e.dirLightMap=!0),0!=(i&je)&&(e.lightMapWithoutAmbient=!1))),t.useLighting){var r=[],a=i?i>>16:1;e.lightMaskDynamic=!!(1&a),n&&(this._collectLights(0,n[0],r,a),this._collectLights(1,n[1],r,a,s),this._collectLights(2,n[2],r,a,s)),e.lights=r}else e.lights=[];0===e.lights.length&&(e.noShadow=!0)},t._updateTexOptions=function(e,t,i,n,s,r,a,o){var h=i+"Map",l=i+"VertexColor",c=i+"VertexColorChannel",u=h+"Channel",d=h+"Transform",f=h+"Uv",p=h+"Identifier";"light"!==i&&(e[h]=!1,e[u]="",e[d]=0,e[f]=0,e[p]=void 0),e[l]=!1,e[c]="";var m="opacity"===i;if((!m||3!==t.blendType||0!==t.alphaTest||t.alphaToCoverage)&&(!a||m)&&("height"!==i&&t[l]&&r&&(e[l]=t[l],e[c]=t[c],e.vertexColors=!0),t[h])){var _=!0;if(0!==t[f]||n||(_=!1),1!==t[f]||s||(_=!1),_){var g=t[h].id,v=o[g];void 0===v&&(o[g]=i,v=i),e[h]=!!t[h],e[p]=v,e[d]=this._getMapTransformID(t.getUniform(d),t[f]),e[u]=t[u],e[f]=t[f]}}},t._collectLights=function(e,t,i,n,s){for(var r=0;r0){var s=1/this.refractionIndex,r=(s-1)/(s+1);this._setParameter("material_f0",r*r)}else this._setParameter("material_f0",1);else this.specularMap&&!this.specularTint||this._setParameter("material_specular",n("specular"));for(var a in this.enableGGXSpecular&&this._setParameter("material_anisotropy",this.anisotropy),this.clearCoat>0&&(this._setParameter("material_clearCoat",this.clearCoat),this._setParameter("material_clearCoatGlossiness",this.clearCoatGlossiness),this._setParameter("material_clearCoatBumpiness",this.clearCoatBumpiness)),this._setParameter("material_shininess",n("shininess")),this.emissiveMap&&!this.emissiveTint||this._setParameter("material_emissive",n("emissive")),1!==this.emissiveIntensity&&this._setParameter("material_emissiveIntensity",this.emissiveIntensity),this.refraction>0&&(this._setParameter("material_refraction",this.refraction),this._setParameter("material_refractionIndex",this.refractionIndex)),this.useDynamicRefraction&&(this._setParameter("material_thickness",this.thickness),this._setParameter("material_attenuation",n("attenuation")),this._setParameter("material_invAttenuationDistance",0===this.attenuationDistance?0:1/this.attenuationDistance)),this.useIridescence&&(this._setParameter("material_iridescence",this.iridescence),this._setParameter("material_iridescenceRefractionIndex",this.iridescenceRefractionIndex),this._setParameter("material_iridescenceThicknessMin",this.iridescenceThicknessMin),this._setParameter("material_iridescenceThicknessMax",this.iridescenceThicknessMax)),this._setParameter("material_opacity",this.opacity),!1===this.opacityFadesSpecular&&this._setParameter("material_alphaFade",this.alphaFade),this.occludeSpecular&&this._setParameter("material_occludeSpecularIntensity",this.occludeSpecularIntensity),1===this.cubeMapProjection&&this._setParameter(n("cubeMapProjectionBox")),as)this._updateMap(a);this.ambientSH&&this._setParameter("ambientSH[0]",this.ambientSH),this.normalMap&&this._setParameter("material_bumpiness",this.bumpiness),this.normalMap&&this.normalDetailMap&&this._setParameter("material_normalDetailMapBumpiness",this.normalDetailMapBumpiness),this.heightMap&&this._setParameter("material_heightMapFactor",n("heightMapFactor"));var o=0===this.shadingModel;this.envAtlas&&this.cubeMap&&!o?(this._setParameter("texture_envAtlas",this.envAtlas),this._setParameter("texture_cubeMap",this.cubeMap)):this.envAtlas&&!o?this._setParameter("texture_envAtlas",this.envAtlas):this.cubeMap?this._setParameter("texture_cubeMap",this.cubeMap):this.sphereMap&&this._setParameter("texture_sphereMap",this.sphereMap),this._setParameter("material_reflectivity",this.reflectivity),this._processParameters("_activeParams"),this._dirtyShader&&this.clearVariants()},i.updateEnvUniforms=function(e,t){var i=0===this.shadingModel;!(this.envAtlas&&!i||this.cubeMap||this.sphereMap)&&this.useSkybox&&(t.envAtlas&&t.skybox&&!i?(this._setParameter("texture_envAtlas",t.envAtlas),this._setParameter("texture_cubeMap",t.skybox)):t.envAtlas&&!i?this._setParameter("texture_envAtlas",t.envAtlas):t.skybox&&this._setParameter("texture_cubeMap",t.skybox),!t.skyboxRotation.equals(Pe.IDENTITY)&&t._skyboxRotationMat3&&this._setParameter("cubeMapRotationMatrix",t._skyboxRotationMat3.data)),this._processParameters("_activeLightingParams")},i.getShaderVariant=function(e,t,i,n,s,r,a,o){this.updateEnvUniforms(e,t);var h=2===s||3===s||Hi.isShadow(s),l=h?os.optionsContextMin:os.optionsContext;h?this.shaderOptBuilder.updateMinRef(l,t,this,i,n,s,r):this.shaderOptBuilder.updateRef(l,t,this,i,n,s,r),this.onUpdateShader&&(l=this.onUpdateShader(l));var c=new Os(a,o),u=e.getProgramLibrary();u.register("standard",os);var d=u.getProgram("standard",l,c);return this._dirtyShader=!1,d},i.destroy=function(){for(var t in this._assetReferences)this._assetReferences[t]._unbind();this._assetReferences=null,e.prototype.destroy.call(this)},$(t,[{key:"shader",get:function(){return null},set:function(e){}},{key:"chunks",get:function(){return this._dirtyShader=!0,this._chunks},set:function(e){this._dirtyShader=!0,this._chunks=e}}]),t}(Bs);Zs.TEXTURE_PARAMETERS=Gs,Zs.CUBEMAP_PARAMETERS=Hs;var $s=function(e,t){Ys[e]=t},Qs=function(e,t,i,n){Object.defineProperty(Zs.prototype,e,{get:n||function(){return this["_"+e]},set:i}),js[e]={value:t}},Js=function(e){return e.defaultValue&&e.defaultValue.clone?function(e){var t="_"+e.name,i=e.dirtyShaderFunc||function(){return!0};Qs(e.name,(function(){return e.defaultValue.clone()}),(function(e){var n=this[t];n.equals(e)||(this._dirtyShader=this._dirtyShader||i(n,e),this[t]=n.copy(e))}),e.getterFunc)}(e):function(e){var t="_"+e.name,i=e.dirtyShaderFunc||function(){return!0};Qs(e.name,(function(){return e.defaultValue}),(function(e){var n=this[t];n!==e&&(this._dirtyShader=this._dirtyShader||i(n,e),this[t]=e)}),e.getterFunc)}(e)};function er(e,t,i,n,s,r){as[e]=i,Js({name:e+"Map",defaultValue:null,dirtyShaderFunc:function(e,t){return!!e!=!!t||e&&(e.type!==t.type||e.fixCubemapSeams!==t.fixCubemapSeams||e.format!==t.format)}}),Js({name:e+"MapTiling",defaultValue:new be(1,1)}),Js({name:e+"MapOffset",defaultValue:new be(0,0)}),Js({name:e+"MapRotation",defaultValue:0}),Js({name:e+"MapUv",defaultValue:t}),i>0&&Js({name:e+"MapChannel",defaultValue:n||(i>1?"rgb":"g")}),s&&(Js({name:e+"VertexColor",defaultValue:!1}),i>0&&Js({name:e+"VertexColorChannel",defaultValue:n||(i>1?"rgb":"g")})),r&&Js({name:e+"Mode",defaultValue:"mul"});var a=e+"MapTiling",o=e+"MapOffset",h=e+"MapRotation",l=e+"MapTransform";$s(l,(function(e,t,i){var n=e[a],s=e[o],r=e[h];if(1===n.x&&1===n.y&&0===s.x&&0===s.y&&0===r)return null;var c=e._allocUniform(l,(function(){return[{name:"texture_"+l+"0",value:new Float32Array(3)},{name:"texture_"+l+"1",value:new Float32Array(3)}]})),u=Math.cos(r*de.DEG_TO_RAD),d=Math.sin(r*de.DEG_TO_RAD),f=c[0].value;f[0]=u*n.x,f[1]=-d*n.y,f[2]=s.x;var p=c[1].value;return p[0]=d*n.x,p[1]=u*n.y,p[2]=1-n.y-s.y,c}))}function tr(e,t){Js({name:e,defaultValue:t,getterFunc:function(){return this._dirtyShader=!0,this["_"+e]}}),$s(e,(function(t,i,n){var s=t._allocUniform(e,(function(){return new Float32Array(3)})),r=t[e];return t.useGammaTonemap&&n.gammaCorrection?(s[0]=Math.pow(r.r,2.2),s[1]=Math.pow(r.g,2.2),s[2]=Math.pow(r.b,2.2)):(s[0]=r.r,s[1]=r.g,s[2]=r.b),s}))}function ir(e,t,i){Js({name:e,defaultValue:t,dirtyShaderFunc:function(e,t){return(0===e||1===e)!=(0===t||1===t)}}),$s(e,i)}function nr(e,t){Js({name:e,defaultValue:null,dirtyShaderFunc:function(e,t){return!!e==!!t}}),$s(e,t)}function sr(e,t){Js({name:e,defaultValue:t})}!function(){tr("ambient",new me(.7,.7,.7)),tr("diffuse",new me(1,1,1)),tr("specular",new me(0,0,0)),tr("emissive",new me(0,0,0)),tr("sheen",new me(1,1,1)),tr("attenuation",new me(1,1,1)),ir("emissiveIntensity",1),ir("specularityFactor",1),ir("sheenGlossiness",0),ir("shininess",25,(function(e,t,i){return 0===e.shadingModel?Math.pow(2,.01*e.shininess*11):.01*e.shininess})),ir("heightMapFactor",1,(function(e,t,i){return.025*e.heightMapFactor})),ir("opacity",1),ir("alphaFade",1),ir("alphaTest",0),ir("bumpiness",1),ir("normalDetailMapBumpiness",1),ir("reflectivity",1),ir("occludeSpecularIntensity",1),ir("refraction",0),ir("refractionIndex",1/1.5),ir("thickness",0),ir("attenuationDistance",0),ir("metalness",1),ir("anisotropy",0),ir("clearCoat",0),ir("clearCoatGlossiness",1),ir("clearCoatBumpiness",1),ir("aoUvSet",0,null),ir("iridescence",0),ir("iridescenceRefractionIndex",1/1.5),ir("iridescenceThicknessMin",0),ir("iridescenceThicknessMax",0),nr("ambientSH"),nr("cubeMapProjectionBox",(function(e,t,i){var n=e._allocUniform("cubeMapProjectionBox",(function(){return[{name:"envBoxMin",value:new Float32Array(3)},{name:"envBoxMax",value:new Float32Array(3)}]})),s=e.cubeMapProjectionBox.getMin(),r=n[0].value;r[0]=s.x,r[1]=s.y,r[2]=s.z;var a=e.cubeMapProjectionBox.getMax(),o=n[1].value;return o[0]=a.x,o[1]=a.y,o[2]=a.z,n})),sr("ambientTint",!1),sr("diffuseTint",!1),sr("specularTint",!1),sr("specularityFactorTint",!1),sr("emissiveTint",!1),sr("fastTbn",!1),sr("useMetalness",!1),sr("useMetalnessSpecularColor",!1),sr("useSheen",!1),sr("enableGGXSpecular",!1),sr("occludeDirect",!1),sr("normalizeNormalMap",!0),sr("conserveEnergy",!0),sr("opacityFadesSpecular",!0),sr("occludeSpecular",1),sr("shadingModel",1),sr("fresnelModel",2),sr("useDynamicRefraction",!1),sr("cubeMapProjection",0),sr("customFragmentShader",null),sr("forceFragmentPrecision",null),sr("useFog",!0),sr("useLighting",!0),sr("useGammaTonemap",!0),sr("useSkybox",!0),sr("forceUv1",!1),sr("pixelSnap",!1),sr("twoSidedLighting",!1),sr("nineSlicedMode",void 0),sr("msdfTextAttribute",!1),sr("useIridescence",!1),er("diffuse",0,3,"",!0),er("specular",0,3,"",!0),er("emissive",0,3,"",!0),er("thickness",0,1,"",!0),er("specularityFactor",0,1,"",!0),er("normal",0,-1,"",!1),er("metalness",0,1,"",!0),er("gloss",0,1,"",!0),er("opacity",0,1,"a",!0),er("refraction",0,1,"",!0),er("height",0,1,"",!1),er("ao",0,1,"",!0),er("light",1,3,"",!0),er("msdf",0,3,"",!1),er("diffuseDetail",0,3,"",!1,!0),er("normalDetail",0,-1,"",!1),er("clearCoat",0,1,"",!0),er("clearCoatGloss",0,1,"",!0),er("clearCoatNormal",0,-1,"",!1),er("sheen",0,3,"",!0),er("sheenGloss",0,1,"",!0),er("iridescence",0,1,"",!0),er("iridescenceThickness",0,1,"",!0),nr("cubeMap"),nr("sphereMap"),nr("envAtlas");var e=[null,null,null,null,null,null];Qs("prefilteredCubemaps",(function(){return e.slice()}),(function(e){var t=this._prefilteredCubemaps;e=e||[];for(var i=!1,n=!0,s=0;s<6;++s){var r=e[s]||null;t[s]!==r&&(t[s]=r,i=!0),n=n&&!!t[s]}i&&(n?this.envAtlas=Ls.generatePrefilteredAtlas(t,{target:this.envAtlas}):this.envAtlas&&(this.envAtlas.destroy(),this.envAtlas=null),this._dirtyShader=!0)}),(function(){return this._prefilteredCubemaps}))}();var rr=function(){function e(e){this.processedCache=new Map,this._device=e,this._cache={},this._generators={},this._isClearingCache=!1,this._precached=!1,this._programsCollection=[],this._defaultStdMatOption={},this._defaultStdMatOptionMin={};var t=new Zs;t.shaderOptBuilder.updateRef(this._defaultStdMatOption,{},t,null,[],0,null),t.shaderOptBuilder.updateMinRef(this._defaultStdMatOptionMin,{},t,null,[],4,null)}var t=e.prototype;return t.register=function(e,t){this.isRegistered(e)||(this._generators[e]=t)},t.unregister=function(e){this.isRegistered(e)&&delete this._generators[e]},t.isRegistered=function(e){return void 0!==this._generators[e]},t.generateShader=function(e,t,i,n){var s=this._cache[i];if(!s){var r;n.lights&&(r=n.lights,n.lights=r.map((function(e){var t=e.clone?e.clone():e;return t.key=e.key,t}))),this.storeNewProgram(t,n),n.lights&&(n.lights=r),this._precached;var a=this._device,o=e.createShaderDefinition(a,n);o.name=t+"-pass:"+n.pass,s=this._cache[i]=new zi(a,o)}return s},t.getProgram=function(e,t,i){var n=this._generators[e];if(!n)return null;var s=n.generateKey(t),r=s+"#"+JSON.stringify(i),a=this.processedCache.get(r);if(!a){var o=this.generateShader(n,e,s,t).definition,h={attributes:o.attributes,vshader:o.vshader,fshader:o.fshader,processingOptions:i};a=new zi(this._device,h),this.processedCache.set(r,a)}return a},t.storeNewProgram=function(e,t){var i={};if("standard"===e){var n=this._getDefaultStdMatOptions(t.pass);for(var s in t)(t.hasOwnProperty(s)&&n[s]!==t[s]||"pass"===s)&&(i[s]=t[s])}else i=t;this._programsCollection.push(JSON.stringify({name:e,options:i}))},t.dumpPrograms=function(){var e="let device = pc.app ? pc.app.graphicsDevice : pc.Application.getApplication().graphicsDevice;\n";e+="let shaders = [",this._programsCollection[0]&&(e+="\n\t"+this._programsCollection[0]);for(var t=1;t1&&this.impl.resolve(this._device,this,e,t)},t.copy=function(e,t,i){if(!this._device){if(!e._device)return!1;this._device=e._device}return this._device.copyRenderTarget(e,this,t,i)},$(e,[{key:"initialized",get:function(){return this.impl.initialized}},{key:"samples",get:function(){return this._samples}},{key:"depth",get:function(){return this._depth}},{key:"stencil",get:function(){return this._stencil}},{key:"colorBuffer",get:function(){return this._colorBuffer}},{key:"depthBuffer",get:function(){return this._depthBuffer}},{key:"face",get:function(){return this._face}},{key:"width",get:function(){var e,t;return(null==(e=this._colorBuffer)?void 0:e.width)||(null==(t=this._depthBuffer)?void 0:t.width)||this._device.width}},{key:"height",get:function(){var e,t;return(null==(e=this._colorBuffer)?void 0:e.height)||(null==(t=this._depthBuffer)?void 0:t.height)||this._device.height}}]),e}();function ur(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}function dr(e,t,i){var n=2*(e+.5)/i-1,s=2*(t+.5)/i-1,r=1/i,a=(n*=1-1/i)-r,o=(s*=1-1/i)-r,h=n+r,l=s+r,c=ur(a,o)-ur(a,l)-ur(h,o)+ur(h,l);return 0===e&&0===t||e===i-1&&0===t||0===e&&t===i-1||e===i-1&&t===i-1?c/=3:0!==e&&0!==t&&e!==i-1&&t!==i-1||(c*=.5),c}var fr={bakeDirLmEndPS:"\n vec4 dirLm = texture2D(texture_dirLightMap, vUv1);\n\n if (bakeDir > 0.5) {\n if (dAtten > 0.00001) {\n dirLm.xyz = dirLm.xyz * 2.0 - vec3(1.0);\n dAtten = saturate(dAtten);\n gl_FragColor.rgb = normalize(dLightDirNormW.xyz*dAtten + dirLm.xyz*dirLm.w) * 0.5 + vec3(0.5);\n gl_FragColor.a = dirLm.w + dAtten;\n gl_FragColor.a = max(gl_FragColor.a, 1.0 / 255.0);\n } else {\n gl_FragColor = dirLm;\n }\n } else {\n gl_FragColor.rgb = dirLm.xyz;\n gl_FragColor.a = max(dirLm.w, dAtten > 0.00001? (1.0/255.0) : 0.0);\n }\n",bakeLmEndPS:"\n gl_FragColor.rgb = dDiffuseLight;\n gl_FragColor.rgb = pow(gl_FragColor.rgb, vec3(0.5));\n gl_FragColor.rgb /= 8.0;\n gl_FragColor.a = clamp( max( max( gl_FragColor.r, gl_FragColor.g ), max( gl_FragColor.b, 1.0 / 255.0 ) ), 0.0,1.0 );\n gl_FragColor.a = ceil(gl_FragColor.a * 255.0) / 255.0;\n gl_FragColor.rgb /= gl_FragColor.a;\n",dilatePS:"\n#define SHADER_NAME Dilate\n\nvarying vec2 vUv0;\n\nuniform sampler2D source;\nuniform vec2 pixelOffset;\n\nvoid main(void) {\n vec4 c = texture2D(source, vUv0);\n c = c.a>0.0? c : texture2D(source, vUv0 - pixelOffset);\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(0, -pixelOffset.y));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(pixelOffset.x, -pixelOffset.y));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(-pixelOffset.x, 0));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(pixelOffset.x, 0));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(-pixelOffset.x, pixelOffset.y));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(0, pixelOffset.y));\n c = c.a>0.0? c : texture2D(source, vUv0 + pixelOffset);\n gl_FragColor = c;\n}\n",bilateralDeNoisePS:"\n// bilateral filter, based on https://www.shadertoy.com/view/4dfGDH# and\n// http://people.csail.mit.edu/sparis/bf_course/course_notes.pdf\n\n// A bilateral filter is a non-linear, edge-preserving, and noise-reducing smoothing filter for images.\n// It replaces the intensity of each pixel with a weighted average of intensity values from nearby pixels.\n// This weight can be based on a Gaussian distribution. Crucially, the weights depend not only on\n// Euclidean distance of pixels, but also on the radiometric differences (e.g., range differences, such\n// as color intensity, depth distance, etc.). This preserves sharp edges.\n\n#define SHADER_NAME BilateralDeNoise\n\nfloat normpdf3(in vec3 v, in float sigma) {\n return 0.39894 * exp(-0.5 * dot(v, v) / (sigma * sigma)) / sigma;\n}\n\nvec3 decodeRGBM(vec4 rgbm) {\n vec3 color = (8.0 * rgbm.a) * rgbm.rgb;\n return color * color;\n}\n\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n\nvec4 encodeRGBM(vec3 color) { // modified RGBM\n vec4 encoded;\n encoded.rgb = pow(color.rgb, vec3(0.5));\n encoded.rgb *= 1.0 / 8.0;\n\n encoded.a = saturate( max( max( encoded.r, encoded.g ), max( encoded.b, 1.0 / 255.0 ) ) );\n encoded.a = ceil(encoded.a * 255.0) / 255.0;\n\n encoded.rgb /= encoded.a;\n return encoded;\n}\n\n// filter size\n#define MSIZE 15\n\nvarying vec2 vUv0;\nuniform sampler2D source;\nuniform vec2 pixelOffset;\nuniform vec2 sigmas;\nuniform float bZnorm;\nuniform float kernel[MSIZE];\n\nvoid main(void) {\n \n vec4 pixelRgbm = texture2D(source, vUv0);\n\n // lightmap specific optimization - skip pixels that were not baked\n // this also allows dilate filter that work on the output of this to work correctly, as it depends on .a being zero\n // to dilate, which the following blur filter would otherwise modify\n if (pixelRgbm.a <= 0.0) {\n gl_FragColor = pixelRgbm;\n return ;\n }\n\n // range sigma - controls blurriness based on a pixel distance\n float sigma = sigmas.x;\n\n // domain sigma - controls blurriness based on a pixel similarity (to preserve edges)\n float bSigma = sigmas.y;\n\n vec3 pixelHdr = decodeRGBM(pixelRgbm);\n vec3 accumulatedHdr = vec3(0.0);\n float accumulatedFactor = 0.0;\n\n // read out the texels\n const int kSize = (MSIZE-1)/2;\n for (int i = -kSize; i <= kSize; ++i) {\n for (int j = -kSize; j <= kSize; ++j) {\n \n // sample the pixel with offset\n vec2 coord = vUv0 + vec2(float(i), float(j)) * pixelOffset;\n vec4 rgbm = texture2D(source, coord);\n\n // lightmap - only use baked pixels\n if (rgbm.a > 0.0) {\n vec3 hdr = decodeRGBM(rgbm);\n\n // bilateral factors\n float factor = kernel[kSize + j] * kernel[kSize + i];\n factor *= normpdf3(hdr - pixelHdr, bSigma) * bZnorm;\n\n // accumulate\n accumulatedHdr += factor * hdr;\n accumulatedFactor += factor;\n }\n }\n }\n\n gl_FragColor = encodeRGBM(accumulatedHdr / accumulatedFactor);\n}\n"},pr=0,mr=function(){function e(e,t,i,n,s){void 0===n&&(n=0),this.device=e,this.format=t,this.numIndices=i,this.usage=n,this.id=pr++,this.impl=e.createIndexBufferImpl(this);var r=gi[t];this.bytesPerIndex=r,this.numBytes=this.numIndices*r,s?this.setData(s):this.storage=new ArrayBuffer(this.numBytes),this.adjustVramSizeTracking(e._vram,this.numBytes),this.device.buffers.push(this)}var t=e.prototype;return t.destroy=function(){var e=this.device,t=e.buffers.indexOf(this);-1!==t&&e.buffers.splice(t,1),this.device.indexBuffer===this&&(this.device.indexBuffer=null),this.impl.initialized&&(this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this.storage.byteLength))},t.adjustVramSizeTracking=function(e,t){e.ib+=t},t.loseContext=function(){this.impl.loseContext()},t.getFormat=function(){return this.format},t.getNumIndices=function(){return this.numIndices},t.lock=function(){return this.storage},t.unlock=function(){this.impl.unlock(this)},t.setData=function(e){return e.byteLength===this.numBytes&&(this.storage=e,this.unlock(),!0)},t._lockTypedArray=function(){var e=this.lock();return 2===this.format?new Uint32Array(e):1===this.format?new Uint16Array(e):new Uint8Array(e)},t.writeData=function(e,t){var i=this._lockTypedArray();if(e.length>t)if(ArrayBuffer.isView(e))e=e.subarray(0,t),i.set(e);else for(var n=0;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(t))t=t.subarray(0,o),n.array.set(t);else for(var h=0;ht||n>t){var s=t/Math.max(i,n),r=Math.floor(i*s),a=Math.floor(n*s),o=document.createElement("canvas");return o.width=r,o.height=a,o.getContext("2d").drawImage(e,0,0,i,n,0,0,r,a),o}return e}var Gr=function(){function e(){this._glTexture=null,this._glTarget=void 0,this._glFormat=void 0,this._glInternalFormat=void 0,this._glPixelType=void 0}var t=e.prototype;return t.destroy=function(e){if(this._glTexture){for(var t=0;te.maxCubeMapSize||h.height>e.maxCubeMapSize)&&(h=Vr(h,e.maxCubeMapSize),0===r&&(t._width=h.width,t._height=h.height)),e.setUnpackFlipY(!1),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+o,r,this._glInternalFormat,this._glFormat,this._glPixelType,h)}}else for(s=1/Math.pow(2,r),o=0;o<6;o++)if(t._levelsUpdated[0][o]){var l=n[o];t._compressed?i.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+o,r,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),0,l):(e.setUnpackFlipY(!1),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+o,r,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),0,this._glFormat,this._glPixelType,l))}}else t._volume?(s=1/Math.pow(2,r),t._compressed?i.compressedTexImage3D(i.TEXTURE_3D,r,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),Math.max(t._depth*s,1),0,n):(e.setUnpackFlipY(!1),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),i.texImage3D(i.TEXTURE_3D,r,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),Math.max(t._depth*s,1),0,this._glFormat,this._glPixelType,n))):(e._isBrowserInterface(n)?(n instanceof HTMLImageElement&&(n.width>e.maxTextureSize||n.height>e.maxTextureSize)&&(n=Vr(n,e.maxTextureSize),0===r&&(t._width=n.width,t._height=n.height)),e.setUnpackFlipY(t._flipY),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),i.texImage2D(i.TEXTURE_2D,r,this._glInternalFormat,this._glFormat,this._glPixelType,n)):(s=1/Math.pow(2,r),t._compressed?i.compressedTexImage2D(i.TEXTURE_2D,r,this._glInternalFormat,Math.max(Math.floor(t._width*s),1),Math.max(Math.floor(t._height*s),1),0,n):(e.setUnpackFlipY(!1),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),i.texImage2D(i.TEXTURE_2D,r,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),0,this._glFormat,this._glPixelType,n))),t._mipmapsUploaded=0!==r);r++}else r++;if(t._needsUpload)if(t._cubemap)for(var c=0;c<6;c++)t._levelsUpdated[0][c]=!1;else t._levelsUpdated[0]=!1;!t._compressed&&t._mipmaps&&t._needsMipmapsUpload&&(t.pot||e.webgl2)&&1===t._levels.length&&(i.generateMipmap(this._glTarget),t._mipmapsUploaded=!0),t._gpuSize&&t.adjustVramSizeTracking(e._vram,-t._gpuSize),t._gpuSize=t.gpuSize,t.adjustVramSizeTracking(e._vram,t._gpuSize)}},e}(),Wr=function(){function e(){this._glFrameBuffer=null,this._glDepthBuffer=null,this._glResolveFrameBuffer=null,this._glMsaaColorBuffer=null,this._glMsaaDepthBuffer=null}var t=e.prototype;return t.destroy=function(e){var t=e.gl;this._glFrameBuffer&&(t.deleteFramebuffer(this._glFrameBuffer),this._glFrameBuffer=null),this._glDepthBuffer&&(t.deleteRenderbuffer(this._glDepthBuffer),this._glDepthBuffer=null),this._glResolveFrameBuffer&&(t.deleteFramebuffer(this._glResolveFrameBuffer),this._glResolveFrameBuffer=null),this._glMsaaColorBuffer&&(t.deleteRenderbuffer(this._glMsaaColorBuffer),this._glMsaaColorBuffer=null),this._glMsaaDepthBuffer&&(t.deleteRenderbuffer(this._glMsaaDepthBuffer),this._glMsaaDepthBuffer=null)},t.init=function(e,t){var i=e.gl;this._glFrameBuffer=i.createFramebuffer(),e.setFramebuffer(this._glFrameBuffer);var n=t._colorBuffer;n&&(n.impl._glTexture||(n._width=Math.min(n.width,e.maxRenderBufferSize),n._height=Math.min(n.height,e.maxRenderBufferSize),e.setTexture(n,0)),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,n._cubemap?i.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:i.TEXTURE_2D,n.impl._glTexture,0));var s=t._depthBuffer;if(s)s.impl._glTexture||(s._width=Math.min(s.width,e.maxRenderBufferSize),s._height=Math.min(s.height,e.maxRenderBufferSize),e.setTexture(s,0)),t._stencil?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,s._cubemap?i.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:i.TEXTURE_2D,t._depthBuffer.impl._glTexture,0):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,s._cubemap?i.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:i.TEXTURE_2D,t._depthBuffer.impl._glTexture,0);else if(t._depth){if(!(t._samples>1&&e.webgl2)){if(this._glDepthBuffer||(this._glDepthBuffer=i.createRenderbuffer()),i.bindRenderbuffer(i.RENDERBUFFER,this._glDepthBuffer),t._stencil)i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,this._glDepthBuffer);else{var r=e.webgl2?i.DEPTH_COMPONENT32F:i.DEPTH_COMPONENT16;i.renderbufferStorage(i.RENDERBUFFER,r,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,this._glDepthBuffer)}i.bindRenderbuffer(i.RENDERBUFFER,null)}}e.webgl2&&t._samples>1&&(this._glResolveFrameBuffer=this._glFrameBuffer,this._glFrameBuffer=i.createFramebuffer(),e.setFramebuffer(this._glFrameBuffer),n&&(this._glMsaaColorBuffer||(this._glMsaaColorBuffer=i.createRenderbuffer()),i.bindRenderbuffer(i.RENDERBUFFER,this._glMsaaColorBuffer),i.renderbufferStorageMultisample(i.RENDERBUFFER,t._samples,n.impl._glInternalFormat,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,this._glMsaaColorBuffer)),t._depth&&(this._glMsaaDepthBuffer||(this._glMsaaDepthBuffer=i.createRenderbuffer()),i.bindRenderbuffer(i.RENDERBUFFER,this._glMsaaDepthBuffer),t._stencil?(i.renderbufferStorageMultisample(i.RENDERBUFFER,t._samples,i.DEPTH24_STENCIL8,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,this._glMsaaDepthBuffer)):(i.renderbufferStorageMultisample(i.RENDERBUFFER,t._samples,i.DEPTH_COMPONENT32F,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,this._glMsaaDepthBuffer))))},t._checkFbo=function(e){var t=e.gl;switch(t.checkFramebufferStatus(t.FRAMEBUFFER)){case t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:console.error("ERROR: FRAMEBUFFER_INCOMPLETE_ATTACHMENT");break;case t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:console.error("ERROR: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT");break;case t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:console.error("ERROR: FRAMEBUFFER_INCOMPLETE_DIMENSIONS");break;case t.FRAMEBUFFER_UNSUPPORTED:console.error("ERROR: FRAMEBUFFER_UNSUPPORTED");case t.FRAMEBUFFER_COMPLETE:}},t.loseContext=function(){this._glFrameBuffer=null,this._glDepthBuffer=null,this._glResolveFrameBuffer=null,this._glMsaaColorBuffer=null,this._glMsaaDepthBuffer=null},t.resolve=function(e,t,i,n){if(e.webgl2){var s=e.gl;s.bindFramebuffer(s.READ_FRAMEBUFFER,this._glFrameBuffer),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,this._glResolveFrameBuffer),s.blitFramebuffer(0,0,t.width,t.height,0,0,t.width,t.height,(i?s.COLOR_BUFFER_BIT:0)|(n?s.DEPTH_BUFFER_BIT:0),s.NEAREST),s.bindFramebuffer(s.FRAMEBUFFER,this._glFrameBuffer)}},$(e,[{key:"initialized",get:function(){return null!==this._glFrameBuffer}}]),e}(),Hr=[];function Xr(e,t){var i=!0,n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,2,2,0,e.RGBA,t,null);var s=e.createFramebuffer();return e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0),e.checkFramebufferStatus(e.FRAMEBUFFER)!==e.FRAMEBUFFER_COMPLETE&&(i=!1),e.bindTexture(e.TEXTURE_2D,null),e.deleteTexture(n),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteFramebuffer(s),i}var qr,jr=function(e){function t(t,i){var n;void 0===i&&(i={}),(n=e.call(this,t)||this).gl=void 0,n.webgl2=void 0,n.deviceType=li,n.defaultFramebuffer=null,n.defaultFramebufferAlpha=i.alpha,n.updateClientRect(),n.contextLost=!1,n._contextLostHandler=function(e){e.preventDefault(),n.contextLost=!0,n.loseContext(),n.fire("devicelost")},n._contextRestoredHandler=function(){n.restoreContext(),n.contextLost=!1,n.fire("devicerestored")},i.stencil=!0,i.powerPreference||(i.powerPreference="high-performance");var s="undefined"!=typeof navigator&&navigator.userAgent;n.forceDisableMultisampling=s&&s.includes("AppleWebKit")&&(s.includes("15.4")||s.includes("15_4")),n.forceDisableMultisampling&&(i.antialias=!1);for(var r=void 0===i.preferWebGl2||i.preferWebGl2?["webgl2","webgl","experimental-webgl"]:["webgl","experimental-webgl"],a=null,o=0;o0;var v=n.vertexUniformsCount;return v-=16,v-=8,v-=1,v-=16,n.boneLimit=Math.floor(v/3),n.boneLimit=Math.min(n.boneLimit,128),"Mali-450 MP"===n.unmaskedRenderer&&(n.boneLimit=34),n.constantTexSource=n.scope.resolve("source"),n.extTextureFloat?n.webgl2?n.textureFloatRenderable=!!n.extColorBufferFloat:n.textureFloatRenderable=Xr(a,a.FLOAT):n.textureFloatRenderable=!1,n.extColorBufferHalfFloat?n.textureHalfFloatRenderable=!!n.extColorBufferHalfFloat:n.extTextureHalfFloat?n.webgl2?n.textureHalfFloatRenderable=!!n.extColorBufferFloat:n.textureHalfFloatRenderable=Xr(a,n.extTextureHalfFloat.HALF_FLOAT_OES):n.textureHalfFloatRenderable=!1,n.supportsMorphTargetTexturesCore="highp"===n.maxPrecision&&n.maxVertexTextures>=2,n._textureFloatHighPrecision=void 0,n._textureHalfFloatUpdatable=void 0,n.areaLightLutFormat=7,n.extTextureHalfFloat&&n.textureHalfFloatUpdatable&&n.extTextureHalfFloatLinear?n.areaLightLutFormat=ct:n.extTextureFloat&&n.extTextureFloatLinear&&(n.areaLightLutFormat=dt),n}J(t,e);var i=t.prototype;return i.destroy=function(){e.prototype.destroy.call(this);var t=this.gl;this.webgl2&&this.feedback&&t.deleteTransformFeedback(this.feedback),this.clearShaderCache(),this.clearVertexArrayObjectCache(),this.canvas.removeEventListener("webglcontextlost",this._contextLostHandler,!1),this.canvas.removeEventListener("webglcontextrestored",this._contextRestoredHandler,!1),this._contextLostHandler=null,this._contextRestoredHandler=null,this.gl=null,e.prototype.postDestroy.call(this)},i.createVertexBufferImpl=function(e,t){return new Fr},i.createIndexBufferImpl=function(e){return new Br(e)},i.createShaderImpl=function(e){return new zr(e)},i.createTextureImpl=function(e){return new Gr},i.createRenderTargetImpl=function(e){return new Wr},i.getPrecision=function(){var e=this.gl,t="highp";if(e.getShaderPrecisionFormat){var i=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT),n=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT),s=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT),r=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),a=i.precision>0&&s.precision>0,o=n.precision>0&&r.precision>0;a||(t=o?"mediump":"lowp")}return t},i.initializeExtensions=function(){var e=this.gl,t=e.getSupportedExtensions(),i=function(){for(var i=0;i0&&e.fullSizeClearRect&&i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,Hr)}if(e.colorOps.resolve&&this.webgl2&&e.samples>1&&t.autoResolve&&t.resolve(!0,!1),e.colorOps.mipmaps){var n=t._colorBuffer;n&&n.impl._glTexture&&n.mipmaps&&(n.pot||this.webgl2)&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(n),this.gl.generateMipmap(n.impl._glTarget))}}this.insideRenderPass=!1},i.updateBegin=function(){if(this.boundVao=null,this._tempEnableSafariTextureUnitWorkaround)for(var e=0;e1&&e.autoResolve&&e.resolve();var t=e._colorBuffer;t&&t.impl._glTexture&&t.mipmaps&&(t.pot||this.webgl2)&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(t),this.gl.generateMipmap(t.impl._glTarget))}},i.setUnpackFlipY=function(e){if(this.unpackFlipY!==e){this.unpackFlipY=e;var t=this.gl;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,e)}},i.setUnpackPremultiplyAlpha=function(e){if(this.unpackPremultiplyAlpha!==e){this.unpackPremultiplyAlpha=e;var t=this.gl;t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e)}},i.activeTexture=function(e){this.textureUnit!==e&&(this.gl.activeTexture(this.gl.TEXTURE0+e),this.textureUnit=e)},i.bindTexture=function(e){var t=e.impl,i=t._glTarget,n=t._glTexture,s=this.textureUnit,r=this.targetToSlot[i];this.textureUnits[s][r]!==n&&(this.gl.bindTexture(i,n),this.textureUnits[s][r]=n)},i.bindTextureOnUnit=function(e,t){var i=e.impl,n=i._glTarget,s=i._glTexture,r=this.targetToSlot[n];this.textureUnits[t][r]!==s&&(this.activeTexture(t),this.gl.bindTexture(n,s),this.textureUnits[t][r]=s)},i.setTextureParameters=function(e){var t=this.gl,i=e._parameterFlags,n=e.impl._glTarget;if(1&i){var s=e._minFilter;(!e.pot&&!this.webgl2||!e._mipmaps||e._compressed&&1===e._levels.length)&&(2===s||3===s?s=0:4!==s&&5!==s||(s=1)),t.texParameteri(n,t.TEXTURE_MIN_FILTER,this.glFilter[s])}if(2&i&&t.texParameteri(n,t.TEXTURE_MAG_FILTER,this.glFilter[e._magFilter]),4&i&&(this.webgl2?t.texParameteri(n,t.TEXTURE_WRAP_S,this.glAddress[e._addressU]):t.texParameteri(n,t.TEXTURE_WRAP_S,this.glAddress[e.pot?e._addressU:1])),8&i&&(this.webgl2?t.texParameteri(n,t.TEXTURE_WRAP_T,this.glAddress[e._addressV]):t.texParameteri(n,t.TEXTURE_WRAP_T,this.glAddress[e.pot?e._addressV:1])),16&i&&this.webgl2&&t.texParameteri(n,t.TEXTURE_WRAP_R,this.glAddress[e._addressW]),32&i&&this.webgl2&&t.texParameteri(n,t.TEXTURE_COMPARE_MODE,e._compareOnRead?t.COMPARE_REF_TO_TEXTURE:t.NONE),64&i&&this.webgl2&&t.texParameteri(n,t.TEXTURE_COMPARE_FUNC,this.glComparison[e._compareFunc]),128&i){var r=this.extTextureFilterAnisotropic;r&&t.texParameterf(n,r.TEXTURE_MAX_ANISOTROPY_EXT,Math.max(1,Math.min(Math.round(e._anisotropy),this.maxAnisotropy)))}},i.setTexture=function(e,t){e.impl._glTexture||e.impl.initialize(this,e),e._parameterFlags>0||e._needsUpload||e._needsMipmapsUpload?(this.activeTexture(t),this.bindTexture(e),e._parameterFlags&&(this.setTextureParameters(e),e._parameterFlags=0),(e._needsUpload||e._needsMipmapsUpload)&&(e.impl.upload(this,e),e._needsUpload=!1,e._needsMipmapsUpload=!1)):this.bindTextureOnUnit(e,t)},i.createVertexArray=function(e){var t,i,n=e.length>1;if(n){t="";for(var s=0;s0?u.drawElementsInstanced(b,S,T,A,t):u.drawElements(b,S,T,A)}else{var M=e.base;t>0?u.drawArraysInstanced(b,M,S,t):u.drawArrays(b,M,S)}this.webgl2&&this.transformFeedbackBuffer&&(u.endTransformFeedback(),u.bindBufferBase(u.TRANSFORM_FEEDBACK_BUFFER,0,null)),this._drawCallsPerFrame++}},i.clear=function(e){var t=this.defaultClearOptions,i=void 0===(e=e||t).flags?t.flags:e.flags;if(0!==i){var n=this.gl;if(1&i){var s=void 0===e.color?t.color:e.color;this.setClearColor(s[0],s[1],s[2],s[3]),this.setColorWrite(!0,!0,!0,!0)}if(2&i){var r=void 0===e.depth?t.depth:e.depth;this.setClearDepth(r),this.setDepthWrite(!0)}if(4&i){var a=void 0===e.stencil?t.stencil:e.stencil;this.setClearStencil(a)}n.clear(this.glClearFlag[i])}},i.readPixels=function(e,t,i,n,s){var r=this.gl;r.readPixels(e,t,i,n,r.RGBA,r.UNSIGNED_BYTE,s)},i.setClearDepth=function(e){e!==this.clearDepth&&(this.gl.clearDepth(e),this.clearDepth=e)},i.setClearColor=function(e,t,i,n){var s=this.clearColor;e===s.r&&t===s.g&&i===s.b&&n===s.a||(this.gl.clearColor(e,t,i,n),this.clearColor.set(e,t,i,n))},i.setClearStencil=function(e){e!==this.clearStencil&&(this.gl.clearStencil(e),this.clearStencil=e)},i.getDepthTest=function(){return this.depthTest},i.setDepthTest=function(e){if(this.depthTest!==e){var t=this.gl;e?t.enable(t.DEPTH_TEST):t.disable(t.DEPTH_TEST),this.depthTest=e}},i.setDepthFunc=function(e){this.depthFunc!==e&&(this.gl.depthFunc(this.glComparison[e]),this.depthFunc=e)},i.getDepthWrite=function(){return this.depthWrite},i.setDepthWrite=function(e){this.depthWrite!==e&&(this.gl.depthMask(e),this.depthWrite=e)},i.setColorWrite=function(e,t,i,n){this.writeRed===e&&this.writeGreen===t&&this.writeBlue===i&&this.writeAlpha===n||(this.gl.colorMask(e,t,i,n),this.writeRed=e,this.writeGreen=t,this.writeBlue=i,this.writeAlpha=n)},i.setAlphaToCoverage=function(e){this.webgl2&&this.alphaToCoverage!==e&&(this.alphaToCoverage=e,e?this.gl.enable(this.gl.SAMPLE_ALPHA_TO_COVERAGE):this.gl.disable(this.gl.SAMPLE_ALPHA_TO_COVERAGE))},i.setTransformFeedbackBuffer=function(e){if(this.transformFeedbackBuffer!==e&&(this.transformFeedbackBuffer=e,this.webgl2)){var t=this.gl;e?(this.feedback||(this.feedback=t.createTransformFeedback()),t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,this.feedback)):t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,null)}},i.setRaster=function(e){this.raster!==e&&(this.raster=e,this.webgl2&&(e?this.gl.disable(this.gl.RASTERIZER_DISCARD):this.gl.enable(this.gl.RASTERIZER_DISCARD)))},i.setDepthBias=function(e){this.depthBiasEnabled!==e&&(this.depthBiasEnabled=e,e?this.gl.enable(this.gl.POLYGON_OFFSET_FILL):this.gl.disable(this.gl.POLYGON_OFFSET_FILL))},i.setDepthBiasValues=function(e,t){this.gl.polygonOffset(t,e)},i.getBlending=function(){return this.blending},i.setBlending=function(e){if(this.blending!==e){var t=this.gl;e?t.enable(t.BLEND):t.disable(t.BLEND),this.blending=e}},i.setStencilTest=function(e){if(this.stencil!==e){var t=this.gl;e?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.stencil=e}},i.setStencilFunc=function(e,t,i){this.stencilFuncFront===e&&this.stencilRefFront===t&&this.stencilMaskFront===i&&this.stencilFuncBack===e&&this.stencilRefBack===t&&this.stencilMaskBack===i||(this.gl.stencilFunc(this.glComparison[e],t,i),this.stencilFuncFront=this.stencilFuncBack=e,this.stencilRefFront=this.stencilRefBack=t,this.stencilMaskFront=this.stencilMaskBack=i)},i.setStencilFuncFront=function(e,t,i){if(this.stencilFuncFront!==e||this.stencilRefFront!==t||this.stencilMaskFront!==i){var n=this.gl;n.stencilFuncSeparate(n.FRONT,this.glComparison[e],t,i),this.stencilFuncFront=e,this.stencilRefFront=t,this.stencilMaskFront=i}},i.setStencilFuncBack=function(e,t,i){if(this.stencilFuncBack!==e||this.stencilRefBack!==t||this.stencilMaskBack!==i){var n=this.gl;n.stencilFuncSeparate(n.BACK,this.glComparison[e],t,i),this.stencilFuncBack=e,this.stencilRefBack=t,this.stencilMaskBack=i}},i.setStencilOperation=function(e,t,i,n){this.stencilFailFront===e&&this.stencilZfailFront===t&&this.stencilZpassFront===i&&this.stencilFailBack===e&&this.stencilZfailBack===t&&this.stencilZpassBack===i||(this.gl.stencilOp(this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[i]),this.stencilFailFront=this.stencilFailBack=e,this.stencilZfailFront=this.stencilZfailBack=t,this.stencilZpassFront=this.stencilZpassBack=i),this.stencilWriteMaskFront===n&&this.stencilWriteMaskBack===n||(this.gl.stencilMask(n),this.stencilWriteMaskFront=n,this.stencilWriteMaskBack=n)},i.setStencilOperationFront=function(e,t,i,n){this.stencilFailFront===e&&this.stencilZfailFront===t&&this.stencilZpassFront===i||(this.gl.stencilOpSeparate(this.gl.FRONT,this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[i]),this.stencilFailFront=e,this.stencilZfailFront=t,this.stencilZpassFront=i),this.stencilWriteMaskFront!==n&&(this.gl.stencilMaskSeparate(this.gl.FRONT,n),this.stencilWriteMaskFront=n)},i.setStencilOperationBack=function(e,t,i,n){this.stencilFailBack===e&&this.stencilZfailBack===t&&this.stencilZpassBack===i||(this.gl.stencilOpSeparate(this.gl.BACK,this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[i]),this.stencilFailBack=e,this.stencilZfailBack=t,this.stencilZpassBack=i),this.stencilWriteMaskBack!==n&&(this.gl.stencilMaskSeparate(this.gl.BACK,n),this.stencilWriteMaskBack=n)},i.setBlendFunction=function(e,t){(this.blendSrc!==e||this.blendDst!==t||this.separateAlphaBlend)&&(this.gl.blendFunc(this.glBlendFunction[e],this.glBlendFunction[t]),this.blendSrc=e,this.blendDst=t,this.separateAlphaBlend=!1)},i.setBlendFunctionSeparate=function(e,t,i,n){this.blendSrc===e&&this.blendDst===t&&this.blendSrcAlpha===i&&this.blendDstAlpha===n&&this.separateAlphaBlend||(this.gl.blendFuncSeparate(this.glBlendFunction[e],this.glBlendFunction[t],this.glBlendFunction[i],this.glBlendFunction[n]),this.blendSrc=e,this.blendDst=t,this.blendSrcAlpha=i,this.blendDstAlpha=n,this.separateAlphaBlend=!0)},i.setBlendEquation=function(e){(this.blendEquation!==e||this.separateAlphaEquation)&&(this.gl.blendEquation(this.glBlendEquation[e]),this.blendEquation=e,this.separateAlphaEquation=!1)},i.setBlendEquationSeparate=function(e,t){this.blendEquation===e&&this.blendAlphaEquation===t&&this.separateAlphaEquation||(this.gl.blendEquationSeparate(this.glBlendEquation[e],this.glBlendEquation[t]),this.blendEquation=e,this.blendAlphaEquation=t,this.separateAlphaEquation=!0)},i.setBlendColor=function(e,t,i,n){var s=this.blendColor;e===s.r&&t===s.g&&i===s.b&&n===s.a||(this.gl.blendColor(e,t,i,n),s.set(e,t,i,n))},i.setCullMode=function(e){if(this.cullMode!==e){if(0===e)this.gl.disable(this.gl.CULL_FACE);else{0===this.cullMode&&this.gl.enable(this.gl.CULL_FACE);var t=this.glCull[e];this.cullFace!==t&&(this.gl.cullFace(t),this.cullFace=t)}this.cullMode=e}},i.getCullMode=function(){return this.cullMode},i.setShader=function(e){if(e!==this.shader){if(e.failed)return!1;if(!e.ready&&!e.impl.postLink(this,e))return e.failed=!0,!1;this.shader=e,this.gl.useProgram(e.impl.glProgram),this.attributesInvalidated=!0}return!0},i.getHdrFormat=function(){return this.textureHalfFloatRenderable?ct:this.textureFloatRenderable?dt:7},i.clearShaderCache=function(){var e=this.gl;for(var t in this.fragmentShaderCache)e.deleteShader(this.fragmentShaderCache[t]),delete this.fragmentShaderCache[t];for(var i in this.vertexShaderCache)e.deleteShader(this.vertexShaderCache[i]),delete this.vertexShaderCache[i];this.programLib.clearCache()},i.clearVertexArrayObjectCache=function(){var e=this.gl;this._vaoMap.forEach((function(t,i,n){e.deleteVertexArray(t)})),this._vaoMap.clear()},i.removeShaderFromCache=function(e){this.programLib.removeFromCache(e)},$(t,[{key:"width",get:function(){return this.gl.drawingBufferWidth||this.canvas.width}},{key:"height",get:function(){return this.gl.drawingBufferHeight||this.canvas.height}},{key:"fullscreen",get:function(){return!!document.fullscreenElement},set:function(e){e?this.gl.canvas.requestFullscreen():document.exitFullscreen()}},{key:"textureFloatHighPrecision",get:function(){return void 0===this._textureFloatHighPrecision&&(this._textureFloatHighPrecision=function(e){if(!e.textureFloatRenderable)return!1;var t=on(e,Wi.fullscreenQuadVS,Wi.precisionTestPS,"ptest1"),i=on(e,Wi.fullscreenQuadVS,Wi.precisionTest2PS,"ptest2"),n={format:dt,width:1,height:1,mipmaps:!1,minFilter:0,magFilter:0,name:"testFHP"},s=new wn(e,n),r=new cr({colorBuffer:s,depth:!1});Ei(e,r,t),n.format=7;var a=new wn(e,n),o=new cr({colorBuffer:a,depth:!1});e.constantTexSource.setValue(s),Ei(e,o,i);var h=e.activeFramebuffer;e.setFramebuffer(o.impl._glFrameBuffer);var l=new Uint8Array(4);e.readPixels(0,0,1,1,l),e.setFramebuffer(h);var c=l[0]/255/16777216+l[1]/255/65536+l[2]/255/256+l[3]/255;return s.destroy(),r.destroy(),a.destroy(),o.destroy(),0===c}(this)),this._textureFloatHighPrecision}},{key:"textureHalfFloatUpdatable",get:function(){return void 0===this._textureHalfFloatUpdatable&&(this.webgl2?this._textureHalfFloatUpdatable=!0:this._textureHalfFloatUpdatable=function(e,t){var i=!0,n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE);var s=new Uint16Array(16);return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,2,2,0,e.RGBA,t,s),e.getError()!==e.NO_ERROR&&(i=!1,console.log("Above error related to HALF_FLOAT_OES can be ignored, it was triggered by testing half float texture support")),e.bindTexture(e.TEXTURE_2D,null),e.deleteTexture(n),i}(this.gl,this.extTextureHalfFloat.HALF_FLOAT_OES)),this._textureHalfFloatUpdatable}}]),t}(or),Yr=function(){function e(){this._refCount=0}var t=e.prototype;return t.incRefCount=function(){this._refCount++},t.decRefCount=function(){this._refCount--},$(e,[{key:"refCount",get:function(){return this._refCount}}]),e}();function Kr(){return qr}function Zr(e){qr=e}var $r=0,Qr=function(){function e(){this.initDefaults()}var t=e.prototype;return t.initDefaults=function(){this.recreate=!1,this.verticesUsage=0,this.indicesUsage=0,this.maxVertices=0,this.maxIndices=0,this.vertexCount=0,this.indexCount=0,this.vertexStreamsUpdated=!1,this.indexStreamUpdated=!1,this.vertexStreamDictionary={},this.indices=null},t._changeVertexCount=function(e,t){this.vertexCount||(this.vertexCount=e)},e}();Qr.DEFAULT_COMPONENTS_POSITION=3,Qr.DEFAULT_COMPONENTS_NORMAL=3,Qr.DEFAULT_COMPONENTS_UV=2,Qr.DEFAULT_COMPONENTS_COLORS=4;var Jr=function(e,t,i,n){this.data=e,this.componentCount=t,this.dataType=i,this.dataTypeNormalize=n},ea=function(e){function t(t){var i;return(i=e.call(this)||this).id=$r++,i.device=t||Kr().graphicsDevice,i.vertexBuffer=null,i.indexBuffer=[null],i.primitive=[{type:0,base:0,count:0}],i.skin=null,i._morph=null,i._geometryData=null,i._aabb=new Oe,i.boneAabb=null,i}J(t,e);var i=t.prototype;return i.destroy=function(){var e=this.morph;e&&(this.morph=null,e.refCount<1&&e.destroy()),this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);for(var t=0;t0){var b=g.array[g.index+x];if(u[b]=!0,t=m.array[m.index],i=m.array[m.index+1],n=m.array[m.index+2],s=c[b],(r=l[b]).x>t&&(r.x=t),r.y>i&&(r.y=i),r.z>n&&(r.z=n),s.xS&&(r.x=S),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(e,t,i,n){void 0===i&&(i=0),void 0===n&&(n=0),this._initGeometryData(),this._geometryData.initDefaults(),this._geometryData.recreate=!0,this._geometryData.maxVertices=i,this._geometryData.maxIndices=n,this._geometryData.verticesUsage=e?0:1,this._geometryData.indicesUsage=t?0:1},i.setVertexStream=function(e,t,i,n,s,r){void 0===s&&(s=6),void 0===r&&(r=!1),this._initGeometryData();var a=n||t.length/i;this._geometryData._changeVertexCount(a,e),this._geometryData.vertexStreamsUpdated=!0,this._geometryData.vertexStreamDictionary[e]=new Jr(t,i,s,r)},i.getVertexStream=function(e,t){var i=0,n=!1;if(this._geometryData){var s=this._geometryData.vertexStreamDictionary[e];s&&(n=!0,i=this._geometryData.vertexCount,ArrayBuffer.isView(t)?t.set(s.data):(t.length=0,t.push(s.data)))}n||this.vertexBuffer&&(i=new Pr(this.vertexBuffer).readData(e,t));return i},i.setPositions=function(e,t,i){void 0===t&&(t=Qr.DEFAULT_COMPONENTS_POSITION),this.setVertexStream(vt,e,t,i,6,!1)},i.setNormals=function(e,t,i){void 0===t&&(t=Qr.DEFAULT_COMPONENTS_NORMAL),this.setVertexStream(yt,e,t,i,6,!1)},i.setUvs=function(e,t,i,n){void 0===i&&(i=Qr.DEFAULT_COMPONENTS_UV),this.setVertexStream(Tt+e,t,i,n,6,!1)},i.setColors=function(e,t,i){void 0===t&&(t=Qr.DEFAULT_COMPONENTS_COLORS),this.setVertexStream(wt,e,t,i,6,!1)},i.setColors32=function(e,t){this.setVertexStream(wt,e,Qr.DEFAULT_COMPONENTS_COLORS,t,1,!0)},i.setIndices=function(e,t){this._initGeometryData(),this._geometryData.indexStreamUpdated=!0,this._geometryData.indices=e,this._geometryData.indexCount=t||e.length},i.getPositions=function(e){return this.getVertexStream(vt,e)},i.getNormals=function(e){return this.getVertexStream(yt,e)},i.getUvs=function(e,t){return this.getVertexStream(Tt+e,t)},i.getColors=function(e){return this.getVertexStream(wt,e)},i.getIndices=function(e){var t=0;if(this._geometryData&&this._geometryData.indices){var i=this._geometryData.indices;t=this._geometryData.indexCount,ArrayBuffer.isView(e)?e.set(i):(e.length=0,e.push(i))}else{if(this.indexBuffer.length>0&&this.indexBuffer[0])t=this.indexBuffer[0].readData(e)}return t},i.update=function(e,t){if(void 0===e&&(e=4),void 0===t&&(t=!0),this._geometryData){if(t){var i=this._geometryData.vertexStreamDictionary.POSITION;i&&3===i.componentCount&&this._aabb.compute(i.data,this._geometryData.vertexCount)}var n=this._geometryData.recreate;this._geometryData.vertexCount>this._geometryData.maxVertices&&(n=!0,this._geometryData.maxVertices=this._geometryData.vertexCount),n&&this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);var s=this._geometryData.recreate;this._geometryData.indexCount>this._geometryData.maxIndices&&(s=!0,this._geometryData.maxIndices=this._geometryData.indexCount),s&&this.indexBuffer.length>0&&this.indexBuffer[0]&&(this.indexBuffer[0].destroy(),this.indexBuffer[0]=null),this._geometryData.vertexStreamsUpdated&&this._updateVertexBuffer(),this._geometryData.indexStreamUpdated&&this._updateIndexBuffer(),this.primitive[0].type=e,this.indexBuffer.length>0&&this.indexBuffer[0]?this._geometryData.indexStreamUpdated&&(this.primitive[0].count=this._geometryData.indexCount,this.primitive[0].indexed=!0):this._geometryData.vertexStreamsUpdated&&(this.primitive[0].count=this._geometryData.vertexCount,this.primitive[0].indexed=!1),this._geometryData.vertexCount=0,this._geometryData.indexCount=0,this._geometryData.vertexStreamsUpdated=!1,this._geometryData.indexStreamUpdated=!1,this._geometryData.recreate=!1,this.updateRenderStates()}},i._buildVertexFormat=function(e){var t=[];for(var i in this._geometryData.vertexStreamDictionary){var n=this._geometryData.vertexStreamDictionary[i];t.push({semantic:i,components:n.componentCount,type:n.dataType,normalize:n.dataTypeNormalize})}return new Ti(this.device,t,e)},i._updateVertexBuffer=function(){if(!this.vertexBuffer){var e=this._geometryData.maxVertices,t=this._buildVertexFormat(e);this.vertexBuffer=new Si(this.device,t,e,this._geometryData.verticesUsage)}var i=new Pr(this.vertexBuffer),n=this._geometryData.vertexCount;for(var s in this._geometryData.vertexStreamDictionary){var r=this._geometryData.vertexStreamDictionary[s];i.writeData(s,r.data,n),delete this._geometryData.vertexStreamDictionary[s]}i.end()},i._updateIndexBuffer=function(){if(this.indexBuffer.length<=0||!this.indexBuffer[0]){var e=this._geometryData.maxVertices>65535?2:1;this.indexBuffer[0]=new mr(this.device,e,this._geometryData.maxIndices,this._geometryData.indicesUsage)}var t=this._geometryData.indices;t&&(this.indexBuffer[0].writeData(t,this._geometryData.indexCount),this._geometryData.indices=null)},i.prepareRenderState=function(e){1===e?this.generateWireframe():2===e&&(this.primitive[2]={type:0,base:0,count:this.vertexBuffer?this.vertexBuffer.numVertices:0,indexed:!1})},i.updateRenderStates=function(){this.primitive[2]&&this.prepareRenderState(2),this.primitive[1]&&this.prepareRenderState(1)},i.generateWireframe=function(){this._destroyIndexBuffer(1);var e,t=[];if(this.indexBuffer.length>0&&this.indexBuffer[0]){for(var i=[[0,1],[1,2],[2,0]],n=this.primitive[0].base,s=this.primitive[0].count,r=this.indexBuffer[0],a=new _i[r.format](r.storage),o={},h=n;hu?u<<16|c:c<<16|u;void 0===o[d]&&(o[d]=0,t.push(c,u))}e=r.format}else{for(var f=0;f65535?2:1}var p=new mr(this.vertexBuffer.device,e,t.length);new _i[p.format](p.storage).set(t),p.unlock(),this.primitive[1]={type:1,base:0,count:t.length,indexed:!0},this.indexBuffer[1]=p},$(t,[{key:"morph",get:function(){return this._morph},set:function(e){e!==this._morph&&(this._morph&&this._morph.decRefCount(),this._morph=e,e&&e.incRefCount())}},{key:"aabb",get:function(){return this._aabb},set:function(e){this._aabb=e}}]),t}(Yr),ta=4/64,ia=.875,na=[];function sa(e,t){for(var i=t.length/3,n=e.length/3,s=new ye,r=new ye,a=new ye,o=new ye,h=new ye,l=new ye,c=[],u=0;u0)for(var v=0;v<=n;v++)for(var y=0;y<=s;y++){var x=y/s*2*Math.PI-Math.PI,b=Math.sin(x),S=Math.cos(x);u.set(b*e,-i/2,S*e),c.set(b*t,i/2,S*t),o.lerp(u,c,v/n),h.sub2(c,u).normalize(),d.set(S,0,-b),l.cross(d,h).normalize(),f.push(o.x,o.y,o.z),p.push(l.x,l.y,l.z);var w=y/s,T=v/n;m.push(w,1-T);var A=T;if(T=w,w=(w=A)*ia+ta,T=T*ia+ta,w/=3,_.push(w,1-T),v0)for(var ue=0;ue1&&g.push(a,a+ue,a+ue-1)}if(a+=s,t>0)for(var ve=0;ve1&&g.push(a,a+ve-1,a+ve)}}return{positions:f,normals:p,uvs:m,uvs1:_,indices:g}}function la(e,t){var i=t&&(t.radius||t.baseRadius);i=void 0!==i?i:.5;var n=t&&void 0!==t.height?t.height:1,s=t&&void 0!==t.heightSegments?t.heightSegments:5,r=t&&void 0!==t.capSegments?t.capSegments:20,a=!(!t||void 0===t.calculateTangents)&&t.calculateTangents,o=ha(i,i,n,s,r,!1);return a&&(o.tangents=ra(o.positions,o.normals,o.uvs,o.indices)),aa(e,o.positions,o)}function ca(e,t){var i=t&&void 0!==t.radius?t.radius:.3,n=t&&void 0!==t.height?t.height:1,s=t&&void 0!==t.heightSegments?t.heightSegments:1,r=t&&void 0!==t.sides?t.sides:20,a=!(!t||void 0===t.calculateTangents)&&t.calculateTangents,o=ha(i,i,n-2*i,s,r,!0);return a&&(o.tangents=ra(o.positions,o.normals,o.uvs,o.indices)),aa(e,o.positions,o)}function ua(e,t){var i=t&&void 0!==t.baseRadius?t.baseRadius:.5,n=t&&void 0!==t.peakRadius?t.peakRadius:0,s=t&&void 0!==t.height?t.height:1,r=t&&void 0!==t.heightSegments?t.heightSegments:5,a=t&&void 0!==t.capSegments?t.capSegments:18,o=!(!t||void 0===t.calculateTangents)&&t.calculateTangents,h=ha(i,n,s,r,a,!1);return o&&(h.tangents=ra(h.positions,h.normals,h.uvs,h.indices)),aa(e,h.positions,h)}function da(e,t){for(var i=t&&void 0!==t.radius?t.radius:.5,n=t&&void 0!==t.latitudeBands?t.latitudeBands:16,s=t&&void 0!==t.longitudeBands?t.longitudeBands:16,r=!(!t||void 0===t.calculateTangents)&&t.calculateTangents,a=[],o=[],h=[],l=[],c=0;c<=n;c++)for(var u=c*Math.PI/n,d=Math.sin(u),f=Math.cos(u),p=0;p<=s;p++){var m=2*p*Math.PI/s-Math.PI/2,_=Math.sin(m),g=Math.cos(m)*d,v=f,y=_*d,x=1-p/s,b=1-c/n;a.push(g*i,v*i,y*i),o.push(g,v,y),h.push(x,1-b)}for(var S=0;S0,vertexColors:this.vertexColors,diffuseMap:!!this.colorMap,pass:s},l=new Os(a,o),c=e.getProgramLibrary();return c.register("basic",_a),c.getProgram("basic",h,l)},t}(Bs),va=function(){function e(e,t,i){this.origMeshInstances=e,this._aabb=new Oe,this.meshInstance=null,this.dynamic=t,this.batchGroupId=i}var t=e.prototype;return t.destroy=function(e,t){this.meshInstance&&(this.removeFromLayers(e,t),this.meshInstance.destroy())},t.addToLayers=function(e,t){for(var i=0;i=0;i--)this.matrices[i].mulAffine2(xa,this.bones[i].getWorldTransform()),this.matrices[i].mulAffine2(this.matrices[i],this.skin.inverseBindPose[i])}},t.updateMatrices=function(e,t){this._updateBeforeCull&&this._updateMatrices(e,t)},t.updateMatrixPalette=function(e,t){this._updateMatrices(e,t);for(var i=this.matrixPalette,n=this.bones.length,s=0;s>16},set:function(e){var t=65535&this._shaderDefs;this._shaderDefs=t|e<<16,this._shader[0]=null,this._shader[1]=null}},{key:"instancingCount",get:function(){return this.instancingData?this.instancingData.count:0},set:function(e){this.instancingData&&(this.instancingData.count=e)}}]),e}();function Oa(e,t,i,n){return(15&e)<<27|(3===t?1:0)<<26|(i?1:0)<<25|(33554431&n)<<0}function Fa(e,t){if(e&&!t)return!1;if(!e&&t)return!1;if((e=e.data)===(t=t.data))return!0;if(e instanceof Float32Array&&t instanceof Float32Array){if(e.length!==t.length)return!1;for(var i=0;i=0?1:-1}var Ha=function(){function e(e,t,i){this.device=e,this.rootNode=t,this.scene=i,this._init=!1,this._batchGroups={},this._batchGroupCounter=0,this._batchList=[],this._dirtyGroups=[]}var t=e.prototype;return t.destroy=function(){this.device=null,this.rootNode=null,this.scene=null,this._batchGroups={},this._batchList=[],this._dirtyGroups=[]},t.addGroup=function(e,t,i,n,s){if(void 0===n&&(n=this._batchGroupCounter,this._batchGroupCounter++),!this._batchGroups[n]){var r=new ya(n,e,t,i,s);return this._batchGroups[n]=r,r}},t.removeGroup=function(e){if(this._batchGroups[e]){for(var t=[],i=0;i=0&&(n._obj[e].splice(s,1),this.markGroupDirty(t))}},t._extractRender=function(e,t,i,n){if(e.render){if(e.render.isStatic){for(var s=this.scene.drawCalls,r=e.render.meshInstances,a=0;a=0&&t.push(r[o])}else t=n[e.render.batchGroupId]=t.concat(e.render.meshInstances);e.render.removeFromLayers()}return t},t._extractModel=function(e,t,i,n){if(e.model&&e.model.model){if(e.model.isStatic){for(var s=this.scene.drawCalls,r=e.model.meshInstances,a=0;a=0&&t.push(r[o])}else t=n[e.model.batchGroupId]=t.concat(e.model.meshInstances);e.model.removeModelFromLayers()}return t},t._extractElement=function(e,t,i){if(e.element){var n=!1;e.element._text&&e.element._text._model.meshInstances.length>0?(t.push(e.element._text._model.meshInstances[0]),e.element.removeModelFromLayers(e.element._text._model),n=!0):e.element._image&&(t.push(e.element._image._renderable.meshInstance),e.element.removeModelFromLayers(e.element._image._renderable.model),e.element._image._renderable.unmaskMeshInstance&&(t.push(e.element._image._renderable.unmaskMeshInstance),e.element._image._renderable.unmaskMeshInstance.stencilFront&&e.element._image._renderable.unmaskMeshInstance.stencilBack||(e.element._dirtifyMask(),e.element._onPrerender())),n=!0),n&&(i._ui=!0)}},t._collectAndRemoveMeshInstances=function(e,t){for(var i=0;i0;){u[d]=[p[0]],f=[];var _=p[0].material,g=p[0].layer,v=p[0]._shaderDefs,y=p[0].parameters,x=p[0].stencilFront,b=p[0]._staticLightList,S=p[0].mesh.vertexBuffer.getNumVertices(),w=p[0].drawOrder;h.copy(p[0].aabb);var T=Wa(p[0]),A=p[0].mesh.vertexBuffer.format.batchingHash,M=p[0].mesh.primitive[0].indexed;c=null;for(var C=1;C=a){f=f.concat(p.slice(C));break}if(_!==E.material||g!==E.layer||A!==E.mesh.vertexBuffer.format.batchingHash||M!==E.mesh.primitive[0].indexed||v!==E._shaderDefs||S+E.mesh.vertexBuffer.getNumVertices()>o)m(E);else if(l.copy(h),l.add(E.aabb),l.halfExtents.x>r||l.halfExtents.y>r||l.halfExtents.z>r)m(E);else if(!x||(s=E.stencilFront)&&x.func===s.func&&x.zpass===s.zpass)if(T===Wa(E))if(Ba(y,E.parameters)){var P=E._staticLightList;if(b&&P){if(!Na(b,P)){m(E);continue}}else if(b||P){m(E);continue}n&&c&&c.intersects(E.aabb)&&E.drawOrder!==w?m(E):(h.add(E.aabb),S+=E.mesh.vertexBuffer.getNumVertices(),u[d].push(E))}else m(E);else m(E);else m(E)}d++,p=f}return u},t.collectBatchedMeshData=function(e,t){for(var i=null,n=0,s=0,r=null,a=0;a=3)if(s===vt)for(var A=0;A0&&r.setIndices(b),r.update(4,!1),t&&((p=p.clone()).chunks.transformVS=this.transformVS,p.chunks.skinTexVS=this.skinTexVS,p.chunks.skinConstVS=this.skinConstVS,p.update());var R=new ka(r,p,this.rootNode);R.castShadow=h.origMeshInstances[0].castShadow,R.parameters=h.origMeshInstances[0].parameters,R.isStatic=h.origMeshInstances[0].isStatic,R.layer=h.origMeshInstances[0].layer,R._staticLightList=h.origMeshInstances[0]._staticLightList,R._shaderDefs=h.origMeshInstances[0]._shaderDefs,R.cull=h.origMeshInstances[0].cull;var I=this._batchGroups[i];if(I&&I._ui&&(R.cull=!1),t){for(var L=[],D=0;D0&&this.generate(this._dirtyGroups);for(var e=0;e0&&a){if(!(n1){t.copy(e[1].min),i.copy(e[1].max);for(var n=2;n1?this.shaderCube:this.shader2d,r=this.device;n>1&&this.initInvViewProjMatrices(),this.blitTextureId.setValue(t.cookie);for(var a=0;a1){var o=oo.z/3,h=this.lightTextureAtlas.cubeSlotsOffsets[a];oo.x+=o*h.x,oo.y+=o*h.y,oo.z=o,oo.w=o,this.invViewProjId.setValue(e._invViewProjMatrices[a].data)}oo.mulScalar(i.colorBuffer.width),Ei(r,i,s,oo)}}},$(e,[{key:"shader2d",get:function(){return this.getShader("blitShader2d","\n varying vec2 uv0;\n uniform sampler2D blitTexture;\n void main(void) {\n gl_FragColor = texture2D(blitTexture, uv0);\n }")}},{key:"shaderCube",get:function(){return this.getShader("blitShaderCube","\n varying vec2 uv0;\n uniform samplerCube blitTexture;\n uniform mat4 invViewProj;\n void main(void) {\n vec4 projPos = vec4(uv0 * 2.0 - 1.0, 0.5, 1.0);\n vec4 worldPos = invViewProj * projPos;\n gl_FragColor = textureCube(blitTexture, worldPos.xyz);\n }")}}]),e}();ho._invViewProjMatrices=null;var lo=function(){function e(e,t){this.texture=e,this.cached=!1,this.renderTargets=t}return e.prototype.destroy=function(){this.texture&&(this.texture.destroy(),this.texture=null);for(var e=this.renderTargets,t=0;t1)for(var h=1/o,l=0;l1)for(var f=0;f0){for(var s=this.slots,r=0;rs&&(s=a)}return yo.min=n,yo.max=s,yo}function bo(e,t){return Math.exp(-e*e/(2*t*t))}var So=new Oe,wo=new Ee,To=new Ee,Ao=new Float32Array(2),Mo=new Se(1,1,0,0),Co={r:1,g:2,b:3,a:4},Eo=new ye,Po=new Ee;function Ro(e){var t=e.material,i=e.skinInstance?10:0,n=0;if(t.opacityMap){var s=t.opacityMapChannel;s&&(n=Co[s])}return i+n}var Io=function(){function e(e,t){this.device=e.device,this.forwardRenderer=e,this.lightTextureAtlas=t;var i=this.device.scope;this.polygonOffsetId=i.resolve("polygonOffset"),this.polygonOffset=new Float32Array(2),this.sourceId=i.resolve("source"),this.pixelOffsetId=i.resolve("pixelOffset"),this.weightId=i.resolve("weight[0]"),this.blurVsmShaderCode=[Wi.blurVSMPS,"#define GAUSS\n"+Wi.blurVSMPS];var n="#define PACKED\n";this.blurPackedVsmShaderCode=[n+this.blurVsmShaderCode[0],n+this.blurVsmShaderCode[1]],this.blurVsmShader=[{},{}],this.blurPackedVsmShader=[{},{}],this.blurVsmWeights={},this.shadowMapLightRadiusId=i.resolve("light_radius"),this.shadowMapCache=new go}var t=e.prototype;return t.destroy=function(){this.shadowMapCache.destroy(),this.shadowMapCache=null},e.createShadowCamera=function(e,t,i,n){var s=Yn.create("ShadowCamera",i,n);return s.clearColor=t>=1&&t<=3?new me(0,0,0,0):new me(1,1,1,1),s.clearDepthBuffer=!0,s.clearStencilBuffer=!1,s},e.setShadowCameraSettings=function(e,t,i,n,s){var r=4===i||0===i&&t.webgl2;1!==n||s||(r=!1),e.clearColorBuffer=!r},t.cullShadowCasters=function(e,t,i){for(var n=0,s=e.length,r=0;rp&&(p=_)}var g=o.right,v=o.up,y=o.forward,x=.25*e._shadowResolution/p,b=Math.ceil(Eo.dot(v)*x)/x,S=Math.ceil(Eo.dot(g)*x)/x,w=v.mulScalar(b),T=g.mulScalar(S),A=Eo.dot(y),M=y.mulScalar(A);Eo.add2(w,T).add(M),o.setPosition(Eo),o.translateLocal(0,0,1e6),a.nearClip=0,a.farClip=2e6,a.orthoHeight=p,this.forwardRenderer.updateCameraFrustum(a),this.cullShadowCasters(t,r.visibleCasters,a);for(var C=!0,E=r.visibleCasters,P=0;P1)this.forwardRenderer.scene.clusteredLightingEnabled&&0!==s||this.applyVsmBlur(t,i);this.restoreRenderState(n)}},t.getVsmBlurShader=function(e,t,i){var n=(e?this.blurPackedVsmShader:this.blurVsmShader)[t][i];if(!n){this.blurVsmWeights[i]=function(e){e>25&&(e=25);for(var t=(e-1)/6,i=.5*(e-1),n=new Array(e),s=0,r=0;rU&&(U=H),X>z&&(z=X),q>V&&(V=q)}var j=6*O;p[j]=F,p[j+1]=B,p[j+2]=N,p[j+3]=U,p[j+4]=z,p[j+5]=V}for(var Y=0;Y=Z.x&&p[ee+1]<=$.y&&p[ee+4]>=Z.y&&p[ee+2]<=$.z&&p[ee+5]>=Z.z&&(d[J]|=Q,k=!0)}}if(k){for(var te={},ie=0;iede&&(de=ge),ve>fe&&(fe=ve),xe>pe&&(pe=xe)}h.set(le,ce,ue),l.set(de,fe,pe);var be=new Oe;be.setMinMax(h,l);var Se=new ea(t);Se.vertexBuffer=w,Se.indexBuffer[0]=he,Se.primitive[0].type=4,Se.primitive[0].base=0,Se.primitive[0].count=oe.length,Se.primitive[0].indexed=!0,Se.aabb=be;var we=new ka(Se,g.material,g.node);we.isStatic=g.isStatic,we.visible=g.visible,we.layer=g.layer,we.castShadow=g.castShadow,we._receiveShadow=g._receiveShadow,we.cull=g.cull,we.pick=g.pick,we.mask=g.mask,we.parameters=g.parameters,we._shaderDefs=g._shaderDefs,we._staticSource=g,g._staticLightList?we._staticLightList=g._staticLightList:we._staticLightList=[];for(var Te=0;Te0&&(this._instancedDrawCalls++,e.setVertexBuffer(Fo.vertexBuffer),e.draw(i.primitive[n],Fo.count)):(Bo=t.node.worldTransform,this.modelMatrixId.setValue(Bo.data),s&&this.normalMatrixId.setValue(t.node.normalMatrix.data),e.draw(i.primitive[n]))},t.drawInstance2=function(e,t,i,n){(Fo=t.instancingData)?Fo.count>0&&(this._instancedDrawCalls++,e.draw(i.primitive[n],Fo.count,!0)):e.draw(i.primitive[n],void 0,!0)},t.renderShadows=function(e,t){for(var i=this.scene.clusteredLightingEnabled,n=0;n0&&n.cull<3){i.flipFaces&&(r*=-1),t&&(r*=-1);var a=i.node.worldTransform;a.getX($o),a.getY(Qo),a.getZ(Jo),$o.cross($o,Qo),$o.dot(Jo)<0&&(r*=-1)}s=r<0?2===n.cull?1:2:n.cull}if(this.device.setCullMode(s),0===s&&0===n.cull){var o=i.node.worldTransform;o.getX($o),o.getY(Qo),o.getZ(Jo),$o.cross($o,Qo),$o.dot(Jo)<0?this.twoSidedLightingNegScaleFactorId.setValue(-1):this.twoSidedLightingNegScaleFactorId.setValue(1)}},t.setVertexBuffers=function(e,t){e.setVertexBuffer(t.vertexBuffer)},t.setMorphing=function(e,t){if(t)if(t.morph.useTextureMorph)e.setVertexBuffer(t.morph.vertexBufferIds),this.morphPositionTex.setValue(t.texturePositions),this.morphNormalTex.setValue(t.textureNormals),this.morphTexParams.setValue(t._textureParams);else{for(var i=0;i=0&&a._shaderVersion!==i&&(a.getShaderVariant!==Bs.prototype.getShaderVariant&&a.clearVariants(),a._shaderVersion=i)}this.passThrough||(this._dirty=!0)},t.removeMeshInstanceFromArray=function(e,t){for(var i=-1,n=0,s=t.length,r=0;r=0)break}i>=0&&t.splice(i,n)},t.removeMeshInstances=function(e,t){for(var i=this.opaqueMeshInstances,n=this.transparentMeshInstances,s=this.shadowCasters,r=0;r=0&&s.splice(o,1)}}this._dirty=!0},t.clearMeshInstances=function(e){(0!==this.opaqueMeshInstances.length||0!==this.transparentMeshInstances.length||!e&&0!==this.shadowCasters.length)&&(this.opaqueMeshInstances.length=0,this.transparentMeshInstances.length=0,e||(this.shadowCasters.length=0),this.passThrough||(this._dirty=!0))},t.addLight=function(e){var t=e.light;this._lightsSet.has(t)||(this._lightsSet.add(t),0!==t.type&&this._clusteredLightsSet.add(t),this._lights.push(t),this._dirtyLights=!0,this._generateLightHash())},t.removeLight=function(e){var t=e.light;this._lightsSet.has(t)&&(this._lightsSet.delete(t),0!==t.type&&this._clusteredLightsSet.delete(t),this._lights.splice(this._lights.indexOf(t),1),this._dirtyLights=!0,this._generateLightHash())},t.clearLights=function(){this._lightsSet.clear(),this._clusteredLightsSet.clear(),this._lights.length=0,this._dirtyLights=!0},t.addShadowCasters=function(e){for(var t=this.shadowCasters,i=0;i=0&&t.splice(n,1)}this._dirtyLights=!0},t._generateLightHash=function(){if(this._lights.length>0){this._lights.sort(hh);for(var e="",t="",i=0;i=0||(this.cameras.push(e),this._dirtyCameras=!0)},t.removeCamera=function(e){var t=this.cameras.indexOf(e);t>=0&&(this.cameras.splice(t,1),this._dirtyCameras=!0,this.instances.delete(t))},t.clearCameras=function(){this.cameras.length=0,this._dirtyCameras=!0},t._calculateSortDistances=function(e,t,i,n){for(var s=0;s0}},{key:"renderTarget",get:function(){return this._renderTarget},set:function(e){this._renderTarget=e,this._dirtyCameras=!0}},{key:"enabled",get:function(){return this._enabled},set:function(e){e!==this._enabled&&(this._enabled=e,e?(this.incrementCounter(),this.onEnable&&this.onEnable()):(this.decrementCounter(),this.onDisable&&this.onDisable()))}},{key:"clearColorBuffer",get:function(){return this._clearColorBuffer},set:function(e){this._clearColorBuffer=e,this._dirtyCameras=!0}},{key:"clearDepthBuffer",get:function(){return this._clearDepthBuffer},set:function(e){this._clearDepthBuffer=e,this._dirtyCameras=!0}},{key:"clearStencilBuffer",get:function(){return this._clearStencilBuffer},set:function(e){this._clearStencilBuffer=e,this._dirtyCameras=!0}},{key:"clusteredLightsSet",get:function(){return this._clusteredLightsSet}}]),e}(),ph=function(e,t){if(e.size!==t.size)return!1;for(var i,n=ne(e);!(i=n()).done;){var s=i.value;if(!t.has(s))return!1}return!0},mh=function(e,t){return e.priority-t.priority},_h=function(e){return e.sort(mh)},gh=function(){function e(){this.layerIndex=0,this.cameraIndex=0,this.camera=null,this.renderTarget=null,this.lightClusters=null,this.clearColor=!1,this.clearDepth=!1,this.clearStencil=!1,this.triggerPostprocess=!1,this.firstCameraUse=!1,this.lastCameraUse=!1,this.directionalLightsSet=new Set,this.directionalLights=[],this.directionalLightsIndices=[],this.viewBindGroups=[]}var t=e.prototype;return t.destroy=function(){this.viewBindGroups.forEach((function(e){e.defaultUniformBuffer.destroy(),e.destroy()})),this.viewBindGroups.length=0},t.reset=function(){this.lightClusters=null,this.directionalLightsSet.clear(),this.directionalLights.length=0,this.directionalLightsIndices.length=0},t.isLayerEnabled=function(e){return e.layerList[this.layerIndex].enabled&&e.subLayerEnabled[this.layerIndex]},t.collectDirectionalLights=function(e,t,i){this.directionalLightsSet.clear(),this.directionalLights.length=0,this.directionalLightsIndices.length=0;for(var n=0;n=0&&!this.directionalLightsSet.has(s)){this.directionalLightsSet.add(s),this.directionalLights.push(s);var a=i.indexOf(s);this.directionalLightsIndices.push(a)}}},$(e,[{key:"hasDirectionalShadowLights",get:function(){return this.directionalLights.length>0}}]),e}(),vh=function(){function e(){this.shadowCastersSet=new Set,this.shadowCastersList=[]}var t=e.prototype;return t.clearShadowCasters=function(){this.shadowCastersSet.clear(),this.shadowCastersList.length=0},t.addShadowCasters=function(e){for(var t=0;t1&&_h(this.cameras);for(var _=[],g=0,v=0;v0&&y.layers.indexOf(A.id)>=0){_.push(A),w||A.id!==y.disablePostEffectsLayer||(w=!0,S&&(S.triggerPostprocess=!0));var M=A.cameras.indexOf(y);M>=0&&(S=this.addRenderAction(this._renderActions,g,A,T,M,x,w),g++,x=!1)}}b=0;u--)if(e[u].camera===l&&e[u].renderTarget===h){c=!0;break}var d=r||!c,f=!!d&&l.clearColorBuffer,p=!!d&&l.clearDepthBuffer,m=!!d&&l.clearStencilBuffer;return f||(f=i.clearColorBuffer),p||(p=i.clearDepthBuffer),m||(m=i.clearStencilBuffer),a&&l.postEffectsEnabled&&(h=null),o.reset(),o.triggerPostprocess=!1,o.layerIndex=n,o.cameraIndex=s,o.camera=l,o.renderTarget=h,o.clearColor=f,o.clearDepth=p,o.clearStencil=m,o.firstCameraUse=r,o.lastCameraUse=!1,o},i.propagateRenderTarget=function(e,t){for(var i=e;i>=0;i--){var n=this._renderActions[i],s=this.layerList[n.layerIndex];if(n.renderTarget&&1!==s.id)break;if(1!==s.id){var r=null==n?void 0:n.camera.camera;if(r&&(!t.camera.rect.equals(r.rect)||!t.camera.scissorRect.equals(r.scissorRect)))break;n.renderTarget=t.renderTarget}}},i._logRenderActions=function(){},i._isLayerAdded=function(e){return this.layerList.indexOf(e)>=0},i._isSublayerAdded=function(e,t){for(var i=0;i=0;)this.layerList.splice(t,1),this.subLayerList.splice(t,1),this.subLayerEnabled.splice(t,1),t=this.layerList.indexOf(e),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("remove",e);var i=this.layerList.length;this._updateOpaqueOrder(0,i-1),this._updateTransparentOrder(0,i-1)},i.pushOpaque=function(e){this._isSublayerAdded(e,!1)||(this.layerList.push(e),this._opaqueOrder[e.id]=this.subLayerList.push(!1)-1,this.subLayerEnabled.push(!0),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("add",e))},i.insertOpaque=function(e,t){if(!this._isSublayerAdded(e,!1)){this.layerList.splice(t,0,e),this.subLayerList.splice(t,0,!1);var i=this.subLayerList.length;this._updateOpaqueOrder(t,i-1),this.subLayerEnabled.splice(t,0,!0),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("add",e)}},i.removeOpaque=function(e){for(var t=0,i=this.layerList.length;t=1?(o[0]=Math.pow(i,2.2)*r,o[1]=Math.pow(n,2.2)*r,o[2]=Math.pow(s,2.2)*r):(o[0]=Math.pow(a[0],2.2),o[1]=Math.pow(a[1],2.2),o[2]=Math.pow(a[2],2.2))},t.setColor=function(){1===arguments.length?this._color.set(arguments[0].r,arguments[0].g,arguments[0].b):3===arguments.length&&this._color.set(arguments[0],arguments[1],arguments[2]),this._updateFinalColor()},t.updateShadow=function(){2!==this.shadowUpdateMode&&(this.shadowUpdateMode=1)},t.layersDirty=function(){var e;null!=(e=this._scene)&&e.layers&&(this._scene.layers._dirtyLights=!0)},t.updateKey=function(){var e=this._type<<29|(this._castShadows?1:0)<<28|this._shadowType<<25|this._falloffMode<<23|(0!==this._normalOffsetBias?1:0)<<22|(this._cookie?1:0)<<21|(this._cookieFalloff?1:0)<<20|Mh[this._cookieChannel.charAt(0)]<<18|(this._cookieTransform?1:0)<<12|this._shape<<10|this.numCascades-1<<8;3===this._cookieChannel.length&&(e|=Mh[this._cookieChannel.charAt(1)]<<16,e|=Mh[this._cookieChannel.charAt(2)]<<14),e!==this.key&&null!==this._scene&&this.layersDirty(),this.key=e},$(e,[{key:"numCascades",get:function(){return this.cascades.length},set:function(e){this.cascades&&this.numCascades===e||(this.cascades=Eh[e-1],this._shadowMatrixPalette=new Float32Array(64),this._shadowCascadeDistances=new Float32Array(4),this._destroyShadowMap(),this.updateKey())}},{key:"shadowMap",get:function(){return this._shadowMap},set:function(e){this._shadowMap!==e&&(this._destroyShadowMap(),this._shadowMap=e)}},{key:"numShadowFaces",get:function(){var e=this._type;return 0===e?this.numCascades:1===e?6:1}},{key:"type",get:function(){return this._type},set:function(e){if(this._type!==e){this._type=e,this._destroyShadowMap(),this.updateKey();var t=this._shadowType;this._shadowType=null,this.shadowType=t}}},{key:"shape",get:function(){return this._shape},set:function(e){if(this._shape!==e){this._shape=e,this._destroyShadowMap(),this.updateKey();var t=this._shadowType;this._shadowType=null,this.shadowType=t}}},{key:"usePhysicalUnits",get:function(){return this._usePhysicalUnits},set:function(e){this._usePhysicalUnits!==e&&(this._usePhysicalUnits=e,this._updateFinalColor())}},{key:"shadowType",get:function(){return this._shadowType},set:function(e){if(this._shadowType!==e){var t=this.device;1===this._type&&(e=0),4!==e||t.webgl2||(e=0),3!==e||t.textureFloatRenderable||(e=2),2!==e||t.textureHalfFloatRenderable||(e=1),this._isVsm=e>=1&&e<=3,this._isPcf=4===e||0===e,this._shadowType=e,this._destroyShadowMap(),this.updateKey()}}},{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled!==e&&(this._enabled=e,this.layersDirty())}},{key:"castShadows",get:function(){return this._castShadows&&4!==this.mask&&0!==this.mask},set:function(e){this._castShadows!==e&&(this._castShadows=e,this._destroyShadowMap(),this.layersDirty(),this.updateKey())}},{key:"shadowResolution",get:function(){return this._shadowResolution},set:function(e){this._shadowResolution!==e&&(e=1===this._type?Math.min(e,this.device.maxCubeMapSize):Math.min(e,this.device.maxTextureSize),this._shadowResolution=e,this._destroyShadowMap())}},{key:"vsmBlurSize",get:function(){return this._vsmBlurSize},set:function(e){this._vsmBlurSize!==e&&(e%2==0&&e++,this._vsmBlurSize=e)}},{key:"normalOffsetBias",get:function(){return this._normalOffsetBias},set:function(e){this._normalOffsetBias!==e&&((!this._normalOffsetBias&&e||this._normalOffsetBias&&!e)&&this.updateKey(),this._normalOffsetBias=e)}},{key:"falloffMode",get:function(){return this._falloffMode},set:function(e){this._falloffMode!==e&&(this._falloffMode=e,this.updateKey())}},{key:"innerConeAngle",get:function(){return this._innerConeAngle},set:function(e){this._innerConeAngle!==e&&(this._innerConeAngle=e,this._innerConeAngleCos=Math.cos(e*Math.PI/180),this._usePhysicalUnits&&this._updateFinalColor())}},{key:"outerConeAngle",get:function(){return this._outerConeAngle},set:function(e){this._outerConeAngle!==e&&(this._outerConeAngle=e,this._outerConeAngleCos=Math.cos(e*Math.PI/180),this._usePhysicalUnits&&this._updateFinalColor())}},{key:"intensity",get:function(){return this._intensity},set:function(e){this._intensity!==e&&(this._intensity=e,this._updateFinalColor())}},{key:"luminance",get:function(){return this._luminance},set:function(e){this._luminance!==e&&(this._luminance=e,this._updateFinalColor())}},{key:"cookieMatrix",get:function(){return this._cookieMatrix||(this._cookieMatrix=new Ee),this._cookieMatrix}},{key:"atlasViewport",get:function(){return this._atlasViewport||(this._atlasViewport=new Se(0,0,1,1)),this._atlasViewport}},{key:"cookie",get:function(){return this._cookie},set:function(e){this._cookie!==e&&(this._cookie=e,this.updateKey())}},{key:"cookieFalloff",get:function(){return this._cookieFalloff},set:function(e){this._cookieFalloff!==e&&(this._cookieFalloff=e,this.updateKey())}},{key:"cookieChannel",get:function(){return this._cookieChannel},set:function(e){if(this._cookieChannel!==e){if(e.length<3)for(var t=e.charAt(e.length-1),i=3-e.length,n=0;n0){var n=i.bakeArea;ls(Oh,e,t),Oh.mulScalar(.5*n),i._node.rotateLocal(Oh.x,0,Oh.y)}i._node.getWorldTransform();var s=this.scene.gammaCorrection?2.2:1,r=Math.pow(this.intensity,s);i.intensity=Math.pow(r/t,1/s)},$(t,[{key:"numVirtualLights",get:function(){return 0===this.light.type?this.light.bakeNumSamples:1}}]),t}(kh),Bh=function(){function e(){this.renderPasses=[],this.renderTargetMap=new Map}var t=e.prototype;return t.addRenderPass=function(e){this.renderPasses.push(e)},t.reset=function(){this.renderPasses.length=0},t.compile=function(){for(var e=this.renderTargetMap,t=this.renderPasses,i=0;i0&&this.material.transparent===t&&(this.mesh.setPositions(this.positions),this.mesh.setColors(this.colors),this.mesh.update(1,!1),this.meshInstance||(this.meshInstance=new ka(this.mesh,this.material,Wh)),this.positions.length=0,this.colors.length=0,e.list.push(this.meshInstance),e.length++)},e}(),qh=function(){function e(e){this.device=e,this.map=new Map}var t=e.prototype;return t.getBatch=function(e,t){var i=this.map.get(e);return i||(i=new Xh(this.device,e,t),this.map.set(e,i)),i},t.onPreRender=function(e,t){this.map.forEach((function(i){i.onPreRender(e,t)}))},e}(),jh=[],Yh=function(){function e(e){this.device=e,this.quadMesh=null,this.textureShader=null,this.depthTextureShader=null,this.cubeLocalPos=null,this.cubeWorldPos=null,this.batchesMap=new Map,this.allBatches=new Set,this.updatedLayers=new Set,this._materialDepth=null,this._materialNoDepth=null,this.layerMeshInstances=new Map}var t=e.prototype;return t.createMaterial=function(e){var t=new ga;return t.vertexColors=!0,t.blend=!0,t.blendType=2,t.depthTest=e,t.update(),t},t.getBatch=function(e,t){var i=this.batchesMap.get(e);i||(i=new qh(this.device),this.batchesMap.set(e,i)),this.allBatches.add(i);var n=t?this.materialDepth:this.materialNoDepth;return i.getBatch(n,e)},e.getTextureVS=function(){return"\n attribute vec2 vertex_position;\n uniform mat4 matrix_model;\n varying vec2 uv0;\n void main(void) {\n gl_Position = matrix_model * vec4(vertex_position, 0, 1);\n uv0 = vertex_position.xy + 0.5;\n }\n "},t.getTextureShader=function(){if(!this.textureShader){this.textureShader=on(this.device,e.getTextureVS(),"\n varying vec2 uv0;\n uniform sampler2D colorMap;\n void main (void) {\n gl_FragColor = vec4(texture2D(colorMap, uv0).xyz, 1);\n }\n ","DebugTextureShader")}return this.textureShader},t.getDepthTextureShader=function(){if(!this.depthTextureShader){var t="\n "+Wi.screenDepthPS+"\n varying vec2 uv0;\n void main() {\n float depth = getLinearScreenDepth(uv0) * camera_params.x;\n gl_FragColor = vec4(vec3(depth), 1.0);\n }\n ";this.depthTextureShader=on(this.device,e.getTextureVS(),t,"DebugDepthTextureShader")}return this.depthTextureShader},t.getQuadMesh=function(){return this.quadMesh||(this.quadMesh=new ea(this.device),this.quadMesh.setPositions([-.5,-.5,0,.5,-.5,0,-.5,.5,0,.5,.5,0]),this.quadMesh.update(5)),this.quadMesh},t.drawMesh=function(e,t,i,n,s){if(!n){var r=this.getGraphNode(t);n=new ka(i,e,r)}var a=this.layerMeshInstances.get(s);a||(a=[],this.layerMeshInstances.set(s,a)),a.push(n)},t.drawWireAlignedBox=function(e,t,i,n,s){jh.push(e.x,e.y,e.z,e.x,t.y,e.z,e.x,t.y,e.z,t.x,t.y,e.z,t.x,t.y,e.z,t.x,e.y,e.z,t.x,e.y,e.z,e.x,e.y,e.z,e.x,e.y,t.z,e.x,t.y,t.z,e.x,t.y,t.z,t.x,t.y,t.z,t.x,t.y,t.z,t.x,e.y,t.z,t.x,e.y,t.z,e.x,e.y,t.z,e.x,e.y,e.z,e.x,e.y,t.z,e.x,t.y,e.z,e.x,t.y,t.z,t.x,t.y,e.z,t.x,t.y,t.z,t.x,e.y,e.z,t.x,e.y,t.z),this.getBatch(s,n).addLinesArrays(jh,i),jh.length=0},t.drawWireSphere=function(e,t,i,n,s,r){for(var a=2*Math.PI/n,o=0,h=0;h=s)throw new Error("Invalid PAX header data format.");var l=parseInt(t.decode(new Uint8Array(e,i+a,h-a)),10),c=t.decode(new Uint8Array(e,i+h+1,l-(h-a)-2)).split("=");if(2!==c.length)throw new Error("Invalid PAX header data format.");0===c[1].length&&(c[1]=null),o.push({name:c[0],value:c[1]}),a+=l}return new n(o)},n.prototype.applyHeader=function(e){for(var t=0;t0&&(r=p.trim()+r.trim())}var m={name:r,start:l,size:o,url:c};return this._globalPaxHeader&&this._globalPaxHeader.applyHeader(m),this._paxHeader&&(this._paxHeader.applyHeader(m),this._paxHeader=null),m},s.prototype.untar=function(e){if(!t)return console.error("Cannot untar because TextDecoder interface is not available for this platform."),[];for(var i=[];this._hasNext();){var n=this._readNextFile();n&&(e&&n.name&&(n.name=e+n.name),i.push(n))}return i},e&&(self.onmessage=function(e){var t=e.data.id;try{var i=new s(e.data.arrayBuffer).untar(e.data.prefix);postMessage({id:t,files:i,arrayBuffer:e.data.arrayBuffer},[e.data.arrayBuffer])}catch(e){postMessage({id:t,error:e.toString()})}})}var Qh=null;var Jh=function(){function e(e){this._requestId=0,this._pendingRequests={},this._filenamePrefix=e,this._worker=new Worker(function(){if(!Qh){var e="("+$h.toString()+")(true)\n\n",t=new Blob([e],{type:"application/javascript"});Qh=URL.createObjectURL(t)}return Qh}()),this._worker.addEventListener("message",this._onMessage.bind(this))}var t=e.prototype;return t._onMessage=function(e){var t=e.data.id;if(this._pendingRequests[t]){var i=this._pendingRequests[t];if(delete this._pendingRequests[t],e.data.error)i(e.data.error);else{for(var n=e.data.arrayBuffer,s=0,r=e.data.files.length;s0},t.destroy=function(){this._worker&&(this._worker.terminate(),this._worker=null,this._pendingRequests=null)},e}();$h();var el=function(){function e(e){this.handlerType="bundle",this._assets=e.assets,this._worker=null,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i=this;pe.get(e.load,{responseType:fe.ResponseType.ARRAY_BUFFER,retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(n,s){if(n)t("Error loading bundle resource "+e.original+": "+n);else try{i._untar(s,t)}catch(i){t("Error loading bundle resource "+e.original+": "+i)}}))},t._untar=function(e,t){var i=this;if(L.workers)i._worker||(i._worker=new Jh(i._assets.prefix)),i._worker.untar(e,(function(e,n){t(e,n),i._worker.hasPendingRequests()||(i._worker.destroy(),i._worker=null)}));else{var n=new Hh(e).untar(i._assets.prefix);t(null,n)}},t.open=function(e,t){return new Zh(t)},t.patch=function(e,t){},e}(),tl=function(){function e(e){this._handlers={},this._requests={},this._cache={},this._app=e}var t=e.prototype;return t.addHandler=function(e,t){this._handlers[e]=t,t._loader=this},t.removeHandler=function(e){delete this._handlers[e]},t.getHandler=function(e){return this._handlers[e]},t.load=function(e,t,i,n){var s=this._handlers[t];if(s)if(e){var r=e+t;if(void 0!==this._cache[r])i(null,this._cache[r]);else if(this._requests[r])this._requests[r].push(i);else{this._requests[r]=[i];var a=this,o=function(e,t){e?a._onFailure(r,e):s.load(t,(function(e,i,o){if(a._requests[r])if(e)a._onFailure(r,e);else try{a._onSuccess(r,s.open(t.original,i,n),o)}catch(e){a._onFailure(r,e)}}),n)},h=e.split("?")[0];if(this._app.enableBundles&&this._app.bundles.hasUrl(h)){if(!this._app.bundles.canLoadUrl(h))return void o("Bundle for "+e+" not loaded yet");this._app.bundles.loadUrl(h,(function(e,t){o(e,{load:t,original:h})}))}else o(null,{load:e,original:n&&n.file.filename||e})}}else this._loadNull(s,i,n);else i("No resource handler for asset type: '"+t+"' when loading ["+e+"]")},t._loadNull=function(e,t,i){e.load(null,(function(n,s,r){if(n)t(n);else try{t(null,e.open(null,s,i),r)}catch(e){t(e)}}),i)},t._onSuccess=function(e,t,i){this._cache[e]=t;for(var n=0;n=0&&e<=1?0:1})),rl(["fr","pt"],(function(e){return e>=0&&e<2?0:1})),rl(["da"],(function(e){return 1===e||!Number.isInteger(e)&&e>=0&&e<=1?0:1})),rl(["de","en","it","el","es","tr","fi","sv","nb","no","ur"],(function(e){return 1===e?0:1})),rl(["ru","uk"],(function(e){if(Number.isInteger(e)){var t=e%10,i=e%100;if(1===t&&11!==i)return 0;if(t>=2&&t<=4&&(i<12||i>14))return 1;if(0===t||t>=5&&t<=9||i>=11&&i<=14)return 2}return 3})),rl(["pl"],(function(e){if(Number.isInteger(e)){if(1===e)return 0;var t=e%10,i=e%100;if(t>=2&&t<=4&&(i<12||i>14))return 1;if(t>=0&&t<=1||t>=5&&t<=9||i>=12&&i<=14)return 2}return 3})),rl(["ar"],(function(e){if(0===e)return 0;if(1===e)return 1;if(2===e)return 2;if(Number.isInteger(e)){var t=e%100;if(t>=3&&t<=10)return 3;if(t>=11&&t<=99)return 4}return 5}));var hl=sl[al(il)];function ll(e){return sl[e]||hl}var cl=new RegExp("^\\s*(?:(?:[a-z]+[a-z0-9\\-\\+\\.]*:)?//|data:|blob:)","i"),ul=function(){function e(e,t,i,n,s,r){this.url=e||"",this.filename=t||"",this.hash=void 0===i?null:i,this.size=void 0===n?null:n,this.opt=void 0===s?null:s,this.contents=r||null}return e.prototype.equals=function(e){return this.url===e.url&&this.filename===e.filename&&this.hash===e.hash&&this.size===e.size&&this.opt===e.opt&&this.contents===e.contents},e}(),dl=-1,fl={pvr:"extCompressedTexturePVRTC",dxt:"extCompressedTextureS3TC",etc2:"extCompressedTextureETC",etc1:"extCompressedTextureETC1",basis:"canvas"},pl=["pvr","dxt","etc2","etc1","basis"],ml=function(e){function t(t,i,n,s,r){var a;return(a=e.call(this)||this)._id=dl--,a.name=t||"",a.type=i,a.tags=new ae(te(a)),a._preload=!1,a._file=null,a._data=s||{},a.options=r||{},a._resources=[],a._i18n={},a.loaded=!1,a.loading=!1,a.registry=null,n&&(a.file=n),a}J(t,e);var i=t.prototype;return i.getFileUrl=function(){var e=this.file;if(!e||!e.url)return null;var t=e.url;if(this.registry&&this.registry.prefix&&!cl.test(t)&&(t=this.registry.prefix+t),"script"!==this.type&&e.hash){var i=-1!==t.indexOf("?")?"&":"?";t+=i+"t="+e.hash}return t},i.getAbsoluteUrl=function(e){if(e.startsWith("blob:")||e.startsWith("data:"))return e;var t=v.getDirectory(this.file.url);return v.join(t,e)},i.getLocalizedAssetId=function(e){return e=ol(e,this._i18n),this._i18n[e]||null},i.addLocalizedAssetId=function(e,t){this._i18n[e]=t,this.fire("add:localized",e,t)},i.removeLocalizedAssetId=function(e){var t=this._i18n[e];t&&(delete this._i18n[e],this.fire("remove:localized",e,t))},i.ready=function(e,t){t=t||this,this.loaded?e.call(t,this):this.once("load",(function(i){e.call(t,i)}))},i.reload=function(){this.loaded&&(this.loaded=!1,this.registry.load(this))},i.unload=function(){if(this.loaded||0!==this._resources.length){this.fire("unload",this),this.registry.fire("unload:"+this.id,this);var e=this._resources;this.resources=[],this.loaded=!1,this.file&&this.registry._loader.clearCache(this.getFileUrl(),this.type);for(var t=0;t0,maxRetries:n},t)},$(t,[{key:"id",get:function(){return this._id},set:function(e){this._id=e}},{key:"file",get:function(){return this._file},set:function(e){var t=this;if(e&&e.variants&&-1!==["texture","textureatlas","bundle"].indexOf(this.type)){var i,n,s=(null==(i=this.registry)||null==(n=i._loader)?void 0:n._app)||Kr(),r=null==s?void 0:s.graphicsDevice;if(r)for(var a=function(i,n){var a=pl[i];if(e.variants[a]&&r[fl[a]])return e=e.variants[a],"break";if(s.enableBundles){var o=s.bundles.listBundlesForAsset(t);if(o&&o.find((function(e){var t;return null==e||null==(t=e.file)?void 0:t.variants[a]})))return"break"}},o=0,h=pl.length;o0?console.assert("Script Ordering Error. Contact support@playcanvas.com"):e._types.push(t)};var t=e.prototype;return t.load=function(t,i){var n=this;"string"==typeof t&&(t={load:t,original:t});var s=this;xl.app=this._app,this._loadScript(t.load,(function(t,r,a){if(t)i(t);else if(xl.legacy){var o=null;e._types.length&&(o=e._types.pop()),o?n._scripts[r]=o:o=null,i(null,o,a)}else{for(var h={},l=0;l0?i[0]:null},t}(m),Sl=function(){function e(e){this._assets=e,this._bundleAssets={},this._assetsInBundles={},this._urlsInBundles={},this._fileRequests={},this._assets.on("add",this._onAssetAdded,this),this._assets.on("remove",this._onAssetRemoved,this)}var t=e.prototype;return t._onAssetAdded=function(e){if("bundle"===e.type){this._bundleAssets[e.id]=e,this._registerBundleEventListeners(e.id);for(var t=0,i=e.data.assets.length;t=3&&i.length<=4){for(var u=0;ui.ind&&(h=i.ind),this._insertScriptInstance(a,h,o),this._scriptsIndex[r]={instance:a,onSwap:function(){n.swap(r)}},this[r]=a,i.preloading||a.__initializeAttributes(),this.fire("create",r,a),this.fire("create:"+r,a),this.system.app.scripts.on("swap:"+r,this._scriptsIndex[r].onSwap),i.preloading||(a.enabled&&!a._initialized&&(a._initialized=!0,a.initialize&&this._scriptMethod(a,t.scriptMethods.initialize)),a.enabled&&!a._postInitialized&&(a._postInitialized=!0,a.postInitialize&&this._scriptMethod(a,t.scriptMethods.postInitialize))),a}}else this._scriptsIndex[r]={awaiting:!0,ind:this._scripts.length};return null},i.destroy=function(e){var t=e,i=e;"string"==typeof i?i=this.system.app.scripts.get(i):i&&(t=i.__name);var n=this._scriptsIndex[t];if(delete this._scriptsIndex[t],!n)return!1;var s=n.instance;if(s&&!s._destroyed)if(s.enabled=!1,s._destroyed=!0,this._isLoopingThroughScripts)this._destroyedScripts.push(s);else{var r=this._removeScriptInstance(s);r>=0&&this._resetExecutionOrder(r,this._scripts.length)}return this.system.app.scripts.off("swap:"+t,n.onSwap),delete this[t],this.fire("destroy",t,s||null),this.fire("destroy:"+t,s||null),s&&s.fire("destroy"),!0},i.swap=function(e){var i=e,n=e;"string"==typeof n?n=this.system.app.scripts.get(n):n&&(i=n.__name);var s=this._scriptsIndex[i];if(!s||!s.instance)return!1;var r=s.instance,a=this._scripts.indexOf(r),o=new n({app:this.system.app,entity:this.entity,enabled:r.enabled,attributes:r.__attributes});return!!o.swap&&(o.__initializeAttributes(),this._scripts[a]=o,this._scriptsIndex[i].instance=o,this[i]=o,o.__executionOrder=a,r.update&&this._updateList.remove(r),r.postUpdate&&this._postUpdateList.remove(r),o.update&&this._updateList.insert(o),o.postUpdate&&this._postUpdateList.insert(o),this._scriptMethod(o,t.scriptMethods.swap,r),this.fire("swap",i,o),this.fire("swap:"+i,o),!0)},i.resolveDuplicatedEntityReferenceProperties=function(e,t){var i=this.entity.script;for(var n in e._scriptsIndex){var s=this.system.app.scripts.get(n);if(s){var r=e._scriptsIndex[n];if(r&&r.instance){var a=i[n].__attributesRaw,o=i[n].__attributes;if(a||o){var h=!!a,l=r.instance.__attributes;for(var c in l)if(l[c]){var u=s.attributes.get(c);if(u)if("entity"===u.type)this._resolveEntityScriptAttribute(u,c,l[c],h,a||o,t);else if("json"===u.type&&Array.isArray(u.schema))for(var d=l[c],f=a?a[c]:o[c],p=0;p=i||t<0)return!1;var n=e,s=e;"string"!=typeof s?s=e.__name:n=null;var r=this._scriptsIndex[s];if(!r||!r.instance)return!1;var a=r.instance;if(n&&!(a instanceof n))return!1;var o=this._scripts.indexOf(a);return-1!==o&&o!==t&&(this._scripts.splice(t,0,this._scripts.splice(o,1)[0]),this._resetExecutionOrder(0,i),this._updateList.sort(),this._postUpdateList.sort(),this.fire("move",s,a,t,o),this.fire("move:"+s,a,t,o),!0)},$(t,[{key:"scripts",get:function(){return this._scripts},set:function(e){for(var t in this._scriptsData=e,e)if(e.hasOwnProperty(t)){var i=this._scriptsIndex[t];if(i){if("boolean"==typeof e[t].enabled&&(i.enabled=!!e[t].enabled),"object"==typeof e[t].attributes)for(var n in e[t].attributes)if(!Ml.reservedNames.has(n)){if(!i.__attributes.hasOwnProperty(n)){var s=this.system.app.scripts.get(t);s&&s.attributes.add(n,{})}i[n]=e[t].attributes[n]}}else console.log(this.order)}}},{key:"enabled",get:function(){return this._enabled},set:function(e){var t=this._enabled;this._enabled=e,this.fire("set","enabled",t,e)}}]),t}(Cl);El.scriptMethods={initialize:"initialize",postInitialize:"postInitialize",update:"update",postUpdate:"postUpdate",swap:"swap"};var Pl=new RegExp("^\\s*function(?:\\s|\\s*\\/\\*.*\\*\\/\\s*)+([^\\(\\s\\/]*)\\s*"),Rl=function(e){function t(t){var i;return(i=e.call(this)||this).app=void 0,i.entity=void 0,i._enabled=void 0,i._enabledOld=void 0,i._initialized=void 0,i._postInitialized=void 0,i.__destroyed=void 0,i.__attributes=void 0,i.__attributesRaw=void 0,i.__scriptType=void 0,i.__executionOrder=void 0,i.initScriptType(t),i}J(t,e);var i=t.prototype;return i.initScriptType=function(e){var t=this.constructor;this.app=e.app,this.entity=e.entity,this._enabled="boolean"!=typeof e.enabled||e.enabled,this._enabledOld=this.enabled,this.__destroyed=!1,this.__attributes={},this.__attributesRaw=e.attributes||{},this.__scriptType=t,this.__executionOrder=-1},t.__getScriptName=function(e){if("function"==typeof e){if("name"in Function.prototype)return e.name;if(e===Function||e===Function.prototype.constructor)return"Function";var t=(""+e).match(Pl);return t?t[1]:void 0}},i.__initializeAttributes=function(e){if(e||this.__attributesRaw){for(var t in this.__scriptType.attributes.index)this.__attributesRaw&&this.__attributesRaw.hasOwnProperty(t)?this[t]=this.__attributesRaw[t]:this.__attributes.hasOwnProperty(t)||(this.__scriptType.attributes.index[t].hasOwnProperty("default")?this[t]=this.__scriptType.attributes.index[t].default:this[t]=null);this.__attributesRaw=null}},t.extend=function(e){for(var t in e)e.hasOwnProperty(t)&&(this.prototype[t]=e[t])},$(t,[{key:"enabled",get:function(){return this._enabled&&!this._destroyed&&this.entity.script.enabled&&this.entity.enabled},set:function(e){this._enabled=!!e,this.enabled!==this._enabledOld&&(this._enabledOld=this.enabled,this.fire(this.enabled?"enable":"disable"),this.fire("state",this.enabled),!this._initialized&&this.enabled&&(this._initialized=!0,this.__initializeAttributes(!0),this.initialize&&this.entity.script._scriptMethod(this,El.scriptMethods.initialize)),this._initialized&&!this._postInitialized&&this.enabled&&!this.entity.script._beingEnabled&&(this._postInitialized=!0,this.postInitialize&&this.entity.script._scriptMethod(this,El.scriptMethods.postInitialize)))}}],[{key:"scriptName",get:function(){return this.__name}},{key:"attributes",get:function(){return this.hasOwnProperty("__attributes")||(this.__attributes=new Ml(this)),this.__attributes}}]),t}(m);Rl.__name=null;var Il=function(e){function t(t){var i;return(i=e.call(this)||this).app=t,i._scripts={},i._list=[],i}J(t,e);var i=t.prototype;return i.destroy=function(){this.app=null,this.off()},i.add=function(e){var t=this,i=e.__name;return this._scripts.hasOwnProperty(i)?(setTimeout((function(){if(e.prototype.swap){var n=t._scripts[i],s=t._list.indexOf(n);t._list[s]=e,t._scripts[i]=e,t.fire("swap",i,e),t.fire("swap:"+i,e)}else console.warn("script registry already has '"+i+"' script, define 'swap' method for new script type to enable code hot swapping")})),!1):(this._scripts[i]=e,this._list.push(e),this.fire("add",i,e),this.fire("add:"+i,e),setTimeout((function(){if(t._scripts.hasOwnProperty(i)&&t.app&&t.app.systems&&t.app.systems.script){var e,n=t.app.systems.script._components,s=[],r=[];for(n.loopIndex=0;n.loopIndex0;){var n=t[0];n.reparent(null),null==n.destroy||n.destroy()}i.applySceneSettings(e.data.settings)}),t)},t.loadScene=function(e,t){var i=this,n=this._app,s=n.loader.getHandler("scene");n.assets&&n.assets.prefix&&!cl.test(e)&&(e=v.join(n.assets.prefix,e)),s.load(e,(function(r,a){if(r)t&&t(r);else{n._preloadScripts(a,(function(){n.systems.script.preloading=!0;var r=s.open(e,a),o=i.findByUrl(e);o&&!o.loaded&&(o.data=a),n.systems.script.preloading=!1,n.loader.clearCache(e,"scene"),n.loader.patch({resource:r,type:"scene"},n.assets),n.root.addChild(r.root),n.systems.rigidbody&&"undefined"!=typeof Ammo&&n.systems.rigidbody.gravity.set(r._gravity.x,r._gravity.y,r._gravity.z),t&&t(null,r)}))}}))},e}(),Nl=["uSceneDepthMap","uDepthMap"],Ul=["uSceneColorMap","texture_grabPass"],zl=function(){function e(e){this.application=e,this.device=e.graphicsDevice,this.layer=null,this.colorFormat=this.device.defaultFramebufferAlpha?7:6,this.device.webgl2?this.initWebGl2():this.initWebGl1()}var t=e.prototype;return t.setupUniform=function(e,t,i){(t?Nl:Ul).forEach((function(t){return e.scope.resolve(t).setValue(i)}))},t.allocateTexture=function(e,t,i,n,s,r){return new wn(e,{name:i,format:n,width:t?t.colorBuffer.width:e.width,height:t?t.colorBuffer.height:e.height,mipmaps:r,minFilter:s?0:r?5:1,magFilter:s?0:1,addressU:1,addressV:1})},t.resizeCondition=function(e,t,i){var n=(null==t?void 0:t.width)||i.width,s=(null==t?void 0:t.height)||i.height;return!e||n!==e.width||s!==e.height},t.allocateRenderTarget=function(e,t,i,n,s,r,a){var o=a?Nl:Ul,h=this.allocateTexture(i,t,o[0],n,s,r);return e?(e.destroyFrameBuffers(),s?e._depthBuffer=h:e._colorBuffer=h):e=new cr({name:"renderTargetSceneGrab",colorBuffer:s?null:h,depthBuffer:s?h:null,depth:!s,stencil:i.supportsStencil,autoResolve:!1}),e},t.releaseRenderTarget=function(e){e&&(e.destroyTextureBuffers(),e.destroy())},t.initWebGl2=function(){var e=this.application,t=this;this.layer=new fh({enabled:!1,name:"Depth",id:1,onDisable:function(){t.releaseRenderTarget(this.depthRenderTarget),this.depthRenderTarget=null,t.releaseRenderTarget(this.colorRenderTarget),this.colorRenderTarget=null},onPreRenderOpaque:function(i){var n,s=e.graphicsDevice,r=this.cameras[i];if(r.renderSceneColorMap){var a;t.resizeCondition(this.colorRenderTarget,null==(a=r.renderTarget)?void 0:a.colorBuffer,s)&&(t.releaseRenderTarget(this.colorRenderTarget),this.colorRenderTarget=t.allocateRenderTarget(this.colorRenderTarget,r.renderTarget,s,this.colorFormat,!1,!0,!1)),s.copyRenderTarget(s.renderTarget,this.colorRenderTarget,!0,!1),s.activeTexture(s.maxCombinedTextures-1);var o=this.colorRenderTarget.colorBuffer;s.bindTexture(o),s.gl.generateMipmap(o.impl._glTarget),t.setupUniform(s,!1,o)}r.renderSceneDepthMap&&(t.resizeCondition(this.depthRenderTarget,null==(n=r.renderTarget)?void 0:n.depthBuffer,s)&&(t.releaseRenderTarget(this.depthRenderTarget),this.depthRenderTarget=t.allocateRenderTarget(this.depthRenderTarget,r.renderTarget,s,pt,!0,!1,!0)),s.copyRenderTarget(s.renderTarget,this.depthRenderTarget,!1,!0),t.setupUniform(s,!0,this.depthRenderTarget.depthBuffer))},onPostRenderOpaque:function(e){}})},t.initWebGl1=function(){var e=this.application,t=this;this.layer=new fh({enabled:!1,name:"Depth",id:1,shaderPass:2,onEnable:function(){this.depthRenderTarget=new cr({name:"depthRenderTarget-webgl1",depth:!0,stencil:e.graphicsDevice.supportsStencil,autoResolve:!1,graphicsDevice:e.graphicsDevice}),this.renderTarget=this.depthRenderTarget},onDisable:function(){this.depthRenderTarget.destroyTextureBuffers(),this.renderTarget=null,t.releaseRenderTarget(this.colorRenderTarget),this.colorRenderTarget=null},onPostCull:function(i){var n=e.graphicsDevice,s=this.cameras[i];if(s.renderSceneDepthMap){var r;t.resizeCondition(this.depthRenderTarget,null==(r=s.renderTarget)?void 0:r.depthBuffer,n)&&(this.depthRenderTarget.destroyTextureBuffers(),this.depthRenderTarget=t.allocateRenderTarget(this.depthRenderTarget,s.renderTarget,n,7,!1,!1,!0));for(var a=this.instances.visibleOpaque[i],o=a.list,h=e.scene.layers,l=h.subLayerEnabled,c=h.subLayerList,u=e.scene.layers.getLayerById(0).renderTarget,d=this.cameras[i],f=0,p=h.layerList,m=0;m0&&this.loader.enableRetry(e.maxAssetRetries),e.useDevicePixelRatio||(e.useDevicePixelRatio=e.use_device_pixel_ratio),e.resolutionMode||(e.resolutionMode=e.resolution_mode),e.fillMode||(e.fillMode=e.fill_mode),this._width=e.width,this._height=e.height,e.useDevicePixelRatio&&(this.graphicsDevice.maxPixelRatio=window.devicePixelRatio),this.setCanvasResolution(e.resolutionMode,this._width,this._height),this.setCanvasFillMode(e.fillMode,this._width,this._height),e.layers&&e.layerOrder){var i=new bh("application"),n={};for(var s in e.layers){var r=e.layers[s];r.id=parseInt(s,10),r.enabled=1!==r.id,n[s]=new fh(r)}for(var a=0,o=e.layerOrder.length;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(e){var t=[];e.settings.priority_scripts&&(t=e.settings.priority_scripts);for(var i=[],n={},s=0;sn._timeToCountFrames?(n.fps=n._fpsAccum,n._fpsAccum=0,n._timeToCountFrames=e+1e3):n._fpsAccum++,this.stats.drawCalls.total=this.graphicsDevice._drawCallsPerFrame,this.graphicsDevice._drawCallsPerFrame=0},n._fillFrameStats=function(){var e=this.stats.frame;e.cameras=this.renderer._camerasRendered,e.materials=this.renderer._materialSwitches,e.shaders=this.graphicsDevice._shaderSwitchesPerFrame,e.shadowMapUpdates=this.renderer._shadowMapUpdates,e.shadowMapTime=this.renderer._shadowMapTime,e.depthMapTime=this.renderer._depthMapTime,e.forwardTime=this.renderer._forwardTime;var t=this.graphicsDevice._primsPerFrame;e.triangles=t[4]/3+Math.max(t[5]-2,0)+Math.max(t[6]-2,0),e.cullTime=this.renderer._cullTime,e.sortTime=this.renderer._sortTime,e.skinTime=this.renderer._skinTime,e.morphTime=this.renderer._morphTime,e.lightClusters=this.renderer._lightClusters,e.lightClustersTime=this.renderer._lightClustersTime,e.otherPrimitives=0;for(var i=0;ii/n?t=(e=i)/s:e=(t=n)*s}else this._fillMode===Gl&&(e=i,t=n);return this.graphicsDevice.canvas.style.width=e+"px",this.graphicsDevice.canvas.style.height=t+"px",this.updateCanvasSize(),{width:e,height:t}}},n.updateCanvasSize=function(){var e;if(this._allowResize&&(null==(e=this.xr)||!e.active)&&this._resolutionMode===Hl){var t=this.graphicsDevice.canvas;this.graphicsDevice.resizeCanvas(t.clientWidth,t.clientHeight)}},n.onLibrariesLoaded=function(){this._librariesLoaded=!0,this.systems.rigidbody&&this.systems.rigidbody.onLibraryLoaded()},n.applySceneSettings=function(e){var t;if(this.systems.rigidbody&&"undefined"!=typeof Ammo){var i=e.physics.gravity;this.systems.rigidbody.gravity.set(i[0],i[1],i[2])}this.scene.applySettings(e),e.render.hasOwnProperty("skybox")&&(e.render.skybox?(t=this.assets.get(e.render.skybox))?this.setSkybox(t):this.assets.once("add:"+e.render.skybox,this.setSkybox,this):this.setSkybox(null))},n.setAreaLightLuts=function(e,t){e&&t&&zh.set(this.graphicsDevice,e,t)},n.setSkybox=function(e){var t=this;if(e!==this._skyboxAsset){var i=function(){t.setSkybox(null)},n=function(){t.scene.setSkybox(t._skyboxAsset?t._skyboxAsset.resources:null)};this._skyboxAsset&&(this.assets.off("load:"+this._skyboxAsset.id,n,this),this.assets.off("remove:"+this._skyboxAsset.id,i,this),this._skyboxAsset.off("change",n,this)),this._skyboxAsset=e,this._skyboxAsset&&(this.assets.on("load:"+this._skyboxAsset.id,n,this),this.assets.once("remove:"+this._skyboxAsset.id,i,this),this._skyboxAsset.on("change",n,this),0!==this.scene.skyboxMip||this._skyboxAsset.loadFaces||(this._skyboxAsset.loadFaces=!0),this.assets.load(this._skyboxAsset)),n()}},n._firstBake=function(){var e;null==(e=this.lightmapper)||e.bake(null,this.scene.lightmapMode)},n._firstBatch=function(){var e;null==(e=this.batcher)||e.generate()},n._processTimestamp=function(e){return e},n.drawLine=function(e,t,i,n,s){this.scene.drawLine(e,t,i,n,s)},n.drawLines=function(e,t,i,n){void 0===i&&(i=!0),void 0===n&&(n=this.scene.defaultDrawLayer),this.scene.drawLines(e,t,i,n)},n.drawLineArrays=function(e,t,i,n){void 0===i&&(i=!0),void 0===n&&(n=this.scene.defaultDrawLayer),this.scene.drawLineArrays(e,t,i,n)},n.drawWireSphere=function(e,t,i,n,s,r){void 0===i&&(i=me.WHITE),void 0===n&&(n=20),void 0===s&&(s=!0),void 0===r&&(r=this.scene.defaultDrawLayer),this.scene.immediate.drawWireSphere(e,t,i,n,s,r)},n.drawWireAlignedBox=function(e,t,i,n,s){void 0===i&&(i=me.WHITE),void 0===n&&(n=!0),void 0===s&&(s=this.scene.defaultDrawLayer),this.scene.immediate.drawWireAlignedBox(e,t,i,n,s)},n.drawMeshInstance=function(e,t){void 0===t&&(t=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(null,null,null,e,t)},n.drawMesh=function(e,t,i,n){void 0===n&&(n=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(t,i,e,null,n)},n.drawQuad=function(e,t,i){void 0===i&&(i=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(t,e,this.scene.immediate.getQuadMesh(),null,i)},n.drawTexture=function(e,t,i,n,s,r,a){void 0===a&&(a=this.scene.defaultDrawLayer);var o=new Ee;o.setTRS(new ye(e,t,0),Pe.IDENTITY,new ye(i,n,0)),r||((r=new Bs).setParameter("colorMap",s),r.shader=this.scene.immediate.getTextureShader(),r.update()),this.drawQuad(o,r,a)},n.drawDepthTexture=function(e,t,i,n,s){void 0===s&&(s=this.scene.defaultDrawLayer);var r=new Bs;r.shader=this.scene.immediate.getDepthTextureShader(),r.update(),this.drawTexture(e,t,i,n,null,r,s)},n.destroy=function(){var e;if(this._inFrameUpdate)this._destroyRequested=!0;else{var t=this.graphicsDevice.canvas.id;this.off("librariesloaded"),"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this._visibilityChangeHandler,!1),document.removeEventListener("mozvisibilitychange",this._visibilityChangeHandler,!1),document.removeEventListener("msvisibilitychange",this._visibilityChangeHandler,!1),document.removeEventListener("webkitvisibilitychange",this._visibilityChangeHandler,!1)),this._visibilityChangeHandler=null,this.root.destroy(),this.root=null,this.mouse&&(this.mouse.off(),this.mouse.detach(),this.mouse=null),this.keyboard&&(this.keyboard.off(),this.keyboard.detach(),this.keyboard=null),this.touch&&(this.touch.off(),this.touch.detach(),this.touch=null),this.elementInput&&(this.elementInput.detach(),this.elementInput=null),this.controller&&(this.controller=null),this.systems.destroy(),this.scene.layers&&this.scene.layers.destroy();for(var n=this.assets.list(),s=0;s0&&t.push(new tc(e,l))}}for(var d=0;d0){var c=1===t?2:1;this.setLightmapping(o,!1,c),this.initBake(i),this.bakeInternal(c,o,h);var u=64;1===t&&(u|=Ge),this.scene.ambientBake&&(u|=je),this.setLightmapping(o,!0,c,u),this.finishBake(o)}var d=oe();this.stats.totalRenderTime=d-n,this.stats.shadersLinked=i._shaderStats.linked-s,this.stats.compileTime=i._shaderStats.compileTime-a,this.stats.fboTime=i._renderTargetCreationTime-r,this.stats.lightmapCount=o.length},t.allocateTextures=function(e,t){for(var i=0;i0){t.copy(e[0].aabb);for(var i=1;i1&&x>1&&v.light.bakeDir&&(x=1);for(var b=0;b1&&v.prepareVirtualLight(b,x),v.startBake();var S=!1,w=this.lightCameraPrepare(s,v);for(m=0;m0&&b>0)&&!(y&&p>0);p++){var M=T.renderTargets[p],C=T.renderTargets[p].colorBuffer.width,E=this.renderTargets.get(C),P=E.colorBuffer;0===p?g=n.updateShaders:g&&(n.updateShaders=!0);var R=this.passMaterials[p];for(y&&b+1===x&&0===p&&(R=this.ambientAOMaterial),c=0;cf)return!1;this.morphTextureWidth=p,this.morphTextureHeight=m;var _=!1,g=3,v=yn.float2Half;this._textureFormat===t.FORMAT_HALF_FLOAT&&(_=!0,g=4);for(var y=this.morphTextureWidth*this.morphTextureHeight*g,x=_?new Uint16Array(y):new Float32Array(y),b=0;b0&&(t+="varying vec2 uv0;\nuniform highp float morphFactor["+e+"];\n");for(var i=0;i=this.maxSubmitCount&&(s(r,a),r=0,a=!0))}(r>0||0===o&&!this.zeroTextures)&&s(r,a)},t._updateTextureMorph=function(){this.device,(this._activeTargets.length>0||!this.zeroTextures)&&(this._updateTextureRenderTarget(this.rtPositions,"texturePositions"),this._updateTextureRenderTarget(this.rtNormals,"textureNormals"),this.zeroTextures=0===this._activeTargets.length)},t._updateVertexMorph=function(){for(var e=this.maxSubmitCount,t=0;t1e-5){this._activeTargets.length<=t&&(this._activeTargets[t]={});var s=this._activeTargets[t++];s.absWeight=n,s.weight=this.getWeight(i),s.target=e[i]}}this._activeTargets.length=t;var r=this.morph.maxActiveTargets;this._activeTargets.length>r&&(this._activeTargets.sort((function(e,t){return e.absWeight0&&(i+=Wi.screenDepthPS),i+=Wi.particle_cpuVS,t.localSpace&&(i+=Wi.particle_localShiftVS),t.animTex&&(i+=this._animTex(t)),t.alignToMotion&&(i+=Wi.particle_pointAlongVS),i+=t.mesh?Wi.particle_meshVS:s,1===t.normal&&(i+=Wi.particle_normalVS),2===t.normal&&(i+=Wi.particle_TBNVS),t.stretch>0&&(i+=Wi.particle_stretchVS),i+=Wi.particle_cpu_endVS,t.soft>0&&(i+=Wi.particle_softVS)):(i+=Wi.particle_initVS,i+=t.pack8?Wi.particleInputRgba8PS:Wi.particleInputFloatPS,t.soft>0&&(i+=Wi.screenDepthPS),i+=Wi.particleVS,t.localSpace&&(i+=Wi.particle_localShiftVS),t.animTex&&(i+=this._animTex(t)),t.wrap&&(i+=Wi.particle_wrapVS),t.alignToMotion&&(i+=Wi.particle_pointAlongVS),i+=t.mesh?Wi.particle_meshVS:s,1===t.normal&&(i+=Wi.particle_normalVS),2===t.normal&&(i+=Wi.particle_TBNVS),t.stretch>0&&(i+=Wi.particle_stretchVS),i+=Wi.particle_endVS,t.soft>0&&(i+=Wi.particle_softVS)),i+="}\n",t.normal>0&&(1===t.normal?n+="\nvarying vec3 Normal;\n":2===t.normal&&(n+="\nvarying mat3 ParticleMat;\n"),n+="\nuniform vec3 lightCube[6];\n"),t.soft&&(n+="\nvarying float vDepth;\n"),0===t.normal&&"none"===t.fog&&(t.srgb=!1),n+=Wi.decodePS,n+=Xi(t.gamma),n+=qi(t.toneMap),"linear"===t.fog?n+=Wi.fogLinearPS:"exp"===t.fog?n+=Wi.fogExpPS:"exp2"===t.fog?n+=Wi.fogExp2PS:n+=Wi.fogNonePS,2===t.normal&&(n+="\nuniform sampler2D normalMap;\n"),t.soft>0&&(n+=Wi.screenDepthPS),n+=Wi.particlePS,t.soft>0&&(n+=Wi.particle_softPS),1===t.normal&&(n+="\nvec3 normal = Normal;\n"),2===t.normal&&(n+=Wi.particle_normalMapPS),t.normal>0&&(n+=t.halflambert?Wi.particle_halflambertPS:Wi.particle_lambertPS),t.normal>0&&(n+=Wi.particle_lightingPS),2===t.blend?n+=Wi.particle_blendNormalPS:1===t.blend?n+=Wi.particle_blendAddPS:5===t.blend&&(n+=Wi.particle_blendMultiplyPS),n+=Wi.particle_endPS,{attributes:rn(i),vshader:i,fshader:n}}},uc=1,dc=new Ee,fc=new Ee,mc=new ye,_c=new ye,gc=new ye,vc=new ye,yc=new ye,xc=new ye,bc=new ye,Sc=new ye,wc=new ye,Tc=new ye,Ac=new ye,Mc=new ye,Cc=new ye;function Ec(e){return e-Math.floor(e)}function Pc(e){return Math.max(Math.min(e,1),0)}function Rc(e,t){return e-t*Math.floor(e/t)}function Ic(e){var t=Ec(e),i=Ec(255*e);return[t-=i/255,i-=i/255]}var Lc=function(){function e(e){this._emitter=e}var t=e.prototype;return t.calcSpawnPosition=function(e,t,i,n,s){var r=this._emitter,a=Math.random(),o=Math.random(),h=Math.random(),l=Math.random();if(r.useCpu&&(e[4*s+0+2*r.numParticlesPot*4]=a,e[4*s+1+2*r.numParticlesPot*4]=o,e[4*s+2+2*r.numParticlesPot*4]=h),_c.x=a-.5,_c.y=o-.5,_c.z=h-.5,0===r.emitterShape){var c=Math.max(Math.abs(_c.x),Math.max(Math.abs(_c.y),Math.abs(_c.z))),u=c+(.5-c)*i[0],d=c+(.5-c)*i[1],f=c+(.5-c)*i[2];_c.x=u*(c===Math.abs(_c.x)?Math.sign(_c.x):2*_c.x),_c.y=d*(c===Math.abs(_c.y)?Math.sign(_c.y):2*_c.y),_c.z=f*(c===Math.abs(_c.z)?Math.sign(_c.z):2*_c.z),r.localSpace?mc.copy(t.transformPoint(_c)):mc.copy(n).add(t.transformPoint(_c))}else{_c.normalize();var p=0===r.emitterRadius?0:r.emitterRadiusInner/r.emitterRadius,m=l*(1-p)+p;r.localSpace?mc.copy(_c.mulScalar(m*r.emitterRadius)):mc.copy(n).add(_c.mulScalar(m*r.emitterRadius))}var _,g,v,y,x,b=-de.lerp(r.rate,r.rate2,a)*s;if(r.pack8){var S=(mc.x-r.worldBounds.center.x)/r.worldBoundsSize.x+.5,w=(mc.y-r.worldBounds.center.y)/r.worldBoundsSize.y+.5,T=(mc.z-r.worldBounds.center.z)/r.worldBoundsSize.z+.5,A=de.lerp(r.startAngle*de.DEG_TO_RAD,r.startAngle2*de.DEG_TO_RAD,a);A=A%(2*Math.PI)/(2*Math.PI);var M=Ic(S);e[4*s]=M[0],e[4*s+1]=M[1];var C=Ic(w);e[4*s+2]=C[0],e[4*s+3]=C[1];var E=Ic(T);e[4*s+0+4*r.numParticlesPot]=E[0],e[4*s+1+4*r.numParticlesPot]=E[1];var P=Ic(A);e[4*s+2+4*r.numParticlesPot]=P[0],e[4*s+3+4*r.numParticlesPot]=P[1];e[4*s+3+4*r.numParticlesPot*2]=1;var R=Math.max(r.lifetime,(r.numParticles-1)*Math.max(r.rate,r.rate2)),I=r.lifetime+1,L=(g=Ec(_=b=(b+R)/(R+I)),v=Ec(255*_),y=Ec(65025*_),x=Ec(160581375*_),[g-=v/255,v-=y/255,y-=x/255,x-=x/255]);e[4*s+0+4*r.numParticlesPot*3]=L[0],e[4*s+1+4*r.numParticlesPot*3]=L[1],e[4*s+2+4*r.numParticlesPot*3]=L[2],e[4*s+3+4*r.numParticlesPot*3]=L[3]}else e[4*s]=mc.x,e[4*s+1]=mc.y,e[4*s+2]=mc.z,e[4*s+3]=de.lerp(r.startAngle*de.DEG_TO_RAD,r.startAngle2*de.DEG_TO_RAD,a),e[4*s+3+4*r.numParticlesPot]=b},t.update=function(e,t,i,n,s,r,a,o){var h,l,c,u=this._emitter;if(u.meshInstance.node){for(var d=u.meshInstance.node.worldTransform,f=0;f<12;f++)dc.data[f]=d.data[f];fc.copy(dc),fc.invert(),ac=u.meshInstance.node.localScale,uc=Math.max(Math.max(ac.x,ac.y),ac.z)}r=null===u.meshInstance.node||u.localSpace?ye.ZERO:u.meshInstance.node.getPosition();for(var p,m,_,g,v,y,x,b,S=u.camera?u.camera._node.getPosition():ye.ZERO,w=u.useMesh?17:15,T=u.precision-1,A=0;A=P)&&this.calcSpawnPosition(i,n,s,r,M);var k=R>0&&R0&&(1===u.emitterShape?(_c.copy(gc).mulScalar(2).sub(ye.ONE).normalize(),xc.add(_c.mulScalar(u.initialVelocity))):xc.add(ye.FORWARD.mulScalar(u.initialVelocity))),yc.x+=(bc.x-yc.x)*gc.x,yc.y+=(bc.y-yc.y)*gc.y,yc.z+=(bc.z-yc.z)*gc.z,_+=(g-_)*gc.y,L=(L+1e4*C%1*(v-L))*uc,D=1e3*C%1*(x-y),u.meshInstance.node&&(u.localSpace?(xc.x/=ac.x,xc.y/=ac.y,xc.z/=ac.z):dc.transformPoint(xc,xc)),u.localSpace?(fc.transformPoint(yc,yc),xc.add(yc).add(wc)):(xc.add(yc.mul(ac)),xc.add(wc.mul(ac))),Mc.copy(xc),Tc.copy(vc).add(xc.mulScalar(a)),Ac.copy(Tc),i[4*M]=Ac.x,i[4*M+1]=Ac.y,i[4*M+2]=Ac.z,i[4*M+3]+=_*a,u.wrap&&u.wrapBounds&&(u.localSpace||Ac.sub(r),Ac.x=Rc(Ac.x,u.wrapBounds.x)-.5*u.wrapBounds.x,Ac.y=Rc(Ac.y,u.wrapBounds.y)-.5*u.wrapBounds.y,Ac.z=Rc(Ac.z,u.wrapBounds.z)-.5*u.wrapBounds.z,u.localSpace||Ac.add(r)),u.sort>0&&(1===u.sort?(Cc.copy(Ac).sub(S),u.particleDistance[M]=-(Cc.x*Cc.x+Cc.y*Cc.y+Cc.z*Cc.z)):2===u.sort?u.particleDistance[M]=R:3===u.sort&&(u.particleDistance[M]=-R))),o?R<0&&(i[4*M+3+2*u.numParticlesPot*4]=-1):(R>=P&&(R-=Math.max(P,(u.numParticles-1)*E),i[4*M+3+2*u.numParticlesPot*4]=u.loop?1:-1),R<0&&u.loop&&(i[4*M+3+2*u.numParticlesPot*4]=1)),i[4*M+3+2*u.numParticlesPot*4]<0&&(k=!1),i[4*M+3+4*u.numParticlesPot]=R;for(var O=0;O0&&u.camera){for(var V=u.useMesh?6:4,G=u.particleDistance,W=0;We.maxTextureSize&&(this.numParticles=e.maxTextureSize),Qc("rate",1),Qc("rate2",this.rate),Qc("lifetime",50),Qc("emitterExtents",new ye(0,0,0)),Qc("emitterExtentsInner",new ye(0,0,0)),Qc("emitterRadius",0),Qc("emitterRadiusInner",0),Qc("emitterShape",0),Qc("initialVelocity",1),Qc("wrap",!1),Qc("localSpace",!1),Qc("screenSpace",!1),Qc("wrapBounds",null),Qc("colorMap",this.defaultParamTexture),Qc("normalMap",null),Qc("loop",!0),Qc("preWarm",!1),Qc("sort",0),Qc("mode",0),Qc("scene",null),Qc("lighting",!1),Qc("halfLambert",!1),Qc("intensity",1),Qc("stretch",0),Qc("alignToMotion",!1),Qc("depthSoftening",0),Qc("mesh",null),Qc("particleNormal",new ye(0,1,0)),Qc("orientation",0),Qc("depthWrite",!1),Qc("noFog",!1),Qc("blendType",2),Qc("node",null),Qc("startAngle",0),Qc("startAngle2",this.startAngle),Qc("animTilesX",1),Qc("animTilesY",1),Qc("animStartFrame",0),Qc("animNumFrames",1),Qc("animNumAnimations",1),Qc("animIndex",0),Qc("randomizeAnimIndex",!1),Qc("animSpeed",1),Qc("animLoop",!0),this._gpuUpdater=new Fc(this,i),this._cpuUpdater=new Lc(this),this.constantLightCube=i.scope.resolve("lightCube[0]"),this.emitterPosUniform=new Float32Array(3),this.wrapBoundsUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),Qc("colorGraph",Xc),Qc("colorGraph2",this.colorGraph),Qc("scaleGraph",Wc),Qc("scaleGraph2",this.scaleGraph),Qc("alphaGraph",Wc),Qc("alphaGraph2",this.alphaGraph),Qc("localVelocityGraph",Hc),Qc("localVelocityGraph2",this.localVelocityGraph),Qc("velocityGraph",Hc),Qc("velocityGraph2",this.velocityGraph),Qc("rotationSpeedGraph",Gc),Qc("rotationSpeedGraph2",this.rotationSpeedGraph),Qc("radialSpeedGraph",Gc),Qc("radialSpeedGraph2",this.radialSpeedGraph),this.lightCube=new Float32Array(18),this.lightCubeDir=new Array(6),this.lightCubeDir[0]=new ye(-1,0,0),this.lightCubeDir[1]=new ye(1,0,0),this.lightCubeDir[2]=new ye(0,-1,0),this.lightCubeDir[3]=new ye(0,1,0),this.lightCubeDir[4]=new ye(0,0,-1),this.lightCubeDir[5]=new ye(0,0,1),this.animTilesParams=new Float32Array(2),this.animParams=new Float32Array(4),this.animIndexParams=new Float32Array(2),this.internalTex0=null,this.internalTex1=null,this.internalTex2=null,this.colorParam=null,this.vbToSort=null,this.vbOld=null,this.particleDistance=null,this.camera=null,this.swapTex=!1,this.useMesh=!0,this.useCpu=!e.supportsGpuParticles,this.pack8=!0,this.localBounds=new Oe,this.worldBoundsNoTrail=new Oe,this.worldBoundsTrail=[new Oe,new Oe],this.worldBounds=new Oe,this.worldBoundsSize=new ye,this.prevWorldBoundsSize=new ye,this.prevWorldBoundsCenter=new ye,this.prevEmitterExtents=this.emitterExtents,this.prevEmitterRadius=this.emitterRadius,this.worldBoundsMul=new ye,this.worldBoundsAdd=new ye,this.timeToSwitchBounds=0,this.shaderParticleUpdateRespawn=null,this.shaderParticleUpdateNoRespawn=null,this.shaderParticleUpdateOnStop=null,this.numParticleVerts=0,this.numParticleIndices=0,this.material=null,this.meshInstance=null,this.drawOrder=0,this.seed=Math.random(),this.fixedTimeStep=1/60,this.maxSubSteps=10,this.simTime=0,this.simTimeTotal=0,this.beenReset=!1,this._layer=null,this.rebuild()}var t=e.prototype;return t.onChangeCamera=function(){this.regenShader(),this.resetMaterial()},t.calculateBoundsMad=function(){this.worldBoundsMul.x=1/this.worldBoundsSize.x,this.worldBoundsMul.y=1/this.worldBoundsSize.y,this.worldBoundsMul.z=1/this.worldBoundsSize.z,this.worldBoundsAdd.copy(this.worldBounds.center).mul(this.worldBoundsMul).mulScalar(-1),this.worldBoundsAdd.x+=.5,this.worldBoundsAdd.y+=.5,this.worldBoundsAdd.z+=.5},t.calculateWorldBounds=function(){if(this.node){if(this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),!this.useCpu){(0===this.emitterShape?!this.emitterExtents.equals(this.prevEmitterExtents):!(this.emitterRadius===this.prevEmitterRadius))&&this.calculateLocalBounds()}var e=this.node.getWorldTransform();this.localSpace?this.worldBoundsNoTrail.copy(this.localBounds):this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,e),this.worldBoundsTrail[0].add(this.worldBoundsNoTrail),this.worldBoundsTrail[1].add(this.worldBoundsNoTrail);var t=this.simTimeTotal;t>=this.timeToSwitchBounds&&(this.worldBoundsTrail[0].copy(this.worldBoundsTrail[1]),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.timeToSwitchBounds=t+this.lifetime),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.localSpace?(this.meshInstance.aabb.setFromTransformedAabb(this.worldBounds,e),this.meshInstance.mesh.aabb.setFromTransformedAabb(this.worldBounds,e)):(this.meshInstance.aabb.copy(this.worldBounds),this.meshInstance.mesh.aabb.copy(this.worldBounds)),this.meshInstance._aabbVer=1-this.meshInstance._aabbVer,this.pack8&&this.calculateBoundsMad()}},t.resetWorldBounds=function(){this.node&&(this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,this.localSpace?Ee.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBoundsNoTrail),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.simTimeTotal=0,this.timeToSwitchBounds=0)},t.calculateLocalBounds=function(){for(var e,t,i,n=Number.MAX_VALUE,s=Number.MAX_VALUE,r=Number.MAX_VALUE,a=-Number.MAX_VALUE,o=-Number.MAX_VALUE,h=-Number.MAX_VALUE,l=0,c=0,u=this.lifetime/this.precision,d=[this.qVelocity,this.qVelocity2],f=[this.qLocalVelocity,this.qLocalVelocity2],p=[0,0],m=[0,0],_=[0,0],g=[0,0],v=[0,0],y=0;y0||e.maxVertexTextures<=1||e.fragmentUniformsCount<64||e.forceCpuParticles||!e.extTextureFloat,this._destroyResources(),this.pack8=(this.pack8||!e.textureFloatRenderable)&&!this.useCpu,qc=this.useCpu||this.pack8?4:2,this.useMesh=!1,this.mesh)&&(this.numParticles*this.mesh.vertexBuffer.numVertices>65535||(this.useMesh=!0));this.numParticlesPot=de.nextPowerOfTwo(this.numParticles),this.rebuildGraphs(),this.calculateLocalBounds(),this.resetWorldBounds(),this.node&&(this.worldBounds.setFromTransformedAabb(this.localBounds,this.localSpace?Ee.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBounds),this.worldBoundsTrail[1].copy(this.worldBounds),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.pack8&&this.calculateBoundsMad()),this.vbToSort=new Array(this.numParticles);for(var t=0;t=1&&(this.animTilesX>1||this.animTilesY>1)&&(this.colorMap&&this.colorMap!==this.defaultParamTexture||this.normalMap)},t.rebuildGraphs=function(){var e=this.precision,t=this.graphicsDevice;this.qLocalVelocity=this.localVelocityGraph.quantize(e),this.qVelocity=this.velocityGraph.quantize(e),this.qColor=this.colorGraph.quantizeClamped(e,0,1),this.qRotSpeed=this.rotationSpeedGraph.quantize(e),this.qScale=this.scaleGraph.quantize(e),this.qAlpha=this.alphaGraph.quantize(e),this.qRadialSpeed=this.radialSpeedGraph.quantize(e),this.qLocalVelocity2=this.localVelocityGraph2.quantize(e),this.qVelocity2=this.velocityGraph2.quantize(e),this.qColor2=this.colorGraph2.quantizeClamped(e,0,1),this.qRotSpeed2=this.rotationSpeedGraph2.quantize(e),this.qScale2=this.scaleGraph2.quantize(e),this.qAlpha2=this.alphaGraph2.quantize(e),this.qRadialSpeed2=this.radialSpeedGraph2.quantize(e);for(var i=0;i0&&e.setParameter("softening",1/(this.depthSoftening*this.depthSoftening*100)),this.stretch>0&&(e.cull=0),this._compParticleFaceParams()},t._compParticleFaceParams=function(){var e,t;if(0===this.orientation)e=new Float32Array([1,0,0]),t=new Float32Array([0,0,1]);else{var i;if(1===this.orientation)i=this.particleNormal.normalize();else i=(null===this.node?Ee.IDENTITY:this.node.getWorldTransform()).transformVector(this.particleNormal).normalize();var n=new ye(1,0,0);1===Math.abs(n.dot(i))&&n.set(0,0,1);var s=(new ye).cross(i,n).normalize();n.cross(s,i).normalize(),e=new Float32Array([n.x,n.y,n.z]),t=new Float32Array([s.x,s.y,s.z])}this.material.setParameter("faceTangent",e),this.material.setParameter("faceBinorm",t)},t._allocate=function(e){var t=e*this.numParticleVerts,i=e*this.numParticleIndices;if(void 0===this.vertexBuffer||this.vertexBuffer.getNumVertices()!==t){if(this.useCpu){var n=[{semantic:kt,components:4,type:6},{semantic:Ot,components:4,type:6},{semantic:Ft,components:4,type:6},{semantic:Bt,components:1,type:6},{semantic:Nt,components:this.useMesh?4:2,type:6}],s=new Ti(this.graphicsDevice,n);this.vertexBuffer=new Si(this.graphicsDevice,s,t,1),this.indexBuffer=new mr(this.graphicsDevice,1,i)}else{var r=[{semantic:kt,components:4,type:6}];this.useMesh&&r.push({semantic:Ot,components:2,type:6});var a=new Ti(this.graphicsDevice,r);this.vertexBuffer=new Si(this.graphicsDevice,a,t,1),this.indexBuffer=new mr(this.graphicsDevice,1,i)}var o,h,l,c=new Float32Array(this.vertexBuffer.lock());if(this.useMesh){h=(o=new Float32Array(this.mesh.vertexBuffer.lock())).length/this.mesh.vertexBuffer.numVertices;for(var u=0;uthis.endTime&&(this.onFinished&&this.onFinished(),this.meshInstance.visible=!1),this.meshInstance&&(this.meshInstance.drawOrder=this.drawOrder)},t._destroyResources=function(){this.particleTexIN&&(this.particleTexIN.destroy(),this.particleTexIN=null),this.particleTexOUT&&(this.particleTexOUT.destroy(),this.particleTexOUT=null),this.particleTexStart&&this.particleTexStart.destroy&&(this.particleTexStart.destroy(),this.particleTexStart=null),this.rtParticleTexIN&&(this.rtParticleTexIN.destroy(),this.rtParticleTexIN=null),this.rtParticleTexOUT&&(this.rtParticleTexOUT.destroy(),this.rtParticleTexOUT=null),this.internalTex0&&(this.internalTex0.destroy(),this.internalTex0=null),this.internalTex1&&(this.internalTex1.destroy(),this.internalTex1=null),this.internalTex2&&(this.internalTex2.destroy(),this.internalTex2=null),this.internalTex3&&(this.internalTex3.destroy(),this.internalTex3=null),this.colorParam&&(this.colorParam.destroy(),this.colorParam=null),this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=void 0),this.indexBuffer&&(this.indexBuffer.destroy(),this.indexBuffer=void 0),this.material&&(this.material.destroy(),this.material=null)},t.destroy=function(){this.camera=null,this._destroyResources()},$(e,[{key:"defaultParamTexture",get:function(){var e=this;return nu.get(this.graphicsDevice,(function(){for(var t=16,i=new Float32Array(1024),n=0;n>16&255)/255,t.pickColor[1]=(s>>8&255)/255,t.pickColor[2]=(255&s)/255,i.setValue(t.pickColor),e.setBlending(!1),t.mapping[s]=n}}),this.layer.addCamera(this.cameraEntity.camera),this.layerComp=new bh("picker"),this.layerComp.pushOpaque(this.layer)},t.prepare=function(e,t,i){e instanceof En&&(e=e.node.camera),i instanceof fh&&(i=[i]),this.layer.clearMeshInstances();for(var n=this.layer.opaqueMeshInstances,s=t.layers.layerList,r=t.layers.subLayerEnabled,a=t.layers.subLayerList,o=0;o=0){h._clearDepthBuffer&&n.push(this.clearDepthCommand);for(var l=a[o]?h.instances.transparentMeshInstances:h.instances.opaqueMeshInstances,c=0;ci){this._time=this.looping?0:i;for(var n=0;n=0?1:-1,l=0;l=0;m+=h){var _=d[m],g=d[m+1];if(_.time<=this._time&&g.time>=this._time){var v=(this._time-_.time)/(g.time-_.time);f._pos.lerp(_.position,g.position,v),f._quat.slerp(_.rotation,g.rotation,v),f._scale.lerp(_.scale,g.scale,v),f._written=!0,this._currKeyIndices[u]=m,p=!0;break}}(1===d.length||!p&&0===this._time&&this.looping)&&(f._pos.copy(d[0].position),f._quat.copy(d[0].rotation),f._scale.copy(d[0].scale),f._written=!0)}}}},t.blend=function(e,t,i){for(var n=this._interpolatedKeys.length,s=0;s0&&i.push(n),i},e.encode=function(e,t,i){return(Array.isArray(e)?e.join("/"):e)+"/"+t+"/"+(Array.isArray(i)?i.join("/"):i)};var t=e.prototype;return t.resolve=function(e){return null},t.unresolve=function(e){},t.update=function(e){},e}(),xu=function(){function e(){this._left=1/0,this._right=-1/0,this._len=0,this._recip=0,this._p0=0,this._p1=0,this._t=0,this._hermite={valid:!1,p0:0,m0:0,p1:0,m1:0}}var t=e.prototype;return t.update=function(e,t){if(e=this._right){var i=t.length;if(i)if(e=t[i-1])this._left=t[i-1],this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=i-1;else{var n=this._findKey(e,t);this._left=t[n],this._right=t[n+1],this._len=this._right-this._left;var s=1/this._len;this._recip=isFinite(s)?s:0,this._p0=n,this._p1=n+1}else this._left=-1/0,this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=0}this._t=0===this._recip?0:(e-this._left)*this._recip,this._hermite.valid=!1},t._findKey=function(e,t){for(var i=0;e>=t[i+1];)i++;return i},t.eval=function(e,t,i){var n=i._data,s=i._components,r=this._p0*s;if(0===t)for(var a=0;athis.track.duration&&(i=t-this.track.duration,t=this.track.duration);this.track.events[this.eventCursor]&&this.track.events[this.eventCursor].time>=e&&(t===this.track.duration?this.track.events[this.eventCursor].time<=t:this.track.events[this.eventCursor].time0&&i>0&&this.activeEventsForFrame(t,t+n*e),t+=n*e,n>=0?t>i&&(s?t=t%i||0:(t=this._track.duration,this.pause())):t<0&&(s?t=i+(t%i||0):(t=0,this.pause())),this._time=t}this._time!==this._snapshot._time&&this._track.eval(this._time,this._snapshot)},t.play=function(){this._playing=!0,this._time=0},t.stop=function(){this._playing=!1,this._time=0},t.pause=function(){this._playing=!1},t.resume=function(){this._playing=!0},t.reset=function(){this._time=0},$(e,[{key:"name",get:function(){return this._name},set:function(e){this._name=e}},{key:"track",get:function(){return this._track}},{key:"snapshot",get:function(){return this._snapshot}},{key:"time",get:function(){return this._time},set:function(e){this._time=e}},{key:"speed",get:function(){return this._speed},set:function(e){this._speed=e}},{key:"loop",get:function(){return this._loop},set:function(e){this._loop=e}},{key:"blendWeight",get:function(){return this._blendWeight},set:function(e){this._blendWeight=e}},{key:"blendOrder",get:function(){return this._blendOrder},set:function(e){this._blendOrder=e}},{key:"eventCursor",get:function(){return this._eventCursor},set:function(e){this._eventCursor=e}}]),e}(),wu=function(){function e(e,t,i,n){this._paths=e,this._input=t,this._output=i,this._interpolation=n}return $(e,[{key:"paths",get:function(){return this._paths}},{key:"input",get:function(){return this._input}},{key:"output",get:function(){return this._output}},{key:"interpolation",get:function(){return this._interpolation}}]),e}(),Tu=function(){function e(e,t){this._components=e,this._data=t}return $(e,[{key:"components",get:function(){return this._components}},{key:"data",get:function(){return this._data}}]),e}(),Au="NONE",Mu="PREV_STATE",Cu="NEXT_STATE",Eu="PREV_STATE_NEXT_STATE",Pu="NEXT_STATE_PREV_STATE",Ru="GREATER_THAN",Iu="LESS_THAN",Lu="GREATER_THAN_EQUAL_TO",Du="LESS_THAN_EQUAL_TO",ku="EQUAL_TO",Ou="NOT_EQUAL_TO",Fu="INTEGER",Bu="FLOAT",Nu="BOOLEAN",Uu="TRIGGER",zu="2D_DIRECTIONAL",Vu="2D_CARTESIAN",Gu="DIRECT",Wu="START",Hu="END",Xu="ANY",qu=[Wu,Hu,Xu],ju="OVERWRITE",Yu="ADDITIVE",Ku=function(){function e(t,i){this._component=t,this.mask=new Int8Array(t.layers.length),this.weights=new Float32Array(t.layers.length),this.totalWeight=0,this.counter=0,this.layerCounter=0,this.valueType=i,this.dirty=!0,this.value=i===e.TYPE_QUAT?[0,0,0,1]:[0,0,0],this.baseValue=null,this.setter=null}var t=e.prototype;return t.getWeight=function(e){return this.dirty&&this.updateWeights(),this._normalizeWeights&&0===this.totalWeight||!this.mask[e]?0:this._normalizeWeights?this.weights[e]/this.totalWeight:de.clamp(this.weights[e],0,1)},t._layerBlendType=function(e){return this._component.layers[e].blendType},t.setMask=function(e,t){this.mask[e]=t,this._normalizeWeights&&(this._component.layers[e].blendType===ju&&(this.mask=this.mask.fill(0,0,e)),this.dirty=!0)},t.updateWeights=function(){this.totalWeight=0;for(var e=0;e0){i=1/Math.sqrt(i);for(var n=t.length,s=0;s0&&(r=1/Math.sqrt(r));for(var a=0;a0;)this.removeClip(0)},t.findClip=function(e){for(var t=this._clips,i=0;i0&&a._update(t);var c=void 0,u=void 0,d=void 0;if(l>=1)for(var f=0;f0)for(var p=0;p=0)this._animationList[n].animTrack=t;else{var s=this._getNodeFromPath(e);s.animTrack=t,this._animationList.push(s)}},$(e,[{key:"name",get:function(){return this._name}},{key:"animations",get:function(){return this._animationList},set:function(e){this._animationList=e}},{key:"speed",get:function(){return this._speed},set:function(e){this._speed=e}},{key:"loop",get:function(){return this._loop},set:function(e){this._loop=e}},{key:"nodeCount",get:function(){return this._blendTree&&this._blendTree.constructor!==td?this._blendTree.getNodeCount():1}},{key:"playable",get:function(){return-1!==qu.indexOf(this.name)||this.animations.length===this.nodeCount}},{key:"looping",get:function(){if(this.animations.length>0){var e=this.name+"."+this.animations[0].animTrack.name,t=this._controller.animEvaluator.findClip(e);if(t)return t.loop}return!1}},{key:"totalWeight",get:function(){for(var e=0,t=0;te&&(e=i.animTrack.duration)}return e}}]),e}(),hd=function(){function e(e){var t=e.from,i=e.to,n=e.time,s=void 0===n?0:n,r=e.priority,a=void 0===r?0:r,o=e.conditions,h=void 0===o?[]:o,l=e.exitTime,c=void 0===l?null:l,u=e.transitionOffset,d=void 0===u?null:u,f=e.interruptionSource,p=void 0===f?Au:f;this._from=t,this._to=i,this._time=s,this._priority=a,this._conditions=h,this._exitTime=c,this._transitionOffset=d,this._interruptionSource=p}return $(e,[{key:"from",get:function(){return this._from}},{key:"to",get:function(){return this._to},set:function(e){this._to=e}},{key:"time",get:function(){return this._time}},{key:"priority",get:function(){return this._priority}},{key:"conditions",get:function(){return this._conditions}},{key:"exitTime",get:function(){return this._exitTime}},{key:"transitionOffset",get:function(){return this._transitionOffset}},{key:"interruptionSource",get:function(){return this._interruptionSource}},{key:"hasExitTime",get:function(){return!!this.exitTime}}]),e}(),ld=function(){function e(e,t,i,n,s,r,a){this._animEvaluator=e,this._states={},this._stateNames=[],this._eventHandler=r,this._consumedTriggers=a;for(var o=0;o"+t];return i||(i=this._transitions.filter((function(i){return i.from===e&&i.to===t})),_h(i),this._findTransitionsBetweenStatesCache[e+"->"+t]=i),i},t._transitionHasConditionsMet=function(e){for(var t=e.conditions,i=0;in.value))return!1;break;case Iu:if(!(s.value=n.value))return!1;break;case Du:if(!(s.value<=n.value))return!1;break;case ku:if(s.value!==n.value)return!1;break;case Ou:if(s.value===n.value)return!1}}return!0},t._findTransition=function(e,t){var i=this,n=[];if(e&&t)n=n.concat(this._findTransitionsBetweenStates(e,t));else if(this._isTransitioning)switch(this._transitionInterruptionSource){case Mu:n=(n=n.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(Xu));break;case Cu:n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Xu));break;case Eu:n=(n=(n=n.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Xu));break;case Pu:n=(n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(Xu))}else n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Xu));if(n=n.filter((function(e){if(e.to===i.activeStateName)return!1;if(e.hasExitTime){var t=i._getActiveStateProgressForTime(i._timeInStateBefore),n=i._getActiveStateProgressForTime(i._timeInState);if(e.exitTime<1&&i.activeState.loop&&(t-=Math.floor(t),n-=Math.floor(n)),!(e.exitTime>t&&e.exitTime<=n))return null}return i._transitionHasConditionsMet(e)})),n.length>0){var s=n[0];if(s.to===Hu){var r=this._findTransitionsFromState(Wu)[0];s.to=r.to}return s}return null},t.updateStateFromTransition=function(e){var t,i,n;this.previousState=e.from?this.activeStateName:null,this.activeState=e.to;for(var s=0;s0&&e.transitionOffset<1,u=0,d=0;if(c){var f=l.timelineDuration*e.transitionOffset;u=f,d=f}this._timeInState=u,this._timeInStateBefore=d;for(var p=0;p0?n.blendWeight=0:n.blendWeight=l.animations[p].normalizedWeight,n.play(),c)n.time=l.timelineDuration*e.transitionOffset;else{var _=l.speed>=0?0:this.activeStateDuration;n.time=_}}},t._transitionToState=function(e){if(this._findState(e)){var t=this._findTransition(this._activeStateName,e);t||(this._animEvaluator.removeClips(),t=new hd({from:null,to:e})),this.updateStateFromTransition(t)}},t.assignAnimation=function(e,t,i,n){var s=e.split("."),r=this._findState(s[0]);r||(r=new od(this,s[0],1),this._states[s[0]]=r,this._stateNames.push(s[0])),r.addAnimation(s,t),void 0!==i&&(r.speed=i),void 0!==n&&(r.loop=n),!this._playing&&this._activate&&this.playable&&this.play()},t.removeNodeAnimations=function(e){if(-1!==qu.indexOf(e))return!1;var t=this._findState(e);return!!t&&(t.animations=[],!0)},t.play=function(e){e&&this._transitionToState(e),this._playing=!0},t.pause=function(){this._playing=!1},t.reset=function(){this._previousStateName=null,this._activeStateName=Wu,this._playing=!1,this._currTransitionTime=1,this._totalTransitionTime=1,this._isTransitioning=!1,this._timeInState=0,this._timeInStateBefore=0,this._animEvaluator.removeClips()},t.rebind=function(){this._animEvaluator.rebind()},t.update=function(e){if(this._playing){var t,i,n;this._timeInStateBefore=this._timeInState,this._timeInState+=e;var s=this._findTransition(this._activeStateName);if(s&&this.updateStateFromTransition(s),this._isTransitioning)if(this._currTransitionTime+=e,this._currTransitionTime<=this._totalTransitionTime){for(var r=0!==this._totalTransitionTime?this._currTransitionTime/this._totalTransitionTime:1,a=0;apd?pd:i.width||512,r=i.height>pd?pd:i.height||512,a=document.createElement("canvas");a.height=r,a.width=s;var o=new wn(n.app.graphicsDevice,{name:"font",format:7,minFilter:5,magFilter:1,addressU:1,addressV:1,mipmaps:!0});return o.setSource(a),n.textures=[o],n.chars="",n.data={},n}J(t,e);var i=t.prototype;return i.createTextures=function(e){var t=this._normalizeCharsSet(e);if(t.length===this.chars.length){for(var i=0;i0&&this._renderAtlas(this.chars.concat(i))},i.destroy=function(){for(var e=0;eC&&(C=this.fontSize*this.fontSize/E,c.font=this.fontWeight+" "+C.toString()+"px "+this.fontName,E=this.fontSize),this.renderCharacter(c,A,S+x,w+b,r);var P=this.padding+(this.glyphSize-E)/2,R=-this.padding+m[A].descent-p,I=E;if(this._addChar(this.data,A,M,S,w,v,y,P,R,I,t-1,n,s),(S+=v)+v>n&&(S=0,(w+=y)+y>s))if(this.textures[t-1].upload(),w=0,++t>d){(i=document.createElement("canvas")).height=s,i.width=n,c=this._getAndClearContext(i,o);var L=new wn(this.app.graphicsDevice,{format:7,mipmaps:!0,name:"font-atlas"});L.setSource(i),L.minFilter=5,L.magFilter=1,L.addressU=1,L.addressV=1,this.textures.push(L)}else i=this.textures[t-1].getSource(),c=this._getAndClearContext(i,o)}if(this.textures[t-1].upload(),tn)return 0;var o=0;return r===_d?o=1-s*(a-i)/(n-i):r===gd?o=i/(i+s*(a-i)):r===vd&&(o=Math.pow(a/i,-s)),de.clamp(o,0,1)}(this.manager.listener.getPosition(),this.position,this.minDistance,this.maxDistance,this.rollOffFactor,this.distanceModel),i=this.getVolume();this.source.volume=i*t}},getMaxDistance:function(){return this.maxDistance},setMaxDistance:function(e){this.maxDistance=e},getMinDistance:function(){return this.minDistance},setMinDistance:function(e){this.minDistance=e},getRollOffFactor:function(){return this.rollOffFactor},setRollOffFactor:function(e){this.rollOffFactor=e},getDistanceModel:function(){return this.distanceModel},setDistanceModel:function(e){this.distanceModel=e}})}var wd=function(){function e(e){this._manager=e,this.position=new ye,this.velocity=new ye,this.orientation=new Ee}var t=e.prototype;return t.getPosition=function(){return this.position},t.setPosition=function(e){this.position.copy(e);var t=this.listener;t&&("positionX"in t?(t.positionX.value=e.x,t.positionY.value=e.y,t.positionZ.value=e.z):t.setPosition&&t.setPosition(e.x,e.y,e.z))},t.getVelocity=function(){return this.velocity},t.setVelocity=function(e){},t.setOrientation=function(e){this.orientation.copy(e);var t=this.listener;if(t){var i=e.data;"forwardX"in t?(t.forwardX.value=-i[8],t.forwardY.value=-i[9],t.forwardZ.value=-i[10],t.upX.value=i[4],t.upY.value=i[5],t.upZ.value=i[6]):t.setOrientation&&t.setOrientation(-i[8],-i[9],-i[10],i[4],i[5],i[6])}},t.getOrientation=function(){return this.orientation},$(e,[{key:"listener",get:function(){var e=this._manager.context;return e?e.listener:null}}]),e}(),Td="running",Ad=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","pointerup","touchend","keydown","keyup"],Md=function(e){function t(t){var i;return(i=e.call(this)||this)._context=null,i._forceWebAudioApi=t.forceWebAudioApi,i._resumeContextCallback=null,i._selfSuspended=!1,i._unlocked=!1,i._unlocking=!1,!yd()&&i._forceWebAudioApi,i.listener=new wd(te(i)),i._volume=1,i}J(t,e);var i=t.prototype;return i.suspend=function(){this._selfSuspended=!0,this.suspended||this.fire("suspend")},i.resume=function(){var e=this;this._selfSuspended=!1,this._context&&(this._unlocked||this._unlocking)&&("interrupted"===this._context.state?this._context.resume().then((function(){e.fire("resume")}),(function(e){})).catch((function(e){})):this.fire("resume"))},i.destroy=function(){this._removeUserInputListeners(),this.fire("destroy"),this._context&&this._context.close&&(this._context.close(),this._context=null)},i.playSound=function(e,t){void 0===t&&(t={});var i=null;return xd&&(i=new xd(this,e,t)).play(),i},i.playSound3d=function(e,t,i){void 0===i&&(i={});var n=null;return bd&&((n=new bd(this,e,i)).setPosition(t),i.volume&&n.setVolume(i.volume),i.loop&&n.setLoop(i.loop),i.maxDistance&&n.setMaxDistance(i.maxDistance),i.minDistance&&n.setMinDistance(i.minDistance),i.rollOffFactor&&n.setRollOffFactor(i.rollOffFactor),i.distanceModel&&n.setDistanceModel(i.distanceModel),n.play()),n},i._addContextUnlockListeners=function(){var e=this;this._unlocking=!1,this._resumeContextCallback||(this._resumeContextCallback=function(){if(e._context&&!e._unlocked&&!e._unlocking){e._unlocking=!0,e.resume();var t=e._context.createBuffer(1,1,e._context.sampleRate),i=e._context.createBufferSource();i.buffer=t,i.connect(e._context.destination),i.start(0),i.onended=function(t){i.disconnect(0),e._unlocked=!0,e._unlocking=!1,e._removeUserInputListeners()}}}),Ad.forEach((function(t){window.addEventListener(t,e._resumeContextCallback,!1)}))},i._removeUserInputListeners=function(){var e=this;this._resumeContextCallback&&(Ad.forEach((function(t){window.removeEventListener(t,e._resumeContextCallback,!1)})),this._resumeContextCallback=null)},$(t,[{key:"volume",get:function(){return this._volume},set:function(e){e=de.clamp(e,0,1),this._volume=e,this.fire("volumechange",e)}},{key:"suspended",get:function(){return!this._context||!this._unlocked||this._context.state!==Td}},{key:"context",get:function(){if(!this._context&&(yd()||this._forceWebAudioApi)&&("undefined"!=typeof AudioContext?this._context=new AudioContext:"undefined"!=typeof webkitAudioContext&&(this._context=new webkitAudioContext),this._context)){this._unlocked=this._context.state===Td,this._unlocked||this._addContextUnlockListeners();var e=this;this._context.onstatechange=function(){e._unlocked&&!e._selfSuspended&&e._context.state!==Td&&e._context.resume().then((function(){}),(function(e){})).catch((function(e){}))}}return this._context}}]),t}(m),Cd=function(){function e(e){this.audio=void 0,this.buffer=void 0,e instanceof Audio?this.audio=e:this.buffer=e}return $(e,[{key:"duration",get:function(){var e=0;return this.buffer?e=this.buffer.duration:this.audio&&(e=this.audio.duration),e||0}}]),e}();function Ed(e,t){return e%t||0}var Pd=function(e){function t(t,i,n){var s;return(s=e.call(this)||this).source=null,s._manager=t,s._volume=void 0!==n.volume?de.clamp(Number(n.volume)||0,0,1):1,s._pitch=void 0!==n.pitch?Math.max(.01,Number(n.pitch)||0):1,s._loop=!(void 0===n.loop||!n.loop),s._sound=i,s._state=2,s._suspended=!1,s._suspendEndEvent=0,s._suspendInstanceEvents=!1,s._playWhenLoaded=!0,s._startTime=Math.max(0,Number(n.startTime)||0),s._duration=Math.max(0,Number(n.duration)||0),s._startOffset=null,s._onPlayCallback=n.onPlay,s._onPauseCallback=n.onPause,s._onResumeCallback=n.onResume,s._onStopCallback=n.onStop,s._onEndCallback=n.onEnd,yd()?(s._startedAt=0,s._currentTime=0,s._currentOffset=0,s._inputNode=null,s._connectorNode=null,s._firstNode=null,s._lastNode=null,s._waitingContextSuspension=!1,s._initializeNodes(),s._endedHandler=s._onEnded.bind(te(s))):(s._isReady=!1,s._loadedMetadataHandler=s._onLoadedMetadata.bind(te(s)),s._timeUpdateHandler=s._onTimeUpdate.bind(te(s)),s._endedHandler=s._onEnded.bind(te(s)),s._createSource()),s}J(t,e);var i=t.prototype;return i._onPlay=function(){this.fire("play"),this._onPlayCallback&&this._onPlayCallback(this)},i._onPause=function(){this.fire("pause"),this._onPauseCallback&&this._onPauseCallback(this)},i._onResume=function(){this.fire("resume"),this._onResumeCallback&&this._onResumeCallback(this)},i._onStop=function(){this.fire("stop"),this._onStopCallback&&this._onStopCallback(this)},i._onEnded=function(){this._suspendEndEvent>0?this._suspendEndEvent--:(this.fire("end"),this._onEndCallback&&this._onEndCallback(this),this.stop())},i._onManagerVolumeChange=function(){this.volume=this._volume},i._onManagerSuspend=function(){0!==this._state||this._suspended||(this._suspended=!0,this.pause())},i._onManagerResume=function(){this._suspended&&(this._suspended=!1,this.resume())},i._initializeNodes=function(){this.gain=this._manager.context.createGain(),this._inputNode=this.gain,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination)},i.play=function(){return 2!==this._state&&this.stop(),this._state=0,this._playWhenLoaded=!1,!this._waitingContextSuspension&&(this._manager.suspended?(this._manager.once("resume",this._playAudioImmediate,this),this._waitingContextSuspension=!0,!1):(this._playAudioImmediate(),!0))},i._playAudioImmediate=function(){if(this._waitingContextSuspension=!1,0===this._state){this.source||this._createSource();var e=Ed(this._startOffset,this.duration);e=Ed(this._startTime+e,this._sound.duration),this._startOffset=null,this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentTime=0,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._manager.on("volumechange",this._onManagerVolumeChange,this),this._manager.on("suspend",this._onManagerSuspend,this),this._manager.on("resume",this._onManagerResume,this),this._manager.on("destroy",this._onManagerDestroy,this),this._suspendInstanceEvents||this._onPlay()}},i.pause=function(){return this._playWhenLoaded=!1,0===this._state&&(this._state=1,this._waitingContextSuspension||(this._updateCurrentTime(),this._suspendEndEvent++,this.source.stop(0),this.source=null,this._startOffset=null,this._suspendInstanceEvents||this._onPause()),!0)},i.resume=function(){if(1!==this._state)return!1;if(this._state=0,this._waitingContextSuspension)return!0;this.source||this._createSource();var e=this.currentTime;return null!==this._startOffset&&(e=Ed(this._startOffset,this.duration),e=Ed(this._startTime+e,this._sound.duration),this._startOffset=null),this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._playWhenLoaded=!1,this._suspendInstanceEvents||this._onResume(),!0},i.stop=function(){if(this._playWhenLoaded=!1,2===this._state)return!1;var e=0===this._state;return this._state=2,this._waitingContextSuspension||(this._manager.off("volumechange",this._onManagerVolumeChange,this),this._manager.off("suspend",this._onManagerSuspend,this),this._manager.off("resume",this._onManagerResume,this),this._manager.off("destroy",this._onManagerDestroy,this),this._startedAt=0,this._currentTime=0,this._currentOffset=0,this._startOffset=null,this._suspendEndEvent++,e&&this.source&&this.source.stop(0),this.source=null,this._suspendInstanceEvents||this._onStop()),!0},i.setExternalNodes=function(e,t){if(e){t||(t=e);var i=this._manager.context.destination;this._firstNode!==e&&(this._firstNode?this._connectorNode.disconnect(this._firstNode):this._connectorNode.disconnect(i),this._firstNode=e,this._connectorNode.connect(e)),this._lastNode!==t&&(this._lastNode&&this._lastNode.disconnect(i),this._lastNode=t,this._lastNode.connect(i))}else console.error("The firstNode must be a valid Audio Node")},i.clearExternalNodes=function(){var e=this._manager.context.destination;this._firstNode&&(this._connectorNode.disconnect(this._firstNode),this._firstNode=null),this._lastNode&&(this._lastNode.disconnect(e),this._lastNode=null),this._connectorNode.connect(e)},i.getExternalNodes=function(){return[this._firstNode,this._lastNode]},i._createSource=function(){if(!this._sound)return null;var e=this._manager.context;return this._sound.buffer&&(this.source=e.createBufferSource(),this.source.buffer=this._sound.buffer,this.source.connect(this._inputNode),this.source.onended=this._endedHandler,this.source.loopStart=Ed(this._startTime,this.source.buffer.duration),this._duration&&(this.source.loopEnd=Math.max(this.source.loopStart,Ed(this._startTime+this._duration,this.source.buffer.duration)))),this.source},i._updateCurrentTime=function(){this._currentTime=Ed((this._manager.context.currentTime-this._startedAt)*this._pitch+this._currentOffset,this.duration)},i._onManagerDestroy=function(){this.source&&0===this._state&&(this.source.stop(0),this.source=null)},$(t,[{key:"currentTime",get:function(){return null!==this._startOffset?this._startOffset:1===this._state?this._currentTime:2!==this._state&&this.source?(this._updateCurrentTime(),this._currentTime):0},set:function(e){if(!(e<0))if(0===this._state){var t=this._suspendInstanceEvents;this._suspendInstanceEvents=!0,this.stop(),this._startOffset=e,this.play(),this._suspendInstanceEvents=t}else this._startOffset=e,this._currentTime=e}},{key:"duration",get:function(){return this._sound?this._duration?Ed(this._duration,this._sound.duration):this._sound.duration:0},set:function(e){this._duration=Math.max(0,Number(e)||0);var t=0===this._state;this.stop(),t&&this.play()}},{key:"isPaused",get:function(){return 1===this._state}},{key:"isPlaying",get:function(){return 0===this._state}},{key:"isStopped",get:function(){return 2===this._state}},{key:"isSuspended",get:function(){return this._suspended}},{key:"loop",get:function(){return this._loop},set:function(e){this._loop=!!e,this.source&&(this.source.loop=this._loop)}},{key:"pitch",get:function(){return this._pitch},set:function(e){this._currentOffset=this.currentTime,this._startedAt=this._manager.context.currentTime,this._pitch=Math.max(Number(e)||0,.01),this.source&&(this.source.playbackRate.value=this._pitch)}},{key:"sound",get:function(){return this._sound},set:function(e){this._sound=e,2!==this._state?this.stop():this._createSource()}},{key:"startTime",get:function(){return this._startTime},set:function(e){this._startTime=Math.max(0,Number(e)||0);var t=0===this._state;this.stop(),t&&this.play()}},{key:"volume",get:function(){return this._volume},set:function(e){e=de.clamp(e,0,1),this._volume=e,this.gain&&(this.gain.gain.value=e*this._manager.volume)}}]),t}(m);yd()||(Object.assign(Pd.prototype,{play:function(){return 2!==this._state&&this.stop(),!(!this.source&&!this._createSource())&&(this.volume=this._volume,this.pitch=this._pitch,this.loop=this._loop,this.source.play(),this._state=0,this._playWhenLoaded=!1,this._manager.on("volumechange",this._onManagerVolumeChange,this),this._manager.on("suspend",this._onManagerSuspend,this),this._manager.on("resume",this._onManagerResume,this),this._manager.on("destroy",this._onManagerDestroy,this),this._manager.suspended&&this._onManagerSuspend(),this._suspendInstanceEvents||this._onPlay(),!0)},pause:function(){return!(!this.source||0!==this._state)&&(this._suspendEndEvent++,this.source.pause(),this._playWhenLoaded=!1,this._state=1,this._startOffset=null,this._suspendInstanceEvents||this._onPause(),!0)},resume:function(){return!(!this.source||1!==this._state)&&(this._state=0,this._playWhenLoaded=!1,this.source.paused&&(this.source.play(),this._suspendInstanceEvents||this._onResume()),!0)},stop:function(){return!(!this.source||2===this._state)&&(this._manager.off("volumechange",this._onManagerVolumeChange,this),this._manager.off("suspend",this._onManagerSuspend,this),this._manager.off("resume",this._onManagerResume,this),this._manager.off("destroy",this._onManagerDestroy,this),this._suspendEndEvent++,this.source.pause(),this._playWhenLoaded=!1,this._state=2,this._startOffset=null,this._suspendInstanceEvents||this._onStop(),!0)},setExternalNodes:function(){},clearExternalNodes:function(){},getExternalNodes:function(){return[null,null]},_onLoadedMetadata:function(){this.source.removeEventListener("loadedmetadata",this._loadedMetadataHandler),this._isReady=!0;var e=Ed(this._startOffset,this.duration);e=Ed(this._startTime+e,this._sound.duration),this._startOffset=null,this.source.currentTime=e},_createSource:function(){return this._sound&&this._sound.audio&&(this._isReady=!1,this.source=this._sound.audio.cloneNode(!0),this.source.addEventListener("loadedmetadata",this._loadedMetadataHandler),this.source.addEventListener("timeupdate",this._timeUpdateHandler),this.source.onended=this._endedHandler),this.source},_onTimeUpdate:function(){this._duration&&this.source.currentTime>Ed(this._startTime+this._duration,this.source.duration)&&(this.loop?this.source.currentTime=Ed(this._startTime,this.source.duration):(this.source.removeEventListener("timeupdate",this._timeUpdateHandler),this.source.pause(),this._onEnded()))},_onManagerDestroy:function(){this.source&&this.source.pause()}}),Object.defineProperty(Pd.prototype,"volume",{get:function(){return this._volume},set:function(e){e=de.clamp(e,0,1),this._volume=e,this.source&&(this.source.volume=e*this._manager.volume)}}),Object.defineProperty(Pd.prototype,"pitch",{get:function(){return this._pitch},set:function(e){this._pitch=Math.max(Number(e)||0,.01),this.source&&(this.source.playbackRate=this._pitch)}}),Object.defineProperty(Pd.prototype,"sound",{get:function(){return this._sound},set:function(e){this.stop(),this._sound=e}}),Object.defineProperty(Pd.prototype,"currentTime",{get:function(){return null!==this._startOffset?this._startOffset:2!==this._state&&this.source?this.source.currentTime-this._startTime:0},set:function(e){e<0||(this._startOffset=e,this.source&&this._isReady&&(this.source.currentTime=Ed(this._startTime+Ed(e,this.duration),this._sound.duration),this._startOffset=null))}}));var Rd=function(e){function t(t,i,n){var s;return void 0===n&&(n={}),(s=e.call(this,t,i,n)||this)._position=new ye,s._velocity=new ye,n.position&&(s.position=n.position),s.maxDistance=void 0!==n.maxDistance?Number(n.maxDistance):1e4,s.refDistance=void 0!==n.refDistance?Number(n.refDistance):1,s.rollOffFactor=void 0!==n.rollOffFactor?Number(n.rollOffFactor):1,s.distanceModel=void 0!==n.distanceModel?n.distanceModel:_d,s}return J(t,e),t.prototype._initializeNodes=function(){this.gain=this._manager.context.createGain(),this.panner=this._manager.context.createPanner(),this.panner.connect(this.gain),this._inputNode=this.panner,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination)},$(t,[{key:"position",get:function(){return this._position},set:function(e){this._position.copy(e);var t=this.panner;"positionX"in t?(t.positionX.value=e.x,t.positionY.value=e.y,t.positionZ.value=e.z):t.setPosition&&t.setPosition(e.x,e.y,e.z)}},{key:"velocity",get:function(){return this._velocity},set:function(e){this._velocity.copy(e)}},{key:"maxDistance",get:function(){return this.panner.maxDistance},set:function(e){this.panner.maxDistance=e}},{key:"refDistance",get:function(){return this.panner.refDistance},set:function(e){this.panner.refDistance=e}},{key:"rollOffFactor",get:function(){return this.panner.rolloffFactor},set:function(e){this.panner.rolloffFactor=e}},{key:"distanceModel",get:function(){return this.panner.distanceModel},set:function(e){this.panner.distanceModel=e}}]),t}(Pd);if(!yd()){var Id=new ye;Object.defineProperty(Rd.prototype,"position",{get:function(){return this._position},set:function(e){if(this._position.copy(e),this.source){var t=function(e,t,i,n,s,r){var a=(Id=Id.sub2(e,t)).length();if(an)return 0;var o=0;return r===_d?o=1-s*(a-i)/(n-i):r===gd?o=i/(i+s*(a-i)):r===vd&&(o=Math.pow(a/i,-s)),de.clamp(o,0,1)}(this._manager.listener.getPosition(),this._position,this.refDistance,this.maxDistance,this.rollOffFactor,this.distanceModel),i=this.volume;this.source.volume=i*t*this._manager.volume}}}),Object.defineProperty(Rd.prototype,"maxDistance",{get:function(){return this._maxDistance},set:function(e){this._maxDistance=e}}),Object.defineProperty(Rd.prototype,"refDistance",{get:function(){return this._refDistance},set:function(e){this._refDistance=e}}),Object.defineProperty(Rd.prototype,"rollOffFactor",{get:function(){return this._rollOffFactor},set:function(e){this._rollOffFactor=e}}),Object.defineProperty(Rd.prototype,"distanceModel",{get:function(){return this._distanceModel},set:function(e){this._distanceModel=e}})}function Ld(){var e,t,i,n=0,s=1,r=2,a=3,o=8,h=9,l=10,c=11,u=12,d=13,f=14,p=16,m={astc:l,dxt:r,etc1:n,etc2:n,pvr:o,atc:c,none:f},_={astc:l,dxt:a,etc1:p,etc2:s,pvr:h,atc:u,none:p},g=21,v=22,y=23,x=8,b=10,S=26,w=27,T=28,A=29,M=30,C=7,E=3,P=5,R=function(e,t){switch(e){case n:return t.formats.etc1?g:v;case s:return y;case r:return x;case a:return b;case o:return S;case h:return w;case l:return T;case c:return A;case u:return M;case d:return C;case f:return E;case p:return P}},I=function(e){for(var t=function(e,t){var i=e*(2/255)-1,n=t*(2/255)-1,s=Math.sqrt(1-Math.min(1,i*i+n*n));return Math.max(0,Math.min(255,Math.floor(.5*(s+1)*255)))},i=0;i>3}return t},D=function(){return"undefined"!=typeof performance?performance.now():0},k=function(e,n,s){if(s){if(e.formats.astc)return"astc"}else if(n){if(e.formats.etc2)return"etc2"}else if(e.formats.etc1||e.formats.etc2)return"etc1";return function(t){for(var i=0;i0?this.clients.shift().run(s):this.queue.push(s)}},t.enqueueClient=function(e){this.queue.length>0?e.run(this.queue.shift()):this.clients.push(e)},t.handleResponse=function(e,t,i){var n=this.callbacks[e];if(t)for(var s=0;s0,maxRetries:e.maxRetries};if(e.glueUrl&&e.wasmUrl&&function(){try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){var e=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(e instanceof WebAssembly.Module)return new WebAssembly.Instance(e)instanceof WebAssembly.Instance}}catch(e){}return!1}()){var s=null,r=null;pe.get(e.glueUrl,n,(function(e,n){e?t(e):r?i(n,r):s=n}));var a=fetch(e.wasmUrl),o=function(){a.then((function(e){return e.arrayBuffer()})).then((function(e){return WebAssembly.compile(e)})).then((function(e){s?i(s,e):r=e})).catch((function(e){t(e,null)}))};WebAssembly.compileStreaming?WebAssembly.compileStreaming(a).then((function(e){s?i(s,e):r=e})).catch((function(e){o()})):o()}else pe.get(e.fallbackUrl,n,(function(e,n){e?t(e,null):i(n,null)}))}(e,(function(e,t){if(e)console.error("failed to initialize basis worker: "+e);else for(var i=0;i0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=fe.ResponseType.JSON),pe.get(e.load,i,(function(i,n){i?t("Error loading animation clip resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){var i=t.name,n=t.duration,s=t.inputs.map((function(e){return new Tu(1,e)})),r=t.outputs.map((function(e){return new Tu(e.components,e.data)})),a=t.curves.map((function(e){return new wu([e.path],e.inputIndex,e.outputIndex,e.interpolation)}));return new Ju(i,n,s,r,a)},t.patch=function(e,t){},e}(),Xd=function(){function e(e){this.handlerType="animstategraph",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=fe.ResponseType.JSON),pe.get(e.load,i,(function(i,n){i?t("Error loading animation state graph resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return new cd(t)},t.patch=function(e,t){},e}(),qd=function(e){function t(){var t;return(t=e.call(this)||this)._meshes=null,t}J(t,e);var i=t.prototype;return i.destroy=function(){this.meshes=null},i.decRefMeshes=function(){if(this._meshes)for(var e=this._meshes.length,t=0;t=0){var r=n[s];r.decRefCount(),0===r.refCount&&(n.splice(s,1),n.length||e._skinInstanceCache.delete(i),t&&(t.destroy(),r.skinInstance=null))}}}}},e}();Yd._skinInstanceCache=new Map;var Kd=function(){function e(t,i,n,s){for(var r=function(t,s,r){var a=e.createAsset(i.name,t,s,r);return n.add(a),a},a=[],o=0;o0&&o(n,Float32Array,1),s.length>0&&o(s,Uint16Array,65535),r.length>0&&o(r,Uint8Array,255)}(y),y.unlock(),y},df=new Ee,ff=new ye,pf=function(e,t,i,n,s,r,a,o,h,l){var c=[];return t.primitives.forEach((function(u){var d,f,p,m=null,_=!0;if(u.hasOwnProperty("extensions")){var g=u.extensions;if(g.hasOwnProperty("KHR_draco_mesh_compression")){var v=Zd||$d();if(v){var y=g.KHR_draco_mesh_compression;if(y.hasOwnProperty("attributes")){var x=n[y.bufferView],b=new v.DecoderBuffer;b.Init(x,x.length);var S,w,T=new v.Decoder,A=T.GetEncodedGeometryType(b);switch(A){case v.POINT_CLOUD:d=0,S=new v.PointCloud,w=T.DecodeBufferToPointCloud(b,S);break;case v.TRIANGULAR_MESH:d=4,S=new v.Mesh,w=T.DecodeBufferToMesh(b,S);case v.INVALID_GEOMETRY_TYPE:}if(!w||!w.ok()||0===S.ptr)return void s("Failed to decode draco compressed asset: "+(w?w.error_msg():"Mesh asset - invalid draco compressed geometry type: "+A));var M=S.num_faces();if(A===v.TRIANGULAR_MESH){var C=S.num_points()>65535,E=(p=3*M)*(C?4:2),P=v._malloc(E);C?(T.GetTrianglesUInt32Array(S,E,P),m=new Uint32Array(v.HEAPU32.buffer,P,p).slice()):(T.GetTrianglesUInt16Array(S,E,P),m=new Uint16Array(v.HEAPU16.buffer,P,p).slice()),v._free(P)}f=function(e,t,i,n,s,r,a){var o=t.num_points(),h=function(e,i){var r,a,h,l,c=n.GetAttributeByUniqueId(t,e),u=o*c.num_components();switch(c.data_type()){case s.DT_UINT8:l=1,h=1,r=s._malloc(u*h),n.GetAttributeDataArrayForAllPoints(t,c,s.DT_UINT8,u*h,r),a=new Uint8Array(s.HEAPU8.buffer,r,u).slice();break;case s.DT_UINT16:l=3,h=2,r=s._malloc(u*h),n.GetAttributeDataArrayForAllPoints(t,c,s.DT_UINT16,u*h,r),a=new Uint16Array(s.HEAPU16.buffer,r,u).slice();break;case s.DT_FLOAT32:default:l=6,h=4,r=s._malloc(u*h),n.GetAttributeDataArrayForAllPoints(t,c,s.DT_FLOAT32,u*h,r),a=new Float32Array(s.HEAPF32.buffer,r,u).slice()}return s._free(r),{values:a,numComponents:c.num_components(),componentSizeInBytes:h,storageType:l,normalized:i===wt&&1===l||c.normalized()}},l={},c=i.attributes;for(var u in c)if(c.hasOwnProperty(u)&&sf.hasOwnProperty(u)){var d=sf[u],f=h(c[u],d),p=f.numComponents*f.componentSizeInBytes;l[d]={values:f.values,buffer:f.values.buffer,size:p,offset:0,stride:p,count:o,components:f.numComponents,type:f.storageType,normalize:f.normalized}}return l.hasOwnProperty(yt)||lf(l,r),uf(e,l,a)}(e,S,y,T,v,m,r),v.destroy(S),v.destroy(T),v.destroy(b),_=!1}}}}f||(m=u.hasOwnProperty("indices")?af(i[u.indices],n,!0):null,f=function(e,t,i,n,s,r,a){var o={},h=[];for(var l in t)t.hasOwnProperty(l)&&sf.hasOwnProperty(l)&&(o[l]=t[l],h.push(l+":"+t[l]));h.sort();var c=h.join(),u=a[c];if(!u){var d={};for(var f in o){var p=n[t[f]],m=af(p,s),_=s[p.bufferView],g=sf[f],v=ef(p.type)*nf(p.componentType),y=_.hasOwnProperty("byteStride")?_.byteStride:v;d[g]={buffer:m.buffer,size:v,offset:m.byteOffset,stride:y,count:p.count,components:ef(p.type),type:tf(p.componentType),normalize:p.normalized}}d.hasOwnProperty(yt)||lf(d,i),u=uf(e,d,r),a[c]=u}return u}(e,u.attributes,m,i,n,r,a),d=function(e){if(!e.hasOwnProperty("mode"))return 4;switch(e.mode){case 0:return 0;case 1:return 1;case 2:return 2;case 3:return 3;case 4:default:return 4;case 5:return 5;case 6:return 6}}(u));var R=null;if(f){if((R=new ea(e)).vertexBuffer=f,R.primitive[0].type=d,R.primitive[0].base=0,R.primitive[0].indexed=null!==m,null!==m){var I;2!==(I=m instanceof Uint8Array?0:m instanceof Uint16Array?1:2)||e.extUintElement||(I=1,m=new Uint16Array(m));var L=new mr(e,I,m.length,0,m);R.indexBuffer[0]=L,R.primitive[0].count=m.length}else R.primitive[0].count=f.numVertices;if(u.hasOwnProperty("extensions")&&u.extensions.hasOwnProperty("KHR_materials_variants")){var D=u.extensions.KHR_materials_variants,k={};D.mappings.forEach((function(e){e.variants.forEach((function(t){k[t]=e.material}))})),o[R.id]=k}h[R.id]=u.material;var O=i[u.attributes.POSITION];if(R.aabb=hf(O),_&&u.hasOwnProperty("targets")){var F=[];u.targets.forEach((function(e,s){var r={};e.hasOwnProperty("POSITION")&&(O=i[e.POSITION],r.deltaPositions=of(O,n),r.deltaPositionsType=6,r.aabb=hf(O)),e.hasOwnProperty("NORMAL")&&(O=i[e.NORMAL],r.deltaNormals=of(O,n),r.deltaNormalsType=6),t.hasOwnProperty("extras")&&t.extras.hasOwnProperty("targetNames")?r.name=t.extras.targetNames[s]:r.name=s.toString(10),t.hasOwnProperty("weights")&&(r.defaultWeight=t.weights[s]),r.preserveData=l.morphPreserveData,F.push(new lc(r))})),R.morph=new rc(F,e)}}c.push(R)})),c},mf=function(e,t,i){var n,s,r=e.texCoord;if(r)for(s=0;s0?i.name=e.name:i.name="node_"+t,e.hasOwnProperty("matrix")&&(df.data.set(e.matrix),df.getTranslation(ff),i.setLocalPosition(ff),df.getEulerAngles(ff),i.setLocalEulerAngles(ff),df.getScale(ff),i.setLocalScale(ff)),e.hasOwnProperty("rotation")){var n=e.rotation;i.setLocalRotation(n[0],n[1],n[2],n[3])}if(e.hasOwnProperty("translation")){var s=e.translation;i.setLocalPosition(s[0],s[1],s[2])}if(e.hasOwnProperty("scale")){var r=e.scale;i.setLocalScale(r[0],r[1],r[2])}return i},Ef=function(e,t){var i="orthographic"===e.type?1:0,n=1===i?e.orthographic:e.perspective,s={enabled:!1,projection:i,nearClip:n.znear,aspectRatioMode:0};n.zfar&&(s.farClip=n.zfar),1===i?(s.orthoHeight=.5*n.ymag,n.ymag&&(s.aspectRatioMode=1,s.aspectRatio=n.xmag/n.ymag)):(s.fov=n.yfov*de.RAD_TO_DEG,n.aspectRatio&&(s.aspectRatioMode=1,s.aspectRatio=n.aspectRatio));var r=new $l(e.name);return r.addComponent("camera",s),r},Pf=function(e,t){var i={enabled:!1,type:"point"===e.type?"omni":e.type,color:e.hasOwnProperty("color")?new me(e.color):me.WHITE,range:e.hasOwnProperty("range")?e.range:9999,falloffMode:1,intensity:e.hasOwnProperty("intensity")?de.clamp(e.intensity,0,2):1};e.hasOwnProperty("spot")&&(i.innerConeAngle=e.spot.hasOwnProperty("innerConeAngle")?e.spot.innerConeAngle*de.RAD_TO_DEG:0,i.outerConeAngle=e.spot.hasOwnProperty("outerConeAngle")?e.spot.outerConeAngle*de.RAD_TO_DEG:Math.PI/4),e.hasOwnProperty("intensity")&&(i.luminance=e.intensity*Ih.getLightUnitConversion(Ch[i.type],i.outerConeAngle,i.innerConeAngle));var n=new $l(t.name);return n.rotateLocal(90,0,0),n.addComponent("light",i),n},Rf=function(e,t,i,n){if(!t.hasOwnProperty("skins")||0===t.skins.length)return[];var s=new Map;return t.skins.map((function(r){return function(e,t,i,n,s,r){var a,o,h,l=t.joints,c=l.length,u=[];if(t.hasOwnProperty("inverseBindMatrices")){var d=t.inverseBindMatrices,f=af(i[d],n,!0),p=[];for(a=0;a0&&"localRotation"===L.paths[0].propertyPath[0]&&2!==L.interpolation&&_.push(E[E.length-1].output)}_.sort();var D,k=null;for(a=0;a<_.length;++a){var O=_[a];if(0===a||O!==k){if(4===(D=C[O]).components)for(var F=D.data,B=F.length-4,N=0;N0){var s=i&&i.camera&&i.camera.preprocess,r=i&&i.camera&&i.camera.process||Ef,a=i&&i.camera&&i.camera.postprocess;e.nodes.forEach((function(i,o){if(i.hasOwnProperty("camera")){var h=e.cameras[i.camera];if(h){s&&s(h);var l=r(h,t[o]);a&&a(h,l),l&&(n||(n=new Map),n.set(i,l))}}}))}return n}(t,l,s),f=If(t,l,i,s),p=function(e,t,i,n){if(!e.hasOwnProperty("materials")||0===e.materials.length)return[];var s=i&&i.material&&i.material.preprocess,r=i&&i.material&&i.material.process||Mf,a=i&&i.material&&i.material.postprocess;return e.materials.map((function(e){s&&s(e);var i=r(e,t,n);return a&&a(e,i),i}))}(t,n.map((function(e){return e.resource})),s,h),m=function(e){if(!e.hasOwnProperty("extensions")||!e.extensions.hasOwnProperty("KHR_materials_variants"))return null;for(var t=e.extensions.KHR_materials_variants.variants,i={},n=0;ni.byteLength)t("Invalid length found in glb header. Found "+r);else{for(var a=[],o=12;oi.byteLength)throw new Error("Invalid chunk length found in glb. Found "+h);var l=i.getUint32(o+4,!0),c=new Uint8Array(i.buffer,i.byteOffset+o+8,h);a.push({length:h,type:l,data:c}),o+=h+8}1===a.length||2===a.length?1313821514===a[0].type?a.length>1&&5130562!==a[1].type?t("Invalid chunk type found in glb file. Expected 0x004E4942, found 0x"+a[1].type.toString(16)):t(null,{gltfChunk:a[0].data,binaryChunk:2===a.length?a[1].data:null}):t("Invalid chunk type found in glb file. Expected 0x4E4F534A, found 0x"+a[0].type.toString(16)):t("Invalid number of chunks found in glb file.")}else t("Invalid version number found in glb header. Expected 2, found "+s);else t("Invalid magic number found in glb header. Expected 0x46546C67, found 0x"+n.toString(16))}(t,i):i(null,{gltfChunk:t,binaryChunk:null})},Bf=function(e,t,i,n){var s=[],r=i&&i.bufferView&&i.bufferView.preprocess,a=i&&i.bufferView&&i.bufferView.processAsync||function(e,t,i){i(null,null)},o=i&&i.bufferView&&i.bufferView.postprocess,h=e.bufferViews?e.bufferViews.length:0;if(h)for(var l=function(t,i){var r=e.bufferViews[t];r.hasOwnProperty("byteStride")&&(i.byteStride=r.byteStride),s[t]=i,o&&o(r,i),0==--h&&n(null,s)},c=0;c=0?e.split("?")[0]:e},t.load=function(t,i,n){var s=this;ml.fetchArrayBuffer(t.load,(function(r,a){r?i(r):e.parseAsync(s._getUrlWithoutParams(t.original),v.extractPath(t.load),a,s._device,n.registry,n.options,(function(e,t){e?i(e):i(null,new Kd(t,n,s._assets,s._defaultMaterial))}))}),n,this.maxRetries)},t.open=function(e,t,i){return t},t.patch=function(e,t){},e}(),Uf=function(){function e(e){this.handlerType="animation",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};(e.load.startsWith("blob:")||e.load.startsWith("data:"))&&(".glb"===v.getExtension(e.original).toLowerCase()?i.responseType=fe.ResponseType.ARRAY_BUFFER:i.responseType=fe.ResponseType.JSON),pe.get(e.load,i,(function(i,n){i?t("Error loading animation resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t,i){if(".glb"===v.getExtension(e).toLowerCase()){var n=Nf.parse("filename.glb",t,null);if(n){var s,r=n.animations;if(null!=i&&null!=(s=i.data)&&s.events)for(var a=0;a0)return parseInt(e.substring(t+5,e.indexOf(".",t)),10);if(e.indexOf("Trident/")>0){var i=e.indexOf("rv:");return parseInt(e.substring(i+3,e.indexOf(".",i)),10)}return!1}(),Vf=[".ogg",".mp3",".wav",".mp4a",".m4a",".mp4",".aac",".opus"],Gf=function(){function e(e){this.handlerType="audio",this.manager=e.soundManager,this.maxRetries=0}var t=e.prototype;return t._isSupported=function(e){var t=v.getExtension(e);return Vf.indexOf(t)>-1},t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i=function(i){var n="Error loading audio url: "+e.original;i&&(n+=": "+(i.message||i)),console.warn(n),t(n)};if(this._createSound){if(!this._isSupported(e.original))return void i("Audio format for "+e.original+" not supported");this._createSound(e.load,(function(e){t(null,new Cd(e))}),i)}else i(null)},t.open=function(e,t){return t},t.patch=function(e,t){},t._createSound=function(e,t,i){if(yd()){var n=this.manager;if(!n.context)return void i("Audio manager has no audio context");var s={retry:this.maxRetries>0,maxRetries:this.maxRetries};(e.startsWith("blob:")||e.startsWith("data:"))&&(s.responseType=fe.ResponseType.ARRAY_BUFFER),pe.get(e,s,(function(e,s){e?i(e):n.context.decodeAudioData(s,t,i)}))}else{var r=null;try{r=new Audio}catch(e){return void i("No support for Audio element")}zf&&document.body.appendChild(r);r.onerror=function(){r.onerror=null,zf&&document.body.removeChild(r),i()},r.addEventListener("canplaythrough",(function e(){r.removeEventListener("canplaythrough",e),zf&&document.body.removeChild(r),t(r)})),r.src=e}},e}(),Wf=function(){function e(e){this.handlerType="binary",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),pe.get(e.load,{responseType:fe.ResponseType.ARRAY_BUFFER,retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?t("Error loading binary resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}(),Hf=function(){function e(){}var t=e.prototype;return t.instantiateModelEntity=function(e){return null},t.instantiateRenderEntity=function(e){return null},t.getMaterialVariants=function(){return null},t.applyMaterialVariant=function(e,t){},t.applyMaterialVariantInstances=function(e,t){},e}(),Xf=function(){function e(e){this.handlerType="container",this.glbParser=new Nf(e.graphicsDevice,e.assets,0),this.parsers={}}var t=e.prototype;return t._getUrlWithoutParams=function(e){return e.indexOf("?")>=0?e.split("?")[0]:e},t._getParser=function(e){var t=e?v.getExtension(this._getUrlWithoutParams(e)).toLowerCase().replace(".",""):null;return this.parsers[t]||this.glbParser},t.load=function(e,t,i){"string"==typeof e&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,i)},t.open=function(e,t,i){return this._getParser(e).open(e,t,i)},t.patch=function(e,t){},$(e,[{key:"maxRetries",get:function(){return this.glbParser.maxRetries},set:function(e){for(var t in this.glbParser.maxRetries=e,this.parsers)this.parsers.hasOwnProperty(t)&&(this.parsers[t].maxRetries=e)}}]),e}(),qf=function(){function e(e){this.handlerType="css",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),pe.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?t("Error loading css resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}();var jf=function(){function e(e){this.handlerType="cubemap",this._device=e.graphicsDevice,this._registry=e.assets,this._loader=e.loader}var t=e.prototype;return t.load=function(e,t,i){this.loadAssets(i,t)},t.open=function(e,t,i){return i?i.resource:null},t.patch=function(e,t){this.loadAssets(e,(function(i,n){i&&(t.fire("error",e),t.fire("error:"+e.id,i,e),e.fire("error",e))}))},t.getAssetIds=function(e){var t=[];if(t[0]=e.file,(e.loadFaces||!e.file)&&e.data&&e.data.textures)for(var i=0;i<6;++i)t[i+1]=e.data.textures[i];else t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=null;return t},t.compareAssetIds=function(e,t){return e&&t?parseInt(e,10)===e||"string"==typeof e?e===t:e.url===t.url:null!==e==(null!==t)},t.update=function(e,t,i){var n,s,r,a=e.data||{},o=e._handlerState.assets,h=e._resources,l=[null,null,null,null,null,null,null],c=function(){return a.hasOwnProperty("type")?a.type:a.hasOwnProperty("rgbm")?a.rgbm?$t:Zt:null};if(e.loaded&&i[0]===o[0])l[1]=h[1]||null,l[2]=h[2]||null,l[3]=h[3]||null,l[4]=h[4]||null,l[5]=h[5]||null,l[6]=h[6]||null;else if(i[0])for(n=i[0].resource,r=0;r<6;++r)l[r+1]=new wn(this._device,{name:e.name+"_prelitCubemap"+(n.width>>r),cubemap:!0,type:c()||n.type,width:n.width>>r,height:n.height>>r,format:n.format,levels:[n._levels[r]],fixCubemapSeams:!0,addressU:1,addressV:1,mipmaps:0===r});var u=i.slice(1);if(e.loaded&&this.cmpArrays(u,o.slice(1)))l[0]=h[0]||null;else if(-1===u.indexOf(null)){var d=u.map((function(e){return e.resource})),f=[];for(s=0;s0,maxRetries:this.maxRetries},(function(i,s){if(i)t("Error loading font resource: "+e.original+" ["+i+"]");else{var r=Kf(s);n._loadTextures(e.load.replace(".json",".png"),r,(function(e,i){if(e)return t(e);t(null,{data:r,textures:i})}))}})):(i&&i.data&&(i.data=Kf(i.data)),this._loadTextures(e.load,i&&i.data,t))},t._loadTextures=function(e,t,i){for(var n=t.info.maps.length,s=0,r=null,a=new Array(n),o=this._loader,h=function(t){var h=function(e,o){if(!r){if(e)return r=e,i(e);o.upload(),a[t]=o,++s===n&&i(null,a)}};0===t?o.load(e,"texture",h):o.load(e.replace(".png",t+".png"),"texture",h)},l=0;l0,maxRetries:t},(function(t,n){if(t){var s="Error while loading scene JSON "+e.original;t.message?(s+=": "+t.message,t.stack&&(s+="\n"+t.stack)):s+=": "+t,i(s)}else i(t,n)}))},np=function(){function e(e){this.handlerType="hierarchy",this._app=e,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){ip(e,this.maxRetries,t)},t.open=function(e,t){this._app.systems.script.preloading=!0;var i=new tp(this._app,!1).parse(t);return this._app.systems.script.preloading=!1,i},e}(),sp=function(){function e(e){this.handlerType="html",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),pe.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?t("Error loading html resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}(),rp=function(){function e(e){this.handlerType="json",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=fe.ResponseType.JSON),pe.get(e.load,i,(function(i,n){i?t("Error loading JSON resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}(),ap=function(){function e(){this.removeInvalid=!0,this.valid=!0,this.enumValidators={occludeSpecular:this._createEnumValidator([0,1,2]),cull:this._createEnumValidator([0,1,2,3]),blendType:this._createEnumValidator([0,1,2,3,4,5,6,7,8,9,10]),depthFunc:this._createEnumValidator([0,1,2,3,4,5,6,7]),shadingModel:this._createEnumValidator([0,1])}}var t=e.prototype;return t.setInvalid=function(e,t){this.valid=!1,this.removeInvalid&&delete t[e]},t.validate=function(e){var t=Vs,i=qs,n="path"===e.mappingFormat;for(var s in e){var r=t[s];if(r)if(r.startsWith("enum")){var a=r.split(":")[1];this.enumValidators[a]&&(this.enumValidators[a](e[s])||this.setInvalid(s,e))}else if("number"===r)"number"!=typeof e[s]&&this.setInvalid(s,e);else if("boolean"===r)"boolean"!=typeof e[s]&&this.setInvalid(s,e);else if("string"===r)"string"!=typeof e[s]&&this.setInvalid(s,e);else if("vec2"===r)e[s]instanceof Array&&2===e[s].length||this.setInvalid(s,e);else if("rgb"===r)e[s]instanceof Array&&3===e[s].length||this.setInvalid(s,e);else if("texture"===r)n?"string"!=typeof e[s]&&null!==e[s]&&(e[s]instanceof wn||this.setInvalid(s,e)):"number"!=typeof e[s]&&null!==e[s]&&(e[s]instanceof wn||this.setInvalid(s,e));else if("boundingbox"===r)e[s].center&&e[s].center instanceof Array&&3===e[s].center.length||this.setInvalid(s,e),e[s].halfExtents&&e[s].halfExtents instanceof Array&&3===e[s].halfExtents.length||this.setInvalid(s,e);else if("cubemap"===r)"number"!=typeof e[s]&&null!==e[s]&&void 0!==e[s]&&(e[s]instanceof wn&&e[s].cubemap||this.setInvalid(s,e));else if("chunks"===r)for(var o=Object.keys(e[s]),h=0;h=0}},e}(),op=function(){function e(){this._validator=null}var t=e.prototype;return t.parse=function(e){var t=this.migrate(e),i=this._validate(t),n=new Zs;return this.initialize(n,i),n},t.initialize=function(e,t){for(var i in t.validated||(t=this._validate(t)),t.chunks&&(e.chunks=Q({},t.chunks)),t){var n=Vs[i],s=t[i];if("vec2"===n)e[i]=new be(s[0],s[1]);else if("rgb"===n)e[i]=new me(s[0],s[1],s[2]);else if("texture"===n)s instanceof wn?e[i]=s:e[i]instanceof wn&&"number"==typeof s&&s>0||(e[i]=null);else if("cubemap"===n)s instanceof wn?e[i]=s:e[i]instanceof wn&&"number"==typeof s&&s>0||(e[i]=null),"cubeMap"!==i||s||(e.prefilteredCubemaps=null);else if("boundingbox"===n){var r=new ye(s.center[0],s.center[1],s.center[2]),a=new ye(s.halfExtents[0],s.halfExtents[1],s.halfExtents[2]);e[i]=new Oe(r,a)}else e[i]=t[i]}e.update()},t.migrate=function(e){var t;void 0===e.shadingModel&&("blinn"===e.shader?e.shadingModel=1:e.shadingModel=0),e.shader&&delete e.shader,e.mapping_format&&(e.mappingFormat=e.mapping_format,delete e.mapping_format);var i=[["bumpMapFactor","bumpiness"],["aoUvSet","aoMapUv"],["aoMapVertexColor","aoVertexColor"],["diffuseMapVertexColor","diffuseVertexColor"],["emissiveMapVertexColor","emissiveVertexColor"],["specularMapVertexColor","specularVertexColor"],["metalnessMapVertexColor","metalnessVertexColor"],["opacityMapVertexColor","opacityVertexColor"],["glossMapVertexColor","glossVertexColor"],["lightMapVertexColor","lightVertexColor"],["diffuseMapTint","diffuseTint"],["specularMapTint","specularTint"],["emissiveMapTint","emissiveTint"],["metalnessMapTint","metalnessTint"]];for(t=0;t0,maxRetries:this.maxRetries},(function(i,n){i?t&&t("Error loading material: "+e.original+" ["+i+"]"):t&&(n._engine=!0,t(null,n))}))},t.open=function(e,t){var i=this._parser.parse(t);return t._engine&&(i._data=t,delete t._engine),i},t._createPlaceholders=function(){this._placeholderTextures={};var e={white:[255,255,255,255],gray:[128,128,128,255],black:[0,0,0,255],normal:[128,128,255,255]};for(var t in e)if(e.hasOwnProperty(t)){this._placeholderTextures[t]=new wn(this._device,{width:2,height:2,format:7,name:"material_placeholder"});for(var i=this._placeholderTextures[t].lock(),n=0;n<4;n++)for(var s=0;s<4;s++)i[4*n+s]=e[t][s];this._placeholderTextures[t].unlock()}},t.patch=function(e,t){e.resource._data&&(e._data=e.resource._data,delete e.resource._data),e.data.name=e.name,e.resource.name=e.name,this._bindAndAssignAssets(e,t),e.off("unload",this._onAssetUnload,this),e.on("unload",this._onAssetUnload,this)},t._onAssetUnload=function(e){delete e.data.parameters,delete e.data.chunks,delete e.data.name},t._assignTexture=function(e,t,i){t.resource[e]=i},t._getPlaceholderTexture=function(e){this._placeholderTextures||this._createPlaceholders();var t=lp[e];return this._placeholderTextures[t]},t._assignPlaceholderTexture=function(e,t){t.resource[e]=this._getPlaceholderTexture(e)},t._onTextureLoad=function(e,t,i){this._assignTexture(e,t,i.resource),t.resource.update()},t._onTextureAdd=function(e,t,i){this._assets.load(i)},t._onTextureRemoveOrUnload=function(e,t,i){var n=t.resource;n&&t.resource[e]===i.resource&&(this._assignPlaceholderTexture(e,t),n.update())},t._assignCubemap=function(e,t,i){t.resource[e]=i[0],"cubeMap"===e&&(t.resource.prefilteredCubemaps=i.slice(1))},t._onCubemapLoad=function(e,t,i){this._assignCubemap(e,t,i.resources),this._parser.initialize(t.resource,t.data)},t._onCubemapAdd=function(e,t,i){0===t.data.shadingModel&&(t.loadFaces=!0),this._assets.load(i)},t._onCubemapRemoveOrUnload=function(e,t,i){var n=t.resource;t.data.prefilteredCubeMap128===i.resources[1]&&(this._assignCubemap(e,t,[null,null,null,null,null,null,null]),n.update())},t._bindAndAssignAssets=function(e,t){var i,n,s,r=this._parser.migrate(e.data),a=e.resource,o="path"===r.mappingFormat,h=Gs;for(i=0;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}),t&&t.push({material:t[r].material,path:t[r].path}));for(s=0;s=0;r--)u[r].mesh===_.originalMesh&&(u.splice(r,1),t&&t.splice(r,1))}!function(e){for(var t=e.vertices,i=e.skins,n=e.meshes,s=e.meshInstances,r=0;r0&&pp(s,null,this._device.getBoneLimit());for(i=0;i0&&(h>65535&&this._device.extUintElement?(s=new mr(this._device,2,a),r=new Uint32Array(s.lock())):(s=new mr(this._device,1,a),r=new Uint16Array(s.lock()))),{buffer:s,data:r}},t._parseMeshes=function(e,t,i,n,s,r){for(var a=e.model,o=[],h=0,l=0;l0,maxRetries:this.maxRetries};(e.load.startsWith("blob:")||e.load.startsWith("data:"))&&(".glb"===v.getExtension(e.original).toLowerCase()?i.responseType=fe.ResponseType.ARRAY_BUFFER:i.responseType=fe.ResponseType.JSON),pe.get(e.load,i,(function(i,n){t&&(i?t("Error loading model: "+e.original+" ["+i+"]"):t(null,n))}))},t.open=function(e,t){for(var i=0;i0,maxRetries:this.maxRetries},(function(i,n){i?t("Error loading shader resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}();function Cp(e){this.resource&&(this.resource.atlas=e.resource)}function Ep(e){this.registry.load(e)}var Pp=function(){function e(e){this.handlerType="sprite",this._assets=e.assets,this._device=e.graphicsDevice,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),".json"===v.getExtension(e.original)&&pe.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(e,i){e?t(e):t(null,i)}))},t.open=function(e,t){var i=new uu(this._device);return e&&(i.__data=t),i},t.patch=function(e,t){var i=e.resource;if(i.__data&&(e.data.pixelsPerUnit=i.__data.pixelsPerUnit,e.data.renderMode=i.__data.renderMode,e.data.frameKeys=i.__data.frameKeys,i.__data.textureAtlasAsset)){var n=t.getByUrl(i.__data.textureAtlasAsset);n?e.data.textureAtlasAsset=n.id:console.warn("Could not find textureatlas with url: "+i.__data.textureAtlasAsset)}i.startUpdate(),i.renderMode=e.data.renderMode,i.pixelsPerUnit=e.data.pixelsPerUnit,i.frameKeys=e.data.frameKeys,this._updateAtlas(e),i.endUpdate(),e.off("change",this._onAssetChange,this),e.on("change",this._onAssetChange,this)},t._updateAtlas=function(e){var t=e.resource;if(e.data.textureAtlasAsset){this._assets.off("load:"+e.data.textureAtlasAsset,Cp,e),this._assets.on("load:"+e.data.textureAtlasAsset,Cp,e);var i=this._assets.get(e.data.textureAtlasAsset);i&&i.resource?t.atlas=i.resource:i?this._assets.load(i):(this._assets.off("add:"+e.data.textureAtlasAsset,Ep,e),this._assets.on("add:"+e.data.textureAtlasAsset,Ep,e))}else t.atlas=null},t._onAssetChange=function(e,t,i,n){"data"===t&&i&&i.textureAtlasAsset&&n&&i.textureAtlasAsset!==n.textureAtlasAsset&&(this._assets.off("load:"+n.textureAtlasAsset,Cp,e),this._assets.off("add:"+n.textureAtlasAsset,Ep,e))},e}(),Rp=function(){function e(e,t){this._app=e,this._data=t,this._templateRoot=null}var t=e.prototype;return t.instantiate=function(){return this._templateRoot||this._parseTemplate(),this._templateRoot.clone()},t._parseTemplate=function(){var e=new tp(this._app,!0);this._templateRoot=e.parse(this._data)},e}(),Ip=function(){function e(e){this.handlerType="template",this._app=e,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};pe.get(e.load,i,(function(i,n){i?t("Error requesting template: "+e.original):t(i,n)}))},t.open=function(e,t){return new Rp(this._app,t)},e}(),Lp=function(){function e(e){this.handlerType="text",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),pe.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?t("Error loading text resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}(),Dp=function(){function e(e,t){this.device=t,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t,i){var n=this.device;ml.fetchArrayBuffer(e.load,(function(s,r){s?t(s):function(s){var r,a,o;Wd(n,e.load,s,t,{isGGGR:0!=(8&(null==i||null==(r=i.file)||null==(a=r.variants)||null==(o=a.basis)?void 0:o.opt))})||t("Basis module not found. Asset '"+i.name+"' basis texture variant will not be loaded.")}(r)}),i,this.maxRetries)},t.open=function(e,t,i){var n=new wn(i,{name:e,addressU:t.cubemap?1:0,addressV:t.cubemap?1:0,width:t.width,height:t.height,format:t.format,cubemap:t.cubemap,levels:t.levels});return n.upload(),n},e}(),kp=function(){function e(e,t){this.crossOrigin=e.prefix?"anonymous":null,this.maxRetries=0,this.device=t}var t=e.prototype;return t.load=function(e,t,i){var n,s=!(null==i||null==(n=i.file)||!n.contents);if(s){if(this.device.supportsImageBitmap)return void this._loadImageBitmapFromData(i.file.contents,t);e={load:URL.createObjectURL(new Blob([i.file.contents])),original:e.original}}var r,a=function(i,n){s&&URL.revokeObjectURL(e.load),t(i,n)};i&&i.options&&i.options.hasOwnProperty("crossOrigin")?r=i.options.crossOrigin:cl.test(e.load)&&(r=this.crossOrigin),this.device.supportsImageBitmap?this._loadImageBitmap(e.load,e.original,r,a):this._loadImage(e.load,e.original,r,a)},t.open=function(e,t,i){var n=v.getExtension(e).toLowerCase(),s=".jpg"===n||".jpeg"===n?6:7,r=new wn(i,{name:e,width:t.width,height:t.height,format:s});return r.setSource(t),r},t._loadImage=function(e,t,i,n){var s=new Image;i&&(s.crossOrigin=i);var r,a=0,o=this.maxRetries;s.onload=function(){n(null,s)},s.onerror=function(){if(!r)if(o>0&&++a<=o){var i=100*Math.pow(2,a);console.log("Error loading Texture from: '"+t+"' - Retrying in "+i+"ms...");var h=e.indexOf("?")>=0?"&":"?";r=setTimeout((function(){s.src=e+h+"retry="+Date.now(),r=null}),i)}else n("Error loading Texture from: '"+t+"'")},s.src=e},t._loadImageBitmap=function(e,t,i,n){var s={cache:!0,responseType:"blob",retry:this.maxRetries>0,maxRetries:this.maxRetries};pe.get(e,s,(function(e,t){e?n(e):createImageBitmap(t,{premultiplyAlpha:"none"}).then((function(e){return n(null,e)})).catch((function(e){return n(e)}))}))},t._loadImageBitmapFromData=function(e,t){createImageBitmap(new Blob([e]),{premultiplyAlpha:"none"}).then((function(e){return t(null,e)})).catch((function(e){return t(e)}))},e}(),Op=[1481919403,3140563232,169478669],Fp={33776:8,33778:9,33779:ht,36196:mt,37492:22,37496:23,35840:26,35841:_t,35842:27,35843:gt,32849:6,32856:7,35905:19,35907:20,35898:18,34843:lt,34842:ct};var Bp=function(){function e(e){this.maxRetries=0}var t=e.prototype;return t.load=function(e,t,i){ml.fetchArrayBuffer(e.load,t,i,this.maxRetries)},t.open=function(e,t,i){var n=this.parse(t);if(!n)return null;var s=new wn(i,{name:e,addressU:n.cubemap?1:0,addressV:n.cubemap?1:0,width:n.width,height:n.height,format:n.format,cubemap:n.cubemap,levels:n.levels});return s.upload(),s},t.parse=function(e){var t=new Uint32Array(e);if(Op[0]!==t[0]||Op[1]!==t[1]||Op[2]!==t[2])return null;var i={endianness:t[3],glType:t[4],glTypeSize:t[5],glFormat:t[6],glInternalFormat:t[7],glBaseInternalFormat:t[8],pixelWidth:t[9],pixelHeight:t[10],pixelDepth:t[11],numberOfArrayElements:t[12],numberOfFaces:t[13],numberOfMipmapLevels:t[14],bytesOfKeyValueData:t[15]};if(i.pixelDepth>1)return null;if(0!==i.numberOfArrayElements)return null;var n=Fp[i.glInternalFormat];if(void 0===n)return null;for(var s,r,a,o=16+i.bytesOfKeyValueData/4,h=i.numberOfFaces>1,l=[],c=0;c<(i.numberOfMipmapLevels||1);c++){var u=t[o++];h&&l.push([]);for(var d=h?l[c]:l,f=0;f<(h?6:1);++f)d.push((s=e,r=4*o,a=u,18===n?new Uint32Array(s,r,a/4):new Uint8Array(s,r,a))),o+=u+3>>2}return{format:n,width:i.pixelWidth,height:i.pixelHeight,levels:l,cubemap:h}},e}(),Np=166,Up=function(){function e(e,t){this.maxRetries=0,this.device=t}var t=e.prototype;return t.load=function(e,t,i){var n=this;ml.fetchArrayBuffer(e.load,(function(s,r){s?t(s,r):n.parse(r,e,t,i)}),i,this.maxRetries)},t.open=function(e,t,i){var n=new wn(i,{name:e,addressU:t.cubemap?1:0,addressV:t.cubemap?1:0,width:t.width,height:t.height,format:t.format,cubemap:t.cubemap,levels:t.levels});return n.upload(),n},t.parse=function(e,t,i,n){var s=new se(e),r=[s.readU32be(),s.readU32be(),s.readU32be()];if(2873840728!==r[0]||540160187!==r[1]||218765834!==r[2])return null;for(var a={vkFormat:s.readU32(),typeSize:s.readU32(),pixelWidth:s.readU32(),pixelHeight:s.readU32(),pixelDepth:s.readU32(),layerCount:s.readU32(),faceCount:s.readU32(),levelCount:s.readU32(),supercompressionScheme:s.readU32()},o={dfdByteOffset:s.readU32(),dfdByteLength:s.readU32(),kvdByteOffset:s.readU32(),kvdByteLength:s.readU32(),sgdByteOffset:s.readU64(),sgdByteLength:s.readU64()},h=[],l=0;l1});for(var b,S=128,w=u?6:1,T=l===d?8:16,A=0;A32767)return this._readPixelsFlat(e,t,i);var s=[0,0,0,0];if(e.readArray(s),2!==s[0]||2!==s[1]||0!=(128&s[2]))return e.skip(-4),this._readPixelsFlat(e,t,i);var r,a,o,h,l,c,u=new ArrayBuffer(t*i*4),d=new Uint8Array(u),f=n?0:4*t*(i-1);for(a=0;a128){if(r+(l-=128)>t)return null;for(c=e.readU8(),o=0;ot)return null;for(o=0;o=0?e.split("?")[0]:e},t._getParser=function(e){var t=v.getExtension(this._getUrlWithoutParams(e)).toLowerCase().replace(".","");return this.parsers[t]||this.imgParser},t.load=function(e,t,i){"string"==typeof e&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,i)},t.open=function(e,t,i){if(e){var n=this._getParser(e).open(e,t,this._device);return null===n?n=new wn(this._device,{width:4,height:4,format:6}):(!function(e){var t=Math.log2(Math.max(e._width,e._height))+1;if(!(7!==e._format&&e._format!==dt||e._volume||e._compressed||1===e._levels.length||e._levels.length===t||(i=e._cubemap?e._levels[0][0]:e._levels[0],i instanceof HTMLCanvasElement||i instanceof HTMLImageElement||i instanceof HTMLVideoElement))){for(var i,n=function(e,t,i){for(var n=Math.max(1,e>>1),s=Math.max(1,t>>1),r=new i.constructor(n*s*4),a=Math.floor(e/n),o=Math.floor(t/s),h=a*o,l=0;l>s-1),a=Math.max(1,e._height>>s-1);if(e._cubemap){for(var o=[],h=0;h<6;++h)o.push(n(r,a,e._levels[s-1][h]));e._levels.push(o)}else e._levels.push(n(r,a,e._levels[s-1]))}e._levelsUpdated=e._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0]}}(n),t.unswizzledGGGR&&(i.file.variants.basis.opt&=-9)),n}},t.patch=function(e,t){var i=e.resource;if(i){e.name&&e.name.length>0&&(i.name=e.name);var n=e.data;n.hasOwnProperty("minfilter")&&(i.minFilter=Wp[n.minfilter]),n.hasOwnProperty("magfilter")&&(i.magFilter=Wp[n.magfilter]),i.cubemap||(n.hasOwnProperty("addressu")&&(i.addressU=Gp[n.addressu]),n.hasOwnProperty("addressv")&&(i.addressV=Gp[n.addressv])),n.hasOwnProperty("mipmaps")&&(i.mipmaps=n.mipmaps),n.hasOwnProperty("anisotropy")&&(i.anisotropy=n.anisotropy),n.hasOwnProperty("flipY")&&(i.flipY=!!n.flipY),n.hasOwnProperty("type")?i.type=Hp[n.type]:n.hasOwnProperty("rgbm")&&n.rgbm?i.type=$t:e.file&&0!=(8&e.file.opt)&&(i.type=ei)}},$(e,[{key:"crossOrigin",get:function(){return this.imgParser.crossOrigin},set:function(e){this.imgParser.crossOrigin=e}},{key:"maxRetries",get:function(){return this.imgParser.maxRetries},set:function(e){for(var t in this.imgParser.maxRetries=e,this.parsers)this.parsers.hasOwnProperty(t)&&(this.parsers[t].maxRetries=e)}}]),e}(),jp={repeat:0,clamp:1,mirror:2},Yp={nearest:0,linear:1,nearest_mip_nearest:2,linear_mip_nearest:4,nearest_mip_linear:3,linear_mip_linear:5},Kp=/^data\.frames\.(\d+)$/,Zp=function(){function e(e){this.handlerType="textureatlas",this._loader=e.loader,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i=this,n=this._loader.getHandler("texture");if(".json"!==v.getExtension(e.original))return n.load(e,t);pe.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(n,s){if(n)t(n);else{var r=e.original.replace(".json",".png");i._loader.load(r,"texture",(function(e,i){e?t(e):t(null,{data:s,texture:i})}))}}))},t.open=function(e,t){var i=new fu;if(t.texture&&t.data)i.texture=t.texture,i.__data=t.data;else{var n=this._loader.getHandler("texture").open(e,t);if(!n)return null;i.texture=n}return i},t.patch=function(e,t){if(e.resource){e.resource.__data&&(void 0!==e.resource.__data.minfilter&&(e.data.minfilter=e.resource.__data.minfilter),void 0!==e.resource.__data.magfilter&&(e.data.magfilter=e.resource.__data.magfilter),void 0!==e.resource.__data.addressu&&(e.data.addressu=e.resource.__data.addressu),void 0!==e.resource.__data.addressv&&(e.data.addressv=e.resource.__data.addressv),void 0!==e.resource.__data.mipmaps&&(e.data.mipmaps=e.resource.__data.mipmaps),void 0!==e.resource.__data.anisotropy&&(e.data.anisotropy=e.resource.__data.anisotropy),void 0!==e.resource.__data.rgbm&&(e.data.rgbm=!!e.resource.__data.rgbm),e.data.frames=e.resource.__data.frames,delete e.resource.__data);var i=e.resource.texture;if(i&&(i.name=e.name,e.data.hasOwnProperty("minfilter")&&i.minFilter!==Yp[e.data.minfilter]&&(i.minFilter=Yp[e.data.minfilter]),e.data.hasOwnProperty("magfilter")&&i.magFilter!==Yp[e.data.magfilter]&&(i.magFilter=Yp[e.data.magfilter]),e.data.hasOwnProperty("addressu")&&i.addressU!==jp[e.data.addressu]&&(i.addressU=jp[e.data.addressu]),e.data.hasOwnProperty("addressv")&&i.addressV!==jp[e.data.addressv]&&(i.addressV=jp[e.data.addressv]),e.data.hasOwnProperty("mipmaps")&&i.mipmaps!==e.data.mipmaps&&(i.mipmaps=e.data.mipmaps),e.data.hasOwnProperty("anisotropy")&&i.anisotropy!==e.data.anisotropy&&(i.anisotropy=e.data.anisotropy),e.data.hasOwnProperty("rgbm"))){var n=e.data.rgbm?$t:Zt;i.type!==n&&(i.type=n)}e.resource.texture=i;var s={};for(var r in e.data.frames){var a=e.data.frames[r];s[r]={rect:new Se(a.rect),pivot:new be(a.pivot),border:new Se(a.border)}}e.resource.frames=s,e.off("change",this._onAssetChange,this),e.on("change",this._onAssetChange,this)}},t._onAssetChange=function(e,t,i){var n;if("data"===t||"data.frames"===t){var s={};for(var r in i.frames)n=i.frames[r],s[r]={rect:new Se(n.rect),pivot:new be(n.pivot),border:new Se(n.border)};e.resource.frames=s}else{var a=t.match(Kp);if(a){var o=a[1];i?(e.resource.frames[o]?((n=e.resource.frames[o]).rect.set(i.rect[0],i.rect[1],i.rect[2],i.rect[3]),n.pivot.set(i.pivot[0],i.pivot[1]),n.border.set(i.border[0],i.border[1],i.border[2],i.border[3])):e.resource.frames[o]={rect:new Se(i.rect),pivot:new be(i.pivot),border:new Se(i.border)},e.resource.fire("set:frame",o,e.resource.frames[o])):e.resource.frames[o]&&(delete e.resource.frames[o],e.resource.fire("remove:frame",o))}}},e}(),$p=function(e){function t(t,i){var n;return(n=e.call(this)||this)._assets=new Set,n._loadingAssets=new Set,n._waitingAssets=new Set,n._registry=i,n._loading=!1,n._loaded=!1,n._failed=[],t.forEach((function(e){if(e instanceof ml)e.registry||(e.registry=i),n._assets.add(e);else{var t=i.get(e);t?n._assets.add(t):n._waitForAsset(e)}})),n}J(t,e);var i=t.prototype;return i.destroy=function(){var e=this;this._registry.off("load",this._onLoad),this._registry.off("error",this._onError),this._waitingAssets.forEach((function(t){e._registry.off("add:"+t,this._onAddAsset)})),this.off("progress"),this.off("load")},i._assetHasDependencies=function(e){var t;return"model"===e.type&&(null==(t=e.file)?void 0:t.url)&&e.file.url&&e.file.url.match(/.json$/g)},i.load=function(e,t){var i=this;if(!this._loading){this._loading=!0,this._callback=e,this._scope=t,this._registry.on("load",this._onLoad,this),this._registry.on("error",this._onError,this);var n=!1;this._assets.forEach((function(e){e.loaded||(n=!0,i._assetHasDependencies(e)&&i._registry.loadFromUrl(e.file.url,e.type,(function(t,n){t?i._onError(t,e):i._onLoad(e)})),i._loadingAssets.add(e),i._registry.add(e))})),this._loadingAssets.forEach((function(e){i._assetHasDependencies(e)||i._registry.load(e)})),n||0!==this._waitingAssets.size||this._loadingComplete()}},i.ready=function(e,t){void 0===t&&(t=this),this._loaded?e.call(t,Array.from(this._assets)):this.once("load",(function(i){e.call(t,i)}))},i._loadingComplete=function(){this._loaded||(this._loaded=!0,this._registry.off("load",this._onLoad,this),this._registry.off("error",this._onError,this),this._failed.length?(this._callback&&this._callback.call(this._scope,"Failed to load some assets",this._failed),this.fire("error",this._failed)):(this._callback&&this._callback.call(this._scope),this.fire("load",Array.from(this._assets))))},i._onLoad=function(e){var t=this;this._loadingAssets.has(e)&&(this.fire("progress",e),this._loadingAssets.delete(e)),0===this._loadingAssets.size&&setTimeout((function(){t._loadingComplete(t._failed)}),0)},i._onError=function(e,t){var i=this;this._loadingAssets.has(t)&&(this._failed.push(t),this._loadingAssets.delete(t)),0===this._loadingAssets.size&&setTimeout((function(){i._loadingComplete(i._failed)}),0)},i._onAddAsset=function(e){this._waitingAssets.delete(e),this._assets.add(e),e.loaded||(this._loadingAssets.add(e),this._registry.load(e))},i._waitForAsset=function(e){this._waitingAssets.add(e),this._registry.once("add:"+e,this._onAddAsset,this)},t}(m),Qp=function(e){function t(t){var i;return(i=e.call(this)||this)._app=t,t.i18n.on("set:locale",i._onSetLocale,te(i)),i._autoLoad=!1,i._disableLocalization=!1,i._defaultAsset=null,i._localizedAsset=null,i}J(t,e);var i=t.prototype;return i._bindDefaultAsset=function(){var e=this._app.assets.get(this._defaultAsset);e?this._onDefaultAssetAdd(e):this._app.assets.once("add:"+this._defaultAsset,this._onDefaultAssetAdd,this)},i._unbindDefaultAsset=function(){if(this._defaultAsset){this._app.assets.off("add:"+this._defaultAsset,this._onDefaultAssetAdd,this);var e=this._app.assets.get(this._defaultAsset);e&&(e.off("add:localized",this._onLocaleAdd,this),e.off("remove:localized",this._onLocaleRemove,this),e.off("remove",this._onDefaultAssetRemove,this))}},i._onDefaultAssetAdd=function(e){this._defaultAsset===e.id&&(e.on("add:localized",this._onLocaleAdd,this),e.on("remove:localized",this._onLocaleRemove,this),e.once("remove",this._onDefaultAssetRemove,this))},i._onDefaultAssetRemove=function(e){this._defaultAsset===e.id&&(e.off("add:localized",this._onLocaleAdd,this),e.off("remove:localized",this._onLocaleAdd,this),this._app.assets.once("add:"+this._defaultAsset,this._onDefaultAssetAdd,this))},i._bindLocalizedAsset=function(){if(this._autoLoad){var e=this._app.assets.get(this._localizedAsset);e&&(e.on("load",this._onLocalizedAssetLoad,this),e.on("change",this._onLocalizedAssetChange,this),e.on("remove",this._onLocalizedAssetRemove,this),e.resource?this._onLocalizedAssetLoad(e):this._app.assets.load(e))}},i._unbindLocalizedAsset=function(){var e=this._app.assets.get(this._localizedAsset);e&&(e.off("load",this._onLocalizedAssetLoad,this),e.off("change",this._onLocalizedAssetChange,this),e.off("remove",this._onLocalizedAssetRemove,this))},i._onLocalizedAssetAdd=function(e){this._localizedAsset===e.id&&this._bindLocalizedAsset()},i._onLocalizedAssetLoad=function(e){this.fire("load",e)},i._onLocalizedAssetChange=function(e,t,i,n){this.fire("change",e,t,i,n)},i._onLocalizedAssetRemove=function(e){this._localizedAsset===e.id&&(this.localizedAsset=this._defaultAsset),this.fire("remove",e)},i._onLocaleAdd=function(e,t){this._app.i18n.locale===e&&this._onSetLocale(e)},i._onLocaleRemove=function(e,t){this._app.i18n.locale===e&&this._onSetLocale(e)},i._onSetLocale=function(e){if(this._defaultAsset){var t=this._app.assets.get(this._defaultAsset);if(t&&!this._disableLocalization){var i=t.getLocalizedAssetId(e);this.localizedAsset=i||this._defaultAsset}else this.localizedAsset=this._defaultAsset}else this.localizedAsset=null},i.destroy=function(){this.defaultAsset=null,this._app.i18n.off("set:locale",this._onSetLocale,this),this.off()},$(t,[{key:"defaultAsset",get:function(){return this._defaultAsset},set:function(e){var t=e instanceof ml?e.id:e;this._defaultAsset!==t&&(this._defaultAsset&&this._unbindDefaultAsset(),this._defaultAsset=t,this._defaultAsset&&this._bindDefaultAsset(),this._onSetLocale(this._app.i18n.locale))}},{key:"localizedAsset",get:function(){return this._localizedAsset},set:function(e){var t=e instanceof ml?e.id:e;this._localizedAsset!==t&&(this._localizedAsset&&(this._app.assets.off("add:"+this._localizedAsset,this._onLocalizedAssetAdd,this),this._unbindLocalizedAsset(),this._localizedAsset=null),this._localizedAsset=t,this._localizedAsset&&(this._app.assets.get(this._localizedAsset)?this._bindLocalizedAsset():this._app.assets.once("add:"+this._localizedAsset,this._onLocalizedAssetAdd,this)))}},{key:"autoLoad",get:function(){return this._autoLoad},set:function(e){this._autoLoad!==e&&(this._autoLoad=e,this._autoLoad&&this._localizedAsset&&(this._unbindLocalizedAsset(),this._bindLocalizedAsset()))}},{key:"disableLocalization",get:function(){return this._disableLocalization},set:function(e){this._disableLocalization!==e&&(this._disableLocalization=e,this._onSetLocale(this._app.i18n.locale))}}]),t}(m),Jp=new Set(["system","entity","create","destroy","swap","move","scripts","_scripts","_scriptsIndex","_scriptsData","enabled","_oldState","onEnable","onDisable","onPostStateChange","_onSetEnabled","_checkState","_onBeforeRemove","_onInitializeAttributes","_onInitialize","_onPostInitialize","_onUpdate","_onPostUpdate","_callbacks","has","get","on","off","fire","once","hasEvent"]);function em(e,t){if(xl.legacy)return null;if(Jp.has(e))throw new Error("script name: '"+e+"' is reserved, please change script name");var i=function(e){m.prototype.initEventHandler.call(this),Rl.prototype.initScriptType.call(this,e)};return(i.prototype=Object.create(Rl.prototype)).constructor=i,i.extend=Rl.extend,i.attributes=new Ml(i),im(i,e,t),i}var tm={};function im(e,t,i){if(!e.legacy){if("function"!=typeof e)throw new Error("script class: '"+e+"' must be a constructor function (i.e. class).");if(!(e.prototype instanceof Rl))throw new Error("script class: '"+Rl.__getScriptName(e)+"' does not extend pc.ScriptType.");if(t=t||e.__name||Rl.__getScriptName(e),Jp.has(t))throw new Error("script name: '"+t+"' is reserved, please change script name");e.__name=t,(i?i.scripts:jl.getApplication().scripts).add(e),gl._push(e)}}Ml.reservedNames.forEach((function(e,t,i){tm[e]=1})),em.reservedAttributes=tm;var nm="mouse",sm="keyboard",rm="gamepad",am="mousedown",om="mousemove",hm="mouseup",lm="mousewheel",cm=function(e,t){t?(this.key=t.keyCode,this.element=t.target,this.event=t):(this.key=null,this.element=null,this.event=null)},um=new cm;function dm(e){return um.key=e.keyCode,um.element=e.target,um.event=e,um}function fm(e){return"string"==typeof e?e.toUpperCase().charCodeAt(0):e}var pm={9:"Tab",13:"Enter",16:"Shift",17:"Control",18:"Alt",27:"Escape",37:"Left",38:"Up",39:"Right",40:"Down",46:"Delete",91:"Win"},mm=function(e){function t(t,i){var n;return void 0===i&&(i={}),(n=e.call(this)||this)._element=null,n._keyDownHandler=n._handleKeyDown.bind(te(n)),n._keyUpHandler=n._handleKeyUp.bind(te(n)),n._keyPressHandler=n._handleKeyPress.bind(te(n)),n._visibilityChangeHandler=n._handleVisibilityChange.bind(te(n)),n._windowBlurHandler=n._handleWindowBlur.bind(te(n)),n._keymap={},n._lastmap={},t&&n.attach(t),n.preventDefault=i.preventDefault||!1,n.stopPropagation=i.stopPropagation||!1,n}J(t,e);var i=t.prototype;return i.attach=function(e){this._element&&this.detach(),this._element=e,this._element.addEventListener("keydown",this._keyDownHandler,!1),this._element.addEventListener("keypress",this._keyPressHandler,!1),this._element.addEventListener("keyup",this._keyUpHandler,!1),document.addEventListener("visibilitychange",this._visibilityChangeHandler,!1),window.addEventListener("blur",this._windowBlurHandler,!1)},i.detach=function(){this._element&&(this._element.removeEventListener("keydown",this._keyDownHandler),this._element.removeEventListener("keypress",this._keyPressHandler),this._element.removeEventListener("keyup",this._keyUpHandler),this._element=null,document.removeEventListener("visibilitychange",this._visibilityChangeHandler,!1),window.removeEventListener("blur",this._windowBlurHandler,!1))},i.toKeyIdentifier=function(e){e=fm(e);var t=pm[e.toString()];if(t)return t;for(var i=e.toString(16).toUpperCase(),n=i.length,s=0;s<4-n;s++)i="0"+i;return"U+"+i},i._handleKeyDown=function(e){var t=e.keyCode||e.charCode;if(void 0!==t){var i=this.toKeyIdentifier(t);this._keymap[i]=!0,this.fire("keydown",dm(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation()}},i._handleKeyUp=function(e){var t=e.keyCode||e.charCode;if(void 0!==t){var i=this.toKeyIdentifier(t);delete this._keymap[i],this.fire("keyup",dm(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation()}},i._handleKeyPress=function(e){this.fire("keypress",dm(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation()},i._handleVisibilityChange=function(){"hidden"===document.visibilityState&&this._handleWindowBlur()},i._handleWindowBlur=function(){this._keymap={},this._lastmap={}},i.update=function(){for(var e in this._lastmap)delete this._lastmap[e];for(var t in this._keymap)this._keymap.hasOwnProperty(t)&&(this._lastmap[t]=this._keymap[t])},i.isPressed=function(e){var t=fm(e),i=this.toKeyIdentifier(t);return!!this._keymap[i]},i.wasPressed=function(e){var t=fm(e),i=this.toKeyIdentifier(t);return!!this._keymap[i]&&!this._lastmap[i]},i.wasReleased=function(e){var t=fm(e),i=this.toKeyIdentifier(t);return!this._keymap[i]&&!!this._lastmap[i]},t}(m);function _m(){return!!(document.pointerLockElement||document.mozPointerLockElement||document.webkitPointerLockElement)}var gm,vm,ym=function e(t,i){var n={x:0,y:0};if(i){if(i instanceof e)throw Error("Expected MouseEvent");n=t._getTargetCoords(i)}else i={};if(n)this.x=n.x,this.y=n.y;else{if(!_m())return;this.x=0,this.y=0}this.wheelDelta=0,"wheel"===i.type&&(i.deltaY>0?this.wheelDelta=1:i.deltaY<0&&(this.wheelDelta=-1)),_m()?(this.dx=i.movementX||i.webkitMovementX||i.mozMovementX||0,this.dy=i.movementY||i.webkitMovementY||i.mozMovementY||0):(this.dx=this.x-t._lastX,this.dy=this.y-t._lastY),"mousedown"===i.type||"mouseup"===i.type?this.button=i.button:this.button=-1,this.buttons=t._buttons.slice(0),this.element=i.target,this.ctrlKey=i.ctrlKey||!1,this.altKey=i.altKey||!1,this.shiftKey=i.shiftKey||!1,this.metaKey=i.metaKey||!1,this.event=i},xm=function(e){function t(t){var i;return(i=e.call(this)||this)._lastX=0,i._lastY=0,i._buttons=[!1,!1,!1],i._lastbuttons=[!1,!1,!1],i._upHandler=i._handleUp.bind(te(i)),i._downHandler=i._handleDown.bind(te(i)),i._moveHandler=i._handleMove.bind(te(i)),i._wheelHandler=i._handleWheel.bind(te(i)),i._contextMenuHandler=function(e){e.preventDefault()},i._target=null,i._attached=!1,i.attach(t),i}J(t,e),t.isPointerLocked=function(){return _m()};var i=t.prototype;return i.attach=function(e){if(this._target=e,!this._attached){this._attached=!0;var t=!!L.passiveEvents&&{passive:!1};window.addEventListener("mouseup",this._upHandler,t),window.addEventListener("mousedown",this._downHandler,t),window.addEventListener("mousemove",this._moveHandler,t),window.addEventListener("wheel",this._wheelHandler,t)}},i.detach=function(){if(this._attached){this._attached=!1,this._target=null;var e=!!L.passiveEvents&&{passive:!1};window.removeEventListener("mouseup",this._upHandler,e),window.removeEventListener("mousedown",this._downHandler,e),window.removeEventListener("mousemove",this._moveHandler,e),window.removeEventListener("wheel",this._wheelHandler,e)}},i.disableContextMenu=function(){this._target&&this._target.addEventListener("contextmenu",this._contextMenuHandler)},i.enableContextMenu=function(){this._target&&this._target.removeEventListener("contextmenu",this._contextMenuHandler)},i.enablePointerLock=function(e,t){if(document.body.requestPointerLock){e&&document.addEventListener("pointerlockchange",(function t(){e(),document.removeEventListener("pointerlockchange",t)}),!1),t&&document.addEventListener("pointerlockerror",(function e(){t(),document.removeEventListener("pointerlockerror",e)}),!1),document.body.requestPointerLock()}else t&&t()},i.disablePointerLock=function(e){if(document.exitPointerLock){e&&document.addEventListener("pointerlockchange",(function t(){e(),document.removeEventListener("pointerlockchange",t)}),!1),document.exitPointerLock()}},i.update=function(){this._lastbuttons[0]=this._buttons[0],this._lastbuttons[1]=this._buttons[1],this._lastbuttons[2]=this._buttons[2]},i.isPressed=function(e){return this._buttons[e]},i.wasPressed=function(e){return this._buttons[e]&&!this._lastbuttons[e]},i.wasReleased=function(e){return!this._buttons[e]&&this._lastbuttons[e]},i._handleUp=function(e){this._buttons[e.button]=!1;var t=new ym(this,e);t.event&&this.fire(hm,t)},i._handleDown=function(e){this._buttons[e.button]=!0;var t=new ym(this,e);t.event&&this.fire(am,t)},i._handleMove=function(e){var t=new ym(this,e);t.event&&(this.fire(om,t),this._lastX=t.x,this._lastY=t.y)},i._handleWheel=function(e){var t=new ym(this,e);t.event&&this.fire(lm,t)},i._getTargetCoords=function(e){var t=this._target.getBoundingClientRect(),i=Math.floor(t.left),n=Math.floor(t.top);return e.clientX=i+this._target.clientWidth||e.clientY=n+this._target.clientHeight?null:{x:e.clientX-i,y:e.clientY-n}},t}(m),bm=function(){function e(e,t){void 0===t&&(t={}),this._keyboard=t.keyboard||null,this._mouse=t.mouse||null,this._gamepads=t.gamepads||null,this._element=null,this._actions={},this._axes={},this._axesValues={},e&&this.attach(e)}var t=e.prototype;return t.attach=function(e){this._element=e,this._keyboard&&this._keyboard.attach(e),this._mouse&&this._mouse.attach(e)},t.detach=function(){this._keyboard&&this._keyboard.detach(),this._mouse&&this._mouse.detach(),this._element=null},t.disableContextMenu=function(){this._mouse||this._enableMouse(),this._mouse.disableContextMenu()},t.enableContextMenu=function(){this._mouse||this._enableMouse(),this._mouse.enableContextMenu()},t.update=function(e){for(var t in this._keyboard&&this._keyboard.update(),this._mouse&&this._mouse.update(),this._gamepads&&this._gamepads.update(),this._axesValues={},this._axes)this._axesValues[t]=[]},t.appendAction=function(e,t){this._actions[e]=this._actions[e]||[],this._actions[e].push(t)},t.registerKeys=function(e,t){if(this._keyboard||this._enableKeyboard(),this._actions[e])throw new Error("Action: "+e+" already registered");if(void 0===t)throw new Error("Invalid button");t.length||(t=[t]),this.appendAction(e,{type:sm,keys:t})},t.registerMouse=function(e,t){if(this._mouse||this._enableMouse(),void 0===t)throw new Error("Invalid button");this.appendAction(e,{type:nm,button:t})},t.registerPadButton=function(e,t,i){if(void 0===i)throw new Error("Invalid button");this.appendAction(e,{type:rm,button:i,pad:t})},t.registerAxis=function(e){var t=e.name;this._axes[t]||(this._axes[t]=[]);var i=this._axes[t].push(t);(e=e||{}).pad=e.pad||0;var n=function(n,s,r,a){switch(s){case"mousex":n._mouse.on(om,(function(e){n._axesValues[t][i]=e.dx/10}));break;case"mousey":n._mouse.on(om,(function(e){n._axesValues[t][i]=e.dy/10}));break;case"key":n._axes[t].push((function(){return n._keyboard.isPressed(a)?r:0}));break;case"padrx":n._axes[t].push((function(){return n._gamepads.getAxis(e.pad,2)}));break;case"padry":n._axes[t].push((function(){return n._gamepads.getAxis(e.pad,3)}));break;case"padlx":n._axes[t].push((function(){return n._gamepads.getAxis(e.pad,0)}));break;case"padly":n._axes[t].push((function(){return n._gamepads.getAxis(e.pad,1)}));break;default:throw new Error("Unknown axis")}};n(this,e.positive,1,e.positiveKey),(e.negativeKey||e.negative!==e.positive)&&n(this,e.negative,-1,e.negativeKey)},t.isPressed=function(e){if(!this._actions[e])return!1;for(var t=this._actions[e].length,i=0;iMath.abs(t)&&(t=s)}else this._axesValues[e]&&Math.abs(this._axesValues[e][n])>Math.abs(t)&&(t=this._axesValues[e][n]);return t},t._enableMouse=function(){if(this._mouse=new xm,!this._element)throw new Error("Controller must be attached to an Element");this._mouse.attach(this._element)},t._enableKeyboard=function(){if(this._keyboard=new mm,!this._element)throw new Error("Controller must be attached to an Element");this._keyboard.attach(this._element)},e}(),Sm=new ye,wm=new ye,Tm=new et,Am=new et,Mm=new et;Tm.end=new ye,Am.end=new ye,Mm.end=new ye;var Cm=new ye,Em=new ye,Pm=new ye,Rm=new ye,Im=new ye,Lm=new ye,Dm=new ye,km=new ye,Om=new ye,Fm=new ye,Bm=new ye,Nm=new ye,Um=new ye,zm=new ye,Vm=new ye,Gm=new ye,Wm=new ye,Hm=new ye,Xm=new ye,qm=new ye,jm=new Se;function Ym(e,t,i){return Bm.cross(e,t).dot(i)}var Km=function(){function e(e,t,i){this.event=e,this.element=t,this.camera=i,this._stopPropagation=!1}return e.prototype.stopPropagation=function(){this._stopPropagation=!0,this.event&&(this.event.stopImmediatePropagation(),this.event.stopPropagation())},e}(),Zm=function(e){function t(t,i,n,s,r,a,o){var h;return(h=e.call(this,t,i,n)||this).x=s,h.y=r,h.ctrlKey=t.ctrlKey||!1,h.altKey=t.altKey||!1,h.shiftKey=t.shiftKey||!1,h.metaKey=t.metaKey||!1,h.button=t.button,xm.isPointerLocked()?(h.dx=t.movementX||t.webkitMovementX||t.mozMovementX||0,h.dy=t.movementY||t.webkitMovementY||t.mozMovementY||0):(h.dx=s-a,h.dy=r-o),h.wheelDelta=0,"wheel"===t.type&&(t.deltaY>0?h.wheelDelta=1:t.deltaY<0&&(h.wheelDelta=-1)),h}return J(t,e),t}(Km),$m=function(e){function t(t,i,n,s,r,a){var o;return(o=e.call(this,t,i,n)||this).touches=t.touches,o.changedTouches=t.changedTouches,o.x=s,o.y=r,o.touch=a,o}return J(t,e),t}(Km),Qm=function(e){function t(t,i,n,s){var r;return(r=e.call(this,t,i,n)||this).inputSource=s,r}return J(t,e),t}(Km),Jm=function(){function e(e,t){this._app=null,this._attached=!1,this._target=null,this._enabled=!0,this._lastX=0,this._lastY=0,this._upHandler=this._handleUp.bind(this),this._downHandler=this._handleDown.bind(this),this._moveHandler=this._handleMove.bind(this),this._wheelHandler=this._handleWheel.bind(this),this._touchstartHandler=this._handleTouchStart.bind(this),this._touchendHandler=this._handleTouchEnd.bind(this),this._touchcancelHandler=this._touchendHandler,this._touchmoveHandler=this._handleTouchMove.bind(this),this._sortHandler=this._sortElements.bind(this),this._elements=[],this._hoveredElement=null,this._pressedElement=null,this._touchedElements={},this._touchesForWhichTouchLeaveHasFired={},this._selectedElements={},this._selectedPressedElements={},this._useMouse=!t||!1!==t.useMouse,this._useTouch=!t||!1!==t.useTouch,this._useXr=!t||!1!==t.useXr,this._selectEventsAttached=!1,L.touch&&(this._clickedEntities={}),this.attach(e)}var t=e.prototype;return t.attach=function(e){this._attached&&(this._attached=!1,this.detach()),this._target=e,this._attached=!0;var t=!!L.passiveEvents&&{passive:!0};this._useMouse&&(window.addEventListener("mouseup",this._upHandler,t),window.addEventListener("mousedown",this._downHandler,t),window.addEventListener("mousemove",this._moveHandler,t),window.addEventListener("wheel",this._wheelHandler,t)),this._useTouch&&L.touch&&(this._target.addEventListener("touchstart",this._touchstartHandler,t),this._target.addEventListener("touchend",this._touchendHandler,!1),this._target.addEventListener("touchmove",this._touchmoveHandler,!1),this._target.addEventListener("touchcancel",this._touchcancelHandler,!1)),this.attachSelectEvents()},t.attachSelectEvents=function(){!this._selectEventsAttached&&this._useXr&&this.app&&this.app.xr&&this.app.xr.supported&&(this._clickedEntities||(this._clickedEntities={}),this._selectEventsAttached=!0,this.app.xr.on("start",this._onXrStart,this))},t.detach=function(){if(this._attached){this._attached=!1;var e=!!L.passiveEvents&&{passive:!0};this._useMouse&&(window.removeEventListener("mouseup",this._upHandler,e),window.removeEventListener("mousedown",this._downHandler,e),window.removeEventListener("mousemove",this._moveHandler,e),window.removeEventListener("wheel",this._wheelHandler,e)),this._useTouch&&(this._target.removeEventListener("touchstart",this._touchstartHandler,e),this._target.removeEventListener("touchend",this._touchendHandler,!1),this._target.removeEventListener("touchmove",this._touchmoveHandler,!1),this._target.removeEventListener("touchcancel",this._touchcancelHandler,!1)),this._selectEventsAttached&&(this._selectEventsAttached=!1,this.app.xr.off("start",this._onXrStart,this),this.app.xr.off("end",this._onXrEnd,this),this.app.xr.off("update",this._onXrUpdate,this),this.app.xr.input.off("selectstart",this._onSelectStart,this),this.app.xr.input.off("selectend",this._onSelectEnd,this),this.app.xr.input.off("remove",this._onXrInputRemove,this)),this._target=null}},t.addElement=function(e){-1===this._elements.indexOf(e)&&this._elements.push(e)},t.removeElement=function(e){var t=this._elements.indexOf(e);-1!==t&&this._elements.splice(t,1)},t._handleUp=function(e){this._enabled&&(xm.isPointerLocked()||(this._calcMouseCoords(e),this._onElementMouseEvent("mouseup",e)))},t._handleDown=function(e){this._enabled&&(xm.isPointerLocked()||(this._calcMouseCoords(e),this._onElementMouseEvent("mousedown",e)))},t._handleMove=function(e){this._enabled&&(this._calcMouseCoords(e),this._onElementMouseEvent("mousemove",e),this._lastX=gm,this._lastY=vm)},t._handleWheel=function(e){this._enabled&&(this._calcMouseCoords(e),this._onElementMouseEvent("mousewheel",e))},t._determineTouchedElements=function(e){for(var t={},i=this.app.systems.camera.cameras,n=i.length-1;n>=0;n--){for(var s=i[n],r=0,a=e.changedTouches.length,o=0;o=0;d--){this._getTargetElementByCoords(t[d],u.x,u.y)===o&&(this._clickedEntities[o.entity.getGuid()]||(this._fireEvent("click",new $m(e,o,h,l,c,r)),this._clickedEntities[o.entity.getGuid()]=!0))}}}}},t._handleTouchMove=function(e){if(e.preventDefault(),this._enabled)for(var t=this._determineTouchedElements(e),i=0,n=e.changedTouches.length;i=0&&(s=r[a],!(i=this._getTargetElementByCoords(s,gm,vm)));a--);this._hoveredElement=i,"mousemove"!==e&&"mouseup"!==e||!this._pressedElement?i&&(this._fireEvent(e,new Zm(t,i,s,gm,vm,this._lastX,this._lastY)),"mousedown"===e&&(this._pressedElement=i)):this._fireEvent(e,new Zm(t,this._pressedElement,s,gm,vm,this._lastX,this._lastY)),n!==this._hoveredElement&&(n&&this._fireEvent("mouseleave",new Zm(t,n,s,gm,vm,this._lastX,this._lastY)),this._hoveredElement&&this._fireEvent("mouseenter",new Zm(t,this._hoveredElement,s,gm,vm,this._lastX,this._lastY))),"mouseup"===e&&this._pressedElement&&(this._pressedElement===this._hoveredElement?(this._pressedElement=null,this._clickedEntities&&this._clickedEntities[this._hoveredElement.entity.getGuid()]||this._fireEvent("click",new Zm(t,this._hoveredElement,s,gm,vm,this._lastX,this._lastY))):this._pressedElement=null)},t._onXrStart=function(){this.app.xr.on("end",this._onXrEnd,this),this.app.xr.on("update",this._onXrUpdate,this),this.app.xr.input.on("selectstart",this._onSelectStart,this),this.app.xr.input.on("selectend",this._onSelectEnd,this),this.app.xr.input.on("remove",this._onXrInputRemove,this)},t._onXrEnd=function(){this.app.xr.off("update",this._onXrUpdate,this),this.app.xr.input.off("selectstart",this._onSelectStart,this),this.app.xr.input.off("selectend",this._onSelectEnd,this),this.app.xr.input.off("remove",this._onXrInputRemove,this)},t._onXrUpdate=function(){if(this._enabled)for(var e=this.app.xr.input.inputSources,t=0;t=0&&(r=o[h],!(n=this._getTargetElementByRay(Mm,r)));h--);}t._elementEntity=n||null,n?(this._selectedElements[t.id]=n,s=n):delete this._selectedElements[t.id],a!==s&&(a&&this._fireEvent("selectleave",new Qm(i,a,r,t)),s&&this._fireEvent("selectenter",new Qm(i,s,r,t))),"selectstart"===e&&(this._selectedPressedElements[t.id]=s,s&&this._fireEvent("selectstart",new Qm(i,s,r,t)));var l=this._selectedPressedElements[t.id];!t.elementInput&&l&&(delete this._selectedPressedElements[t.id],a&&this._fireEvent("selectend",new Qm(i,a,r,t))),"selectend"===e&&t.elementInput&&(delete this._selectedPressedElements[t.id],a&&this._fireEvent("selectend",new Qm(i,a,r,t)),l&&l===a&&this._fireEvent("click",new Qm(i,l,r,t)))},t._fireEvent=function(e,t){for(var i=t.element;i.fire(e,t),!t._stopPropagation&&i.entity.parent&&(i=i.entity.parent.element););},t._calcMouseCoords=function(e){var t=this._target.getBoundingClientRect(),i=Math.floor(t.left),n=Math.floor(t.top);gm=e.clientX-i,vm=e.clientY-n},t._calcTouchCoords=function(e){for(var t=0,i=0,n=e.target;!(n instanceof HTMLElement);)n=n.parentNode;var s=n;do{t+=s.offsetLeft-s.scrollLeft,i+=s.offsetTop-s.scrollTop,s=s.offsetParent}while(s);return{x:e.pageX-t,y:e.pageY-i}},t._sortElements=function(e,t){var i=this.app.scene.layers.sortTransparentLayers(e.layers,t.layers);return 0!==i?i:e.screen&&!t.screen?-1:!e.screen&&t.screen?1:e.screen||t.screen?e.screen.screen.screenSpace&&!t.screen.screen.screenSpace?-1:t.screen.screen.screenSpace&&!e.screen.screen.screenSpace?1:t.drawOrder-e.drawOrder:0},t._getTargetElementByCoords=function(e,t,i){var n=this._calculateRayScreen(t,i,e,Tm)?Tm:null,s=this._calculateRay3d(t,i,e,Am)?Am:null;return this._getTargetElement(e,n,s)},t._getTargetElementByRay=function(e,t){Tm.origin.copy(e.origin),Tm.direction.copy(e.direction),Tm.end.copy(Tm.direction).mulScalar(2*t.farClip).add(Tm.origin);var i=Tm,n=t.worldToScreen(i.origin,Sm),s=this._calculateRayScreen(n.x,n.y,t,Am)?Am:null;return this._getTargetElement(t,s,i)},t._getTargetElement=function(e,t,i){var n=null,s=1/0;this._elements.sort(this._sortHandler);for(var r=0,a=this._elements.length;r=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)},t._calculateRay3d=function(e,t,i,n){var s=this._target.clientWidth,r=this._target.clientHeight,a=i.rect.z*s,o=i.rect.w*r,h=i.rect.x*s,l=h+a,c=(1-i.rect.y)*r,u=c-o,d=e,f=t;return e>=h&&e<=l&&t<=c&&f>=u&&(d=s*(d-h)/a,f=r*(f-u)/o,i.screenToWorld(d,f,i.nearClip,Sm),i.screenToWorld(d,f,i.farClip,wm),n.origin.copy(Sm),n.direction.set(0,0,-1),n.end.copy(wm),!0)},t._checkElement=function(e,t,i){if(t.maskedBy&&this._checkElement(e,t.maskedBy.element,i)<0)return-1;var n;n=i?this._calculateScaleToScreen(t):this._calculateScaleToWorld(t);var s=this._buildHitCorners(t,i?t.screenCorners:t.worldCorners,n.x,n.y,n.z);return function(e,t,i){Cm.sub2(t,e),Em.sub2(i[0],e),Pm.sub2(i[1],e),Rm.sub2(i[2],e),Lm.cross(Rm,Cm);var n,s,r=Em.dot(Lm);if(r>=0){if((n=-Pm.dot(Lm))<0)return-1;if((s=Ym(Cm,Pm,Em))<0)return-1;var a=1/(n+r+s);Dm.copy(i[0]).mulScalar(n*a),km.copy(i[1]).mulScalar(r*a),Om.copy(i[2]).mulScalar(s*a),Fm.copy(Dm).add(km).add(Om)}else{if(Im.sub2(i[3],e),(n=Im.dot(Lm))<0)return-1;if((s=Ym(Cm,Em,Im))<0)return-1;var o=1/(n+(r=-r)+s);Dm.copy(i[0]).mulScalar(n*o),km.copy(i[3]).mulScalar(r*o),Om.copy(i[2]).mulScalar(s*o),Fm.copy(Dm).add(km).add(Om)}return Cm.sub2(i[0],i[2]).lengthSq()<1e-8||Cm.sub2(i[1],i[3]).lengthSq()<1e-8?-1:Fm.sub(e).lengthSq()}(e.origin,e.end,s)},$(e,[{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"app",get:function(){return this._app||Kr()},set:function(e){this._app=e}}]),e}(),e_={DEFAULT:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_3","PAD_FACE_4","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_UP","PAD_DOWN","PAD_LEFT","PAD_RIGHT","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"]},PS3:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_4","PAD_FACE_3","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_UP","PAD_DOWN","PAD_LEFT","PAD_RIGHT","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"]}},t_={"Product: 0268":"PS3"},i_=function(){function e(){this.gamepadsSupported=!!navigator.getGamepads||!!navigator.webkitGetGamepads,this.current=[],this.previous=[],this.deadZone=.25}var t=e.prototype;return t.update=function(){for(var e=0,t=this.current.length;e0&&(e.length=0),this.gamepadsSupported)for(var t=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads(),i=0,n=t.length;i=0)return e_[t_[t]];return e_.DEFAULT},t.isPressed=function(e,t){if(!this.current[e])return!1;var i=this.current[e].map.buttons[t];return this.current[e].pad.buttons[pc[i]].pressed},t.wasPressed=function(e,t){if(!this.current[e])return!1;var i=this.current[e].map.buttons[t],n=pc[i];return this.current[e].pad.buttons[n].pressed&&!(this.previous[e]&&this.previous[e][n])},t.wasReleased=function(e,t){if(!this.current[e])return!1;var i=this.current[e].map.buttons[t],n=pc[i];return!this.current[e].pad.buttons[n].pressed&&this.previous[e]&&this.previous[e][n]},t.getAxis=function(e,t){if(!this.current[e])return 0;var i=this.current[e].map.axes[t],n=this.current[e].pad.axes[pc[i]];return Math.abs(n)0&&!!this.prevAnim,this.blending&&(this.blend=0,this.blendSpeed=1/t),this.skeleton&&(this.blending?(this.fromSkel.animation=i,this.fromSkel.addTime(this.skeleton._time),this.toSkel.animation=n):this.skeleton.animation=n),this.animEvaluator){var s=this.animEvaluator;if(this.blending)for(;s.clips.length>1;)s.removeClip(0);else this.animEvaluator.removeClips();var r=new Su(this.animations[this.currAnim],0,1,!0,this.loop);r.name=this.currAnim,r.blendWeight=this.blending?0:1,r.reset(),this.animEvaluator.addClip(r)}}this.playing=!0}},i.getAnimation=function(e){return this.animations[e]},i.setModel=function(e){e!==this.model&&(this._resetAnimationController(),this.model=e,this.animations&&this.currAnim&&this.animations[this.currAnim]&&this.play(this.currAnim))},i.onSetAnimations=function(){var e=this.entity.model;if(e){var t=e.model;t&&t!==this.model&&this.setModel(t)}if(!this.currAnim&&this.activate&&this.enabled&&this.entity.enabled){var i=Object.keys(this._animations);i.length>0&&this.play(i[0])}},i._resetAnimationController=function(){this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animEvaluator=null},i._createAnimationController=function(){var e=this.model,t=this.animations,i=!1,n=!1;for(var s in t){if(t.hasOwnProperty(s))t[s].constructor===Ju?n=!0:i=!0}var r=e.getGraph();i?(this.fromSkel=new vu(r),this.toSkel=new vu(r),this.skeleton=new vu(r),this.skeleton.looping=this.loop,this.skeleton.setGraph(r)):n&&(this.animEvaluator=new Zu(new ed(this.entity)))},i.loadAnimationAssets=function(e){var t=this;if(e&&e.length)for(var i=this.system.app.assets,n=function(e){if(e.resources.length>1)for(var i=0;i1){if(n&&n.length>1)for(var r=0;r1)for(var o=0;o1)for(var h=0;h1)for(var t=0;t0&&this.play(a[0])}},i.onBeforeRemove=function(){for(var e=0;e=1&&(this.blend=1)),this.playing){var t=this.skeleton;if(null!==t&&null!==this.model){if(this.blending)t.blend(this.fromSkel,this.toSkel,this.blend);else{var i=e*this.speed;t.addTime(i),(this.speed>0&&t._time===t.animation.duration&&!this.loop||this.speed<0&&0===t._time&&!this.loop)&&(this.playing=!1)}this.blending&&1===this.blend&&(t.animation=this.toSkel.animation),t.updateGraph()}}var n=this.animEvaluator;if(n){for(var s=0;s1&&(n.clips[1].blendWeight=this.blend),n.update(e)}this.blending&&1===this.blend&&(this.blending=!1)},$(t,[{key:"animations",get:function(){return this._animations},set:function(e){this._animations=e,this.onSetAnimations()}},{key:"assets",get:function(){return this._assets},set:function(e){var t=this._assets;if(t&&t.length)for(var i=0;i0)return e[e.length-1].time}return 0},set:function(e){if(this.skeleton&&(this.skeleton.currentTime=e,this.skeleton.addTime(0),this.skeleton.updateGraph()),this.animEvaluator)for(var t=this.animEvaluator.clips,i=0;i1){var l=t.length>2?this._resolvePath(e,t.slice(0,-1)):e,c=t[t.length-2];return function(e){n[s]=i(e),l[c]=n}}return function(e){n[s]=i(e)}},i._createAnimTargetForProperty=function(e,i,n){if(this.handlers&&i[0].startsWith("weight."))return this.handlers.weight(e,i[0].replace("weight.",""));if(this.handlers&&"material"===i[0]&&2===i.length){var s=i[1];if(s.endsWith("Map"))return this.handlers.materialTexture(e,s)}var r,a,o,h=this._resolvePath(e,i,!0);if(void 0===h)return null;if("number"==typeof h)r=this._setter(e,i,t._packFloat),a="vector",o=1;else if("boolean"==typeof h)r=this._setter(e,i,t._packBoolean),a="vector",o=1;else if("object"==typeof h)switch(h.constructor){case be:r=this._setter(e,i,t._packVec2),a="vector",o=2;break;case ye:r=this._setter(e,i,t._packVec3),a="vector",o=3;break;case Se:r=this._setter(e,i,t._packVec4),a="vector",o=4;break;case me:r=this._setter(e,i,t._packColor),a="vector",o=4;break;case Pe:r=this._setter(e,i,t._packQuat),a="quaternion",o=4;break;default:return null}return-1!==i.indexOf("material")?new $u((function(t){r(t),e.material.update()}),a,o,n):new $u(r,a,o,n)},i.rebind=function(){this.targetCache={},this.animComponent.rootBone?this.graph=this.animComponent.rootBone:this.graph=this.animComponent.entity;var e={};!function t(i){e[i.name]=i;for(var n=0;n0?this._layers[0]:null}}]),t}(Cl),S_=function(){this.enabled=!0},w_=["enabled"],T_=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="anim",i.ComponentType=b_,i.DataType=S_,i.schema=w_,i.on("beforeremove",i.onBeforeRemove,te(i)),i.app.systems.on("animationUpdate",i.onAnimationUpdate,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){e.prototype.initializeComponentData.call(this,t,i,w_);var s=["animationAssets","stateGraph","layers","masks"];Object.keys(i).forEach((function(e){s.includes(e)||(t[e]=i[e])})),i.stateGraph&&(t.stateGraph=i.stateGraph,t.loadStateGraph(t.stateGraph)),i.layers?i.layers.forEach((function(e,i){e._controller.states.forEach((function(n){e._controller._states[n]._animationList.forEach((function(e){t.layers[i].assignAnimation(e.name,e.animTrack)}))}))})):i.animationAssets&&(t.animationAssets=Object.assign(t.animationAssets,i.animationAssets)),i.masks&&Object.keys(i.masks).forEach((function(e){if(t.layers[e]){var n=i.masks[e].mask,s={};Object.keys(n).forEach((function(e){s[decodeURI(e)]=n[e]})),t.layers[e].mask=s}}))},i.onAnimationUpdate=function(e){var t=this.store;for(var i in t)if(t.hasOwnProperty(i)){var n=t[i].entity.anim;n.data.enabled&&n.entity.enabled&&n.playing&&n.update(e)}},i.cloneComponent=function(e,t){var i;e.anim.rootBone&&e.anim.rootBone!==e||(i={},e.anim.layers.forEach((function(e,n){if(e.mask){var s={};Object.keys(e.mask).forEach((function(i){var n=i.split("/");n.shift();var r=[t.name].concat(n).join("/");s[r]=e.mask[i]})),i[n]={mask:s}}})));var n={stateGraphAsset:e.anim.stateGraphAsset,animationAssets:e.anim.animationAssets,speed:e.anim.speed,activate:e.anim.activate,playing:e.anim.playing,rootBone:e.anim.rootBone,stateGraph:e.anim.stateGraph,layers:e.anim.layers,layerIndices:e.anim.layerIndices,parameters:e.anim.parameters,normalizeWeights:e.anim.normalizeWeights,masks:i};return this.addComponent(t,n)},i.onBeforeRemove=function(e,t){t.onBeforeRemove()},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("animationUpdate",this.onAnimationUpdate,this)},t}(h_);Cl._buildAccessors(b_.prototype,w_);var A_=function(e){function t(t,i){return e.call(this,t,i)||this}J(t,e);var i=t.prototype;return i.setCurrentListener=function(){if(this.enabled&&this.entity.audiolistener&&this.entity.enabled){this.system.current=this.entity;var e=this.system.current.getPosition();this.system.manager.listener.setPosition(e)}},i.onEnable=function(){this.setCurrentListener()},i.onDisable=function(){this.system.current===this.entity&&(this.system.current=null)},t}(Cl),M_=function(){this.enabled=!0},C_=["enabled"],E_=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="audiolistener",i.ComponentType=A_,i.DataType=M_,i.schema=C_,i.manager=t.soundManager,i.current=null,i.app.systems.on("update",i.onUpdate,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){n=["enabled"],e.prototype.initializeComponentData.call(this,t,i,n)},i.onUpdate=function(e){if(this.current){var t=this.current.getPosition();this.manager.listener.setPosition(t);var i=this.current.getWorldTransform();this.manager.listener.setOrientation(i)}},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},t}(h_);Cl._buildAccessors(A_.prototype,C_);var P_=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this).on("set_assets",n.onSetAssets,te(n)),n.on("set_loop",n.onSetLoop,te(n)),n.on("set_volume",n.onSetVolume,te(n)),n.on("set_pitch",n.onSetPitch,te(n)),n.on("set_minDistance",n.onSetMinDistance,te(n)),n.on("set_maxDistance",n.onSetMaxDistance,te(n)),n.on("set_rollOffFactor",n.onSetRollOffFactor,te(n)),n.on("set_distanceModel",n.onSetDistanceModel,te(n)),n.on("set_3d",n.onSet3d,te(n)),n}J(t,e);var i=t.prototype;return i.play=function(e){if(this.enabled&&this.entity.enabled){var t;this.channel&&this.stop();var i=this.data;if(i.sources[e])if(i["3d"]){var n=this.entity.getPosition();t=this.system.manager.playSound3d(i.sources[e],n,i),i.currentSource=e,i.channel=t}else t=this.system.manager.playSound(i.sources[e],i),i.currentSource=e,i.channel=t}},i.pause=function(){this.channel&&this.channel.pause()},i.unpause=function(){this.channel&&this.channel.paused&&this.channel.unpause()},i.stop=function(){this.channel&&(this.channel.stop(),this.channel=null)},i.onSetAssets=function(e,t,i){var n=[],s=i.length;if(t&&t.length)for(var r=0;r1e-5){var i=this._tweenInfo.lerpColor;i.lerp(this._tweenInfo.from,this._tweenInfo.to,t),this._applyTintImmediately(new me(i.r,i.g,i.b,i.a))}else this._applyTintImmediately(this._tweenInfo.to),this._cancelTween()},i._cancelTween=function(){delete this._tweenInfo},i.onUpdate=function(){this._tweenInfo&&this._updateTintTween()},i.onEnable=function(){this._isHovering=!1,this._hoveringCounter=0,this._isPressed=!1,this._imageReference.onParentComponentEnable(),this._toggleHitElementListeners("on"),this._forceReapplyVisualState()},i.onDisable=function(){this._toggleHitElementListeners("off"),this._resetToDefaultVisualState(this.transitionMode)},i.onRemove=function(){this._toggleLifecycleListeners("off",this.system),this.onDisable()},t}(Cl);function Y_(e){return new me(e.r,e.g,e.b)}var K_=function(){this.enabled=!0,this.active=!0,this.imageEntity=null,this.hitPadding=new Se,this.transitionMode=0,this.hoverTint=new me(.75,.75,.75),this.pressedTint=new me(.5,.5,.5),this.inactiveTint=new me(.25,.25,.25),this.fadeDuration=0,this.hoverSpriteAsset=null,this.hoverSpriteFrame=0,this.pressedSpriteAsset=null,this.pressedSpriteFrame=0,this.inactiveSpriteAsset=null,this.inactiveSpriteFrame=0},Z_=["enabled","active",{name:"imageEntity",type:"entity"},{name:"hitPadding",type:"vec4"},"transitionMode",{name:"hoverTint",type:"rgba"},{name:"pressedTint",type:"rgba"},{name:"inactiveTint",type:"rgba"},"fadeDuration","hoverSpriteAsset","hoverSpriteFrame","pressedSpriteAsset","pressedSpriteFrame","inactiveSpriteAsset","inactiveSpriteFrame"],$_=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="button",i.ComponentType=j_,i.DataType=K_,i.schema=Z_,i.on("beforeremove",i._onRemoveComponent,te(i)),i.app.systems.on("update",i.onUpdate,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){e.prototype.initializeComponentData.call(this,t,i,Z_)},i.onUpdate=function(e){var t=this.store;for(var i in t){var n=t[i].entity,s=n.button;s.enabled&&n.enabled&&s.onUpdate()}},i._onRemoveComponent=function(e,t){t.onRemove()},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},t}(h_);Cl._buildAccessors(j_.prototype,Z_);var Q_,J_,eg,tg=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._compoundParent=null,n.entity.on("insert",n._onInsert,te(n)),n.on("set_type",n.onSetType,te(n)),n.on("set_halfExtents",n.onSetHalfExtents,te(n)),n.on("set_radius",n.onSetRadius,te(n)),n.on("set_height",n.onSetHeight,te(n)),n.on("set_axis",n.onSetAxis,te(n)),n.on("set_asset",n.onSetAsset,te(n)),n.on("set_renderAsset",n.onSetRenderAsset,te(n)),n.on("set_model",n.onSetModel,te(n)),n.on("set_render",n.onSetRender,te(n)),n}J(t,e);var i=t.prototype;return i.onSetType=function(e,t,i){t!==i&&this.system.changeType(this,t,i)},i.onSetHalfExtents=function(e,t,i){var n=this.data.type;this.data.initialized&&"box"===n&&this.system.recreatePhysicalShapes(this)},i.onSetRadius=function(e,t,i){var n=this.data.type;!this.data.initialized||"sphere"!==n&&"capsule"!==n&&"cylinder"!==n&&"cone"!==n||this.system.recreatePhysicalShapes(this)},i.onSetHeight=function(e,t,i){var n=this.data.type;!this.data.initialized||"capsule"!==n&&"cylinder"!==n&&"cone"!==n||this.system.recreatePhysicalShapes(this)},i.onSetAxis=function(e,t,i){var n=this.data.type;!this.data.initialized||"capsule"!==n&&"cylinder"!==n&&"cone"!==n||this.system.recreatePhysicalShapes(this)},i.onSetAsset=function(e,t,i){var n=this.system.app.assets;if(t){var s=n.get(t);s&&s.off("remove",this.onAssetRemoved,this)}if(i){i instanceof ml&&(this.data.asset=i.id);var r=n.get(this.data.asset);r&&(r.off("remove",this.onAssetRemoved,this),r.on("remove",this.onAssetRemoved,this))}this.data.initialized&&"mesh"===this.data.type&&(i||(this.data.model=null),this.system.recreatePhysicalShapes(this))},i.onSetRenderAsset=function(e,t,i){var n=this.system.app.assets;if(t){var s=n.get(t);s&&s.off("remove",this.onRenderAssetRemoved,this)}if(i){i instanceof ml&&(this.data.renderAsset=i.id);var r=n.get(this.data.renderAsset);r&&(r.off("remove",this.onRenderAssetRemoved,this),r.on("remove",this.onRenderAssetRemoved,this))}this.data.initialized&&"mesh"===this.data.type&&(i||(this.data.render=null),this.system.recreatePhysicalShapes(this))},i.onSetModel=function(e,t,i){this.data.initialized&&"mesh"===this.data.type&&this.system.implementations.mesh.doRecreatePhysicalShape(this)},i.onSetRender=function(e,t,i){this.onSetModel(e,t,i)},i.onAssetRemoved=function(e){e.off("remove",this.onAssetRemoved,this),this.data.asset===e.id&&(this.asset=null)},i.onRenderAssetRemoved=function(e){e.off("remove",this.onRenderAssetRemoved,this),this.data.renderAsset===e.id&&(this.renderAsset=null)},i._getCompoundChildShapeIndex=function(e){for(var t=this.data.shape,i=t.getNumChildShapes(),n=0;n-1&&t.rigidbody._triggers.splice(i,1),t.rigidbody.removeBody(e),e.forceActivationState(5)}},e}(),lg=new Ee,cg=new ye,ug=new Pe,dg=new Hn,fg=["enabled","type","halfExtents","radius","axis","height","asset","renderAsset","shape","model","render"],pg=function(){function e(e){this.system=e}var t=e.prototype;return t.beforeInitialize=function(e,t){t.shape=null,t.model=new hc,t.model.graph=new Hn},t.afterInitialize=function(e,t){this.recreatePhysicalShapes(e),e.data.initialized=!0},t.reset=function(e,t){this.beforeInitialize(e,t),this.afterInitialize(e,t)},t.recreatePhysicalShapes=function(e){var t=e.entity,i=e.data;if("undefined"!=typeof Ammo){t.trigger&&(t.trigger.destroy(),delete t.trigger),i.shape&&(e._compoundParent&&(this.system._removeCompoundChild(e._compoundParent,i.shape),e._compoundParent.entity.rigidbody&&e._compoundParent.entity.rigidbody.activate()),Ammo.destroy(i.shape),i.shape=null),i.shape=this.createPhysicalShape(e.entity,i);var n=!e._compoundParent;if("compound"!==i.type||e._compoundParent&&e!==e._compoundParent){if("compound"!==i.type&&(e._compoundParent&&e===e._compoundParent&&t.forEach(this.system.implementations.compound._updateEachDescendant,e),!e.rigidbody)){e._compoundParent=null;for(var s=t.parent;s;){if(s.collision&&"compound"===s.collision.type){e._compoundParent=s.collision;break}s=s.parent}}}else e._compoundParent=e,t.forEach(this._addEachDescendant,e);e._compoundParent&&e!==e._compoundParent&&(n&&0===e._compoundParent.shape.getNumChildShapes()?this.system.recreatePhysicalShapes(e._compoundParent):(this.system.updateCompoundChildTransform(t),e._compoundParent.entity.rigidbody&&e._compoundParent.entity.rigidbody.activate())),t.rigidbody?(t.rigidbody.disableSimulation(),t.rigidbody.createBody(),t.enabled&&t.rigidbody.enabled&&t.rigidbody.enableSimulation()):e._compoundParent||(t.trigger?t.trigger.initialize(i):t.trigger=new hg(this.system.app,e,i))}},t.createPhysicalShape=function(e,t){},t.updateTransform=function(e,t,i,n){e.entity.trigger&&e.entity.trigger.updateTransform()},t.beforeRemove=function(e,t){t.data.shape&&(t._compoundParent&&!t._compoundParent.entity._destroying&&(this.system._removeCompoundChild(t._compoundParent,t.data.shape),t._compoundParent.entity.rigidbody&&t._compoundParent.entity.rigidbody.activate()),t._compoundParent=null,Ammo.destroy(t.data.shape),t.data.shape=null)},t.remove=function(e,t){e.rigidbody&&e.rigidbody.body&&e.rigidbody.disableSimulation(),e.trigger&&(e.trigger.destroy(),delete e.trigger)},t.clone=function(e,t){var i=this.system.store[e.getGuid()],n={enabled:i.data.enabled,type:i.data.type,halfExtents:[i.data.halfExtents.x,i.data.halfExtents.y,i.data.halfExtents.z],radius:i.data.radius,axis:i.data.axis,height:i.data.height,asset:i.data.asset,renderAsset:i.data.renderAsset,model:i.data.model,render:i.data.render};return this.system.addComponent(t,n)},e}(),mg=function(e){function t(){return e.apply(this,arguments)||this}return J(t,e),t.prototype.createPhysicalShape=function(e,t){if("undefined"!=typeof Ammo){var i=t.halfExtents,n=new Ammo.btVector3(i?i.x:.5,i?i.y:.5,i?i.z:.5),s=new Ammo.btBoxShape(n);return Ammo.destroy(n),s}},t}(pg),_g=function(e){function t(){return e.apply(this,arguments)||this}return J(t,e),t.prototype.createPhysicalShape=function(e,t){if("undefined"!=typeof Ammo)return new Ammo.btSphereShape(t.radius)},t}(pg),gg=function(e){function t(){return e.apply(this,arguments)||this}return J(t,e),t.prototype.createPhysicalShape=function(e,t){var i=void 0!==t.axis?t.axis:1,n=t.radius||.5,s=Math.max((t.height||2)-2*n,0),r=null;if("undefined"!=typeof Ammo)switch(i){case 0:r=new Ammo.btCapsuleShapeX(n,s);break;case 1:r=new Ammo.btCapsuleShape(n,s);break;case 2:r=new Ammo.btCapsuleShapeZ(n,s)}return r},t}(pg),vg=function(e){function t(){return e.apply(this,arguments)||this}return J(t,e),t.prototype.createPhysicalShape=function(e,t){var i=void 0!==t.axis?t.axis:1,n=void 0!==t.radius?t.radius:.5,s=void 0!==t.height?t.height:1,r=null,a=null;if("undefined"!=typeof Ammo)switch(i){case 0:r=new Ammo.btVector3(.5*s,n,n),a=new Ammo.btCylinderShapeX(r);break;case 1:r=new Ammo.btVector3(n,.5*s,n),a=new Ammo.btCylinderShape(r);break;case 2:r=new Ammo.btVector3(n,n,.5*s),a=new Ammo.btCylinderShapeZ(r)}return r&&Ammo.destroy(r),a},t}(pg),yg=function(e){function t(){return e.apply(this,arguments)||this}return J(t,e),t.prototype.createPhysicalShape=function(e,t){var i=void 0!==t.axis?t.axis:1,n=void 0!==t.radius?t.radius:.5,s=void 0!==t.height?t.height:1,r=null;if("undefined"!=typeof Ammo)switch(i){case 0:r=new Ammo.btConeShapeX(n,s);break;case 1:r=new Ammo.btConeShape(n,s);break;case 2:r=new Ammo.btConeShapeZ(n,s)}return r},t}(pg),xg=function(e){function t(){return e.apply(this,arguments)||this}J(t,e);var i=t.prototype;return i.beforeInitialize=function(e,t){},i.createAmmoMesh=function(e,t,i){var n;if(this.system._triMeshCache[e.id])n=this.system._triMeshCache[e.id];else{for(var s,r,a=e.vertexBuffer,o=a.getFormat(),h=0;h=0&&this.model.meshInstances.splice(i,1),this.unmaskMeshInstance=null}this._entity.enabled&&this._element.enabled&&(this._element.removeModelFromLayers(this.model),this._element.addModelToLayers(this.model))}},t.setMaterial=function(e){this.meshInstance&&(this.meshInstance.material=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.material=e))},t.setParameter=function(e,t){this.meshInstance&&(this.meshInstance.setParameter(e,t),this.unmaskMeshInstance&&this.unmaskMeshInstance.setParameter(e,t))},t.deleteParameter=function(e){this.meshInstance&&(this.meshInstance.deleteParameter(e),this.unmaskMeshInstance&&this.unmaskMeshInstance.deleteParameter(e))},t.setUnmaskDrawOrder=function(){if(this.meshInstance){if(this.unmaskMeshInstance){var e=function e(t){var i,n=t.children,s=n.length;if(s){for(var r=0;r0){var s=t.calculatedWidth/t.calculatedHeight;t.fitMode===N_&&s>this._targetAspectRatio||t.fitMode===U_&&s0&&(this._targetAspectRatio=i.rect.z/i.rect.w)}this.mesh=e?t:this._defaultMesh,this.refreshMesh()},t.refreshMesh=function(){this.mesh&&(this._element._beingInitialized?this._meshDirty=!0:this._updateMesh(this.mesh))},t._updateAabb=function(e){return e.center.set(0,0,0),e.halfExtents.set(.5*this._outerScale.x,.5*this._outerScale.y,.001),e.setFromTransformedAabb(e,this._renderable.node.getWorldTransform()),e},t._toggleMask=function(){this._element._dirtifyMask();var e=this._element._isScreenSpace();this._updateMaterial(e),this._renderable.setMask(!!this._mask)},t._onMaterialLoad=function(e){this.material=e.resource},t._onMaterialAdded=function(e){this._system.app.assets.off("add:"+e.id,this._onMaterialAdded,this),this._materialAsset===e.id&&this._bindMaterialAsset(e)},t._bindMaterialAsset=function(e){this._entity.enabled&&(e.on("load",this._onMaterialLoad,this),e.on("change",this._onMaterialChange,this),e.on("remove",this._onMaterialRemove,this),e.resource?this._onMaterialLoad(e):this._system.app.assets.load(e))},t._unbindMaterialAsset=function(e){e.off("load",this._onMaterialLoad,this),e.off("change",this._onMaterialChange,this),e.off("remove",this._onMaterialRemove,this)},t._onMaterialChange=function(){},t._onMaterialRemove=function(){},t._onTextureAdded=function(e){this._system.app.assets.off("add:"+e.id,this._onTextureAdded,this),this._textureAsset===e.id&&this._bindTextureAsset(e)},t._bindTextureAsset=function(e){this._entity.enabled&&(e.on("load",this._onTextureLoad,this),e.on("change",this._onTextureChange,this),e.on("remove",this._onTextureRemove,this),e.resource?this._onTextureLoad(e):this._system.app.assets.load(e))},t._unbindTextureAsset=function(e){e.off("load",this._onTextureLoad,this),e.off("change",this._onTextureChange,this),e.off("remove",this._onTextureRemove,this)},t._onTextureLoad=function(e){this.texture=e.resource},t._onTextureChange=function(e){},t._onTextureRemove=function(e){},t._onSpriteAssetAdded=function(e){this._system.app.assets.off("add:"+e.id,this._onSpriteAssetAdded,this),this._spriteAsset===e.id&&this._bindSpriteAsset(e)},t._bindSpriteAsset=function(e){this._entity.enabled&&(e.on("load",this._onSpriteAssetLoad,this),e.on("change",this._onSpriteAssetChange,this),e.on("remove",this._onSpriteAssetRemove,this),e.resource?this._onSpriteAssetLoad(e):this._system.app.assets.load(e))},t._unbindSpriteAsset=function(e){e.off("load",this._onSpriteAssetLoad,this),e.off("change",this._onSpriteAssetChange,this),e.off("remove",this._onSpriteAssetRemove,this),e.data.textureAtlasAsset&&this._system.app.assets.off("load:"+e.data.textureAtlasAsset,this._onTextureAtlasLoad,this)},t._onSpriteAssetLoad=function(e){if(e&&e.resource)if(e.resource.atlas)this.sprite=e.resource;else{var t=e.data.textureAtlasAsset;if(t){var i=this._system.app.assets;i.off("load:"+t,this._onTextureAtlasLoad,this),i.once("load:"+t,this._onTextureAtlasLoad,this)}}else this.sprite=null},t._onSpriteAssetChange=function(e){this._onSpriteAssetLoad(e)},t._onSpriteAssetRemove=function(e){},t._bindSprite=function(e){e.on("set:meshes",this._onSpriteMeshesChange,this),e.on("set:pixelsPerUnit",this._onSpritePpuChange,this),e.on("set:atlas",this._onAtlasTextureChange,this),e.atlas&&e.atlas.on("set:texture",this._onAtlasTextureChange,this)},t._unbindSprite=function(e){e.off("set:meshes",this._onSpriteMeshesChange,this),e.off("set:pixelsPerUnit",this._onSpritePpuChange,this),e.off("set:atlas",this._onAtlasTextureChange,this),e.atlas&&e.atlas.off("set:texture",this._onAtlasTextureChange,this)},t._onSpriteMeshesChange=function(){this._sprite&&(this._spriteFrame=de.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite()},t._onSpritePpuChange=function(){0!==this.sprite.renderMode&&null===this._pixelsPerUnit&&this._updateSprite()},t._onAtlasTextureChange=function(){this.sprite&&this.sprite.atlas&&this.sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"))},t._onTextureAtlasLoad=function(e){var t=this._spriteAsset;t instanceof ml?this._onSpriteAssetLoad(t):this._onSpriteAssetLoad(this._system.app.assets.get(t))},t.onEnable=function(){if(this._materialAsset){var e=this._system.app.assets.get(this._materialAsset);e&&e.resource!==this._material&&this._bindMaterialAsset(e)}if(this._textureAsset){var t=this._system.app.assets.get(this._textureAsset);t&&t.resource!==this._texture&&this._bindTextureAsset(t)}if(this._spriteAsset){var i=this._system.app.assets.get(this._spriteAsset);i&&i.resource!==this._sprite&&this._bindSpriteAsset(i)}this._element.addModelToLayers(this._renderable.model)},t.onDisable=function(){this._element.removeModelFromLayers(this._renderable.model)},t._setStencil=function(e){this._renderable.meshInstance.stencilFront=e,this._renderable.meshInstance.stencilBack=e;var t=0;if(this._element.maskedBy&&(t=this._element.maskedBy.element._image._maskRef),this._renderable.unmaskMeshInstance){var i=new du({ref:t+1,func:2,zpass:5});this._renderable.unmaskMeshInstance.stencilFront=i,this._renderable.unmaskMeshInstance.stencilBack=i}},$(e,[{key:"color",get:function(){return this._color},set:function(e){var t=e.r,i=e.g,n=e.b;this._color.r===t&&this._color.g===i&&this._color.b===n||(this._color.r=t,this._color.g=i,this._color.b=n,this._colorUniform[0]=t,this._colorUniform[1]=i,this._colorUniform[2]=n,this._renderable.setParameter("material_emissive",this._colorUniform)),this._element&&this._element.fire("set:color",this._color)}},{key:"opacity",get:function(){return this._color.a},set:function(e){e!==this._color.a&&(this._color.a=e,this._renderable.setParameter("material_opacity",e)),this._element&&this._element.fire("set:opacity",e)}},{key:"rect",get:function(){return this._rect},set:function(e){var t,i,n,s;e instanceof Se?(t=e.x,i=e.y,n=e.z,s=e.w):(t=e[0],i=e[1],n=e[2],s=e[3]),t===this._rect.x&&i===this._rect.y&&n===this._rect.z&&s===this._rect.w||(this._rect.set(t,i,n,s),this._renderable.mesh&&(this._element._beingInitialized?this._meshDirty=!0:this._updateMesh(this._renderable.mesh)))}},{key:"material",get:function(){return this._material},set:function(e){if(this._material!==e){if(!e){var t=this._element._isScreenSpace();e=this.mask?t?this._system.defaultScreenSpaceImageMaskMaterial:this._system.defaultImageMaskMaterial:t?this._system.defaultScreenSpaceImageMaterial:this._system.defaultImageMaterial}this._material=e,e&&(this._renderable.setMaterial(e),this._hasUserMaterial()?(this._renderable.deleteParameter("material_opacity"),this._renderable.deleteParameter("material_emissive")):(this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._renderable.setParameter("material_emissive",this._colorUniform),this._renderable.setParameter("material_opacity",this._color.a)))}}},{key:"materialAsset",get:function(){return this._materialAsset},set:function(e){var t=this._system.app.assets,i=e;if(e instanceof ml&&(i=e.id),this._materialAsset!==i){if(this._materialAsset){t.off("add:"+this._materialAsset,this._onMaterialAdded,this);var n=t.get(this._materialAsset);n&&(n.off("load",this._onMaterialLoad,this),n.off("change",this._onMaterialChange,this),n.off("remove",this._onMaterialRemove,this))}if(this._materialAsset=i,this._materialAsset){var s=t.get(this._materialAsset);s?this._bindMaterialAsset(s):(this.material=null,t.on("add:"+this._materialAsset,this._onMaterialAdded,this))}else this.material=null}}},{key:"texture",get:function(){return this._texture},set:function(e){if(this._texture!==e){if(this._textureAsset){var t=this._system.app.assets.get(this._textureAsset);t&&t.resource!==e&&(this.textureAsset=null)}if(this._texture=e,e){this._spriteAsset&&(this.spriteAsset=null),this._renderable.setParameter("texture_emissiveMap",this._texture),this._renderable.setParameter("texture_opacityMap",this._texture),this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._renderable.setParameter("material_emissive",this._colorUniform),this._renderable.setParameter("material_opacity",this._color.a);var i=this._texture.width/this._texture.height;i!==this._targetAspectRatio&&(this._targetAspectRatio=i,this._element.fitMode!==B_&&this.refreshMesh())}else this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"),this._targetAspectRatio=-1,this._element.fitMode!==B_&&this.refreshMesh()}}},{key:"textureAsset",get:function(){return this._textureAsset},set:function(e){var t=this._system.app.assets,i=e;if(e instanceof ml&&(i=e.id),this._textureAsset!==i){if(this._textureAsset){t.off("add:"+this._textureAsset,this._onTextureAdded,this);var n=t.get(this._textureAsset);n&&(n.off("load",this._onTextureLoad,this),n.off("change",this._onTextureChange,this),n.off("remove",this._onTextureRemove,this))}if(this._textureAsset=i,this._textureAsset){var s=t.get(this._textureAsset);s?this._bindTextureAsset(s):(this.texture=null,t.on("add:"+this._textureAsset,this._onTextureAdded,this))}else this.texture=null}}},{key:"spriteAsset",get:function(){return this._spriteAsset},set:function(e){var t=this._system.app.assets,i=e;if(e instanceof ml&&(i=e.id),this._spriteAsset!==i){if(this._spriteAsset){t.off("add:"+this._spriteAsset,this._onSpriteAssetAdded,this);var n=t.get(this._spriteAsset);n&&this._unbindSpriteAsset(n)}if(this._spriteAsset=i,this._spriteAsset){var s=t.get(this._spriteAsset);s?this._bindSpriteAsset(s):(this.sprite=null,t.on("add:"+this._spriteAsset,this._onSpriteAssetAdded,this))}else this.sprite=null}this._element&&this._element.fire("set:spriteAsset",i)}},{key:"sprite",get:function(){return this._sprite},set:function(e){if(this._sprite!==e){if(this._sprite&&this._unbindSprite(this._sprite),this._spriteAsset){var t=this._system.app.assets.get(this._spriteAsset);t&&t.resource!==e&&(this.spriteAsset=null)}this._sprite=e,this._sprite&&(this._bindSprite(this._sprite),this._textureAsset&&(this.textureAsset=null)),this._sprite&&this._sprite.atlas&&this._sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap")),this._sprite&&(this._spriteFrame=de.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite()}}},{key:"spriteFrame",get:function(){return this._spriteFrame},set:function(e){var t=this._spriteFrame;this._sprite?this._spriteFrame=de.clamp(e,0,this._sprite.frameKeys.length-1):this._spriteFrame=e,this._spriteFrame!==t&&this._updateSprite(),this._element&&this._element.fire("set:spriteFrame",e)}},{key:"mesh",get:function(){return this._renderable.mesh},set:function(e){this._renderable.setMesh(e),this._defaultMesh===e?this._renderable.setAabbFunc(null):this._renderable.setAabbFunc(this._updateAabbFunc)}},{key:"mask",get:function(){return this._mask},set:function(e){this._mask!==e&&(this._mask=e,this._toggleMask())}},{key:"pixelsPerUnit",get:function(){return this._pixelsPerUnit},set:function(e){this._pixelsPerUnit!==e&&(this._pixelsPerUnit=e,!this._sprite||1!==this._sprite.renderMode&&2!==this._sprite.renderMode||this._updateSprite())}},{key:"aabb",get:function(){return this._renderable.meshInstance?this._renderable.meshInstance.aabb:null}}]),e}(),Ag=/[A-Z|a-z|0-9|_|-|/]/,Mg=function(){function e(e){this._symbols=e,this._index=0,this._last=0,this._cur=this._symbols.length>0?this._symbols[0]:null,this._buf=[],this._mode="text",this._error=null}var t=e.prototype;return t.read=function(){for(var e=this._read();8===e;)e=this._read();return 0!==e&&1!==e&&(this._last=this._index),e},t.buf=function(){return this._buf},t.last=function(){return this._last},t.error=function(){return this._error},t.debugPrint=function(){for(var e=["EOF","ERROR","TEXT","OPEN_BRACKET","CLOSE_BRACKET","EQUALS","STRING","IDENTIFIER","WHITESPACE"],t=this.read(),i="";i+=(i.length>0?"\n":"")+e[t]+" '"+this.buf().join("")+"'",0!==t&&1!==t;)t=this.read();return i},t._read=function(){return this._buf=[],this._eof()?0:"text"===this._mode?this._text():this._tag()},t._text=function(){for(;;)switch(this._cur){case null:return this._buf.length>0?2:0;case"[":return this._mode="tag",this._buf.length>0?2:this._tag();case"\\":if(this._next(),"["===this._cur)this._store();else this._output("\\");break;default:this._store()}},t._tag=function(){switch(this._cur){case null:return this._error="unexpected end of input reading tag",1;case"[":return this._store(),3;case"]":return this._store(),this._mode="text",4;case"=":return this._store(),5;case" ":case"\t":case"\n":case"\r":case"\v":case"\f":return this._whitespace();case'"':return this._string();default:return this._isIdentifierSymbol(this._cur)?this._identifier():(this._error="unrecognized character",1)}},t._whitespace=function(){for(this._store();-1!==" \t\n\r\v\f".indexOf(this._cur);)this._store();return 8},t._string=function(){for(this._next();;)switch(this._cur){case null:return this._error="unexpected end of input reading string",1;case'"':return this._next(),6;default:this._store()}},t._identifier=function(){for(this._store();null!==this._cur&&this._isIdentifierSymbol(this._cur);)this._store();return 7},t._isIdentifierSymbol=function(e){return 1===e.length&&null!==e.match(Ag)},t._eof=function(){return null===this._cur},t._next=function(){return this._eof()||(this._index++,this._cur=this._index=0;--s)if(n==="/"+t[s].name&&null===t[s].end)return t[s].end=e.length,4===(i=this._scanner.read())||(this._error="expected close bracket",!1);return this._error="failed to find matching tag",!1}var r={name:n,value:null,attributes:{},start:e.length,end:null};if(5===(i=this._scanner.read())){if(6!==(i=this._scanner.read()))return this._error="expected string",!1;r.value=this._scanner.buf().join(""),i=this._scanner.read()}for(;;){switch(i){case 4:return t.push(r),!0;case 7:var a=this._scanner.buf().join("");if(5!==(i=this._scanner.read()))return this._error="expected equals",!1;if(6!==(i=this._scanner.read()))return this._error="expected string",!1;var o=this._scanner.buf().join("");r.attributes[a]=o;break;default:return this._error="expected close bracket or identifier",!1}i=this._scanner.read()}},e}();function Eg(e,t){for(var i in t)if(t.hasOwnProperty(i)){var n=t[i];n instanceof Object?(e.hasOwnProperty(i)||(e[i]={}),Eg(e[i],t[i])):e[i]=n}}function Pg(e){if(0===e.length)return null;for(var t={},i=0;i=1e-4,v=this._element.calculatedWidth;(this.autoWidth&&!g||!this._wrapLines)&&(v=Number.POSITIVE_INFINITY);var y,x,b,S,w=0,T=0;function A(e,i,n){t._lineWidths.push(Math.abs(n));var s=f>i?i+1:f,r=f>i?f+1:i,h=e.slice(s,r);if(_)for(var l=h.length;l--&&_>0;)kg.test(h[l])&&(h.splice(l,1),_--);t._lineContents.push(h.join("")),a=0,o-=t._scaledLineHeight,c++,p=0,m=0,_=0,u=0,f=i}for(var M=!0;M;){M=!1,this._scaledLineHeight=s?this._lineHeight*this._fontSize/(this._maxFontSize||1e-4):this._lineHeight,this.width=0,this.height=0,this._lineWidths=[],this._lineContents=[],a=0,o=0,h=0,l=0,c=1,u=0,d=0,f=0,p=0,m=0,_=0;var C=this._fontSize/32;w=this._fontMinY*C,T=this._fontMaxY*C;for(var E=0;E=r?null:this._symbols[N+1],kg.test(y))_++,(!this._wrapLines||this._maxLines<0||c0){var j=this._font.data.kerning;if(j){var Y=j[q.getCodePoint(this._symbols[N-1])||0];Y&&(X=Y[q.getCodePoint(this._symbols[N])||0]||0)}}W=x.scale||1,G=C*((x.width+x.height)/2)/W,V=(x.xadvance+X)*C,U=(x.xoffset-X)*C,z=x.yoffset*C}else console.error("Couldn't substitute missing character: '"+y+"'");var K=Og.test(y),Z=x&&x.map||0,$=-this._font.data.info.maps[Z].width/this._font.data.info.maps[Z].height,Q=this._meshInfo[Z],J=a+this._spacing*V;if(J>v&&m>0&&!K&&(this._maxLines<0||cthis._element.calculatedWidth&&(ue=Math.floor(this._element.fontSize*this._element.calculatedWidth/(this.width||1e-4)),(ue=de.clamp(ue,i,n))!==this._element.fontSize)){this._fontSize=ue,M=!0;break}if(this.height=Math.max(this.height,T-(o+w)),this._shouldAutoFitHeight()&&this.height>this._element.calculatedHeight&&(ue=de.clamp(this._fontSize-1,i,n))!==this._element.fontSize){this._fontSize=ue,M=!0;break}a+=this._spacing*V,K||(l=a),(this._isWordBoundary(y)||this._isValidNextChar(S)&&(this._isNextCJKBoundary(y,S)||this._isNextCJKWholeWord(S)))&&(p++,u=l,d=N+1),m++;var fe=this._getUv(y);if(Q.uvs[4*b*2+0]=fe[0],Q.uvs[4*b*2+1]=1-fe[1],Q.uvs[4*b*2+2]=fe[2],Q.uvs[4*b*2+3]=1-fe[1],Q.uvs[4*b*2+4]=fe[2],Q.uvs[4*b*2+5]=1-fe[3],Q.uvs[4*b*2+6]=fe[0],Q.uvs[4*b*2+7]=1-fe[3],this._symbolColors){var pe=3*this._symbolColors[N];P=this._colorPalette[pe],R=this._colorPalette[pe+1],I=this._colorPalette[pe+2]}if(Q.colors[4*b*4+0]=P,Q.colors[4*b*4+1]=R,Q.colors[4*b*4+2]=I,Q.colors[4*b*4+3]=255,Q.colors[4*b*4+4]=P,Q.colors[4*b*4+5]=R,Q.colors[4*b*4+6]=I,Q.colors[4*b*4+7]=255,Q.colors[4*b*4+8]=P,Q.colors[4*b*4+9]=R,Q.colors[4*b*4+10]=I,Q.colors[4*b*4+11]=255,Q.colors[4*b*4+12]=P,Q.colors[4*b*4+13]=R,Q.colors[4*b*4+14]=I,Q.colors[4*b*4+15]=255,this._symbolOutlineParams){var me=5*this._symbolOutlineParams[N];L=this._outlinePalette[me]+256*this._outlinePalette[me+1],D=this._outlinePalette[me+2]+256*this._outlinePalette[me+3],k=this._outlinePalette[me+4]}if(Q.outlines[4*b*3+0]=L,Q.outlines[4*b*3+1]=D,Q.outlines[4*b*3+2]=k,Q.outlines[4*b*3+3]=L,Q.outlines[4*b*3+4]=D,Q.outlines[4*b*3+5]=k,Q.outlines[4*b*3+6]=L,Q.outlines[4*b*3+7]=D,Q.outlines[4*b*3+8]=k,Q.outlines[4*b*3+9]=L,Q.outlines[4*b*3+10]=D,Q.outlines[4*b*3+11]=k,this._symbolShadowParams){var _e=6*this._symbolShadowParams[N];O=this._shadowPalette[_e]+256*this._shadowPalette[_e+1],F=this._shadowPalette[_e+2]+256*this._shadowPalette[_e+3],B=this._shadowPalette[_e+4]+127+256*Math.round($*this._shadowPalette[_e+5]+127)}Q.shadows[4*b*3+0]=O,Q.shadows[4*b*3+1]=F,Q.shadows[4*b*3+2]=B,Q.shadows[4*b*3+3]=O,Q.shadows[4*b*3+4]=F,Q.shadows[4*b*3+5]=B,Q.shadows[4*b*3+6]=O,Q.shadows[4*b*3+7]=F,Q.shadows[4*b*3+8]=B,Q.shadows[4*b*3+9]=O,Q.shadows[4*b*3+10]=F,Q.shadows[4*b*3+11]=B,Q.quad++}}M||f=Oe?(Fe.element.POSITION.set(0,0,0),Fe.element.TEXCOORD0.set(0,0),Fe.element.COLOR.set(0,0,0,0),Fe.element.ATTR8.set(0,0,0,0),Fe.element.ATTR9.set(0,0,0,0)):(Fe.element.POSITION.set(this._meshInfo[be].positions[3*Be+0],this._meshInfo[be].positions[3*Be+1],this._meshInfo[be].positions[3*Be+2]),Fe.element.TEXCOORD0.set(this._meshInfo[be].uvs[2*Be+0],this._meshInfo[be].uvs[2*Be+1]),Fe.element.COLOR.set(this._meshInfo[be].colors[4*Be+0],this._meshInfo[be].colors[4*Be+1],this._meshInfo[be].colors[4*Be+2],this._meshInfo[be].colors[4*Be+3]),Fe.element.ATTR8.set(this._meshInfo[be].outlines[3*Be+0],this._meshInfo[be].outlines[3*Be+1],this._meshInfo[be].outlines[3*Be+2]),Fe.element.ATTR9.set(this._meshInfo[be].shadows[3*Be+0],this._meshInfo[be].shadows[3*Be+1],this._meshInfo[be].shadows[3*Be+2])),Fe.next();Fe.end(),this._meshInfo[be].meshInstance.mesh.aabb.compute(this._meshInfo[be].positions),this._meshInfo[be].meshInstance._aabbVer=-1}this._aabbDirty=!0},t._onFontRender=function(){this.font=this._font},t._onFontLoad=function(e){this.font!==e.resource&&(this.font=e.resource)},t._onFontChange=function(e,t,i,n){if("data"===t){this._font.data=i;for(var s=this._font.data.info.maps.length,r=0;rthis._font.textures.length&&(this._meshInfo.length=this._font.textures.length),this._updateText()}}},{key:"alignment",get:function(){return this._alignment},set:function(e){e instanceof be?this._alignment.set(e.x,e.y):this._alignment.set(e[0],e[1]),this._font&&this._updateText()}},{key:"autoWidth",get:function(){return this._autoWidth},set:function(e){var t=this._autoWidth;if(this._autoWidth=e,e&&Math.abs(this._element.anchor.x-this._element.anchor.z)<1e-4&&(this._element.width=this.width),t!==e){var i=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;i!==this._fontSize&&(this._fontSize=i,this._font&&this._updateText())}}},{key:"autoHeight",get:function(){return this._autoHeight},set:function(e){var t=this._autoHeight;if(this._autoHeight=e,e&&Math.abs(this._element.anchor.y-this._element.anchor.w)<1e-4&&(this._element.height=this.height),t!==e){var i=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;i!==this._fontSize&&(this._fontSize=i,this._font&&this._updateText())}}},{key:"rtlReorder",get:function(){return this._rtlReorder},set:function(e){this._rtlReorder!==e&&(this._rtlReorder=e,this._font&&this._updateText())}},{key:"unicodeConverter",get:function(){return this._unicodeConverter},set:function(e){this._unicodeConverter!==e&&(this._unicodeConverter=e,this._setText(this._text))}},{key:"aabb",get:function(){if(this._aabbDirty){for(var e=!1,t=0;t=0&&this.system._prerender.splice(i,1),this.system._prerender.indexOf(e)<0&&this.system._prerender.push(e)}e=t}},i._onPrerender=function(){for(var e=0;e=0)&&(null==(e=this.system.app.batcher)||e.insert(ya.ELEMENT,this.batchGroupId,this.entity));this.fire("enableelement")},i.onDisable=function(){var e;(this.system.app.scene.off("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.off("add",this.onLayerAdded,this),this.system.app.scene.layers.off("remove",this.onLayerRemoved,this)),this._image&&this._image.onDisable(),this._text&&this._text.onDisable(),this._group&&this._group.onDisable(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this._batchGroupId>=0)&&(null==(e=this.system.app.batcher)||e.remove(ya.ELEMENT,this.batchGroupId,this.entity));this.fire("disableelement")},i.onRemove=function(){this.entity.off("insert",this._onInsert,this),this._unpatch(),this._image&&this._image.destroy(),this._text&&this._text.destroy(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this.screen&&this.screen.screen&&(this._unbindScreen(this.screen.screen),this.screen.screen.syncDrawOrder()),this.off()},i._calculateSize=function(e,t){if(this.entity._parent||this.screen){this._calculateLocalAnchors();var i=this._absRight-this._absLeft,n=this._absTop-this._absBottom;e?this._setWidth(i):this._setCalculatedWidth(i,!1),t?this._setHeight(n):this._setCalculatedHeight(n,!1);var s=this.entity.getLocalPosition();s.x=this._margin.x+this._calculatedWidth*this._pivot.x,s.y=this._margin.y+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(s),this._sizeDirty=!1}},i._setWidth=function(e){this._width=e,this._setCalculatedWidth(e,!1),this.fire("set:width",this._width)},i._setHeight=function(e){this._height=e,this._setCalculatedHeight(e,!1),this.fire("set:height",this._height)},i._setCalculatedWidth=function(e,t){if(!(Math.abs(e-this._calculatedWidth)<=1e-4)){if(this._calculatedWidth=e,this.entity._dirtifyLocal(),t){var i=this.entity.getLocalPosition(),n=this._pivot;this._margin.x=i.x-this._calculatedWidth*n.x,this._margin.z=this._localAnchor.z-this._localAnchor.x-this._calculatedWidth-this._margin.x}this._flagChildrenAsDirty(),this.fire("set:calculatedWidth",this._calculatedWidth),this.fire("resize",this._calculatedWidth,this._calculatedHeight)}},i._setCalculatedHeight=function(e,t){if(!(Math.abs(e-this._calculatedHeight)<=1e-4)){if(this._calculatedHeight=e,this.entity._dirtifyLocal(),t){var i=this.entity.getLocalPosition(),n=this._pivot;this._margin.y=i.y-this._calculatedHeight*n.y,this._margin.w=this._localAnchor.w-this._localAnchor.y-this._calculatedHeight-this._margin.y}this._flagChildrenAsDirty(),this.fire("set:calculatedHeight",this._calculatedHeight),this.fire("resize",this._calculatedWidth,this._calculatedHeight)}},i._flagChildrenAsDirty=function(){for(var e=this.entity._children,t=0,i=e.length;t=0&&this._addedModels.splice(t,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(e){var t;e instanceof Se?this._anchor.copy(e):(t=this._anchor).set.apply(t,e);this.entity._parent||this.screen?this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY):this._calculateLocalAnchors(),this._anchorDirty=!0,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:anchor",this._anchor)}},{key:"batchGroupId",get:function(){return this._batchGroupId},set:function(e){if(this._batchGroupId!==e){var t,i;if(this.entity.enabled&&this._batchGroupId>=0)null==(t=this.system.app.batcher)||t.remove(ya.ELEMENT,this.batchGroupId,this.entity);if(this.entity.enabled&&e>=0)null==(i=this.system.app.batcher)||i.insert(ya.ELEMENT,e,this.entity);e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&(this._image&&this._image._renderable.model?this.addModelToLayers(this._image._renderable.model):this._text&&this._text._model&&this.addModelToLayers(this._text._model)),this._batchGroupId=e}}},{key:"bottom",get:function(){return this._margin.y},set:function(e){this._margin.y=e;var t=this.entity.getLocalPosition(),i=this._absTop,n=this._localAnchor.y+e;this._setHeight(i-n),t.y=e+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(t)}},{key:"calculatedWidth",get:function(){return this._calculatedWidth},set:function(e){this._setCalculatedWidth(e,!0)}},{key:"calculatedHeight",get:function(){return this._calculatedHeight},set:function(e){this._setCalculatedHeight(e,!0)}},{key:"canvasCorners",get:function(){if(!this._canvasCornersDirty||!this.screen||!this.screen.screen.screenSpace)return this._canvasCorners;for(var e=this.system.app.graphicsDevice,t=this.screenCorners,i=e.canvas.clientWidth/e.width,n=e.canvas.clientHeight/e.height,s=0;s<4;s++)this._canvasCorners[s].set(t[s].x*i,(e.height-t[s].y)*n);return this._canvasCornersDirty=!1,this._canvasCorners}},{key:"drawOrder",get:function(){return this._drawOrder},set:function(e){var t=0;this.screen&&(t=this.screen.screen.priority),e>16777215&&(e=16777215),this._drawOrder=(t<<24)+e,this.fire("set:draworder",this._drawOrder)}},{key:"height",get:function(){return this._height},set:function(e){this._height=e,this._hasSplitAnchorsY||this._setCalculatedHeight(e,!0),this.fire("set:height",this._height)}},{key:"layers",get:function(){return this._layers},set:function(e){if(this._addedModels.length)for(var t=0;t.001,a=Math.abs(t.anchor.y-t.anchor.w)>.001,o=!1;void 0!==i.margin&&(i.margin instanceof Se?t.margin.copy(i.margin):t._margin.set(i.margin[0],i.margin[1],i.margin[2],i.margin[3]),o=!0),void 0!==i.left&&(t._margin.x=i.left,o=!0),void 0!==i.bottom&&(t._margin.y=i.bottom,o=!0),void 0!==i.right&&(t._margin.z=i.right,o=!0),void 0!==i.top&&(t._margin.w=i.top,o=!0),o&&(t.margin=t._margin);var h=!1;void 0===i.width||r?r&&(h=!0):t.width=i.width,void 0===i.height||a?a&&(h=!0):t.height=i.height,h&&(t.anchor=t.anchor),void 0!==i.enabled&&(t.enabled=i.enabled),void 0!==i.useInput&&(t.useInput=i.useInput),void 0!==i.fitMode&&(t.fitMode=i.fitMode),t.batchGroupId=void 0===i.batchGroupId||null===i.batchGroupId?-1:i.batchGroupId,i.layers&&Array.isArray(i.layers)&&(t.layers=i.layers.slice(0)),void 0!==i.type&&(t.type=i.type),t.type===O_?(void 0!==i.rect&&(t.rect=i.rect),void 0!==i.color&&((s=i.color)instanceof me||(s=new me(i.color[0],i.color[1],i.color[2])),t.color=s),void 0!==i.opacity&&(t.opacity=i.opacity),void 0!==i.textureAsset&&(t.textureAsset=i.textureAsset),i.texture&&(t.texture=i.texture),void 0!==i.spriteAsset&&(t.spriteAsset=i.spriteAsset),i.sprite&&(t.sprite=i.sprite),void 0!==i.spriteFrame&&(t.spriteFrame=i.spriteFrame),void 0!==i.pixelsPerUnit&&null!==i.pixelsPerUnit&&(t.pixelsPerUnit=i.pixelsPerUnit),void 0!==i.materialAsset&&(t.materialAsset=i.materialAsset),i.material&&(t.material=i.material),void 0!==i.mask&&(t.mask=i.mask)):t.type===F_&&(void 0!==i.autoWidth&&(t.autoWidth=i.autoWidth),void 0!==i.autoHeight&&(t.autoHeight=i.autoHeight),void 0!==i.rtlReorder&&(t.rtlReorder=i.rtlReorder),void 0!==i.unicodeConverter&&(t.unicodeConverter=i.unicodeConverter),null!==i.text&&void 0!==i.text?t.text=i.text:null!==i.key&&void 0!==i.key&&(t.key=i.key),void 0!==i.color&&((s=i.color)instanceof me||(s=new me(s[0],s[1],s[2])),t.color=s),void 0!==i.opacity&&(t.opacity=i.opacity),void 0!==i.spacing&&(t.spacing=i.spacing),void 0!==i.fontSize&&(t.fontSize=i.fontSize,i.lineHeight||(t.lineHeight=i.fontSize)),void 0!==i.lineHeight&&(t.lineHeight=i.lineHeight),void 0!==i.maxLines&&(t.maxLines=i.maxLines),void 0!==i.wrapLines&&(t.wrapLines=i.wrapLines),void 0!==i.minFontSize&&(t.minFontSize=i.minFontSize),void 0!==i.maxFontSize&&(t.maxFontSize=i.maxFontSize),i.autoFitWidth&&(t.autoFitWidth=i.autoFitWidth),i.autoFitHeight&&(t.autoFitHeight=i.autoFitHeight),void 0!==i.fontAsset&&(t.fontAsset=i.fontAsset),void 0!==i.font&&(t.font=i.font),void 0!==i.alignment&&(t.alignment=i.alignment),void 0!==i.outlineColor&&(t.outlineColor=i.outlineColor),void 0!==i.outlineThickness&&(t.outlineThickness=i.outlineThickness),void 0!==i.shadowColor&&(t.shadowColor=i.shadowColor),void 0!==i.shadowOffset&&(t.shadowOffset=i.shadowOffset),void 0!==i.enableMarkup&&(t.enableMarkup=i.enableMarkup));var l=t._parseUpToScreen();l.screen&&t._updateScreen(l.screen),e.prototype.initializeComponentData.call(this,t,i,n),t._beingInitialized=!1,t.type===O_&&t._image._meshDirty&&t._image._updateMesh(t._image.mesh)},i.onRemoveComponent=function(e,t){t.onRemove()},i.cloneComponent=function(e,t){var i=e.element,n={enabled:i.enabled,width:i.width,height:i.height,anchor:i.anchor.clone(),pivot:i.pivot.clone(),margin:i.margin.clone(),alignment:i.alignment&&i.alignment.clone()||i.alignment,autoWidth:i.autoWidth,autoHeight:i.autoHeight,type:i.type,rect:i.rect&&i.rect.clone()||i.rect,rtlReorder:i.rtlReorder,unicodeConverter:i.unicodeConverter,materialAsset:i.materialAsset,material:i.material,color:i.color&&i.color.clone()||i.color,opacity:i.opacity,textureAsset:i.textureAsset,texture:i.texture,spriteAsset:i.spriteAsset,sprite:i.sprite,spriteFrame:i.spriteFrame,pixelsPerUnit:i.pixelsPerUnit,spacing:i.spacing,lineHeight:i.lineHeight,wrapLines:i.wrapLines,layers:i.layers,fontSize:i.fontSize,minFontSize:i.minFontSize,maxFontSize:i.maxFontSize,autoFitWidth:i.autoFitWidth,autoFitHeight:i.autoFitHeight,maxLines:i.maxLines,fontAsset:i.fontAsset,font:i.font,useInput:i.useInput,fitMode:i.fitMode,batchGroupId:i.batchGroupId,mask:i.mask,outlineColor:i.outlineColor&&i.outlineColor.clone()||i.outlineColor,outlineThickness:i.outlineThickness,shadowColor:i.shadowColor&&i.shadowColor.clone()||i.shadowColor,shadowOffset:i.shadowOffset&&i.shadowOffset.clone()||i.shadowOffset,enableMarkup:i.enableMarkup};return void 0!==i.key&&null!==i.key?n.key=i.key:n.text=i.text,this.addComponent(t,n)},i.getTextElementMaterial=function(e,t,i){var n=(e&&1)|(t&&2)|(i&&4),s=this._defaultTextMaterials[n];if(s)return s;var r="TextMaterial";return s=new Zs,t?(s.msdfMap=this._defaultTexture,s.msdfTextAttribute=i,s.emissive.set(1,1,1)):(r="Bitmap"+r,s.emissive.set(.5,.5,.5),s.emissiveMap=this._defaultTexture,s.emissiveTint=!0,s.opacityMap=this._defaultTexture,s.opacityMapChannel="a"),e&&(r="ScreenSpace"+r,s.depthTest=!1),s.name="default"+r,s.useLighting=!1,s.useGammaTonemap=!1,s.useFog=!1,s.useSkybox=!1,s.diffuse.set(0,0,0),s.opacity=.5,s.blendType=4,s.depthWrite=!1,s.emissiveVertexColor=!0,s.update(),this._defaultTextMaterials[n]=s,s},i._createBaseImageMaterial=function(){var e=new Zs;return e.diffuse.set(0,0,0),e.emissive.set(.5,.5,.5),e.emissiveMap=this._defaultTexture,e.emissiveTint=!0,e.opacityMap=this._defaultTexture,e.opacityMapChannel="a",e.opacityTint=!0,e.opacity=0,e.useLighting=!1,e.useGammaTonemap=!1,e.useFog=!1,e.useSkybox=!1,e.blendType=4,e.depthWrite=!1,e},i.getImageElementMaterial=function(e,t,i,n){return e?t?i?(this.defaultScreenSpaceImageMask9SlicedMaterial||(this.defaultScreenSpaceImageMask9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMask9SlicedMaterial.name="defaultScreenSpaceImageMask9SlicedMaterial",this.defaultScreenSpaceImageMask9SlicedMaterial.nineSlicedMode=1,this.defaultScreenSpaceImageMask9SlicedMaterial.depthTest=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9SlicedMaterial.redWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.greenWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.blueWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9SlicedMaterial)),this.defaultScreenSpaceImageMask9SlicedMaterial):n?(this.defaultScreenSpaceImageMask9TiledMaterial||(this.defaultScreenSpaceImageMask9TiledMaterial=this.defaultScreenSpaceImage9TiledMaterial.clone(),this.defaultScreenSpaceImageMask9TiledMaterial.name="defaultScreenSpaceImageMask9TiledMaterial",this.defaultScreenSpaceImageMask9TiledMaterial.nineSlicedMode=2,this.defaultScreenSpaceImageMask9TiledMaterial.depthTest=!1,this.defaultScreenSpaceImageMask9TiledMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9TiledMaterial.redWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.greenWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.blueWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9TiledMaterial)),this.defaultScreenSpaceImageMask9TiledMaterial):(this.defaultScreenSpaceImageMaskMaterial||(this.defaultScreenSpaceImageMaskMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaskMaterial.name="defaultScreenSpaceImageMaskMaterial",this.defaultScreenSpaceImageMaskMaterial.depthTest=!1,this.defaultScreenSpaceImageMaskMaterial.alphaTest=1,this.defaultScreenSpaceImageMaskMaterial.redWrite=!1,this.defaultScreenSpaceImageMaskMaterial.greenWrite=!1,this.defaultScreenSpaceImageMaskMaterial.blueWrite=!1,this.defaultScreenSpaceImageMaskMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaskMaterial)),this.defaultScreenSpaceImageMaskMaterial):i?(this.defaultScreenSpaceImage9SlicedMaterial||(this.defaultScreenSpaceImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9SlicedMaterial.name="defaultScreenSpaceImage9SlicedMaterial",this.defaultScreenSpaceImage9SlicedMaterial.nineSlicedMode=1,this.defaultScreenSpaceImage9SlicedMaterial.depthTest=!1,this.defaultScreenSpaceImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9SlicedMaterial)),this.defaultScreenSpaceImage9SlicedMaterial):n?(this.defaultScreenSpaceImage9TiledMaterial||(this.defaultScreenSpaceImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9TiledMaterial.name="defaultScreenSpaceImage9TiledMaterial",this.defaultScreenSpaceImage9TiledMaterial.nineSlicedMode=2,this.defaultScreenSpaceImage9TiledMaterial.depthTest=!1,this.defaultScreenSpaceImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9TiledMaterial)),this.defaultScreenSpaceImage9TiledMaterial):(this.defaultScreenSpaceImageMaterial||(this.defaultScreenSpaceImageMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaterial.name="defaultScreenSpaceImageMaterial",this.defaultScreenSpaceImageMaterial.depthTest=!1,this.defaultScreenSpaceImageMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaterial)),this.defaultScreenSpaceImageMaterial):t?i?(this.defaultImage9SlicedMaskMaterial||(this.defaultImage9SlicedMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaskMaterial.name="defaultImage9SlicedMaskMaterial",this.defaultImage9SlicedMaskMaterial.nineSlicedMode=1,this.defaultImage9SlicedMaskMaterial.alphaTest=1,this.defaultImage9SlicedMaskMaterial.redWrite=!1,this.defaultImage9SlicedMaskMaterial.greenWrite=!1,this.defaultImage9SlicedMaskMaterial.blueWrite=!1,this.defaultImage9SlicedMaskMaterial.alphaWrite=!1,this.defaultImage9SlicedMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaskMaterial)),this.defaultImage9SlicedMaskMaterial):n?(this.defaultImage9TiledMaskMaterial||(this.defaultImage9TiledMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaskMaterial.name="defaultImage9TiledMaskMaterial",this.defaultImage9TiledMaskMaterial.nineSlicedMode=2,this.defaultImage9TiledMaskMaterial.alphaTest=1,this.defaultImage9TiledMaskMaterial.redWrite=!1,this.defaultImage9TiledMaskMaterial.greenWrite=!1,this.defaultImage9TiledMaskMaterial.blueWrite=!1,this.defaultImage9TiledMaskMaterial.alphaWrite=!1,this.defaultImage9TiledMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaskMaterial)),this.defaultImage9TiledMaskMaterial):(this.defaultImageMaskMaterial||(this.defaultImageMaskMaterial=this._createBaseImageMaterial(),this.defaultImageMaskMaterial.name="defaultImageMaskMaterial",this.defaultImageMaskMaterial.alphaTest=1,this.defaultImageMaskMaterial.redWrite=!1,this.defaultImageMaskMaterial.greenWrite=!1,this.defaultImageMaskMaterial.blueWrite=!1,this.defaultImageMaskMaterial.alphaWrite=!1,this.defaultImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaskMaterial)),this.defaultImageMaskMaterial):i?(this.defaultImage9SlicedMaterial||(this.defaultImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaterial.name="defaultImage9SlicedMaterial",this.defaultImage9SlicedMaterial.nineSlicedMode=1,this.defaultImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaterial)),this.defaultImage9SlicedMaterial):n?(this.defaultImage9TiledMaterial||(this.defaultImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaterial.name="defaultImage9TiledMaterial",this.defaultImage9TiledMaterial.nineSlicedMode=2,this.defaultImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaterial)),this.defaultImage9TiledMaterial):(this.defaultImageMaterial||(this.defaultImageMaterial=this._createBaseImageMaterial(),this.defaultImageMaterial.name="defaultImageMaterial",this.defaultImageMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaterial)),this.defaultImageMaterial)},i.registerUnicodeConverter=function(e){this._unicodeConverter=e},i.registerRtlReorder=function(e){this._rtlReorder=e},i.getUnicodeConverter=function(){return this._unicodeConverter},i.getRtlReorder=function(){return this._rtlReorder},t}(h_);Cl._buildAccessors(Jg.prototype,iv);var sv="free",rv="limited",av="locked",ov=["angularDampingX","angularDampingY","angularDampingZ","angularEquilibriumX","angularEquilibriumY","angularEquilibriumZ","angularLimitsX","angularLimitsY","angularLimitsZ","angularMotionX","angularMotionY","angularMotionZ","angularSpringX","angularSpringY","angularSpringZ","angularStiffnessX","angularStiffnessY","angularStiffnessZ","breakForce","enableCollision","enabled","entityA","entityB","linearDampingX","linearDampingY","linearDampingZ","linearEquilibriumX","linearEquilibriumY","linearEquilibriumZ","linearLimitsX","linearLimitsY","linearLimitsZ","linearMotionX","linearMotionY","linearMotionZ","linearSpringX","linearSpringY","linearSpringZ","linearStiffnessX","linearStiffnessY","linearStiffnessZ"],hv=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._constraint=null,n._entityA=null,n._entityB=null,n._breakForce=34e37,n._enableCollision=!0,n._linearMotionX=av,n._linearLimitsX=new be(0,0),n._linearSpringX=!1,n._linearStiffnessX=0,n._linearDampingX=1,n._linearEquilibriumX=0,n._linearMotionY=av,n._linearLimitsY=new be(0,0),n._linearSpringY=!1,n._linearStiffnessY=0,n._linearDampingY=1,n._linearEquilibriumY=0,n._linearMotionZ=av,n._linearLimitsZ=new be(0,0),n._linearSpringZ=!1,n._linearStiffnessZ=0,n._linearDampingZ=1,n._linearEquilibriumZ=0,n._angularMotionX=av,n._angularLimitsX=new be(0,0),n._angularSpringX=!1,n._angularStiffnessX=0,n._angularDampingX=1,n._angularEquilibriumX=0,n._angularMotionY=av,n._angularLimitsY=new be(0,0),n._angularSpringY=!1,n._angularStiffnessY=0,n._angularDampingY=1,n._angularEquilibriumY=0,n._angularMotionZ=av,n._angularLimitsZ=new be(0,0),n._angularSpringZ=!1,n._angularEquilibriumZ=0,n._angularDampingZ=1,n._angularStiffnessZ=0,n.on("set_enabled",n._onSetEnabled,te(n)),n}J(t,e);var i=t.prototype;return i._convertTransform=function(e,t){var i=e.getTranslation(),n=new Pe;n.setFromMat4(e);var s=new Ammo.btVector3(i.x,i.y,i.z),r=new Ammo.btQuaternion(n.x,n.y,n.z,n.w);t.setOrigin(s),t.setRotation(r),Ammo.destroy(s),Ammo.destroy(r)},i._updateAngularLimits=function(){var e=this._constraint;if(e){var t,i,n,s,r,a;this._angularMotionX===rv?(t=this._angularLimitsX.x*de.DEG_TO_RAD,s=this._angularLimitsX.y*de.DEG_TO_RAD):this._angularMotionX===sv?(t=1,s=0):t=s=0,this._angularMotionY===rv?(i=this._angularLimitsY.x*de.DEG_TO_RAD,r=this._angularLimitsY.y*de.DEG_TO_RAD):this._angularMotionY===sv?(i=1,r=0):i=r=0,this._angularMotionZ===rv?(n=this._angularLimitsZ.x*de.DEG_TO_RAD,a=this._angularLimitsZ.y*de.DEG_TO_RAD):this._angularMotionZ===sv?(n=1,a=0):n=a=0;var o=new Ammo.btVector3(t,i,n);e.setAngularLowerLimit(o),o.setValue(s,r,a),e.setAngularUpperLimit(o),Ammo.destroy(o)}},i._updateLinearLimits=function(){var e=this._constraint;if(e){var t,i,n,s,r,a;this._linearMotionX===rv?(t=this._linearLimitsX.x,s=this._linearLimitsX.y):this._linearMotionX===sv?(t=1,s=0):t=s=0,this._linearMotionY===rv?(i=this._linearLimitsY.x,r=this._linearLimitsY.y):this._linearMotionY===sv?(i=1,r=0):i=r=0,this._linearMotionZ===rv?(n=this._linearLimitsZ.x,a=this._linearLimitsZ.y):this._linearMotionZ===sv?(n=1,a=0):n=a=0;var o=new Ammo.btVector3(t,i,n);e.setLinearLowerLimit(o),o.setValue(s,r,a),e.setLinearUpperLimit(o),Ammo.destroy(o)}},i._createConstraint=function(){if(this._entityA&&this._entityA.rigidbody){this._destroyConstraint();var e=new Ee,t=this._entityA.rigidbody.body;t.activate();var i=this.entity.getWorldTransform(),n=this._entityA.getWorldTransform().clone().invert();e.mul2(n,i);var s=new Ammo.btTransform;if(this._convertTransform(e,s),this._entityB&&this._entityB.rigidbody){var r=this._entityB.rigidbody.body;r.activate();var a=this._entityB.getWorldTransform().clone().invert();e.mul2(a,i);var o=new Ammo.btTransform;this._convertTransform(e,o),this._constraint=new Ammo.btGeneric6DofSpringConstraint(t,r,s,o,!this._enableCollision),Ammo.destroy(o)}else this._constraint=new Ammo.btGeneric6DofSpringConstraint(t,s,!this._enableCollision);Ammo.destroy(s);for(var h=["X","Y","Z","X","Y","Z"],l=0;l<6;l++){var c=l<3?"_linear":"_angular";this._constraint.enableSpring(l,this[c+"Spring"+h[l]]),this._constraint.setDamping(l,this[c+"Damping"+h[l]]),this._constraint.setEquilibriumPoint(l,this[c+"Equilibrium"+h[l]]),this._constraint.setStiffness(l,this[c+"Stiffness"+h[l]])}this._constraint.setBreakingImpulseThreshold(this._breakForce),this._updateLinearLimits(),this._updateAngularLimits(),this.system.app.systems.rigidbody.dynamicsWorld.addConstraint(this._constraint,!this._enableCollision)}},i._destroyConstraint=function(){this._constraint&&(this.system.app.systems.rigidbody.dynamicsWorld.removeConstraint(this._constraint),Ammo.destroy(this._constraint),this._constraint=null)},i.initFromData=function(e){for(var t,i=ne(ov);!(t=i()).done;){var n=t.value;e.hasOwnProperty(n)&&(e[n]instanceof be?this["_"+n].copy(e[n]):this["_"+n]=e[n])}this._createConstraint()},i.onEnable=function(){this._createConstraint()},i.onDisable=function(){this._destroyConstraint()},i._onSetEnabled=function(e,t,i){},i._onBeforeRemove=function(){this.fire("remove")},$(t,[{key:"entityA",get:function(){return this._entityA},set:function(e){this._destroyConstraint(),this._entityA=e,this._createConstraint()}},{key:"entityB",get:function(){return this._entityB},set:function(e){this._destroyConstraint(),this._entityB=e,this._createConstraint()}},{key:"breakForce",get:function(){return this._breakForce},set:function(e){this._constraint&&this._breakForce!==e&&(this._constraint.setBreakingImpulseThreshold(e),this._breakForce=e)}},{key:"enableCollision",get:function(){return this._enableCollision},set:function(e){this._destroyConstraint(),this._enableCollision=e,this._createConstraint()}},{key:"angularLimitsX",get:function(){return this._angularLimitsX},set:function(e){this._angularLimitsX.equals(e)||(this._angularLimitsX.copy(e),this._updateAngularLimits())}},{key:"angularMotionX",get:function(){return this._angularMotionX},set:function(e){this._angularMotionX!==e&&(this._angularMotionX=e,this._updateAngularLimits())}},{key:"angularLimitsY",get:function(){return this._angularLimitsY},set:function(e){this._angularLimitsY.equals(e)||(this._angularLimitsY.copy(e),this._updateAngularLimits())}},{key:"angularMotionY",get:function(){return this._angularMotionY},set:function(e){this._angularMotionY!==e&&(this._angularMotionY=e,this._updateAngularLimits())}},{key:"angularLimitsZ",get:function(){return this._angularLimitsZ},set:function(e){this._angularLimitsZ.equals(e)||(this._angularLimitsZ.copy(e),this._updateAngularLimits())}},{key:"angularMotionZ",get:function(){return this._angularMotionZ},set:function(e){this._angularMotionZ!==e&&(this._angularMotionZ=e,this._updateAngularLimits())}},{key:"linearLimitsX",get:function(){return this._linearLimitsX},set:function(e){this._linearLimitsX.equals(e)||(this._linearLimitsX.copy(e),this._updateLinearLimits())}},{key:"linearMotionX",get:function(){return this._linearMotionX},set:function(e){this._linearMotionX!==e&&(this._linearMotionX=e,this._updateLinearLimits())}},{key:"linearLimitsY",get:function(){return this._linearLimitsY},set:function(e){this._linearLimitsY.equals(e)||(this._linearLimitsY.copy(e),this._updateLinearLimits())}},{key:"linearMotionY",get:function(){return this._linearMotionY},set:function(e){this._linearMotionY!==e&&(this._linearMotionY=e,this._updateLinearLimits())}},{key:"linearLimitsZ",get:function(){return this._linearLimitsZ},set:function(e){this._linearLimitsZ.equals(e)||(this._linearLimitsZ.copy(e),this._updateLinearLimits())}},{key:"linearMotionZ",get:function(){return this._linearMotionZ},set:function(e){this._linearMotionZ!==e&&(this._linearMotionZ=e,this._updateLinearLimits())}}]),t}(Cl),lv={Damping:"setDamping",Equilibrium:"setEquilibriumPoint",Spring:"enableSpring",Stiffness:"setStiffness"};["linear","angular"].forEach((function(e){["Damping","Equilibrium","Spring","Stiffness"].forEach((function(t){["X","Y","Z"].forEach((function(i){var n=e+t+i,s="_"+n,r="linear"===e?0:3;"Y"===i&&(r+=1),"Z"===i&&(r+=2),Object.defineProperty(hv.prototype,n,{get:function(){return this[s]},set:function(e){this[s]!==e&&(this[s]=e,this._constraint[lv[t]](r,e))}})}))}))}));var cv=function(){this.enabled=!0},uv=["enabled"],dv=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="joint",i.app=t,i.ComponentType=hv,i.DataType=cv,i.schema=uv,i}return J(t,e),t.prototype.initializeComponentData=function(e,t,i){e.initFromData(t)},t}(h_);Cl._buildAccessors(hv.prototype,uv);var fv=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._minWidth=0,n._minHeight=0,n._maxWidth=null,n._maxHeight=null,n._fitWidthProportion=0,n._fitHeightProportion=0,n._excludeFromLayout=!1,n}return J(t,e),$(t,[{key:"minWidth",get:function(){return this._minWidth},set:function(e){e!==this._minWidth&&(this._minWidth=e,this.fire("resize"))}},{key:"minHeight",get:function(){return this._minHeight},set:function(e){e!==this._minHeight&&(this._minHeight=e,this.fire("resize"))}},{key:"maxWidth",get:function(){return this._maxWidth},set:function(e){e!==this._maxWidth&&(this._maxWidth=e,this.fire("resize"))}},{key:"maxHeight",get:function(){return this._maxHeight},set:function(e){e!==this._maxHeight&&(this._maxHeight=e,this.fire("resize"))}},{key:"fitWidthProportion",get:function(){return this._fitWidthProportion},set:function(e){e!==this._fitWidthProportion&&(this._fitWidthProportion=e,this.fire("resize"))}},{key:"fitHeightProportion",get:function(){return this._fitHeightProportion},set:function(e){e!==this._fitHeightProportion&&(this._fitHeightProportion=e,this.fire("resize"))}},{key:"excludeFromLayout",get:function(){return this._excludeFromLayout},set:function(e){e!==this._excludeFromLayout&&(this._excludeFromLayout=e,this.fire("resize"))}}]),t}(Cl),pv=function(){this.enabled=!0},mv=["enabled"],_v=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="layoutchild",i.ComponentType=fv,i.DataType=pv,i.schema=mv,i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){void 0!==i.enabled&&(t.enabled=i.enabled),void 0!==i.minWidth&&(t.minWidth=i.minWidth),void 0!==i.minHeight&&(t.minHeight=i.minHeight),void 0!==i.maxWidth&&(t.maxWidth=i.maxWidth),void 0!==i.maxHeight&&(t.maxHeight=i.maxHeight),void 0!==i.fitWidthProportion&&(t.fitWidthProportion=i.fitWidthProportion),void 0!==i.fitHeightProportion&&(t.fitHeightProportion=i.fitHeightProportion),void 0!==i.excludeFromLayout&&(t.excludeFromLayout=i.excludeFromLayout),e.prototype.initializeComponentData.call(this,t,i,n)},i.cloneComponent=function(e,t){var i=e.layoutchild;return this.addComponent(t,{enabled:i.enabled,minWidth:i.minWidth,minHeight:i.minHeight,maxWidth:i.maxWidth,maxHeight:i.maxHeight,fitWidthProportion:i.fitWidthProportion,fitHeightProportion:i.fitHeightProportion,excludeFromLayout:i.excludeFromLayout})},t}(h_);Cl._buildAccessors(fv.prototype,mv);var gv={0:{axis:"x",size:"width",calculatedSize:"calculatedWidth",minSize:"minWidth",maxSize:"maxWidth",fitting:"widthFitting",fittingProportion:"fitWidthProportion"},1:{axis:"y",size:"height",calculatedSize:"calculatedHeight",minSize:"minHeight",maxSize:"maxHeight",fitting:"heightFitting",fittingProportion:"fitHeightProportion"}},vv={0:1,1:0},yv={minWidth:0,minHeight:0,maxWidth:Number.POSITIVE_INFINITY,maxHeight:Number.POSITIVE_INFINITY,width:null,height:null,fitWidthProportion:0,fitHeightProportion:0},xv="NONE",bv="APPLY_STRETCHING",Sv="APPLY_SHRINKING",wv=new be;function Tv(e){var t,i=gv[e],n=gv[vv[e]];function s(e,t){return-t[i.size]*e.pivot[i.axis]}function r(e,t){return-t[n.size]*e.pivot[n.axis]}function a(e,t){return t[i.size]*(1-e.pivot[i.axis])}function o(e){var t=e.entity.layoutchild;return!t||!t.enabled||!t.excludeFromLayout}function h(e,t,i){switch(e){case 0:return xv;case 1:return t=i?Sv:xv;case 3:return t=0;--n)i[t[n]]=i[t[n+1]]+e[t[n]];return i}return function(e,d){e=e.filter(o),t=d,wv.x=t.containerSize.x-t.padding.x-t.padding.z,wv.y=t.containerSize.y-t.padding.y-t.padding.w,function(e){for(var t=0;t0&&(r+=t.spacing[i.axis]);var h=s[o][i.size];r+=h,!a&&r>wv[i.axis]&&0!==n[n.length-1].length&&(r=h,n.push([])),n[n.length-1].push(e[o]),a&&r>wv[i.axis]&&o!==e.length-1&&(r=0,n.push([]))}return n}(e)),m=function(e,i){for(var s=[],r=[],a=0;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(t[n.fitting],p,wv[n.axis]);m===bv?c(r,p,n):m===Sv&&u(r,p,n);for(var _=0;_0;){var t=this._reflowQueue.slice();this._reflowQueue.length=0,t.sort((function(e,t){return e.entity.graphDepth-t.entity.graphDepth}));for(var i=0;i=100){console.warn("Max reflow iterations limit reached, bailing.");break}}},i._onRemoveComponent=function(e,t){t.onRemove()},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("postUpdate",this._onPostUpdate,this)},t}(h_);Cl._buildAccessors(Pv.prototype,Iv);var Dv=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._type="asset",n._asset=null,n._model=null,n._mapping={},n._castShadows=!0,n._receiveShadows=!0,n._materialAsset=null,n._material=void 0,n._castShadowsLightmap=!0,n._lightmapped=!1,n._lightmapSizeMultiplier=1,n._isStatic=!1,n._layers=[0],n._batchGroupId=-1,n._customAabb=null,n._area=null,n._materialEvents=null,n._clonedModel=!1,n._material=t.defaultMaterial,i.on("remove",n.onRemoveChild,te(n)),i.on("removehierarchy",n.onRemoveChild,te(n)),i.on("insert",n.onInsertChild,te(n)),i.on("inserthierarchy",n.onInsertChild,te(n)),n}J(t,e);var i=t.prototype;return i.addModelToLayers=function(){for(var e=this.system.app.scene.layers,t=0;t=0&&(null==(n=e.batcher)||n.insert(ya.MODEL,this.batchGroupId,this.entity))},i.onDisable=function(){var e,t=this.system.app,i=t.scene;(i.off("set:layers",this.onLayersChanged,this),i.layers&&(i.layers.off("add",this.onLayerAdded,this),i.layers.off("remove",this.onLayerRemoved,this)),this._batchGroupId>=0)&&(null==(e=t.batcher)||e.remove(ya.MODEL,this.batchGroupId,this.entity));this._model&&this.removeModelFromLayers()},i.hide=function(){if(this._model)for(var e=this._model.meshInstances,t=0,i=e.length;t=0)null==(t=this.system.app.batcher)||t.remove(ya.MODEL,this.batchGroupId,this.entity);if(this.entity.enabled&&e>=0)null==(i=this.system.app.batcher)||i.insert(ya.MODEL,e,this.entity);e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addModelToLayers(),this._batchGroupId=e}}},{key:"materialAsset",get:function(){return this._materialAsset},set:function(e){var t=e;e instanceof ml&&(t=e.id);var i=this.system.app.assets;if(t!==this._materialAsset){if(this._materialAsset){i.off("add:"+this._materialAsset,this._onMaterialAssetAdd,this);var n=i.get(this._materialAsset);n&&this._unbindMaterialAsset(n)}if(this._materialAsset=t,this._materialAsset){var s=i.get(this._materialAsset);s?this._bindMaterialAsset(s):(this._setMaterial(this.system.defaultMaterial),i.on("add:"+this._materialAsset,this._onMaterialAssetAdd,this))}else this._setMaterial(this.system.defaultMaterial)}}},{key:"material",get:function(){return this._material},set:function(e){this._material!==e&&(this.materialAsset=null,this._setMaterial(e))}},{key:"mapping",get:function(){return this._mapping},set:function(e){if("asset"===this._type&&(this._unsetMaterialEvents(),e||(e={}),this._mapping=e,this._model))for(var t=this._model.meshInstances,i=this.asset?this.system.app.assets.get(this.asset):null,n=i?i.data.mapping:null,s=null,r=0,a=t.length;r=0))continue;n=this.system.app.assets.get(n)}n&&!n.resource&&this.system.app.assets.load(n)}}if(!this.emitter){var s=e.mesh;s instanceof ea||(s=null),this.emitter=new su(this.system.app.graphicsDevice,{numParticles:e.numParticles,emitterExtents:e.emitterExtents,emitterExtentsInner:e.emitterExtentsInner,emitterRadius:e.emitterRadius,emitterRadiusInner:e.emitterRadiusInner,emitterShape:e.emitterShape,initialVelocity:e.initialVelocity,wrap:e.wrap,localSpace:e.localSpace,screenSpace:e.screenSpace,wrapBounds:e.wrapBounds,lifetime:e.lifetime,rate:e.rate,rate2:e.rate2,orientation:e.orientation,particleNormal:e.particleNormal,animTilesX:e.animTilesX,animTilesY:e.animTilesY,animStartFrame:e.animStartFrame,animNumFrames:e.animNumFrames,animNumAnimations:e.animNumAnimations,animIndex:e.animIndex,randomizeAnimIndex:e.randomizeAnimIndex,animSpeed:e.animSpeed,animLoop:e.animLoop,startAngle:e.startAngle,startAngle2:e.startAngle2,scaleGraph:e.scaleGraph,scaleGraph2:e.scaleGraph2,colorGraph:e.colorGraph,colorGraph2:e.colorGraph2,alphaGraph:e.alphaGraph,alphaGraph2:e.alphaGraph2,localVelocityGraph:e.localVelocityGraph,localVelocityGraph2:e.localVelocityGraph2,velocityGraph:e.velocityGraph,velocityGraph2:e.velocityGraph2,rotationSpeedGraph:e.rotationSpeedGraph,rotationSpeedGraph2:e.rotationSpeedGraph2,radialSpeedGraph:e.radialSpeedGraph,radialSpeedGraph2:e.radialSpeedGraph2,colorMap:e.colorMap,normalMap:e.normalMap,loop:e.loop,preWarm:e.preWarm,sort:e.sort,stretch:e.stretch,alignToMotion:e.alignToMotion,lighting:e.lighting,halfLambert:e.halfLambert,intensity:e.intensity,depthSoftening:e.depthSoftening,scene:this.system.app.scene,mesh:s,depthWrite:e.depthWrite,noFog:e.noFog,node:this.entity,blendType:e.blendType}),this.emitter.meshInstance.node=this.entity,this.emitter.drawOrder=this.drawOrder,e.autoPlay||(this.pause(),this.emitter.meshInstance.visible=!1)}this.emitter.colorMap&&this.addMeshInstanceToLayers(),this.system.app.scene.on("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.on("add",this.onLayerAdded,this),this.system.app.scene.layers.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&e.depthSoftening&&this._requestDepth()},i.onDisable=function(){this.system.app.scene.off("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.off("add",this.onLayerAdded,this),this.system.app.scene.layers.off("remove",this.onLayerRemoved,this)),this.emitter&&(this.removeMeshInstanceFromLayers(),this.data.depthSoftening&&this._releaseDepth(),this.emitter.camera=null)},i.onBeforeRemove=function(){this.enabled&&(this.enabled=!1),this.emitter&&(this.emitter.destroy(),this.emitter=null);for(var e=0;eh.fixedTimeStep&&(t=Math.floor(h.simTime/h.fixedTimeStep),h.simTime-=t*h.fixedTimeStep),t){t=Math.min(t,h.maxSubSteps);for(var v=0;v=0&&(null==(i=e.batcher)||i.insert(ya.RENDER,this.batchGroupId,this.entity))},i.onDisable=function(){var e,t=this.system.app,i=t.scene;(i.off("set:layers",this.onLayersChanged,this),i.layers&&(i.layers.off("add",this.onLayerAdded,this),i.layers.off("remove",this.onLayerRemoved,this)),this._batchGroupId>=0)&&(null==(e=t.batcher)||e.remove(ya.RENDER,this.batchGroupId,this.entity));this.removeFromLayers()},i.hide=function(){if(this._meshInstances)for(var e=0;e=0)null==(t=this.system.app.batcher)||t.remove(ya.RENDER,this.batchGroupId,this.entity);if(this.entity.enabled&&e>=0)null==(i=this.system.app.batcher)||i.insert(ya.RENDER,e,this.entity);e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addToLayers(),this._batchGroupId=e}}},{key:"material",get:function(){return this._material},set:function(e){if(this._material!==e&&(this._material=e,this._meshInstances&&"asset"!==this._type))for(var t=0;te.length){for(var t=e.length;tthis._pool.length)for(var t=this._pool.length;t=this._pool.length&&this._resize(2*this._pool.length),this._pool[this._count++]},t.freeAll=function(){this._count=0},e}(),ry=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._angularDamping=0,n._angularFactor=new ye(1,1,1),n._angularVelocity=new ye,n._body=null,n._friction=.5,n._group=2,n._linearDamping=0,n._linearFactor=new ye(1,1,1),n._linearVelocity=new ye,n._mask=og,n._mass=1,n._restitution=0,n._rollingFriction=0,n._simulationEnabled=!1,n._type=ng,n}J(t,e),t.onLibraryLoaded=function(){"undefined"!=typeof Ammo&&($v=new Ammo.btTransform,Qv=new Ammo.btVector3,Jv=new Ammo.btVector3,ey=new Ammo.btQuaternion,ty=new Ammo.btVector3(0,0,0))};var i=t.prototype;return i.createBody=function(){var e,t=this.entity;if(t.collision&&(e=t.collision.shape,t.trigger&&(t.trigger.destroy(),delete t.trigger)),e){this._body&&this.system.onRemove(t,this);var i=this._type===sg?this._mass:0;this._getEntityTransform($v);var n=this.system.createBody(i,e,$v);if(n.setRestitution(this._restitution),n.setFriction(this._friction),n.setRollingFriction(this._rollingFriction),n.setDamping(this._linearDamping,this._angularDamping),this._type===sg){var s=this._linearFactor;Qv.setValue(s.x,s.y,s.z),n.setLinearFactor(Qv);var r=this._angularFactor;Qv.setValue(r.x,r.y,r.z),n.setAngularFactor(Qv)}else this._type===rg&&(n.setCollisionFlags(2|n.getCollisionFlags()),n.setActivationState(4));n.entity=t,this.body=n,this.enabled&&t.enabled&&this.enableSimulation()}},i.isActive=function(){return!!this._body&&this._body.isActive()},i.activate=function(){this._body&&this._body.activate()},i.enableSimulation=function(){var e=this.entity;if(e.collision&&e.collision.enabled&&!this._simulationEnabled){var t=this._body;if(t){switch(this.system.addBody(t,this._group,this._mask),this._type){case sg:this.system._dynamic.push(this),t.forceActivationState(1),this.syncEntityToBody();break;case rg:this.system._kinematic.push(this),t.forceActivationState(4);break;case ng:t.forceActivationState(1),this.syncEntityToBody()}"compound"===e.collision.type&&this.system._compounds.push(e.collision),t.activate(),this._simulationEnabled=!0}}},i.disableSimulation=function(){var e=this._body;if(e&&this._simulationEnabled){var t=this.system,i=t._compounds.indexOf(this.entity.collision);i>-1&&t._compounds.splice(i,1),(i=t._dynamic.indexOf(this))>-1&&t._dynamic.splice(i,1),(i=t._kinematic.indexOf(this))>-1&&t._kinematic.splice(i,1),t.removeBody(e),e.forceActivationState(5),this._simulationEnabled=!1}},i.applyForce=function(){var e,t,i,n,s,r;switch(arguments.length){case 1:e=arguments[0].x,t=arguments[0].y,i=arguments[0].z;break;case 2:e=arguments[0].x,t=arguments[0].y,i=arguments[0].z,n=arguments[1].x,s=arguments[1].y,r=arguments[1].z;break;case 3:e=arguments[0],t=arguments[1],i=arguments[2];break;case 6:e=arguments[0],t=arguments[1],i=arguments[2],n=arguments[3],s=arguments[4],r=arguments[5]}var a=this._body;a&&(a.activate(),Qv.setValue(e,t,i),void 0!==n?(Jv.setValue(n,s,r),a.applyForce(Qv,Jv)):a.applyForce(Qv,ty))},i.applyTorque=function(){var e,t,i;switch(arguments.length){case 1:e=arguments[0].x,t=arguments[0].y,i=arguments[0].z;break;case 3:e=arguments[0],t=arguments[1],i=arguments[2];break;default:return}var n=this._body;n&&(n.activate(),Qv.setValue(e,t,i),n.applyTorque(Qv))},i.applyImpulse=function(){var e,t,i,n,s,r;switch(arguments.length){case 1:e=arguments[0].x,t=arguments[0].y,i=arguments[0].z;break;case 2:e=arguments[0].x,t=arguments[0].y,i=arguments[0].z,n=arguments[1].x,s=arguments[1].y,r=arguments[1].z;break;case 3:e=arguments[0],t=arguments[1],i=arguments[2];break;case 6:e=arguments[0],t=arguments[1],i=arguments[2],n=arguments[3],s=arguments[4],r=arguments[5];break;default:return}var a=this._body;a&&(a.activate(),Qv.setValue(e,t,i),void 0!==n?(Jv.setValue(n,s,r),a.applyImpulse(Qv,Jv)):a.applyImpulse(Qv,ty))},i.applyTorqueImpulse=function(){var e,t,i;switch(arguments.length){case 1:e=arguments[0].x,t=arguments[0].y,i=arguments[0].z;break;case 3:e=arguments[0],t=arguments[1],i=arguments[2];break;default:return}var n=this._body;n&&(n.activate(),Qv.setValue(e,t,i),n.applyTorqueImpulse(Qv))},i.isStatic=function(){return this._type===ng},i.isStaticOrKinematic=function(){return this._type===ng||this._type===rg},i.isKinematic=function(){return this._type===rg},i._getEntityTransform=function(e){var t=this.entity,i=t.getPosition(),n=t.getRotation();Qv.setValue(i.x,i.y,i.z),ey.setValue(n.x,n.y,n.z,n.w),e.setOrigin(Qv),e.setRotation(ey)},i.syncEntityToBody=function(){var e=this._body;if(e){if(this._getEntityTransform($v),e.setWorldTransform($v),this._type===rg){var t=e.getMotionState();t&&t.setWorldTransform($v)}e.activate()}},i._updateDynamic=function(){var e=this._body;if(e.isActive()){var t=e.getMotionState();if(t){t.getWorldTransform($v);var i=$v.getOrigin(),n=$v.getRotation();this.entity.setPosition(i.x(),i.y(),i.z()),this.entity.setRotation(n.x(),n.y(),n.z(),n.w())}}},i._updateKinematic=function(){var e=this._body.getMotionState();e&&(this._getEntityTransform($v),e.setWorldTransform($v))},i.teleport=function(){arguments.length<3?(arguments[0]&&this.entity.setPosition(arguments[0]),arguments[1]&&(arguments[1]instanceof Pe?this.entity.setRotation(arguments[1]):this.entity.setEulerAngles(arguments[1]))):(6===arguments.length&&this.entity.setEulerAngles(arguments[3],arguments[4],arguments[5]),this.entity.setPosition(arguments[0],arguments[1],arguments[2])),this.syncEntityToBody()},i.onEnable=function(){this._body||this.createBody(),this.enableSimulation()},i.onDisable=function(){this.disableSimulation()},$(t,[{key:"angularDamping",get:function(){return this._angularDamping},set:function(e){this._angularDamping!==e&&(this._angularDamping=e,this._body&&this._body.setDamping(this._linearDamping,e))}},{key:"angularFactor",get:function(){return this._angularFactor},set:function(e){this._angularFactor.equals(e)||(this._angularFactor.copy(e),this._body&&this._type===sg&&(Qv.setValue(e.x,e.y,e.z),this._body.setAngularFactor(Qv)))}},{key:"angularVelocity",get:function(){if(this._body&&this._type===sg){var e=this._body.getAngularVelocity();this._angularVelocity.set(e.x(),e.y(),e.z())}return this._angularVelocity},set:function(e){this._body&&this._type===sg&&(this._body.activate(),Qv.setValue(e.x,e.y,e.z),this._body.setAngularVelocity(Qv),this._angularVelocity.copy(e))}},{key:"body",get:function(){return this._body},set:function(e){this._body!==e&&(this._body=e,e&&this._simulationEnabled&&e.activate())}},{key:"friction",get:function(){return this._friction},set:function(e){this._friction!==e&&(this._friction=e,this._body&&this._body.setFriction(e))}},{key:"group",get:function(){return this._group},set:function(e){this._group!==e&&(this._group=e,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()))}},{key:"linearDamping",get:function(){return this._linearDamping},set:function(e){this._linearDamping!==e&&(this._linearDamping=e,this._body&&this._body.setDamping(e,this._angularDamping))}},{key:"linearFactor",get:function(){return this._linearFactor},set:function(e){this._linearFactor.equals(e)||(this._linearFactor.copy(e),this._body&&this._type===sg&&(Qv.setValue(e.x,e.y,e.z),this._body.setLinearFactor(Qv)))}},{key:"linearVelocity",get:function(){if(this._body&&this._type===sg){var e=this._body.getLinearVelocity();this._linearVelocity.set(e.x(),e.y(),e.z())}return this._linearVelocity},set:function(e){this._body&&this._type===sg&&(this._body.activate(),Qv.setValue(e.x,e.y,e.z),this._body.setLinearVelocity(Qv),this._linearVelocity.copy(e))}},{key:"mask",get:function(){return this._mask},set:function(e){this._mask!==e&&(this._mask=e,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()))}},{key:"mass",get:function(){return this._mass},set:function(e){if(this._mass!==e&&(this._mass=e,this._body&&this._type===sg)){var t=this.enabled&&this.entity.enabled;t&&this.disableSimulation(),this._body.getCollisionShape().calculateLocalInertia(e,Qv),this._body.setMassProps(e,Qv),this._body.updateInertiaTensor(),t&&this.enableSimulation()}}},{key:"restitution",get:function(){return this._restitution},set:function(e){this._restitution!==e&&(this._restitution=e,this._body&&this._body.setRestitution(e))}},{key:"rollingFriction",get:function(){return this._rollingFriction},set:function(e){this._rollingFriction!==e&&(this._rollingFriction=e,this._body&&this._body.setRollingFriction(e))}},{key:"type",get:function(){return this._type},set:function(e){if(this._type!==e){switch(this._type=e,this.disableSimulation(),e){case sg:this._group=1,this._mask=ag;break;case rg:this._group=4,this._mask=ag;break;default:this._group=2,this._mask=og}this.createBody()}}}]),t}(Cl),ay=function(){this.enabled=!0},oy=function(e,t,i){this.entity=e,this.point=t,this.normal=i},hy=function(e,t,i){0===arguments.length?(this.a=null,this.b=null,this.impulse=0,this.localPointA=new ye,this.localPointB=new ye,this.pointA=new ye,this.pointB=new ye,this.normal=new ye):(this.a=e,this.b=t,this.impulse=i.impulse,this.localPointA=i.localPoint,this.localPointB=i.localPointOther,this.pointA=i.point,this.pointB=i.pointOther,this.normal=i.normal)},ly=function(e,t,i,n,s,r){void 0===e&&(e=new ye),void 0===t&&(t=new ye),void 0===i&&(i=new ye),void 0===n&&(n=new ye),void 0===s&&(s=new ye),void 0===r&&(r=0),this.localPoint=e,this.localPointOther=t,this.point=i,this.pointOther=n,this.normal=s,this.impulse=r},cy=function(e,t){this.other=e,this.contacts=t},uy=["enabled"],dy=function(e){function t(t){var i;return(i=e.call(this,t)||this).maxSubSteps=10,i.fixedTimeStep=1/60,i.gravity=new ye(0,-9.81,0),i._dynamic=[],i._kinematic=[],i._triggers=[],i._compounds=[],i.id="rigidbody",i._stats=t.stats.frame,i.ComponentType=ry,i.DataType=ay,i.contactPointPool=null,i.contactResultPool=null,i.singleContactResultPool=null,i.schema=uy,i.collisions={},i.frameCollisions={},i.on("beforeremove",i.onBeforeRemove,te(i)),i.on("remove",i.onRemove,te(i)),i}J(t,e);var i=t.prototype;return i.onLibraryLoaded=function(){if("undefined"!=typeof Ammo){if(this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.overlappingPairCache=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.dynamicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.overlappingPairCache,this.solver,this.collisionConfiguration),this.dynamicsWorld.setInternalTickCallback){var e=Ammo.addFunction(this._checkForCollisions.bind(this),"vif");this.dynamicsWorld.setInternalTickCallback(e)}iy=new Ammo.btVector3,ny=new Ammo.btVector3,ry.onLibraryLoaded(),this.contactPointPool=new sy(ly,1),this.contactResultPool=new sy(cy,1),this.singleContactResultPool=new sy(hy,1),this.app.systems.on("update",this.onUpdate,this)}else this.app.systems.off("update",this.onUpdate,this)},i.initializeComponentData=function(t,i,n){for(var s=0,r=["mass","linearDamping","angularDamping","linearFactor","angularFactor","friction","rollingFriction","restitution","type","group","mask"];s2){var h=arguments[2];h(i)}}}return Ammo.destroy(n),i},i.raycastAll=function(e,t){var i=[];iy.setValue(e.x,e.y,e.z),ny.setValue(t.x,t.y,t.z);var n=new Ammo.AllHitsRayResultCallback(iy,ny);if(this.dynamicsWorld.rayTest(iy,ny,n),n.hasHit())for(var s=n.get_m_collisionObjects(),r=n.get_m_hitPointWorld(),a=n.get_m_hitNormalWorld(),o=s.size(),h=0;h0)if(4&d||4&f){var v=c.collision&&(c.collision.hasEvent("triggerenter")||c.collision.hasEvent("triggerleave")),y=u.collision&&(u.collision.hasEvent("triggerenter")||u.collision.hasEvent("triggerleave")),x=c.rigidbody&&(c.rigidbody.hasEvent("triggerenter")||c.rigidbody.hasEvent("triggerleave")),b=u.rigidbody&&(u.rigidbody.hasEvent("triggerenter")||u.rigidbody.hasEvent("triggerleave"));v&&(!(g=this._storeCollision(c,u))||4&f||c.collision.fire("triggerenter",u)),y&&(!(g=this._storeCollision(u,c))||4&d||u.collision.fire("triggerenter",c)),x&&(g||(g=this._storeCollision(u,c)),g&&c.rigidbody.fire("triggerenter",u)),b&&(g||(g=this._storeCollision(c,u)),g&&u.rigidbody.fire("triggerenter",c))}else{var S=this._hasContactEvent(c),w=this._hasContactEvent(u),T=this.hasEvent("contact");if(T||S||w){for(var A=0;A=0&&n!==e.element.drawOrder)null==(i=this.system.app.batcher)||i.markGroupDirty(e.element._batchGroupId)}e.particlesystem&&(e.particlesystem.drawOrder=t++);for(var s=e.children,r=0;r255&&(e=255),this._priority!==e&&(this._priority=e,this.syncDrawOrder())}}]),t}(Cl),gy=function(){this.enabled=!0},vy=["enabled"],yy=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="screen",i.ComponentType=_y,i.DataType=gy,i.schema=vy,i.windowResolution=new be,i._drawOrderSyncQueue=new j,i.app.graphicsDevice.on("resizecanvas",i._onResize,te(i)),i.app.systems.on("update",i._onUpdate,te(i)),i.on("beforeremove",i.onRemoveComponent,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){void 0!==i.priority&&(t.priority=i.priority),void 0!==i.screenSpace&&(t.screenSpace=i.screenSpace),t.cull=t.screenSpace,void 0!==i.scaleMode&&(t.scaleMode=i.scaleMode),void 0!==i.scaleBlend&&(t.scaleBlend=i.scaleBlend),void 0!==i.resolution&&(i.resolution instanceof be?t._resolution.copy(i.resolution):t._resolution.set(i.resolution[0],i.resolution[1]),t.resolution=t._resolution),void 0!==i.referenceResolution&&(i.referenceResolution instanceof be?t._referenceResolution.copy(i.referenceResolution):t._referenceResolution.set(i.referenceResolution[0],i.referenceResolution[1]),t.referenceResolution=t._referenceResolution),t.syncDrawOrder(),e.prototype.initializeComponentData.call(this,t,i,n)},i.destroy=function(){e.prototype.destroy.call(this),this.app.graphicsDevice.off("resizecanvas",this._onResize,this),this.app.systems.off("update",this._onUpdate,this)},i._onUpdate=function(e){var t=this.store;for(var i in t)t[i].entity.screen.update&&t[i].entity.screen.update(e)},i._onResize=function(e,t){this.windowResolution.x=e,this.windowResolution.y=t},i.cloneComponent=function(e,t){var i=e.screen;return this.addComponent(t,{enabled:i.enabled,screenSpace:i.screenSpace,scaleMode:i.scaleMode,resolution:i.resolution.clone(),referenceResolution:i.referenceResolution.clone()})},i.onRemoveComponent=function(e,t){t.onRemove()},i.processDrawOrderSyncQueue=function(){for(var e=this._drawOrderSyncQueue.list(),t=0;t=0&&this.instancesWithUpdate.splice(s,1)}if(n.fixedUpdate){var r=this.instancesWithFixedUpdate.indexOf(n);r>=0&&this.instancesWithFixedUpdate.splice(r,1)}if(n.postUpdate){var a=this.instancesWithPostUpdate.indexOf(n);a>=0&&this.instancesWithPostUpdate.splice(a,1)}if(n.toolsUpdate){var o=this.instancesWithToolsUpdate.indexOf(n);o>=0&&this.instancesWithToolsUpdate.splice(o,1)}e.instances[i].instance===e[i]&&delete e[i],delete e.instances[i]}},i._postInitializeScriptComponent=function(e){this._callInstancesMethod(e,Ty),e.data.postInitialized=!0},i._updateInstances=function(e,t,i){for(var n=0,s=t.length;n0){var i=Dy.point.sub(Ly.origin).dot(Dy.normal)/t,n=Ly.origin.add(Ly.direction.mulScalar(i));return ky.copy(this._element.entity.getRotation()).invert().transformVector(n,n),n.mul(this._dragScale),n}return null},i._determineInputPosition=function(e){var t=this._app.graphicsDevice.maxPixelRatio;void 0!==e.x&&void 0!==e.y?(Ry.x=e.x*t,Ry.y=e.y*t):e.changedTouches?(Ry.x=e.changedTouches[0].x*t,Ry.y=e.changedTouches[0].y*t):console.warn("Could not determine position from input event")},i._chooseRayOriginAndDirection=function(){this._element.screen&&this._element.screen.screen.screenSpace?(Ly.origin.set(Ry.x,-Ry.y,0),Ly.direction.copy(ye.FORWARD)):(Iy.copy(this._dragCamera.screenToWorld(Ry.x,Ry.y,1)),Ly.origin.copy(this._dragCamera.entity.getPosition()),Ly.direction.copy(Iy).sub(Ly.origin).normalize())},i._calculateDragScale=function(){var e=this._element.entity.parent,t=this._element.screen&&this._element.screen.screen,i=t&&t.screenSpace,n=i?t.scale:1,s=this._dragScale;for(s.set(n,n,n);e&&(s.mul(e.getLocalScale()),e=e.parent,!i||!e.screen););s.x=1/s.x,s.y=1/s.y,s.z=1/s.z},i._onMove=function(e){var t=this._element,i=this._deltaMousePosition,n=this._deltaHandlePosition,s=this._axis;if(t&&this._isDragging&&this.enabled&&t.enabled&&t.entity.enabled){var r=this._screenToLocal(e);if(r){if(i.sub2(r,this._dragStartMousePosition),n.add2(this._dragStartHandlePosition,i),s){var a=t.entity.getLocalPosition(),o=Oy[s];n[o]=a[o]}t.entity.setLocalPosition(n),this.fire("drag:move",n)}}},i.destroy=function(){this._toggleLifecycleListeners("off"),this._toggleDragListeners("off")},$(t,[{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"isDragging",get:function(){return this._isDragging}}]),t}(m),By=new be,Ny=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._viewportReference=new D_(te(n),"viewportEntity",{"element#gain":n._onViewportElementGain,"element#resize":n._onSetContentOrViewportSize}),n._contentReference=new D_(te(n),"contentEntity",{"element#gain":n._onContentElementGain,"element#lose":n._onContentElementLose,"element#resize":n._onSetContentOrViewportSize}),n._scrollbarUpdateFlags={},n._scrollbarReferences={},n._scrollbarReferences[0]=new D_(te(n),"horizontalScrollbarEntity",{"scrollbar#set:value":n._onSetHorizontalScrollbarValue,"scrollbar#gain":n._onHorizontalScrollbarGain}),n._scrollbarReferences[1]=new D_(te(n),"verticalScrollbarEntity",{"scrollbar#set:value":n._onSetVerticalScrollbarValue,"scrollbar#gain":n._onVerticalScrollbarGain}),n._prevContentSizes={},n._prevContentSizes[0]=null,n._prevContentSizes[1]=null,n._scroll=new be,n._velocity=new ye,n._dragStartPosition=new ye,n._disabledContentInput=!1,n._disabledContentInputEntities=[],n._toggleLifecycleListeners("on",t),n._toggleElementListeners("on"),n}J(t,e);var i=t.prototype;return i._toggleLifecycleListeners=function(e,t){this[e]("set_horizontal",this._onSetHorizontalScrollingEnabled,this),this[e]("set_vertical",this._onSetVerticalScrollingEnabled,this),t.app.systems.element[e]("add",this._onElementComponentAdd,this),t.app.systems.element[e]("beforeremove",this._onElementComponentRemove,this)},i._toggleElementListeners=function(e){if(this.entity.element){if("on"===e&&this._hasElementListeners)return;this.entity.element[e]("resize",this._onSetContentOrViewportSize,this),this.entity.element[e](lm,this._onMouseWheel,this),this._hasElementListeners="on"===e}},i._onElementComponentAdd=function(e){this.entity===e&&this._toggleElementListeners("on")},i._onElementComponentRemove=function(e){this.entity===e&&this._toggleElementListeners("off")},i._onViewportElementGain=function(){this._syncAll()},i._onContentElementGain=function(){this._destroyDragHelper(),this._contentDragHelper=new Fy(this._contentReference.entity.element),this._contentDragHelper.on("drag:start",this._onContentDragStart,this),this._contentDragHelper.on("drag:end",this._onContentDragEnd,this),this._contentDragHelper.on("drag:move",this._onContentDragMove,this),this._prevContentSizes[0]=null,this._prevContentSizes[1]=null,this._syncAll()},i._onContentElementLose=function(){this._destroyDragHelper()},i._onContentDragStart=function(){this._contentReference.entity&&this.enabled&&this.entity.enabled&&this._dragStartPosition.copy(this._contentReference.entity.getLocalPosition())},i._onContentDragEnd=function(){this._prevContentDragPosition=null,this._enableContentInput()},i._onContentDragMove=function(e){if(this._contentReference.entity&&this.enabled&&this.entity.enabled&&(this._wasDragged=!0,this._setScrollFromContentPosition(e),this._setVelocityFromContentPositionDelta(e),!this._disabledContentInput)){var t=e.x-this._dragStartPosition.x,i=e.y-this._dragStartPosition.y;(Math.abs(t)>this.dragThreshold||Math.abs(i)>this.dragThreshold)&&this._disableContentInput()}},i._onSetContentOrViewportSize=function(){this._syncAll()},i._onSetHorizontalScrollbarValue=function(e){!this._scrollbarUpdateFlags[0]&&this.enabled&&this.entity.enabled&&this._onSetScroll(e,null)},i._onSetVerticalScrollbarValue=function(e){!this._scrollbarUpdateFlags[1]&&this.enabled&&this.entity.enabled&&this._onSetScroll(null,e)},i._onSetHorizontalScrollingEnabled=function(){this._syncScrollbarEnabledState(0)},i._onSetVerticalScrollingEnabled=function(){this._syncScrollbarEnabledState(1)},i._onHorizontalScrollbarGain=function(){this._syncScrollbarEnabledState(0),this._syncScrollbarPosition(0)},i._onVerticalScrollbarGain=function(){this._syncScrollbarEnabledState(1),this._syncScrollbarPosition(1)},i._onSetScroll=function(e,t,i){!1!==i&&this._velocity.set(0,0,0);var n=this._updateAxis(e,"x",0),s=this._updateAxis(t,"y",1);(n||s)&&this.fire("set:scroll",this._scroll)},i._updateAxis=function(e,t,i){var n=null!==e&&Math.abs(e-this._scroll[t])>1e-5;return(n||this._isDragging()||0===e)&&(this._scroll[t]=this._determineNewScrollValue(e,t,i),this._syncContentPosition(i),this._syncScrollbarPosition(i)),n},i._determineNewScrollValue=function(e,t,i){if(!this._getScrollingEnabled(i))return this._scroll[t];switch(this.scrollMode){case 0:return de.clamp(e,0,this._getMaxScrollValue(i));case 1:return this._setVelocityFromOvershoot(e,t,i),e;case 2:return e;default:return console.warn("Unhandled scroll mode:"+this.scrollMode),e}},i._syncAll=function(){this._syncContentPosition(0),this._syncContentPosition(1),this._syncScrollbarPosition(0),this._syncScrollbarPosition(1),this._syncScrollbarEnabledState(0),this._syncScrollbarEnabledState(1)},i._syncContentPosition=function(e){var t=this._getAxis(e),i=this._getSign(e),n=this._contentReference.entity;if(n){var s=this._prevContentSizes[e],r=this._getContentSize(e);if(null!==s&&Math.abs(s-r)>1e-4){var a=this._getMaxOffset(e,s),o=this._getMaxOffset(e,r);this._scroll[t]=0===o?1:de.clamp(this._scroll[t]*a/o,0,1)}var h=this._scroll[t]*this._getMaxOffset(e),l=n.getLocalPosition();l[t]=h*i,n.setLocalPosition(l),this._prevContentSizes[e]=r}},i._syncScrollbarPosition=function(e){var t=this._getAxis(e),i=this._scrollbarReferences[e].entity;i&&i.scrollbar&&(this._scrollbarUpdateFlags[e]=!0,i.scrollbar.value=this._scroll[t],i.scrollbar.handleSize=this._getScrollbarHandleSize(t,e),this._scrollbarUpdateFlags[e]=!1)},i._syncScrollbarEnabledState=function(e){var t=this._scrollbarReferences[e].entity;if(t){var i=this._getScrollingEnabled(e),n=this._getScrollbarVisibility(e);switch(n){case 0:return void(t.enabled=i);case 1:return void(t.enabled=i&&this._contentIsLargerThanViewport(e));default:console.warn("Unhandled scrollbar visibility:"+n),t.enabled=i}}},i._contentIsLargerThanViewport=function(e){return this._getContentSize(e)>this._getViewportSize(e)},i._contentPositionToScrollValue=function(e){var t=this._getMaxOffset(0),i=this._getMaxOffset(1);return By.x=0===t?0:e.x/t,By.y=0===i?0:e.y/-i,By},i._getMaxOffset=function(e,t){t=void 0===t?this._getContentSize(e):t;var i=this._getViewportSize(e);return t1e-4||Math.abs(this._velocity.y)>1e-4){var e=this._contentReference.entity.getLocalPosition();e.x+=this._velocity.x,e.y+=this._velocity.y,this._contentReference.entity.setLocalPosition(e),this._setScrollFromContentPosition(e)}this._velocity.x*=1-this.friction,this._velocity.y*=1-this.friction}},i._hasOvershoot=function(e,t){return Math.abs(this._toOvershoot(this.scroll[e],t))>.001},i._toOvershoot=function(e,t){var i=this._getMaxScrollValue(t);return e<0?e:e>i?e-i:0},i._setVelocityFromOvershoot=function(e,t,i){var n=this._toOvershoot(e,i)*this._getMaxOffset(i)*this._getSign(i);Math.abs(n)>0&&(this._velocity[t]=-n/(50*this.bounceAmount+1))},i._setVelocityFromContentPositionDelta=function(e){this._prevContentDragPosition?(this._velocity.sub2(e,this._prevContentDragPosition),this._prevContentDragPosition.copy(e)):(this._velocity.set(0,0,0),this._prevContentDragPosition=e.clone())},i._setScrollFromContentPosition=function(e){var t=this._contentPositionToScrollValue(e);this._isDragging()&&(t=this._applyScrollValueTension(t)),this._onSetScroll(t.x,t.y,!1)},i._applyScrollValueTension=function(e){var t=this._getMaxScrollValue(0),i=this._toOvershoot(e.x,0);return i>0?e.x=t+1*Math.log10(1+i):i<0&&(e.x=-1*Math.log10(1-i)),t=this._getMaxScrollValue(1),(i=this._toOvershoot(e.y,1))>0?e.y=t+1*Math.log10(1+i):i<0&&(e.y=-1*Math.log10(1-i)),e},i._isDragging=function(){return this._contentDragHelper&&this._contentDragHelper.isDragging},i._setScrollbarComponentsEnabled=function(e){this._scrollbarReferences[0].hasComponent("scrollbar")&&(this._scrollbarReferences[0].entity.scrollbar.enabled=e),this._scrollbarReferences[1].hasComponent("scrollbar")&&(this._scrollbarReferences[1].entity.scrollbar.enabled=e)},i._setContentDraggingEnabled=function(e){this._contentDragHelper&&(this._contentDragHelper.enabled=e)},i._onMouseWheel=function(e){if(this.useMouseWheel){var t=e.event,i=t.deltaX/this._contentReference.entity.element.calculatedWidth*this.mouseWheelSensitivity.x,n=t.deltaY/this._contentReference.entity.element.calculatedHeight*this.mouseWheelSensitivity.y,s=de.clamp(this._scroll.x+i,0,this._getMaxScrollValue(0)),r=de.clamp(this._scroll.y+n,0,this._getMaxScrollValue(1));this.scroll=new be(s,r)}},i._enableContentInput=function(){for(;this._disabledContentInputEntities.length;){var e=this._disabledContentInputEntities.pop();e.element&&(e.element.useInput=!0)}this._disabledContentInput=!1},i._disableContentInput=function(){var e=this,t=function t(i){i.element&&i.element.useInput&&(e._disabledContentInputEntities.push(i),i.element.useInput=!1);for(var n=i.children,s=0,r=n.length;s1e-5&&(this.data.value=de.clamp(i,0,1),this._updateHandlePositionAndSize(),this.fire("set:value",this.data.value))},i._onSetHandleSize=function(e,t,i){Math.abs(i-t)>1e-5&&(this.data.handleSize=de.clamp(i,0,1),this._updateHandlePositionAndSize())},i._onSetHandleAlignment=function(){this._updateHandlePositionAndSize()},i._onSetOrientation=function(e,t,i){i!==t&&this._handleReference.hasComponent("element")&&(this._handleReference.entity.element[this._getOppositeDimension()]=0)},i._updateHandlePositionAndSize=function(){var e=this._handleReference.entity,t=e&&e.element;if(e){var i=e.getLocalPosition();i[this._getAxis()]=this._getHandlePosition(),this._handleReference.entity.setLocalPosition(i)}t&&(t[this._getDimension()]=this._getHandleLength())},i._handlePositionToScrollValue=function(e){return e*this._getSign()/this._getUsableTrackLength()},i._scrollValueToHandlePosition=function(e){return e*this._getSign()*this._getUsableTrackLength()},i._getUsableTrackLength=function(){return Math.max(this._getTrackLength()-this._getHandleLength(),.001)},i._getTrackLength=function(){return this.entity.element?0===this.orientation?this.entity.element.calculatedWidth:this.entity.element.calculatedHeight:0},i._getHandleLength=function(){return this._getTrackLength()*this.handleSize},i._getHandlePosition=function(){return this._scrollValueToHandlePosition(this.value)},i._getSign=function(){return 0===this.orientation?1:-1},i._getAxis=function(){return 0===this.orientation?"x":"y"},i._getDimension=function(){return 0===this.orientation?"width":"height"},i._getOppositeDimension=function(){return 0===this.orientation?"height":"width"},i._destroyDragHelper=function(){this._handleDragHelper&&this._handleDragHelper.destroy()},i._setHandleDraggingEnabled=function(e){this._handleDragHelper&&(this._handleDragHelper.enabled=e)},i.onEnable=function(){this._handleReference.onParentComponentEnable(),this._setHandleDraggingEnabled(!0)},i.onDisable=function(){this._setHandleDraggingEnabled(!1)},i.onRemove=function(){this._destroyDragHelper(),this._toggleLifecycleListeners("off")},t}(Cl),Wy=function(){this.enabled=!0},Hy=[{name:"enabled",type:"boolean"},{name:"orientation",type:"number"},{name:"value",type:"number"},{name:"handleSize",type:"number"},{name:"handleEntity",type:"entity"}],Xy=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="scrollbar",i.ComponentType=Gy,i.DataType=Wy,i.schema=Hy,i.on("beforeremove",i._onRemoveComponent,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){e.prototype.initializeComponentData.call(this,t,i,Hy)},i._onRemoveComponent=function(e,t){t.onRemove()},t}(h_);Cl._buildAccessors(Gy.prototype,Hy);var qy={volume:0,pitch:0,loop:!1,startTime:0,duration:0,position:new ye,maxDistance:0,refDistance:0,rollOffFactor:0,distanceModel:0,onPlay:null,onPause:null,onResume:null,onStop:null,onEnd:null},jy=function(e){function t(t,i,n){var s;return void 0===i&&(i="Untitled"),void 0===n&&(n={}),(s=e.call(this)||this).name=void 0,s.instances=[],s._component=t,s._assets=t.system.app.assets,s._manager=t.system.manager,s.name=i,s._volume=void 0!==n.volume?de.clamp(Number(n.volume)||0,0,1):1,s._pitch=void 0!==n.pitch?Math.max(.01,Number(n.pitch)||0):1,s._loop=!(void 0===n.loop||!n.loop),s._duration=n.duration>0?n.duration:null,s._startTime=Math.max(0,Number(n.startTime)||0),s._overlap=!!n.overlap,s._autoPlay=!!n.autoPlay,s._firstNode=null,s._lastNode=null,s._asset=n.asset,s._asset instanceof ml&&(s._asset=s._asset.id),s._onInstancePlayHandler=s._onInstancePlay.bind(te(s)),s._onInstancePauseHandler=s._onInstancePause.bind(te(s)),s._onInstanceResumeHandler=s._onInstanceResume.bind(te(s)),s._onInstanceStopHandler=s._onInstanceStop.bind(te(s)),s._onInstanceEndHandler=s._onInstanceEnd.bind(te(s)),s}J(t,e);var i=t.prototype;return i.play=function(){if(this.overlap||this.stop(),this.isLoaded||this._hasAsset()){var e=this._createInstance();if(this.instances.push(e),this.isLoaded)e.play();else{var t=function(t){var i=e._playWhenLoaded;e.sound=t,i&&e.play()};this.off("load",t),this.once("load",t),this.load()}return e}},i.pause=function(){for(var e=!1,t=this.instances,i=0,n=t.length;i=0;r--){var a=s[r].isPlaying||s[r].isSuspended,o=s[r].currentTime;a&&s[r].stop();var h=n._createInstance();a&&(h.play(),h.currentTime=o),s.push(h)}}}},{key:"slots",get:function(){return this._slots},set:function(e){var t=this._slots;if(t)for(var i in t)t[i].stop();var n={};for(var s in e)e[s]instanceof jy?n[e[s].name]=e[s]:e[s].name&&(n[e[s].name]=new jy(this,e[s].name,e[s]));this._slots=n,this.enabled&&this.entity.enabled&&this.onEnable()}}]),t}(Cl),Ky=function(){this.enabled=!0},Zy=["enabled"],$y=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="sound",i.ComponentType=Yy,i.DataType=Ky,i.schema=Zy,i.manager=t.soundManager,i.app.systems.on("update",i.onUpdate,te(i)),i.on("beforeremove",i.onBeforeRemove,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){n=["volume","pitch","positional","refDistance","maxDistance","rollOffFactor","distanceModel","slots"];for(var s=0;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(e){this._time=e;var t=this.duration;this._time<0?this.loop?this._time=this._time%t+t:this._time=0:this._time>t&&(this.loop?this._time%=t:this._time=t)},i._setFrame=function(e){this._sprite?this._frame=de.clamp(e,0,this._sprite.frameKeys.length-1):this._frame=e,this._component.currentClip===this&&this._component._showFrame(this._frame)},i._destroy=function(){this._sprite&&(this.sprite=null),this._spriteAsset&&(this.spriteAsset=null)},i.play=function(){this._playing||(this._playing=!0,this._paused=!1,this.frame=0,this.fire("play"),this._component.fire("play",this))},i.pause=function(){this._playing&&!this._paused&&(this._paused=!0,this.fire("pause"),this._component.fire("pause",this))},i.resume=function(){this._paused&&(this._paused=!1,this.fire("resume"),this._component.fire("resume",this))},i.stop=function(){this._playing&&(this._playing=!1,this._paused=!1,this._time=0,this.frame=0,this.fire("stop"),this._component.fire("stop",this))},$(t,[{key:"duration",get:function(){if(this._sprite){var e=this.fps||Number.MIN_VALUE;return this._sprite.frameKeys.length/Math.abs(e)}return 0}},{key:"frame",get:function(){return this._frame},set:function(e){this._setFrame(e);var t=this.fps||Number.MIN_VALUE;this._setTime(this._frame/t)}},{key:"isPaused",get:function(){return this._paused}},{key:"isPlaying",get:function(){return this._playing}},{key:"sprite",get:function(){return this._sprite},set:function(e){var t;(this._sprite&&(this._sprite.off("set:meshes",this._onSpriteMeshesChange,this),this._sprite.off("set:pixelsPerUnit",this._onSpritePpuChanged,this),this._sprite.off("set:atlas",this._onSpriteMeshesChange,this),this._sprite.atlas&&this._sprite.atlas.off("set:texture",this._onSpriteMeshesChange,this)),this._sprite=e,this._sprite&&(this._sprite.on("set:meshes",this._onSpriteMeshesChange,this),this._sprite.on("set:pixelsPerUnit",this._onSpritePpuChanged,this),this._sprite.on("set:atlas",this._onSpriteMeshesChange,this),this._sprite.atlas&&this._sprite.atlas.on("set:texture",this._onSpriteMeshesChange,this)),this._component.currentClip===this)&&(e&&e.atlas?(e.atlas.texture&&((t=this._component._meshInstance)&&(t.setParameter("texture_emissiveMap",e.atlas.texture),t.setParameter("texture_opacityMap",e.atlas.texture)),this._component.enabled&&this._component.entity.enabled&&this._component._showModel()),this.time&&this.fps?this.time=this.time:this.frame=this.frame):((t=this._component._meshInstance)&&(t.deleteParameter("texture_emissiveMap"),t.deleteParameter("texture_opacityMap")),this._component._hideModel()))}},{key:"spriteAsset",get:function(){return this._spriteAsset},set:function(e){var t=this._component.system.app.assets,i=e;if(e instanceof ml&&(i=e.id),this._spriteAsset!==i){if(this._spriteAsset){var n=t.get(this._spriteAsset);n&&this._unbindSpriteAsset(n)}if(this._spriteAsset=i,this._spriteAsset){var s=t.get(this._spriteAsset);s?this._bindSpriteAsset(s):(this.sprite=null,t.on("add:"+this._spriteAsset,this._onSpriteAssetAdded,this))}else this.sprite=null}}},{key:"time",get:function(){return this._time},set:function(e){this._setTime(e),this._sprite?this.frame=Math.min(this._sprite.frameKeys.length-1,Math.floor(this._time*Math.abs(this.fps))):this.frame=0}}]),t}(m),tx="texture_emissiveMap",ix="texture_opacityMap",nx="material_emissive",sx="material_opacity",rx=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._type=Qy,n._material=t.defaultMaterial,n._color=new me(1,1,1,1),n._colorUniform=new Float32Array(3),n._speed=1,n._flipX=!1,n._flipY=!1,n._width=1,n._height=1,n._drawOrder=0,n._layers=[0],n._outerScale=new be(1,1),n._outerScaleUniform=new Float32Array(2),n._innerOffset=new Se,n._innerOffsetUniform=new Float32Array(4),n._atlasRect=new Se,n._atlasRectUniform=new Float32Array(4),n._batchGroupId=-1,n._batchGroup=null,n._node=new Hn,n._model=new hc,n._model.graph=n._node,n._meshInstance=null,i.addChild(n._model.graph),n._model._entity=i,n._updateAabbFunc=n._updateAabb.bind(te(n)),n._addedModel=!1,n._autoPlayClip=null,n._clips={},n._defaultClip=new ex(te(n),{name:n.entity.name,fps:0,loop:!1,spriteAsset:null}),n._currentClip=n._defaultClip,n}J(t,e);var i=t.prototype;return i.onEnable=function(){var e,t=this.system.app,i=t.scene;(i.on("set:layers",this._onLayersChanged,this),i.layers&&(i.layers.on("add",this._onLayerAdded,this),i.layers.on("remove",this._onLayerRemoved,this)),this._showModel(),this._autoPlayClip&&this._tryAutoPlay(),this._batchGroupId>=0)&&(null==(e=t.batcher)||e.insert(ya.SPRITE,this._batchGroupId,this.entity))},i.onDisable=function(){var e,t=this.system.app,i=t.scene;(i.off("set:layers",this._onLayersChanged,this),i.layers&&(i.layers.off("add",this._onLayerAdded,this),i.layers.off("remove",this._onLayerRemoved,this)),this.stop(),this._hideModel(),this._batchGroupId>=0)&&(null==(e=t.batcher)||e.remove(ya.SPRITE,this._batchGroupId,this.entity))},i.onDestroy=function(){for(var e in this._currentClip=null,this._defaultClip&&(this._defaultClip._destroy(),this._defaultClip=null),this._clips)this._clips[e]._destroy();this._clips=null,this._hideModel(),this._model=null,this._node&&(this._node.parent&&this._node.parent.removeChild(this._node),this._node=null),this._meshInstance&&(this._meshInstance.material=null,this._meshInstance.mesh=null,this._meshInstance=null)},i._showModel=function(){if(!this._addedModel&&this._meshInstance){for(var e=[this._meshInstance],t=0,i=this._layers.length;t=0)null==(t=this.system.app.batcher)||t.remove(ya.SPRITE,n,this.entity);if(this.entity.enabled&&e>=0)null==(i=this.system.app.batcher)||i.insert(ya.SPRITE,e,this.entity);else n>=0&&this._currentClip&&this._currentClip.sprite&&this.enabled&&this.entity.enabled&&this._showModel()}}},{key:"autoPlayClip",get:function(){return this._autoPlayClip},set:function(e){this._autoPlayClip=e instanceof ex?e.name:e,this._tryAutoPlay()}},{key:"drawOrder",get:function(){return this._drawOrder},set:function(e){this._drawOrder=e,this._meshInstance&&(this._meshInstance.drawOrder=e)}},{key:"layers",get:function(){return this._layers},set:function(e){this._addedModel&&this._hideModel(),this._layers=e,this._meshInstance&&this.enabled&&this.entity.enabled&&this._showModel()}},{key:"aabb",get:function(){return this._meshInstance?this._meshInstance.aabb:null}}]),t}(Cl),ax=function(){this.enabled=!0},ox=["enabled"],hx=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="sprite",i.ComponentType=rx,i.DataType=ax,i.schema=ox,i._defaultTexture=null,i._defaultMaterial=null,i._default9SlicedMaterialSlicedMode=null,i._default9SlicedMaterialTiledMode=null,i.app.systems.on("update",i.onUpdate,te(i)),i.on("beforeremove",i.onBeforeRemove,te(i)),i}J(t,e);var i=t.prototype;return i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this),this._defaultTexture&&(this._defaultTexture.destroy(),this._defaultTexture=null)},i.initializeComponentData=function(t,i,n){if(void 0!==i.enabled&&(t.enabled=i.enabled),t.type=i.type,i.layers&&Array.isArray(i.layers)&&(t.layers=i.layers.slice(0)),void 0!==i.drawOrder&&(t.drawOrder=i.drawOrder),void 0!==i.color&&(i.color instanceof me?t.color.set(i.color.r,i.color.g,i.color.b,void 0!==i.opacity?i.opacity:1):t.color.set(i.color[0],i.color[1],i.color[2],void 0!==i.opacity?i.opacity:1),t.color=t.color),void 0!==i.opacity&&(t.opacity=i.opacity),void 0!==i.flipX&&(t.flipX=i.flipX),void 0!==i.flipY&&(t.flipY=i.flipY),void 0!==i.width&&(t.width=i.width),void 0!==i.height&&(t.height=i.height),void 0!==i.spriteAsset&&(t.spriteAsset=i.spriteAsset),i.sprite&&(t.sprite=i.sprite),void 0!==i.frame&&(t.frame=i.frame),i.clips)for(var s in i.clips)t.addClip(i.clips[s]);void 0!==i.speed&&(t.speed=i.speed),i.autoPlayClip&&(t.autoPlayClip=i.autoPlayClip),t.batchGroupId=void 0===i.batchGroupId||null===i.batchGroupId?-1:i.batchGroupId,e.prototype.initializeComponentData.call(this,t,i,n)},i.cloneComponent=function(e,t){var i=e.sprite;return this.addComponent(t,{enabled:i.enabled,type:i.type,spriteAsset:i.spriteAsset,sprite:i.sprite,frame:i.frame,color:i.color.clone(),opacity:i.opacity,flipX:i.flipX,flipY:i.flipY,speed:i.speed,clips:i.clips,autoPlayClip:i.autoPlayClip,batchGroupId:i.batchGroupId,drawOrder:i.drawOrder,layers:i.layers.slice(0)})},i.onUpdate=function(e){var t=this.store;for(var i in t)if(t.hasOwnProperty(i)){var n=t[i];if(n.data.enabled&&n.entity.enabled){var s=n.entity.sprite;s._currentClip&&s._currentClip._update(e)}}},i.onBeforeRemove=function(e,t){t.onDestroy()},$(t,[{key:"defaultMaterial",get:function(){if(!this._defaultMaterial){var e=new wn(this.app.graphicsDevice,{width:1,height:1,format:7,name:"sprite"}),t=new Uint8Array(e.lock());t[0]=t[1]=t[2]=t[3]=255,e.unlock();var i=new Zs;i.diffuse.set(0,0,0),i.emissive.set(.5,.5,.5),i.emissiveMap=e,i.emissiveTint=!0,i.opacityMap=e,i.opacityMapChannel="a",i.opacityTint=!0,i.opacity=0,i.useLighting=!1,i.useGammaTonemap=!1,i.useFog=!1,i.useSkybox=!1,i.blendType=4,i.depthWrite=!1,i.pixelSnap=!1,i.cull=0,i.update(),this._defaultTexture=e,this._defaultMaterial=i}return this._defaultMaterial},set:function(e){this._defaultMaterial=e}},{key:"default9SlicedMaterialSlicedMode",get:function(){if(!this._default9SlicedMaterialSlicedMode){var e=this.defaultMaterial.clone();e.nineSlicedMode=1,e.update(),this._default9SlicedMaterialSlicedMode=e}return this._default9SlicedMaterialSlicedMode},set:function(e){this._default9SlicedMaterialSlicedMode=e}},{key:"default9SlicedMaterialTiledMode",get:function(){if(!this._default9SlicedMaterialTiledMode){var e=this.defaultMaterial.clone();e.nineSlicedMode=2,e.update(),this._default9SlicedMaterialTiledMode=e}return this._default9SlicedMaterialTiledMode},set:function(e){this._default9SlicedMaterialTiledMode=e}}]),t}(h_);Cl._buildAccessors(rx.prototype,ox);var lx=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._oldState=!0,n._size=new ye,n.on("set_enabled",n._onSetEnabled,te(n)),n}J(t,e);var i=t.prototype;return i.onEnable=function(){this._checkState()},i.onDisable=function(){this._checkState()},i._onSetEnabled=function(e,t,i){this._checkState()},i._checkState=function(){var e=this.enabled&&this.entity.enabled;e!==this._oldState&&(this._oldState=e,this.fire("enable"),this.fire("state",this.enabled))},i._onBeforeRemove=function(){this.fire("remove")},$(t,[{key:"size",get:function(){return this._size},set:function(e){e instanceof ye?this._size.copy(e):e instanceof Array&&e.length>=3&&this.size.set(e[0],e[1],e[2])}}]),t}(Cl),cx=function(){this.enabled=!0},ux=["enabled"],dx=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="zone",i.ComponentType=lx,i.DataType=cx,i.schema=ux,i.on("beforeremove",i._onBeforeRemove,te(i)),i}J(t,e);var i=t.prototype;return i.initializeComponentData=function(e,t,i){e.enabled=!t.hasOwnProperty("enabled")||!!t.enabled,t.size&&(t.size instanceof ye?e.size.copy(t.size):t.size instanceof Array&&t.size.length>=3&&e.size.set(t.size[0],t.size[1],t.size[2]))},i.cloneComponent=function(e,t){var i={size:e.zone.size};return this.addComponent(t,i)},i._onBeforeRemove=function(e,t){t._onBeforeRemove()},t}(h_);Cl._buildAccessors(lx.prototype,ux);var fx=function(e,t){this.effect=e,this.inputTarget=t,this.outputTarget=null,this.name=e.constructor.name},px=function(){function e(e,t){this.app=e,this.camera=t,this.destinationRenderTarget=null,this.effects=[],this.enabled=!1,this.depthTarget=null,t.on("set:rect",this.onCameraRectChanged,this)}var t=e.prototype;return t._allocateColorBuffer=function(e,t){var i=this.camera.rect,n=Math.floor(i.z*this.app.graphicsDevice.width),s=Math.floor(i.w*this.app.graphicsDevice.height);return new wn(this.app.graphicsDevice,{name:t,format:e,width:n,height:s,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1})},t._createOffscreenTarget=function(e,t){var i=this.app.graphicsDevice,n=t?i.getHdrFormat():7,s=this.camera.entity.name+"-posteffect-"+this.effects.length,r=this._allocateColorBuffer(n,s);return new cr({colorBuffer:r,depth:e,stencil:e&&this.app.graphicsDevice.supportsStencil,samples:e?i.samples:1})},t._resizeOffscreenTarget=function(e){var t=e.colorBuffer.format,i=e.colorBuffer.name;e.destroyFrameBuffers(),e.destroyTextureBuffers(),e._colorBuffer=this._allocateColorBuffer(t,i)},t._destroyOffscreenTarget=function(e){e.destroyTextureBuffers(),e.destroy()},t.addEffect=function(e){var t=this.effects,i=0===t.length,n=this._createOffscreenTarget(i,e.hdr),s=new fx(e,n);t.push(s),this._sourceTarget=s.inputTarget,t.length>1&&(t[t.length-2].outputTarget=s.inputTarget),this._newPostEffect=e,e.needsDepthBuffer&&this._requestDepthMap(),this.enable(),this._newPostEffect=void 0},t.removeEffect=function(e){for(var t=-1,i=0,n=this.effects.length;i=0&&(t>0?this.effects[t-1].outputTarget=t+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[t].inputTarget),this.effects.splice(t,1)),this.enabled&&e.needsDepthBuffer&&this._releaseDepthMap(),0===this.effects.length&&this.disable()},t._requestDepthMaps=function(){for(var e=0,t=this.effects.length;e0}},{key:"renderSceneDepthMap",get:function(){return this._renderSceneDepthMap>0}},{key:"frustum",get:function(){return this._camera.frustum}},{key:"layers",get:function(){return this._camera.layers},set:function(e){for(var t=this._camera.layers,i=0;i=0&&(this.cameras.splice(t,1),_h(this.cameras))},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},t}(h_);Cl._buildAccessors(_x.prototype,vx);var xx=[],bx=[],Sx=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._cookieAsset=null,n._cookieAssetId=null,n._cookieAssetAdd=!1,n._cookieMatrix=null,n}J(t,e);var i=t.prototype;return i.addLightToLayers=function(){for(var e=0;e=0&&this.enabled&&this.entity.enabled&&e.addLight(this)},i.onLayerRemoved=function(e){this.layers.indexOf(e.id)>=0&&e.removeLight(this)},i.refreshProperties=function(){for(var e=0;eNumber.MAX_SAFE_INTEGER&&this._resetExecutionOrder(),e.enabled=!t.hasOwnProperty("enabled")||!!t.enabled,e.enabled&&e.entity.enabled&&this._enabledComponents.append(e),t.hasOwnProperty("order")&&t.hasOwnProperty("scripts")){e._scriptsData=t.scripts;for(var i=0;i=0&&t._onBeforeRemove(),this._removeComponentFromEnabled(t),this._components.remove(t)},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("initialize",this._onInitialize,this),this.app.systems.off("postInitialize",this._onPostInitialize,this),this.app.systems.off("update",this._onUpdate,this),this.app.systems.off("postUpdate",this._onPostUpdate,this)},t}(h_),Px="inline",Rx="immersive-vr",Ix="immersive-ar",Lx="viewer",Dx="left",kx="cpu-optimized",Ox="gpu-optimized",Fx="luminance-alpha",Bx=[],Nx=[],Ux=function(e){function t(t,i,n){var s;return(s=e.call(this)||this).manager=void 0,s._xrHitTestSource=void 0,s._transient=void 0,s.manager=t,s._xrHitTestSource=i,s._transient=n,s}J(t,e);var i=t.prototype;return i.remove=function(){if(this._xrHitTestSource){var e=this.manager.hitTest.sources,t=e.indexOf(this);-1!==t&&e.splice(t,1),this.onStop()}},i.onStop=function(){this._xrHitTestSource.cancel(),this._xrHitTestSource=null,this.fire("remove"),this.manager.hitTest.fire("remove",this)},i.update=function(e){if(this._transient)for(var t=e.getHitTestResultsForTransientInput(this._xrHitTestSource),i=0;ithis.views.length)for(var r=0;r<=s-this.views.length;r++){var a=this.viewsPool.pop();a||(a={viewport:new Se,projMat:new Ee,viewMat:new Ee,viewOffMat:new Ee,viewInvMat:new Ee,viewInvOffMat:new Ee,projViewOffMat:new Ee,viewMat3:new xe,position:new Float32Array(3),rotation:new Pe}),this.views.push(a)}else if(s<=this.views.length)for(var o=0;o=0},Kh.prototype.getModels=function(e){return this.models},Object.defineProperty(va.prototype,"model",{get:function(){return null}}),ah.prototype.renderComposition=function(e){Kr().renderComposition(e)},ah.prototype.updateShader=function(e,t,i,n,s){var r=e.material._scene||Kr().scene;return e.updatePassShader(r,n,i,s)},ka.prototype.syncAabb=function(){},rc.prototype.getTarget=function(e){return this.targets[e]},Hn.prototype._dirtify=function(e){e?this._dirtifyLocal():this._dirtifyWorld()},Hn.prototype.addLabel=function(e){this._labels[e]=!0},Hn.prototype.getLabels=function(){return Object.keys(this._labels)},Hn.prototype.hasLabel=function(e){return!!this._labels[e]},Hn.prototype.removeLabel=function(e){delete this._labels[e]},Hn.prototype.findByLabel=function(e,t){void 0===t&&(t=[]),this.hasLabel(e)&&t.push(this);for(var i=0;i