/** * @license * PlayCanvas Engine v1.46.5 revision e4663eb * Copyright 2011-2021 PlayCanvas Ltd. All rights reserved. */ !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";Array.prototype.fill||Object.defineProperty(Array.prototype,"fill",{value: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}),String.prototype.includes||(String.prototype.includes=function(e,t){return"number"!=typeof t&&(t=0),!(t+e.length>this.length)&&-1!==this.indexOf(e,t)}),String.prototype.startsWith||(String.prototype.startsWith=function(e,t){return this.substr(!t||t<0?0:+t,e.length)===e}),Int8Array.prototype.fill||(Int8Array.prototype.fill=Array.prototype.fill),Uint8Array.prototype.fill||(Uint8Array.prototype.fill=Array.prototype.fill),Uint8ClampedArray.prototype.fill||(Uint8ClampedArray.prototype.fill=Array.prototype.fill),Int16Array.prototype.fill||(Int16Array.prototype.fill=Array.prototype.fill),Uint16Array.prototype.fill||(Uint16Array.prototype.fill=Array.prototype.fill),Int32Array.prototype.fill||(Int32Array.prototype.fill=Array.prototype.fill),Uint32Array.prototype.fill||(Uint32Array.prototype.fill=Array.prototype.fill),Float32Array.prototype.fill||(Float32Array.prototype.fill=Array.prototype.fill);var t={};function i(e,i){var n;t[e]=!0,void 0!==i&&(n=i,window.console&&window.console.error&&window.console.error(n))}var n=function e(t){var i=t.gl;this.ext=t,this.isAlive=!0,this.hasBeenBound=!1,this.elementArrayBuffer=null,this.attribs=new Array(t.maxVertexAttribs);for(var n=0;n0?r=r.slice(0,r.length-2):(a>0&&r.push(y.delimiter),r.push(n[a])));return s=r.join(""),t||s[0]!==y.delimiter||(s=s.slice(1)),i&&s[s.length-1]!==y.delimiter&&(s+=y.delimiter),s},split:function(e){var t=e.split(y.delimiter),i=t.slice(t.length-1)[0];return[t.slice(0,t.length-1).join(y.delimiter),i]},getBasename:function(e){return y.split(e)[1]},getDirectory:function(e){var t=e.split(y.delimiter);return t.slice(0,t.length-1).join(y.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(y.isRelativePath(e))if("."===i[0])for(n=0;n0),C="getGamepads"in navigator,E="undefined"!=typeof Worker;try{var R=Object.defineProperty({},"passive",{get:function(){return P=!0,!1}});window.addEventListener("testpassive",null,R),window.removeEventListener("testpassive",null,R)}catch(e){}}var L="undefined"!=typeof window?"browser":"node",D={environment:L,global:"browser"===L?window:global,browser:"browser"===L,desktop:x,mobile:b,ios:M,android:w,windows:S,xbox:T,gamepads:C,touch:A,workers:E,passiveEvents:P},k="abcdefghijklmnopqrstuvwxyz",O="ABCDEFGHIJKLMNOPQRSTUVWXYZ",F=55296,B=127462,N=127487,z=65024,U=65039;function V(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>=F&&n<=56319){var s=e.charCodeAt(t+1);if(s>=56320&&s<=57343)return{code:1024*(n-F)+s-56320+65536,long:!0}}return{code:n,long:!1}}function G(e,t,i){if(!e)return!1;var n=V(e);if(n){var s=n.code;return s>=t&&s<=i}return!1}function W(e,t){if(t===e.length-1)return 1;if(G(e[t],F,56319)){var i=e.substring(t,t+2),n=e.substring(t+2,t+4);return G(n,127995,127999)||G(i,B,N)&&G(n,B,N)?4:G(n,z,U)?3:2}return G(e[t+1],z,U)?2:1}var H={ASCII_LOWERCASE:k,ASCII_UPPERCASE:O,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("")}},X=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}(),q=function(){function e(e){this._sortBy=e.sortBy,this.items=[],this.length=0,this.loopIndex=-1,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}();function j(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 te=function(e){function t(t){var i;return(i=e.call(this)||this)._index={},i._list=[],i._parent=t,i}Z(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)>>>32},lerp:function(e,t,i){return e+(t-e)*he.clamp(i,0,1)},lerpAngle:function(e,t,i){return t-e>180&&(t-=360),t-e<-180&&(t+=360),he.lerp(e,t,he.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},float2Half:(se=new Float32Array(1),re=new Int32Array(se.buffer),function(e){se[0]=e;var t=re[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)}),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].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;(a=s.getResponseHeader("Content-Type"))&&(o=a.split(";")[0].trim());try{r=o===this.ContentType.JSON||i.split("?")[0].endsWith(".json")?JSON.parse(s.responseText):this._isBinaryContentType(o)||s.responseType===e.ResponseType.ARRAY_BUFFER||s.responseType===e.ResponseType.BLOB||s.responseType===e.ResponseType.JSON?s.response:s.responseType===e.ResponseType.DOCUMENT||o===this.ContentType.XML?s.responseXML:s.responseText,n.callback(null,r)}catch(e){n.callback(e)}},t._onError=function(t,i,n,s){if(!n.retrying)if(n.retry&&n.retries7?t=he.intToBytes32(i):(t=he.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}();ue.BLACK=Object.freeze(new ue(0,0,0,1)),ue.BLUE=Object.freeze(new ue(0,0,1,1)),ue.CYAN=Object.freeze(new ue(0,1,1,1)),ue.GRAY=Object.freeze(new ue(.5,.5,.5,1)),ue.GREEN=Object.freeze(new ue(0,1,0,1)),ue.MAGENTA=Object.freeze(new ue(1,0,1,1)),ue.RED=Object.freeze(new ue(1,0,0,1)),ue.WHITE=Object.freeze(new ue(1,1,1,1)),ue.YELLOW=Object.freeze(new ue(1,1,0,1));var de=function(){function e(e,t){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||0)}var t=e.prototype;return t.evaluate=function(e,t){var i;(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?he.lerp(this._p0,this._p1,s):1===n?he.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}(),fe=function(){function e(e){if(this.keys=[],this.type=1,this.tension=.5,this._eval=new de(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 t=new e;return t.keys=l(t.keys,this.keys),t.type=this.type,t.tension=this.tension,t},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}();me.ZERO=Object.freeze(new me(0,0,0)),me.ONE=Object.freeze(new me(1,1,1)),me.UP=Object.freeze(new me(0,1,0)),me.DOWN=Object.freeze(new me(0,-1,0)),me.RIGHT=Object.freeze(new me(1,0,0)),me.LEFT=Object.freeze(new me(-1,0,0)),me.FORWARD=Object.freeze(new me(0,0,-1)),me.BACK=Object.freeze(new me(0,0,1));var _e=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 e).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(){for(var e="[",t=0;t<9;t++)e+=this.data[t],e+=8!==t?", ":"";return e+="]"},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 me);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}();_e.IDENTITY=Object.freeze(new _e),_e.ZERO=Object.freeze((new _e).set([0,0,0,0,0,0,0,0,0]));var ge=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 e(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}();ge.ZERO=Object.freeze(new ge(0,0)),ge.ONE=Object.freeze(new ge(1,1)),ge.UP=Object.freeze(new ge(0,1)),ge.DOWN=Object.freeze(new ge(0,-1)),ge.RIGHT=Object.freeze(new ge(1,0)),ge.LEFT=Object.freeze(new ge(-1,0));var ve=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 e(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}();ve.ZERO=Object.freeze(new ve(0,0,0,0)),ve.ONE=Object.freeze(new ve(1,1,1,1));var ye=new ge,xe=new me,be=new me,Se=new me,Te=new me,we=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 e).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],T=a[14],w=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+T*r,h[3]=d*i+_*n+x*s+w*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+T*r,h[7]=d*i+_*n+x*s+w*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+T*r,h[11]=d*i+_*n+x*s+w*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+T*r,h[15]=d*i+_*n+x*s+w*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 me);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 me);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 ve);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){Se.sub2(e,t).normalize(),be.copy(i).normalize(),xe.cross(be,Se).normalize(),be.cross(Se,xe);var n=this.data;return n[0]=xe.x,n[1]=xe.y,n[2]=xe.z,n[3]=0,n[4]=be.x,n[5]=be.y,n[6]=be.z,n[7]=0,n[8]=Se.x,n[9]=Se.y,n[10]=Se.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(ye,t,i,n,r),this.setFrustum(-ye.x,ye.x,-ye.y,ye.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*=he.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,T=l*p-c*f,w=l*m-u*f,M=l*_-d*f,A=c*m-u*p,C=c*_-d*p,E=u*_-d*m,P=g*E-v*C+y*A+x*M-b*w+S*T;if(0===P)this.setIdentity();else{var I=1/P;e[0]=(a*E-o*C+h*A)*I,e[1]=(-i*E+n*C-s*A)*I,e[2]=(p*S-m*b+_*x)*I,e[3]=(-c*S+u*b-d*x)*I,e[4]=(-r*E+o*M-h*w)*I,e[5]=(t*E-n*M+s*w)*I,e[6]=(-f*S+m*y-_*v)*I,e[7]=(l*S-u*y+d*v)*I,e[8]=(r*C-a*M+h*T)*I,e[9]=(-t*C+i*M-s*T)*I,e[10]=(f*b-p*y+_*g)*I,e[11]=(-l*b+c*y-d*g)*I,e[12]=(-r*A+a*w-o*T)*I,e[13]=(t*A-i*w+n*T)*I,e[14]=(-f*x+p*v-m*g)*I,e[15]=(l*x-c*v+u*g)*I}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 me),e.set(this.data[12],this.data[13],this.data[14])},t.getX=function(e){return void 0===e&&(e=new me),e.set(this.data[0],this.data[1],this.data[2])},t.getY=function(e){return void 0===e&&(e=new me),e.set(this.data[4],this.data[5],this.data[6])},t.getZ=function(e){return void 0===e&&(e=new me),e.set(this.data[8],this.data[9],this.data[10])},t.getScale=function(e){return void 0===e&&(e=new me),this.getX(xe),this.getY(be),this.getZ(Se),e.set(xe.length(),be.length(),Se.length()),e},t.setFromEulerAngles=function(e,t,i){e*=he.DEG_TO_RAD,t*=he.DEG_TO_RAD,i*=he.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 me),this.getScale(Te);var t=Te.x,i=Te.y,n=Te.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(he.RAD_TO_DEG)},t.toString=function(){for(var e="[",t=0;t<16;t+=1)e+=this.data[t],e+=15!==t?", ":"";return e+="]"},e}();we.IDENTITY=Object.freeze(new we),we.ZERO=Object.freeze((new we).set([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]));var Me=function(){function e(e,t,i,n){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=1),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 e(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*he.RAD_TO_DEG},t.getEulerAngles=function(e){var t,i,n;void 0===e&&(e=new me);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(he.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*he.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){var n=.5*he.DEG_TO_RAD;e*=n,t*=n,i*=n;var s=Math.sin(e),r=Math.cos(e),a=Math.sin(t),o=Math.cos(t),h=Math.sin(i),l=Math.cos(i);return this.x=s*o*l-r*a*h,this.y=r*a*l+s*o*h,this.z=r*o*h-s*a*l,this.w=r*o*l+s*a*h,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 me);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}();Me.IDENTITY=Object.freeze(new Me(0,0,0,1)),Me.ZERO=Object.freeze(new Me(0,0,0,0));var Ae=new me,Ce=new me,Ee=new me,Pe=new me,Ie=new me,Re=function(){function e(e,t){void 0===e&&(e=new me),void 0===t&&(t=new me(.5,.5,.5)),this.center=e,this.halfExtents=t,this._min=new me,this._max=new me}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,T=_-x,w=_+x,M=g-b,A=g+b,C=v-S,E=v+S;Tc&&(c=w),Md&&(d=A),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=Ae.copy(this.getMin()).sub(e.origin),n=Ce.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=Ee.set(Math.min(i.x,n.x),Math.min(i.y,n.y),Math.min(i.z,n.z)),a=Pe.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=Ae,i=Ce,n=Ee,s=Pe,r=Ie,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){var i=e.center,n=e.halfExtents,s=t.data,r=s[0],a=s[4],o=s[8],h=s[1],l=s[5],c=s[9],u=s[2],d=s[6],f=s[10];this.center.set(s[12]+r*i.x+a*i.y+o*i.z,s[13]+h*i.x+l*i.y+c*i.z,s[14]+u*i.x+d*i.y+f*i.z),this.halfExtents.set(Math.abs(r)*n.x+Math.abs(a)*n.y+Math.abs(o)*n.z,Math.abs(h)*n.x+Math.abs(l)*n.y+Math.abs(c)*n.z,Math.abs(u)*n.x+Math.abs(d)*n.y+Math.abs(f)*n.z)},t.compute=function(e,t){if((t=void 0===t?e.length/3:t)>0){for(var i=Ae.set(e[0],e[1],e[2]),n=Ce.set(e[0],e[1],e[2]),s=1;sn.x&&(n.x=r),a>n.y&&(n.y=a),o>n.z&&(n.z=o)}this.setMinMax(i,n)}},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){Ae.add2(this.getMin(),e),Ce.add2(this.getMax(),t),this.setMinMax(Ae,Ce)},e}(),Le=new me,De=new me,ke=function(){function e(e,t){void 0===e&&(e=new me),void 0===t&&(t=.5),this.center=e,this.radius=t}var t=e.prototype;return t.containsPoint=function(e){var t=Le.sub2(e,this.center).lengthSq(),i=this.radius;return t0&&n>0)return null;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){Le.sub2(e.center,this.center);var t=e.radius+this.radius;return Le.lengthSq()<=t*t},e}(),Oe="none",Fe="linear",Be=64,Ne=128,ze=256,Ue=1024,Ve=2048,Ge=4096,We=18,He=[new me,new me,new me,new me,new me,new me,new me,new me],Xe=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=He;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}(),qe=function(){function e(e,t){void 0===e&&(e=new me),void 0===t&&(t=new me(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}(),je=new qe,Ye=new me,Ke=new ke,Ze=new we,$e=function(){function e(e,t){void 0===e&&(e=new we),void 0===t&&(t=new me(.5,.5,.5)),this.halfExtents=t,this._modelTransform=e.clone().invert(),this._worldTransform=e.clone(),this._aabb=new Re(new me,this.halfExtents)}var t=e.prototype;return t.intersectsRay=function(e,t){if(this._modelTransform.transformPoint(e.origin,je.origin),this._modelTransform.transformVector(e.direction,je.direction),t){var i=this._aabb._intersectsRay(je,t);return Ze.copy(this._modelTransform).invert().transformPoint(t,t),i}return this._aabb._fastIntersectsRay(je)},t.containsPoint=function(e){return this._modelTransform.transformPoint(e,Ye),this._aabb.containsPoint(Ye)},t.intersectsBoundingSphere=function(e){return this._modelTransform.transformPoint(e.center,Ke.center),Ke.radius=e.radius,!!this._aabb.intersectsBoundingSphere(Ke)},Y(e,[{key:"worldTransform",get:function(){return this._worldTransform},set:function(e){this._worldTransform.copy(e),this._modelTransform.copy(e).invert()}}]),e}(),Qe=new me,Je=function(){function e(e,t){void 0===e&&(e=new me),void 0===t&&(t=new me(0,0,1)),this.normal=t,this.point=e}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=Qe.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}(),et=10,tt=11,it=12,nt=13,st=14,rt=16,at=17,ot=21,ht=24,lt=25,ct="POSITION",ut="NORMAL",dt="TANGENT",ft="BLENDWEIGHT",pt="BLENDINDICES",mt="COLOR",_t="TEXCOORD",gt="TEXCOORD0",vt="TEXCOORD1",yt="TEXCOORD2",xt="TEXCOORD3",bt="TEXCOORD4",St="TEXCOORD5",Tt="TEXCOORD6",wt="TEXCOORD7",Mt="ATTR",At="ATTR0",Ct="ATTR1",Et="ATTR2",Pt="ATTR3",It="ATTR4",Rt="ATTR5",Lt="ATTR6",Dt="ATTR7",kt="ATTR8",Ot="ATTR9",Ft="ATTR10",Bt="ATTR11",Nt="ATTR12",zt="ATTR13",Ut="ATTR14",Vt="ATTR15",Gt="default",Wt="rgbm",Ht="rgbe",Xt="swizzleGGGR",qt="none",jt="cube",Yt="equirect",Kt="octahedral",Zt=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array],$t=[1,1,2,2,4,4,4],Qt={Int8Array:0,Uint8Array:1,Int16Array:2,Uint16Array:3,Int32Array:4,Uint32Array:5,Float32Array:6},Jt=[Uint8Array,Uint16Array,Uint32Array],ei={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},ti=0,ii=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=ti++,this._vao=null,this.instancing=!1,this.numBytes=t.verticesByteSize?t.verticesByteSize:t.size*i,e._vram.vb+=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);if(-1!==t&&e.buffers.splice(t,1),this.bufferId){var i=e.gl;e.boundVao=null,i.bindVertexArray(null),i.deleteBuffer(this.bufferId),e._vram.vb-=this.storage.byteLength,this.bufferId=null}},t.loseContext=function(){this.bufferId=void 0,this._vao=null},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(){var e,t=this.device.gl;switch(this.bufferId||(this.bufferId=t.createBuffer()),this.usage){case 0:e=t.STATIC_DRAW;break;case 1:e=t.DYNAMIC_DRAW;break;case 2:e=t.STREAM_DRAW;break;case 3:e=this.device.webgl2?t.DYNAMIC_COPY:t.STATIC_DRAW}t.bindBuffer(t.ARRAY_BUFFER,this.bufferId),t.bufferData(t.ARRAY_BUFFER,this.storage,e)},t.setData=function(e){return e.byteLength!==this.numBytes?(console.error("VertexBuffer: wrong initial data size: expected "+this.numBytes+", got "+e.byteLength),!1):(this.storage=e,this.unlock(),!0)},e}();function ni(e){for(var t=0,i=0,n=e.length;ithis.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;h 0.5) {\n\t\tif (dAtten > 0.00001) {\n\t\t\tdirLm.xyz = dirLm.xyz * 2.0 - vec3(1.0);\n\t\t\tdAtten = saturate(dAtten);\n\t\t\tgl_FragColor.rgb = normalize(dLightDirNormW.xyz*dAtten + dirLm.xyz*dirLm.w) * 0.5 + vec3(0.5);\n\t\t\tgl_FragColor.a = dirLm.w + dAtten;\n\t\t\tgl_FragColor.a = max(gl_FragColor.a, 1.0 / 255.0);\n\t\t} else {\n\t\t\tgl_FragColor = dirLm;\n\t\t}\n\t} else {\n\t\tgl_FragColor.rgb = dirLm.xyz;\n\t\tgl_FragColor.a = max(dirLm.w, dAtten > 0.00001? (1.0/255.0) : 0.0);\n\t}\n",bakeLmEndPS:"\tgl_FragColor.rgb = dDiffuseLight;\n\tgl_FragColor.rgb = pow(gl_FragColor.rgb, vec3(0.5));\n\tgl_FragColor.rgb /= 8.0;\n\tgl_FragColor.a = clamp( max( max( gl_FragColor.r, gl_FragColor.g ), max( gl_FragColor.b, 1.0 / 255.0 ) ), 0.0,1.0 );\n\tgl_FragColor.a = ceil(gl_FragColor.a * 255.0) / 255.0;\n\tgl_FragColor.rgb /= gl_FragColor.a;\n",basePS:"uniform vec3 view_position;\nuniform vec3 light_globalAmbient;\nfloat square(float x) {\n\treturn x*x;\n}\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\nvec3 saturate(vec3 x) {\n\treturn clamp(x, vec3(0.0), vec3(1.0));\n}\n",baseVS:"attribute vec3 vertex_position;\nattribute vec3 vertex_normal;\nattribute vec4 vertex_tangent;\nattribute vec2 vertex_texCoord0;\nattribute vec2 vertex_texCoord1;\nattribute vec4 vertex_color;\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\nuniform mat3 matrix_normal;\nvec3 dPositionW;\nmat4 dModelMatrix;\nmat3 dNormalMatrix;\n",baseNineSlicedPS:"#define NINESLICED\nvarying vec2 vMask;\nvarying vec2 vTiledUv;\nuniform mediump vec4 innerOffset;\nuniform mediump vec2 outerScale;\nuniform mediump vec4 atlasRect;\nvec2 nineSlicedUv;\n",baseNineSlicedVS:"#define NINESLICED\nvarying vec2 vMask;\nvarying vec2 vTiledUv;\nuniform mediump vec4 innerOffset;\nuniform mediump vec2 outerScale;\nuniform mediump vec4 atlasRect;\n",baseNineSlicedTiledPS:"#define NINESLICED\n#define NINESLICETILED\nvarying vec2 vMask;\nvarying vec2 vTiledUv;\nuniform mediump vec4 innerOffset;\nuniform mediump vec2 outerScale;\nuniform mediump vec4 atlasRect;\nvec2 nineSlicedUv;\n",biasConstPS:"#define SHADOWBIAS\nfloat getShadowBias(float resolution, float maxBias) {\n\treturn maxBias;\n}\n",blurVSMPS:"varying vec2 vUv0;\nuniform sampler2D source;\nuniform vec2 pixelOffset;\n#ifdef GAUSS\nuniform float weight[SAMPLES];\n#endif\n#ifdef PACKED\nfloat decodeFloatRG(vec2 rg) {\n\treturn rg.y*(1.0/255.0) + rg.x;\n}\nvec2 encodeFloatRG( float v ) {\n\tvec2 enc = vec2(1.0, 255.0) * v;\n\tenc = fract(enc);\n\tenc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n\treturn enc;\n}\n#endif\nvoid main(void) {\n\tvec3 moments = vec3(0.0);\n\tvec2 uv = vUv0 - pixelOffset * (float(SAMPLES) * 0.5);\n\tfor (int i=0; i clusterPixelsPerCell) {\n\t\t\tbreak;\n\t\t}\n\t}\n}\n",clusteredLightPS:"uniform sampler2D clusterWorldTexture;\nuniform sampler2D lightsTexture8;\nuniform highp sampler2D lightsTextureFloat;\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;\nfloat DecodeClusterFloat4(vec4 data) {\n\treturn dot(data, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n}\nfloat DecodeClusterFloat2(vec2 data) {\n\treturn dot(data, vec2(1.0, 1.0 / 255.0));\n}\nvoid EvaluateClusterLight(float lightIndex) {\n\tfloat lightV = (lightIndex + 0.5) * lightsTextureInvSize.w;\n\tvec4 lightInfo = texture2D(lightsTexture8, vec2(0.5 * lightsTextureInvSize.z, lightV));\n\tfloat lightType = lightInfo.x;\n\tfloat lightShape = lightInfo.y;\n\tfloat falloffMode = lightInfo.z;\n\tvec4 colorA = texture2D(lightsTexture8, vec2(1.5 * lightsTextureInvSize.z, lightV));\n\tvec4 colorB = texture2D(lightsTexture8, vec2(2.5 * lightsTextureInvSize.z, lightV));\n\tvec3 lightColor = vec3(\n\t\tDecodeClusterFloat2(colorA.xy),\n\t\tDecodeClusterFloat2(colorA.zw),\n\t\tDecodeClusterFloat2(colorB.xy)\n\t) * clusterCompressionLimit0.y;\n\tvec4 coneAngle = texture2D(lightsTexture8, vec2(3.5 * lightsTextureInvSize.z, lightV));\n\tfloat innerConeAngleCos = DecodeClusterFloat2(coneAngle.xy) * 2.0 - 1.0;\n\tfloat outerConeAngleCos = DecodeClusterFloat2(coneAngle.zw) * 2.0 - 1.0;\n\t#ifdef CLUSTER_TEXTURE_FLOAT\n\t\tvec4 lightPosRange = texture2D(lightsTextureFloat, vec2(0.5 * lightsTextureInvSize.x, lightV));\n\t\tvec3 lightPos = lightPosRange.xyz;\n\t\tfloat range = lightPosRange.w;\n\t\tvec4 lightDir_Unused = texture2D(lightsTextureFloat, vec2(1.5 * lightsTextureInvSize.x, lightV));\n\t\tvec3 lightDir = lightDir_Unused.xyz;\n\t#else\n\t\tvec4 encPosX = texture2D(lightsTexture8, vec2(4.5 * lightsTextureInvSize.z, lightV));\n\t\tvec4 encPosY = texture2D(lightsTexture8, vec2(5.5 * lightsTextureInvSize.z, lightV));\n\t\tvec4 encPosZ = texture2D(lightsTexture8, vec2(6.5 * lightsTextureInvSize.z, lightV));\n\t\tvec3 lightPos = vec3(\n\t\t\tDecodeClusterFloat4(encPosX),\n\t\t\tDecodeClusterFloat4(encPosY),\n\t\t\tDecodeClusterFloat4(encPosZ)\n\t\t) * clusterBoundsDelta + clusterBoundsMin;\n\t\tvec4 encRange = texture2D(lightsTexture8, vec2(7.5 * lightsTextureInvSize.z, lightV));\n\t\tfloat range = DecodeClusterFloat4(encRange) * clusterCompressionLimit0.x;\n\t\tvec4 encDirX = texture2D(lightsTexture8, vec2(8.5 * lightsTextureInvSize.z, lightV));\n\t\tvec4 encDirY = texture2D(lightsTexture8, vec2(9.5 * lightsTextureInvSize.z, lightV));\n\t\tvec4 encDirZ = texture2D(lightsTexture8, vec2(10.5 * lightsTextureInvSize.z, lightV));\n\t\tvec3 lightDir = vec3(\n\t\t\tDecodeClusterFloat4(encDirX),\n\t\t\tDecodeClusterFloat4(encDirY),\n\t\t\tDecodeClusterFloat4(encDirZ)\n\t\t) * 2.0 - 1.0;\n\t#endif\n\tgetLightDirPoint(lightPos);\n\tdAtten = getFalloffLinear(range);\n\tif (dAtten > 0.00001) {\n\t\tif (lightType > 0.5) {\n\t\t\tdAtten *= getSpotEffect(lightDir, innerConeAngleCos, outerConeAngleCos);\n\t\t}\n\t\tdAtten *= getLightDiffuse();\n\t\tdDiffuseLight += dAtten * lightColor;\n\t}\n}\n",combineClearCoatPS:"vec3 combineColorCC() {\n\treturn combineColor()+(ccSpecularLight*ccSpecularity+ccReflection.rgb*ccSpecularity*ccReflection.a);\n}\n",combineDiffusePS:"vec3 combineColor() {\n\treturn dAlbedo * dDiffuseLight;\n}\n",combineDiffuseSpecularPS:"vec3 combineColor() {\n\treturn mix(dAlbedo * dDiffuseLight, dSpecularLight + dReflection.rgb * dReflection.a, dSpecularity);\n}\n",combineDiffuseSpecularNoConservePS:"vec3 combineColor() {\n\treturn dAlbedo * dDiffuseLight + (dSpecularLight + dReflection.rgb * dReflection.a) * dSpecularity;\n}\n",combineDiffuseSpecularNoReflPS:"vec3 combineColor() {\n\treturn dAlbedo * dDiffuseLight + dSpecularLight * dSpecularity;\n}\n",combineDiffuseSpecularNoReflSeparateAmbientPS:"uniform vec3 material_ambient;\nvec3 combineColor() {\n\treturn (dDiffuseLight - light_globalAmbient) * dAlbedo + dSpecularLight * dSpecularity + material_ambient * light_globalAmbient;\n}\n",combineDiffuseSpecularOldPS:"vec3 combineColor() {\n\treturn mix(dAlbedo * dDiffuseLight + dSpecularLight * dSpecularity, dReflection.rgb, dReflection.a);\n}\n",cookiePS:"vec4 getCookie2D(sampler2D tex, mat4 transform, float intensity) {\n\tvec4 projPos = transform * vec4(vPositionW, 1.0);\n\tprojPos.xy /= projPos.w;\n\treturn mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);\n}\nvec4 getCookie2DClip(sampler2D tex, mat4 transform, float intensity) {\n\tvec4 projPos = transform * vec4(vPositionW, 1.0);\n\tprojPos.xy /= projPos.w;\n\tif (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0);\n\treturn mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);\n}\nvec4 getCookie2DXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {\n\tvec4 projPos = transform * vec4(vPositionW, 1.0);\n\tprojPos.xy /= projPos.w;\n\tprojPos.xy += cookieOffset;\n\tvec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);\n\treturn mix(vec4(1.0), texture2D(tex, uv), intensity);\n}\nvec4 getCookie2DClipXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {\n\tvec4 projPos = transform * vec4(vPositionW, 1.0);\n\tprojPos.xy /= projPos.w;\n\tprojPos.xy += cookieOffset;\n\tif (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0);\n\tvec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);\n\treturn mix(vec4(1.0), texture2D(tex, uv), intensity);\n}\nvec4 getCookieCube(samplerCube tex, mat4 transform, float intensity) {\n\treturn mix(vec4(1.0), textureCube(tex, dLightDirNormW * mat3(transform)), intensity);\n}\n",cubeMapProjectBoxPS:"uniform vec3 envBoxMin, envBoxMax;\nvec3 cubeMapProject(vec3 nrdir) {\n\tnrdir = cubeMapRotate(nrdir);\n\tvec3 rbmax = (envBoxMax - vPositionW) / nrdir;\n\tvec3 rbmin = (envBoxMin - vPositionW) / nrdir;\n\tvec3 rbminmax;\n\trbminmax.x = nrdir.x>0.0? rbmax.x : rbmin.x;\n\trbminmax.y = nrdir.y>0.0? rbmax.y : rbmin.y;\n\trbminmax.z = nrdir.z>0.0? rbmax.z : rbmin.z;\n\tfloat fa = min(min(rbminmax.x, rbminmax.y), rbminmax.z);\n\tvec3 posonbox = vPositionW + nrdir * fa;\n\tvec3 envBoxPos = (envBoxMin + envBoxMax) * 0.5;\n\treturn posonbox - envBoxPos;\n}\n",cubeMapProjectNonePS:"vec3 cubeMapProject(vec3 dir) {\n\treturn cubeMapRotate(dir);\n}\n",cubeMapRotatePS:"#ifdef CUBEMAP_ROTATION\nuniform mat3 cubeMapRotationMatrix;\n#endif\nvec3 cubeMapRotate(vec3 refDir) {\n#ifdef CUBEMAP_ROTATION\n\treturn refDir * cubeMapRotationMatrix;\n#else\n\treturn refDir;\n#endif\n}\n",detailModesPS:"vec3 detailMode_mul(vec3 c1, vec3 c2) {\n\treturn c1 * c2;\n}\nvec3 detailMode_add(vec3 c1, vec3 c2) {\n\treturn c1 + c2;\n}\nvec3 detailMode_screen(vec3 c1, vec3 c2) {\n\treturn 1.0 - (1.0 - c1)*(1.0 - c2);\n}\nvec3 detailMode_overlay(vec3 c1, vec3 c2) {\n\treturn mix(1.0 - 2.0*(1.0 - c1)*(1.0 - c2), 2.0*c1*c2, step(c1, vec3(0.5)));\n}\nvec3 detailMode_min(vec3 c1, vec3 c2) {\n\treturn min(c1, c2);\n}\nvec3 detailMode_max(vec3 c1, vec3 c2) {\n\treturn max(c1, c2);\n}\n",diffusePS:"#ifdef MAPCOLOR\nuniform vec3 material_diffuse;\n#endif\n#ifdef MAPTEXTURE\nuniform sampler2D texture_diffuseMap;\n#endif\nvoid getAlbedo() {\n\tdAlbedo = vec3(1.0);\n\t#ifdef MAPCOLOR\n\tdAlbedo *= material_diffuse.rgb;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tdAlbedo *= gammaCorrectInput(addAlbedoDetail(texture2D(texture_diffuseMap, $UV).$CH));\n\t#endif\n\t#ifdef MAPVERTEX\n\tdAlbedo *= gammaCorrectInput(saturate(vVertexColor.$VC));\n\t#endif\n}\n",diffuseDetailMapPS:"#ifdef MAPTEXTURE\nuniform sampler2D texture_diffuseDetailMap;\n#endif\nvec3 addAlbedoDetail(vec3 albedo) {\n\t#ifdef MAPTEXTURE\n\tvec3 albedoDetail = vec3(texture2D(texture_diffuseDetailMap, $UV).$CH);\n\treturn detailMode_$DETAILMODE(albedo, albedoDetail);\n\t#else\n\treturn albedo;\n\t#endif\n}\n",dilatePS:"varying vec2 vUv0;\nuniform sampler2D source;\nuniform vec2 pixelOffset;\nvoid main(void) {\n\tvec4 c = texture2D(source, vUv0);\n\tc = c.a>0.0? c : texture2D(source, vUv0 - pixelOffset);\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(0, -pixelOffset.y));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(pixelOffset.x, -pixelOffset.y));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(-pixelOffset.x, 0));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(pixelOffset.x, 0));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(-pixelOffset.x, pixelOffset.y));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + vec2(0, pixelOffset.y));\n\tc = c.a>0.0? c : texture2D(source, vUv0 + pixelOffset);\n\tgl_FragColor = c;\n}\n",dpAtlasQuadPS:"varying vec2 vUv0;\nuniform sampler2D source;\nuniform vec4 params;\nvoid main(void) {\n\tvec2 uv = vUv0;\n\tuv = uv * 2.0 - vec2(1.0);\n\tuv *= params.xy;\n\tuv = uv * 0.5 + 0.5;\n\tgl_FragColor = texture2D(source, uv);\n}\n",emissivePS:"#ifdef MAPCOLOR\nuniform vec3 material_emissive;\n#endif\n#ifdef MAPFLOAT\nuniform float material_emissiveIntensity;\n#endif\n#ifdef MAPTEXTURE\nuniform sampler2D texture_emissiveMap;\n#endif\nvec3 getEmission() {\n\tvec3 emission = vec3(1.0);\n\t#ifdef MAPFLOAT\n\temission *= material_emissiveIntensity;\n\t#endif\n\t#ifdef MAPCOLOR\n\temission *= material_emissive;\n\t#endif\n\t#ifdef MAPTEXTURE\n\temission *= $texture2DSAMPLE(texture_emissiveMap, $UV).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\temission *= gammaCorrectInput(saturate(vVertexColor.$VC));\n\t#endif\n\treturn emission;\n}\n",endPS:"\t#ifdef CLEARCOAT\n\tgl_FragColor.rgb = combineColorCC();\n\t#else\n\tgl_FragColor.rgb = combineColor();\n\t#endif\n\tgl_FragColor.rgb += getEmission();\n\tgl_FragColor.rgb = addFog(gl_FragColor.rgb);\n\t#ifndef HDR\n\tgl_FragColor.rgb = toneMap(gl_FragColor.rgb);\n\tgl_FragColor.rgb = gammaCorrectOutput(gl_FragColor.rgb);\n\t#endif\n",endVS:"\n",envConstPS:"vec3 processEnvironment(vec3 color) {\n\treturn color;\n}\n",envMultiplyPS:"uniform float skyboxIntensity;\nvec3 processEnvironment(vec3 color) {\n\treturn color * skyboxIntensity;\n}\n",extensionPS:"\n",extensionVS:"\n",falloffInvSquaredPS:"float getFalloffWindow(float lightRadius) {\n\tfloat sqrDist = dot(dLightDirW, dLightDirW);\n\tfloat invRadius = 1.0 / lightRadius;\n\treturn square( saturate( 1.0 - square( sqrDist * square(invRadius) ) ) );\n}\nfloat getFalloffInvSquared(float lightRadius) {\n\tfloat sqrDist = dot(dLightDirW, dLightDirW);\n\tfloat falloff = 1.0 / (sqrDist + 1.0);\n\tfloat invRadius = 1.0 / lightRadius;\n\tfalloff *= 16.0;\n\tfalloff *= square( saturate( 1.0 - square( sqrDist * square(invRadius) ) ) );\n\treturn falloff;\n}\n",falloffLinearPS:"float getFalloffLinear(float lightRadius) {\n\tfloat d = length(dLightDirW);\n\treturn max(((lightRadius - d) / lightRadius), 0.0);\n}\n",fixCubemapSeamsNonePS:"vec3 fixSeams(vec3 vec, float mipmapIndex) {\n\treturn vec;\n}\nvec3 fixSeams(vec3 vec) {\n\treturn vec;\n}\nvec3 fixSeamsStatic(vec3 vec, float invRecMipSize) {\n\treturn vec;\n}\nvec3 calcSeam(vec3 vec) {\n\treturn vec3(0);\n}\nvec3 applySeam(vec3 vec, vec3 seam, float scale) {\n\treturn vec;\n}\n",fixCubemapSeamsStretchPS:"vec3 fixSeams(vec3 vec, float mipmapIndex) {\n\tfloat scale = 1.0 - exp2(mipmapIndex) / 128.0;\n\tfloat M = max(max(abs(vec.x), abs(vec.y)), abs(vec.z));\n\tif (abs(vec.x) != M) vec.x *= scale;\n\tif (abs(vec.y) != M) vec.y *= scale;\n\tif (abs(vec.z) != M) vec.z *= scale;\n\treturn vec;\n}\nvec3 fixSeams(vec3 vec) {\n\tfloat scale = 1.0 - 1.0 / 128.0;\n\tfloat M = max(max(abs(vec.x), abs(vec.y)), abs(vec.z));\n\tif (abs(vec.x) != M) vec.x *= scale;\n\tif (abs(vec.y) != M) vec.y *= scale;\n\tif (abs(vec.z) != M) vec.z *= scale;\n\treturn vec;\n}\nvec3 fixSeamsStatic(vec3 vec, float invRecMipSize) {\n\tfloat scale = invRecMipSize;\n\tfloat M = max(max(abs(vec.x), abs(vec.y)), abs(vec.z));\n\tif (abs(vec.x) != M) vec.x *= scale;\n\tif (abs(vec.y) != M) vec.y *= scale;\n\tif (abs(vec.z) != M) vec.z *= scale;\n\treturn vec;\n}\nvec3 calcSeam(vec3 vec) {\n\tvec3 avec = abs(vec);\n\tfloat M = max(avec.x, max(avec.y, avec.z));\n\treturn vec3(avec.x != M ? 1.0 : 0.0,\n\t\t\t\tavec.y != M ? 1.0 : 0.0,\n\t\t\t\tavec.z != M ? 1.0 : 0.0);\n}\nvec3 applySeam(vec3 vec, vec3 seam, float scale) {\n\treturn vec * (seam * -scale + vec3(1.0));\n}\n",fogExpPS:"uniform vec3 fog_color;\nuniform float fog_density;\nfloat dBlendModeFogFactor = 1.0;\nvec3 addFog(vec3 color) {\n\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\tfloat fogFactor = exp(-depth * fog_density);\n\tfogFactor = clamp(fogFactor, 0.0, 1.0);\n\treturn mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogExp2PS:"uniform vec3 fog_color;\nuniform float fog_density;\nfloat dBlendModeFogFactor = 1.0;\nvec3 addFog(vec3 color) {\n\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\tfloat fogFactor = exp(-depth * depth * fog_density * fog_density);\n\tfogFactor = clamp(fogFactor, 0.0, 1.0);\n\treturn mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogLinearPS:"uniform vec3 fog_color;\nuniform float fog_start;\nuniform float fog_end;\nfloat dBlendModeFogFactor = 1.0;\nvec3 addFog(vec3 color) {\n\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\tfloat fogFactor = (fog_end - depth) / (fog_end - fog_start);\n\tfogFactor = clamp(fogFactor, 0.0, 1.0);\n\tfogFactor = gammaCorrectInput(fogFactor);\n\treturn mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogNonePS:"float dBlendModeFogFactor = 1.0;\nvec3 addFog(vec3 color) {\n\treturn color;\n}\n",fresnelSchlickPS:"\nuniform float material_fresnelFactor;\nvoid getFresnel() {\n\tfloat fresnel = 1.0 - max(dot(dNormalW, dViewDirW), 0.0);\n\tfloat fresnel2 = fresnel * fresnel;\n\tfresnel *= fresnel2 * fresnel2;\n\tfresnel *= dGlossiness * dGlossiness;\n\tdSpecularity = dSpecularity + (1.0 - dSpecularity) * fresnel;\n\t#ifdef CLEARCOAT\n\tfresnel = 1.0 - max(dot(ccNormalW, dViewDirW), 0.0);\n\tfresnel2 = fresnel * fresnel;\n\tfresnel *= fresnel2 * fresnel2;\n\tfresnel *= ccGlossiness * ccGlossiness;\n\tccSpecularity = ccSpecularity + (1.0 - ccSpecularity) * fresnel;\n\t#endif\n}\n",fullscreenQuadPS:"varying vec2 vUv0;\nuniform sampler2D source;\nvoid main(void) {\n\tgl_FragColor = texture2D(source, vUv0);\n}\n",fullscreenQuadVS:"attribute vec2 vertex_position;\nvarying vec2 vUv0;\nvoid main(void)\n{\n\tgl_Position = vec4(vertex_position, 0.5, 1.0);\n\tvUv0 = vertex_position.xy*0.5+0.5;\n}\n",gamma1_0PS:"vec4 texture2DSRGB(sampler2D tex, vec2 uv) {\n\treturn texture2D(tex, uv);\n}\nvec4 texture2DSRGB(sampler2D tex, vec2 uv, float bias) {\n\treturn texture2D(tex, uv, bias);\n}\nvec4 textureCubeSRGB(samplerCube tex, vec3 uvw) {\n\treturn textureCube(tex, uvw);\n}\nvec3 gammaCorrectOutput(vec3 color) {\n\treturn color;\n}\nvec3 gammaCorrectInput(vec3 color) {\n\treturn color;\n}\nfloat gammaCorrectInput(float color) {\n\treturn color;\n}\nvec4 gammaCorrectInput(vec4 color) {\n\treturn color;\n}\n",gamma2_2PS:"vec3 gammaCorrectInput(vec3 color) {\n\treturn pow(color, vec3(2.2));\n}\nfloat gammaCorrectInput(float color) {\n\treturn pow(color, 2.2);\n}\nvec4 gammaCorrectInput(vec4 color) {\n\treturn vec4(pow(color.rgb, vec3(2.2)), color.a);\n}\nvec4 texture2DSRGB(sampler2D tex, vec2 uv) {\n\tvec4 rgba = texture2D(tex, uv);\n\trgba.rgb = gammaCorrectInput(rgba.rgb);\n\treturn rgba;\n}\nvec4 texture2DSRGB(sampler2D tex, vec2 uv, float bias) {\n\tvec4 rgba = texture2D(tex, uv, bias);\n\trgba.rgb = gammaCorrectInput(rgba.rgb);\n\treturn rgba;\n}\nvec4 textureCubeSRGB(samplerCube tex, vec3 uvw) {\n\tvec4 rgba = textureCube(tex, uvw);\n\trgba.rgb = gammaCorrectInput(rgba.rgb);\n\treturn rgba;\n}\nvec3 gammaCorrectOutput(vec3 color) {\n\t#ifdef HDR\n\treturn color;\n\t#else\n\tcolor += vec3(0.0000001);\n\treturn pow(color, vec3(0.45));\n\t#endif\n}\n",genParaboloidPS:"varying vec2 vUv0;\nuniform samplerCube source;\nuniform vec4 params;\nvoid main(void) {\n\tvec2 uv = vUv0;\n\tfloat side = uv.x < 0.5? 1.0 : -1.0;\n\tvec2 tc;\n\ttc.x = fract(uv.x * 2.0) * 2.0 - 1.0;\n\ttc.y = uv.y * 2.0 - 1.0;\n\tconst float scale = 1.1;\n\ttc *= scale;\n\tvec3 dir;\n\tdir.y = (dot(tc, tc) - 1.0) * side;\n\tdir.xz = tc * -2.0;\n\tdir.x *= -side * params.y;\n\tdir = fixSeams(dir, params.x);\n\tvec4 color = textureCube(source, dir, -100.0);\n\tgl_FragColor = color;\n}\n",gles3PS:"#define varying in\nout highp vec4 pc_fragColor;\n#define gl_FragColor pc_fragColor\n#define texture2D 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",gles3VS:"#define attribute in\n#define varying out\n#define texture2D texture\n#define GL2\n#define VERTEXSHADER\n",glossPS:"#ifdef MAPFLOAT\nuniform float material_shininess;\n#endif\n#ifdef MAPTEXTURE\nuniform sampler2D texture_glossMap;\n#endif\nvoid getGlossiness() {\n\tdGlossiness = 1.0;\n\t#ifdef MAPFLOAT\n\tdGlossiness *= material_shininess;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tdGlossiness *= texture2D(texture_glossMap, $UV).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tdGlossiness *= saturate(vVertexColor.$VC);\n\t#endif\n\tdGlossiness += 0.0000001;\n}\n",instancingVS:"attribute vec4 instance_line1;\nattribute vec4 instance_line2;\nattribute vec4 instance_line3;\nattribute vec4 instance_line4;\n",lightDiffuseLambertPS:"float getLightDiffuse() {\n\treturn max(dot(dNormalW, -dLightDirNormW), 0.0);\n}\n",lightDirPointPS:"void getLightDirPoint(vec3 lightPosW) {\n\tdLightDirW = vPositionW - lightPosW;\n\tdLightDirNormW = normalize(dLightDirW);\n\tdLightPosW = lightPosW;\n}\n",lightmapDirPS:"uniform sampler2D texture_lightMap;\nuniform sampler2D texture_dirLightMap;\nvoid addLightMap() {\n\tvec3 color = $texture2DSAMPLE(texture_lightMap, $UV).$CH;\n\tvec3 dir = texture2D(texture_dirLightMap, $UV).xyz;\n\tif (dot(dir, vec3(1.0)) < 0.00001) {\n\t\tdDiffuseLight += color;\n\t} else {\n\t\tdLightDirNormW = normalize(dir * 2.0 - vec3(1.0));\n\t\tfloat vlight = saturate(dot(dLightDirNormW, -dVertexNormalW));\n\t\tfloat flight = saturate(dot(dLightDirNormW, -dNormalW));\n\t\tfloat nlight = (flight / max(vlight, 0.01)) * 0.5;\n\t\tdDiffuseLight += color * nlight * 2.0;\n\t}\n\tdSpecularLight += color * getLightSpecular();\n}\n",lightmapSinglePS:"#ifdef MAPTEXTURE\nuniform sampler2D texture_lightMap;\n#endif\nvoid addLightMap() {\n\tvec3 lm = vec3(1.0);\n\t#ifdef MAPTEXTURE\n\tlm *= $texture2DSAMPLE(texture_lightMap, $UV).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tlm *= saturate(vVertexColor.$VC);\n\t#endif\n\tdDiffuseLight += lm;\n}\n",lightmapSingleVertPS:"void addLightMap() {\n\tdDiffuseLight += saturate(vVertexColor.$CH);\n}\n",lightSpecularAnisoGGXPS:"\nfloat calcLightSpecular(float tGlossiness, vec3 tNormalW) {\n\tfloat PI = 3.141592653589793;\n\tfloat roughness = max((1.0 - tGlossiness) * (1.0 - tGlossiness), 0.001);\n\tfloat anisotropy = material_anisotropy * roughness;\n\tfloat at = max((roughness + anisotropy), roughness / 4.0);\n\tfloat ab = max((roughness - anisotropy), roughness / 4.0);\n\tvec3 h = normalize(normalize(-dLightDirNormW) + normalize(dViewDirW));\n\tfloat NoH = dot(tNormalW, h);\n\tfloat ToH = dot(dTBN[0], h);\n\tfloat BoH = dot(dTBN[1], h);\n\tfloat a2 = at * ab;\n\tvec3 v = vec3(ab * ToH, at * BoH, a2 * NoH);\n\tfloat v2 = dot(v, v);\n\tfloat w2 = a2 / v2;\n\tfloat D = a2 * w2 * w2 * (1.0 / PI);\n\tfloat ToV = dot(dTBN[0], dViewDirW);\n\tfloat BoV = dot(dTBN[1], dViewDirW);\n\tfloat ToL = dot(dTBN[0], -dLightDirNormW);\n\tfloat BoL = dot(dTBN[1], -dLightDirNormW);\n\tfloat NoV = dot(tNormalW, dViewDirW);\n\tfloat NoL = dot(tNormalW, -dLightDirNormW);\n\tfloat lambdaV = NoL * length(vec3(at * ToV, ab * BoV, NoV));\n\tfloat lambdaL = NoV * length(vec3(at * ToL, ab * BoL, NoL));\n\tfloat G = 0.5 / (lambdaV + lambdaL);\n\treturn D * G;\n}\nfloat getLightSpecular() {\n\treturn calcLightSpecular(dGlossiness, dNormalW);\n}\nfloat getLightSpecularCC() {\n\treturn calcLightSpecular(ccGlossiness, ccNormalW);\n}\n",lightSpecularBlinnPS:"\nfloat calcLightSpecular(float tGlossiness, vec3 tNormalW) {\n\tvec3 h = normalize( -dLightDirNormW + dViewDirW );\n\tfloat nh = max( dot( h, tNormalW ), 0.0 );\n\tfloat specPow = exp2(tGlossiness * 11.0);\n\tspecPow = antiAliasGlossiness(specPow);\n\tspecPow = max(specPow, 0.0001);\n\treturn pow(nh, specPow) * (specPow + 2.0) / 8.0;\n}\nfloat getLightSpecular() {\n\treturn calcLightSpecular(dGlossiness, dNormalW);\n}\nfloat getLightSpecularCC() {\n\treturn calcLightSpecular(ccGlossiness, ccNormalW);\n}\n",lightSpecularPhongPS:"float calcLightSpecular(float tGlossiness, vec3 tReflDirW) {\n\tfloat specPow = tGlossiness;\n\tspecPow = antiAliasGlossiness(specPow);\n\treturn pow(max(dot(tReflDirW, -dLightDirNormW), 0.0), specPow + 0.0001);\n}\nfloat getLightSpecular() {\n\treturn calcLightSpecular(dGlossiness, dReflDirW);\n}\nfloat getLightSpecularCC() {\n\treturn calcLightSpecular(ccGlossiness, ccReflDirW);\n}\n",ltc:"\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nstruct Coords {\n\tvec3 coord0;\n\tvec3 coord1;\n\tvec3 coord2;\n\tvec3 coord3;\n};\nfloat LTC_EvaluateRect( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in Coords rectCoords) {\n\tvec3 v1 = rectCoords.coord1 - rectCoords.coord0;\n\tvec3 v2 = rectCoords.coord3 - rectCoords.coord0;\n\tvec3 lightNormal = cross( v1, v2 );\n\tfloat factor = sign(-dot( lightNormal, P - rectCoords.coord0 ));\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = factor * cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords.coord0 - P );\n\tcoords[ 1 ] = mat * ( rectCoords.coord1 - P );\n\tcoords[ 2 ] = mat * ( rectCoords.coord2 - P );\n\tcoords[ 3 ] = mat * ( rectCoords.coord3 - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn result;\n}\nCoords dLTCCoords;\nCoords getLTCLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){\n\tCoords coords;\n\tcoords.coord0 = lightPos + halfWidth - halfHeight;\n\tcoords.coord1 = lightPos - halfWidth - halfHeight;\n\tcoords.coord2 = lightPos - halfWidth + halfHeight;\n\tcoords.coord3 = lightPos + halfWidth + halfHeight;\n\treturn coords;\n}\nfloat dSphereRadius;\nCoords getSphereLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){\n\tCoords coords;\n\tfloat radius = max(length(halfWidth), length(halfWidth));\n\tdSphereRadius = radius;\n\tvec3 f = normalize(lightPos-view_position);\n\tvec3 w = normalize(cross(f, halfHeight));\n\tvec3 h = normalize(cross(f, w));\n\tcoords.coord0 = lightPos + w * radius - h * radius;\n\tcoords.coord1 = lightPos - w * radius - h * radius;\n\tcoords.coord2 = lightPos - w * radius + h * radius;\n\tcoords.coord3 = lightPos + w * radius + h * radius;\n\treturn coords;\n}\nvec2 dLTCUV;\n#ifdef CLEARCOAT\nvec2 ccLTCUV;\n#endif\nvec2 getLTCLightUV(float tGlossiness, vec3 tNormalW)\n{\n\tfloat roughness = max((1.0 - tGlossiness) * (1.0 - tGlossiness), 0.001);\n\treturn LTC_Uv( tNormalW, dViewDirW, roughness );\n}\nvec3 dLTCSpecFres;\n#ifdef CLEARCOAT\nvec3 ccLTCSpecFres;\n#endif\nvec3 getLTCLightSpecFres(vec2 uv, vec3 tSpecularity)\n{\n\tvec4 t2 = texture2D( areaLightsLutTex2, uv );\n\t#ifdef AREA_R8_G8_B8_A8_LUTS\n\tt2 *= vec4(0.693103,1,1,1);\n\tt2 += vec4(0.306897,0,0,0);\n\t#endif\n\treturn tSpecularity * t2.x + ( vec3( 1.0 ) - tSpecularity) * t2.y;\n}\nvoid calcLTCLightValues()\n{\n\tdLTCUV = getLTCLightUV(dGlossiness, dNormalW);\n\tdLTCSpecFres = getLTCLightSpecFres(dLTCUV, dSpecularityNoFres);\n#ifdef CLEARCOAT\n\tccLTCUV = getLTCLightUV(ccGlossiness, ccNormalW);\n\tccLTCSpecFres = getLTCLightSpecFres(ccLTCUV, vec3(ccSpecularityNoFres));\n#endif\n}\nvoid calcRectLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n\tdLTCCoords = getLTCLightCoords(lightPos, halfWidth, halfHeight);\n\tcalcLTCLightValues();\n}\nvoid calcDiskLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n\tcalcRectLightValues(lightPos, halfWidth, halfHeight);\n}\nvoid calcSphereLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n\tdLTCCoords = getSphereLightCoords(lightPos, halfWidth, halfHeight);\n\tcalcLTCLightValues();\n}\nvec3 SolveCubic(vec4 Coefficient)\n{\n\tfloat pi = 3.14159;\n\tCoefficient.xyz /= Coefficient.w;\n\tCoefficient.yz /= 3.0;\n\tfloat A = Coefficient.w;\n\tfloat B = Coefficient.z;\n\tfloat C = Coefficient.y;\n\tfloat D = Coefficient.x;\n\tvec3 Delta = vec3(\n\t\t-Coefficient.z * Coefficient.z + Coefficient.y,\n\t\t-Coefficient.y * Coefficient.z + Coefficient.x,\n\t\tdot(vec2(Coefficient.z, -Coefficient.y), Coefficient.xy)\n\t);\n\tfloat Discriminant = dot(vec2(4.0 * Delta.x, -Delta.y), Delta.zy);\n\tvec3 RootsA, RootsD;\n\tvec2 xlc, xsc;\n\t{\n\t\tfloat A_a = 1.0;\n\t\tfloat C_a = Delta.x;\n\t\tfloat D_a = -2.0 * B * Delta.x + Delta.y;\n\t\tfloat Theta = atan(sqrt(Discriminant), -D_a) / 3.0;\n\t\tfloat x_1a = 2.0 * sqrt(-C_a) * cos(Theta);\n\t\tfloat x_3a = 2.0 * sqrt(-C_a) * cos(Theta + (2.0 / 3.0) * pi);\n\t\tfloat xl;\n\t\tif ((x_1a + x_3a) > 2.0 * B)\n\t\t\txl = x_1a;\n\t\telse\n\t\t\txl = x_3a;\n\t\txlc = vec2(xl - B, A);\n\t}\n\t{\n\t\tfloat A_d = D;\n\t\tfloat C_d = Delta.z;\n\t\tfloat D_d = -D * Delta.y + 2.0 * C * Delta.z;\n\t\tfloat Theta = atan(D * sqrt(Discriminant), -D_d) / 3.0;\n\t\tfloat x_1d = 2.0 * sqrt(-C_d) * cos(Theta);\n\t\tfloat x_3d = 2.0 * sqrt(-C_d) * cos(Theta + (2.0 / 3.0) * pi);\n\t\tfloat xs;\n\t\tif (x_1d + x_3d < 2.0 * C)\n\t\t\txs = x_1d;\n\t\telse\n\t\t\txs = x_3d;\n\t\txsc = vec2(-D, xs + C);\n\t}\n\tfloat E = xlc.y * xsc.y;\n\tfloat F = -xlc.x * xsc.y - xlc.y * xsc.x;\n\tfloat G = xlc.x * xsc.x;\n\tvec2 xmc = vec2(C * F - B * G, -B * F + C * E);\n\tvec3 Root = vec3(xsc.x / xsc.y, xmc.x / xmc.y, xlc.x / xlc.y);\n\tif (Root.x < Root.y && Root.x < Root.z)\n\t\tRoot.xyz = Root.yxz;\n\telse if (Root.z < Root.x && Root.z < Root.y)\n\t\tRoot.xyz = Root.xzy;\n\treturn Root;\n}\nfloat LTC_EvaluateDisk(vec3 N, vec3 V, vec3 P, mat3 Minv, Coords points)\n{\n\tvec3 T1, T2;\n\tT1 = normalize(V - N * dot(V, N));\n\tT2 = cross(N, T1);\n\tmat3 R = transposeMat3( mat3( T1, T2, N ) );\n\tvec3 L_[ 3 ];\n\tL_[ 0 ] = R * ( points.coord0 - P );\n\tL_[ 1 ] = R * ( points.coord1 - P );\n\tL_[ 2 ] = R * ( points.coord2 - P );\n\tvec3 Lo_i = vec3(0);\n\tvec3 C = 0.5 * (L_[0] + L_[2]);\n\tvec3 V1 = 0.5 * (L_[1] - L_[2]);\n\tvec3 V2 = 0.5 * (L_[1] - L_[0]);\n\tC = Minv * C;\n\tV1 = Minv * V1;\n\tV2 = Minv * V2;\n\tfloat a, b;\n\tfloat d11 = dot(V1, V1);\n\tfloat d22 = dot(V2, V2);\n\tfloat d12 = dot(V1, V2);\n\tif (abs(d12) / sqrt(d11 * d22) > 0.0001)\n\t{\n\t\tfloat tr = d11 + d22;\n\t\tfloat det = -d12 * d12 + d11 * d22;\n\t\tdet = sqrt(det);\n\t\tfloat u = 0.5 * sqrt(tr - 2.0 * det);\n\t\tfloat v = 0.5 * sqrt(tr + 2.0 * det);\n\t\tfloat e_max = (u + v) * (u + v);\n\t\tfloat e_min = (u - v) * (u - v);\n\t\tvec3 V1_, V2_;\n\t\tif (d11 > d22)\n\t\t{\n\t\t\tV1_ = d12 * V1 + (e_max - d11) * V2;\n\t\t\tV2_ = d12 * V1 + (e_min - d11) * V2;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tV1_ = d12*V2 + (e_max - d22)*V1;\n\t\t\tV2_ = d12*V2 + (e_min - d22)*V1;\n\t\t}\n\t\ta = 1.0 / e_max;\n\t\tb = 1.0 / e_min;\n\t\tV1 = normalize(V1_);\n\t\tV2 = normalize(V2_);\n\t}\n\telse\n\t{\n\t\ta = 1.0 / dot(V1, V1);\n\t\tb = 1.0 / dot(V2, V2);\n\t\tV1 *= sqrt(a);\n\t\tV2 *= sqrt(b);\n\t}\n\tvec3 V3 = cross(V1, V2);\n\tif (dot(C, V3) < 0.0)\n\t\tV3 *= -1.0;\n\tfloat L = dot(V3, C);\n\tfloat x0 = dot(V1, C) / L;\n\tfloat y0 = dot(V2, C) / L;\n\tfloat E1 = inversesqrt(a);\n\tfloat E2 = inversesqrt(b);\n\ta *= L * L;\n\tb *= L * L;\n\tfloat c0 = a * b;\n\tfloat c1 = a * b * (1.0 + x0 * x0 + y0 * y0) - a - b;\n\tfloat c2 = 1.0 - a * (1.0 + x0 * x0) - b * (1.0 + y0 * y0);\n\tfloat c3 = 1.0;\n\tvec3 roots = SolveCubic(vec4(c0, c1, c2, c3));\n\tfloat e1 = roots.x;\n\tfloat e2 = roots.y;\n\tfloat e3 = roots.z;\n\tvec3 avgDir = vec3(a * x0 / (a - e2), b * y0 / (b - e2), 1.0);\n\tmat3 rotate = mat3(V1, V2, V3);\n\tavgDir = rotate * avgDir;\n\tavgDir = normalize(avgDir);\n\tfloat L1 = sqrt(-e2 / e3);\n\tfloat L2 = sqrt(-e2 / e1);\n\tfloat formFactor = L1 * L2 * inversesqrt((1.0 + L1 * L1) * (1.0 + L2 * L2));\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tvec2 uv = vec2(avgDir.z * 0.5 + 0.5, formFactor);\n\tuv = uv*LUT_SCALE + LUT_BIAS;\n\tfloat scale = texture2D( areaLightsLutTex2, uv ).w;\n\treturn formFactor*scale;\n}\nfloat getRectLightDiffuse() {\n\treturn LTC_EvaluateRect( dNormalW, dViewDirW, vPositionW, mat3( 1.0 ), dLTCCoords );\n}\nfloat getDiskLightDiffuse() {\n\treturn LTC_EvaluateDisk( dNormalW, dViewDirW, vPositionW, mat3( 1.0 ), dLTCCoords );\n}\nfloat getSphereLightDiffuse() {\n\tfloat falloff = dSphereRadius / (dot(dLightDirW, dLightDirW) + dSphereRadius);\n\treturn getLightDiffuse()*falloff;\n}\nmat3 getLTCLightInvMat(vec2 uv)\n{\n\tvec4 t1 = texture2D( areaLightsLutTex1, uv );\n\t#ifdef AREA_R8_G8_B8_A8_LUTS\n\tt1 *= vec4(1.001, 0.3239, 0.60437568, 1.0);\n\tt1 += vec4(0.0, -0.2976, -0.01381, 0.0);\n\t#endif\n\treturn mat3(\n\t\tvec3( t1.x, 0, t1.y ),\n\t\tvec3(\t0, 1,\t0 ),\n\t\tvec3( t1.z, 0, t1.w )\n\t);\n}\nfloat calcRectLightSpecular(vec3 tNormalW, vec2 uv) {\n\tmat3 mInv = getLTCLightInvMat(uv);\n\treturn LTC_EvaluateRect( tNormalW, dViewDirW, vPositionW, mInv, dLTCCoords );\n}\nfloat getRectLightSpecular() {\n\treturn calcRectLightSpecular(dNormalW, dLTCUV);\n}\n#ifdef CLEARCOAT\nfloat getRectLightSpecularCC() {\n\treturn calcRectLightSpecular(ccNormalW, ccLTCUV);\n}\n#endif\nfloat calcDiskLightSpecular(vec3 tNormalW, vec2 uv) {\n\tmat3 mInv = getLTCLightInvMat(uv);\n\treturn LTC_EvaluateDisk( tNormalW, dViewDirW, vPositionW, mInv, dLTCCoords );\n}\nfloat getDiskLightSpecular() {\n\treturn calcDiskLightSpecular(dNormalW, dLTCUV);\n}\n#ifdef CLEARCOAT\nfloat getDiskLightSpecularCC() {\n\treturn calcDiskLightSpecular(ccNormalW, ccLTCUV);\n}\n#endif\nfloat getSphereLightSpecular() {\n\treturn calcDiskLightSpecular(dNormalW, dLTCUV);\n}\n#ifdef CLEARCOAT\nfloat getSphereLightSpecularCC() {\n\treturn calcDiskLightSpecular(ccNormalW, ccLTCUV);\n}\n#endif\n",metalnessPS:"void processMetalness(float metalness) {\n\tconst float dielectricF0 = 0.04;\n\tdSpecularity = mix(vec3(dielectricF0), dAlbedo, metalness);\n\tdAlbedo *= 1.0 - metalness;\n}\n#ifdef MAPFLOAT\nuniform float material_metalness;\n#endif\n#ifdef MAPTEXTURE\nuniform sampler2D texture_metalnessMap;\n#endif\nvoid getSpecularity() {\n\tfloat metalness = 1.0;\n\t#ifdef MAPFLOAT\n\tmetalness *= material_metalness;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tmetalness *= texture2D(texture_metalnessMap, $UV).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tmetalness *= saturate(vVertexColor.$VC);\n\t#endif\n\tprocessMetalness(metalness);\n}\n",msdfPS:"uniform sampler2D texture_msdfMap;\n#ifdef GL_OES_standard_derivatives\n#define USE_FWIDTH\n#endif\n#ifdef GL2\n#define USE_FWIDTH\n#endif\nfloat median(float r, float g, float b) {\n\treturn max(min(r, g), min(max(r, g), b));\n}\nfloat map (float min, float max, float v) {\n\treturn (v - min) / (max - min);\n}\nuniform float font_sdfIntensity;\nuniform float font_pxrange;\nuniform float font_textureWidth;\nuniform vec4 outline_color;\nuniform float outline_thickness;\nuniform vec4 shadow_color;\nuniform vec2 shadow_offset;\nvec4 applyMsdf(vec4 color) {\n\tvec3 tsample = texture2D(texture_msdfMap, vUv0).rgb;\n\tvec2 uvShdw = vUv0 - shadow_offset;\n\tvec3 ssample = texture2D(texture_msdfMap, uvShdw).rgb;\n\tfloat sigDist = median(tsample.r, tsample.g, tsample.b);\n\tfloat sigDistShdw = median(ssample.r, ssample.g, ssample.b);\n\t#ifdef USE_FWIDTH\n\tvec2 w = fwidth(vUv0);\n\tfloat smoothing = clamp(w.x * font_textureWidth / font_pxrange, 0.0, 0.5);\n\t#else\n\tfloat font_size = 16.0;\n\tfloat smoothing = clamp(font_pxrange / font_size, 0.0, 0.5);\n\t#endif\n\tfloat mapMin = 0.05;\n\tfloat mapMax = clamp(1.0 - font_sdfIntensity, mapMin, 1.0);\n\tfloat sigDistInner = map(mapMin, mapMax, sigDist);\n\tfloat sigDistOutline = map(mapMin, mapMax, sigDist + outline_thickness);\n\tsigDistShdw = map(mapMin, mapMax, sigDistShdw + outline_thickness);\n\tfloat center = 0.5;\n\tfloat inside = smoothstep(center-smoothing, center+smoothing, sigDistInner);\n\tfloat outline = smoothstep(center-smoothing, center+smoothing, sigDistOutline);\n\tfloat shadow = smoothstep(center-smoothing, center+smoothing, sigDistShdw);\n\tvec4 tcolor = (outline > inside) ? outline * vec4(outline_color.a * outline_color.rgb, outline_color.a) : vec4(0.0);\n\ttcolor = mix(tcolor, color, inside);\n\tvec4 scolor = (shadow > outline) ? shadow * vec4(shadow_color.a * shadow_color.rgb, shadow_color.a) : tcolor;\n\ttcolor = mix(scolor, tcolor, outline);\n\treturn tcolor;\n}\n",normalVS:"#ifdef MORPHING_TEXTURE_BASED_NORMAL\nuniform highp sampler2D morphNormalTex;\n#endif\nvec3 getNormal() {\n\t#ifdef SKIN\n\tdNormalMatrix = mat3(dModelMatrix[0].xyz, dModelMatrix[1].xyz, dModelMatrix[2].xyz);\n\t#elif defined(INSTANCING)\n\tdNormalMatrix = mat3(instance_line1.xyz, instance_line2.xyz, instance_line3.xyz);\n\t#else\n\tdNormalMatrix = matrix_normal;\n\t#endif\n\tvec3 tempNormal = vertex_normal;\n\t#ifdef MORPHING\n\t#ifdef MORPHING_NRM03\n\ttempNormal += morph_weights_a[0] * morph_nrm0;\n\ttempNormal += morph_weights_a[1] * morph_nrm1;\n\ttempNormal += morph_weights_a[2] * morph_nrm2;\n\ttempNormal += morph_weights_a[3] * morph_nrm3;\n\t#endif\n\t#ifdef MORPHING_NRM47\n\ttempNormal += morph_weights_b[0] * morph_nrm4;\n\ttempNormal += morph_weights_b[1] * morph_nrm5;\n\ttempNormal += morph_weights_b[2] * morph_nrm6;\n\ttempNormal += morph_weights_b[3] * morph_nrm7;\n\t#endif\n\t#endif\n\t#ifdef MORPHING_TEXTURE_BASED_NORMAL\n\tvec2 morphUV = getTextureMorphCoords();\n\tvec3 morphNormal = texture2D(morphNormalTex, morphUV).xyz;\n\ttempNormal += morphNormal;\n\t#endif\n\treturn normalize(dNormalMatrix * tempNormal);\n}\n",normalDetailMapPS:"#ifdef MAPTEXTURE\nuniform sampler2D texture_normalDetailMap;\nuniform float material_normalDetailMapBumpiness;\nvec3 blendNormals(vec3 n1, vec3 n2) {\n\tn1 += vec3(0, 0, 1);\n\tn2 *= vec3(-1, -1, 1);\n\treturn normalize(n1*dot(n1, n2)/n1.z - n2);\n}\n#endif\nvec3 addNormalDetail(vec3 normalMap) {\n\t#ifdef MAPTEXTURE\n\tvec3 normalDetailMap = unpackNormal(texture2D(texture_normalDetailMap, $UV));\n\tnormalDetailMap = normalize(mix(vec3(0.0, 0.0, 1.0), normalDetailMap, material_normalDetailMapBumpiness));\n\treturn blendNormals(normalMap, normalDetailMap);\n\t#else\n\treturn normalMap;\n\t#endif\n}\n",normalInstancedVS:"vec3 getNormal() {\n\tdNormalMatrix = mat3(instance_line1.xyz, instance_line2.xyz, instance_line3.xyz);\n\treturn normalize(dNormalMatrix * vertex_normal);\n}\n",normalMapPS:"uniform sampler2D texture_normalMap;\nuniform float material_bumpiness;\nvoid getNormal() {\n\tvec3 normalMap = unpackNormal(texture2D(texture_normalMap, $UV));\n\tnormalMap = normalize(mix(vec3(0.0, 0.0, 1.0), normalMap, material_bumpiness));\n\tdNormalMap = addNormalDetail(normalMap);\n\tdNormalW = dTBN * dNormalMap;\n}\n",normalMapFastPS:"uniform sampler2D texture_normalMap;\nvoid getNormal() {\n\tvec3 normalMap = unpackNormal(texture2D(texture_normalMap, $UV));\n\tdNormalMap = addNormalDetail(normalMap);\n\tdNormalW = dTBN * dNormalMap;\n}\n",normalSkinnedVS:"vec3 getNormal() {\n\tdNormalMatrix = mat3(dModelMatrix[0].xyz, dModelMatrix[1].xyz, dModelMatrix[2].xyz);\n\treturn normalize(dNormalMatrix * vertex_normal);\n}\n",normalVertexPS:"void getNormal() {\n\tdNormalW = normalize(dVertexNormalW);\n}\n",normalXYPS:"vec3 unpackNormal(vec4 nmap) {\n\tvec3 normal;\n\tnormal.xy = nmap.wy * 2.0 - 1.0;\n\tnormal.z = sqrt(1.0 - saturate(dot(normal.xy, normal.xy)));\n\treturn normal;\n}\n",normalXYZPS:"vec3 unpackNormal(vec4 nmap) {\n\treturn nmap.xyz * 2.0 - 1.0;\n}\n",opacityPS:"#ifdef MAPFLOAT\nuniform float material_opacity;\n#endif\n#ifdef MAPTEXTURE\nuniform sampler2D texture_opacityMap;\n#endif\nvoid getOpacity() {\n\tdAlpha = 1.0;\n\t#ifdef MAPFLOAT\n\tdAlpha *= material_opacity;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tdAlpha *= texture2D(texture_opacityMap, $UV).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tdAlpha *= clamp(vVertexColor.$VC, 0.0, 1.0);\n\t#endif\n}\n",outputAlphaPS:"gl_FragColor.a = dAlpha;\n",outputAlphaOpaquePS:"gl_FragColor.a = 1.0;\n",outputAlphaPremulPS:"gl_FragColor.rgb *= dAlpha;\ngl_FragColor.a = dAlpha;\n",outputCubemapPS:"varying vec2 vUv0;\nuniform samplerCube source;\nuniform vec4 params;\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\nvec4 encodeRGBM(vec4 color) {\n\tcolor.rgb = pow(color.rgb, vec3(0.5));\n\tcolor.rgb *= 1.0 / 8.0;\n\tcolor.a = saturate( max( max( color.r, color.g ), max( color.b, 1.0 / 255.0 ) ) );\n\tcolor.a = ceil(color.a * 255.0) / 255.0;\n\tcolor.rgb /= color.a;\n\treturn color;\n}\nvoid main(void) {\n\tvec2 st = vUv0 * 2.0 - 1.0;\n\tfloat face = params.x;\n\tvec3 vec;\n\tif (face==0.0) {\n\t\tvec = vec3(1, -st.y, -st.x);\n\t} else if (face==1.0) {\n\t\tvec = vec3(-1, -st.y, st.x);\n\t} else if (face==2.0) {\n\t\tvec = vec3(st.x, 1, st.y);\n\t} else if (face==3.0) {\n\t\tvec = vec3(st.x, -1, -st.y);\n\t} else if (face==4.0) {\n\t\tvec = vec3(st.x, -st.y, 1);\n\t} else {\n\t\tvec = vec3(-st.x, -st.y, -1);\n\t}\n\tgl_FragColor = textureCube(source, vec);\n\tif (params.w >= 2.0) gl_FragColor = encodeRGBM(gl_FragColor);\n}\n",outputTex2DPS:"varying vec2 vUv0;\nuniform sampler2D source;\nvoid main(void) {\n\tgl_FragColor = texture2D(source, vUv0);\n}\n",packDepthPS:"\nvec4 packFloat(float depth) {\n\tconst vec4 bit_shift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);\n\tvec4 res = mod(depth * bit_shift * vec4(255), vec4(256) ) / vec4(255);\n\tres -= res.xxyz * bit_mask;\n\treturn res;\n}\n",packDepthMaskPS:"vec4 packFloat(float depth) {\n\tconst vec4 bit_shift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);\n\tvec4 res = mod(depth * bit_shift * vec4(255), vec4(256) ) / vec4(255);\n\tres.x = 0.0;\n\tres -= res.xxyz * bit_mask;\n\treturn res;\n}\n",parallaxPS:"uniform sampler2D texture_heightMap;\nuniform float material_heightMapFactor;\nvoid getParallax() {\n\tfloat parallaxScale = material_heightMapFactor;\n\tfloat height = texture2D(texture_heightMap, $UV).$CH;\n\theight = height * parallaxScale - parallaxScale*0.5;\n\tvec3 viewDirT = dViewDirW * dTBN;\n\tviewDirT.z += 0.42;\n\tdUvOffset = height * (viewDirT.xy / viewDirT.z);\n}\n",particlePS:"varying vec4 texCoordsAlphaLife;\nuniform sampler2D colorMap;\nuniform sampler2D colorParam;\nuniform float graphSampleSize;\nuniform float graphNumSamples;\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n#endif\nuniform float softening;\nuniform float colorMult;\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n\tconst vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n\tfloat depth = dot(rgbaDepth, bitShift);\n\treturn depth;\n}\n#endif\nvoid main(void) {\n\tvec4 tex = texture2DSRGB(colorMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y));\n\tvec4 ramp = texture2DSRGB(colorParam, vec2(texCoordsAlphaLife.w, 0.0));\n\tramp.rgb *= colorMult;\n\tramp.a += texCoordsAlphaLife.z;\n\tvec3 rgb = tex.rgb * ramp.rgb;\n\tfloat a = tex.a * ramp.a;\n",particleVS:"vec3 unpack3NFloats(float src) {\n\tfloat r = fract(src);\n\tfloat g = fract(src * 256.0);\n\tfloat b = fract(src * 65536.0);\n\treturn vec3(r, g, b);\n}\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\nvec4 tex1Dlod_lerp(highp sampler2D tex, vec2 tc) {\n\treturn mix( texture2D(tex,tc), texture2D(tex,tc + graphSampleSize), fract(tc.x*graphNumSamples) );\n}\nvec4 tex1Dlod_lerp(highp sampler2D tex, vec2 tc, out vec3 w) {\n\tvec4 a = texture2D(tex,tc);\n\tvec4 b = texture2D(tex,tc + graphSampleSize);\n\tfloat c = fract(tc.x*graphNumSamples);\n\tvec3 unpackedA = unpack3NFloats(a.w);\n\tvec3 unpackedB = unpack3NFloats(b.w);\n\tw = mix(unpackedA, unpackedB, c);\n\treturn mix(a, b, c);\n}\nvec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix) {\n\tfloat c = cos(pRotation);\n\tfloat s = sin(pRotation);\n\tmat2 m = mat2(c, -s, s, c);\n\trotMatrix = m;\n\treturn m * quadXY;\n}\nvec3 billboard(vec3 InstanceCoords, vec2 quadXY) {\n\t#ifdef SCREEN_SPACE\n\t\tvec3 pos = vec3(-1, 0, 0) * quadXY.x + vec3(0, -1, 0) * quadXY.y;\n\t#else\n\t\tvec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;\n\t#endif\n\treturn pos;\n}\nvec3 customFace(vec3 InstanceCoords, vec2 quadXY) {\n\tvec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;\n\treturn pos;\n}\nvec2 safeNormalize(vec2 v) {\n\tfloat l = length(v);\n\treturn (l > 1e-06) ? v / l : v;\n}\nvoid main(void) {\n\tvec3 meshLocalPos = particle_vertexData.xyz;\n\tfloat id = floor(particle_vertexData.w);\n\tfloat rndFactor = fract(sin(id + 1.0 + seed));\n\tvec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));\n\tfloat uv = id / numParticlesPot;\n\treadInput(uv);\n#ifdef LOCAL_SPACE\n\tinVel = mat3(matrix_model) * inVel;\n#endif\n\tvec2 velocityV = safeNormalize((mat3(matrix_view) * inVel).xy);\n\tfloat particleLifetime = lifetime;\n\tif (inLife <= 0.0 || inLife > particleLifetime || !inShow) meshLocalPos = vec3(0.0);\n\tvec2 quadXY = meshLocalPos.xy;\n\tfloat nlife = clamp(inLife / particleLifetime, 0.0, 1.0);\n\tvec3 paramDiv;\n\tvec4 params = tex1Dlod_lerp(internalTex2, vec2(nlife, 0), paramDiv);\n\tfloat scale = params.y;\n\tfloat scaleDiv = paramDiv.x;\n\tfloat alphaDiv = paramDiv.z;\n\tscale += (scaleDiv * 2.0 - 1.0) * scaleDivMult * fract(rndFactor*10000.0);\n#ifndef USE_MESH\n\ttexCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);\n#else\n\ttexCoordsAlphaLife = vec4(particle_uv, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);\n#endif\n\tvec3 particlePos = inPos;\n\tvec3 particlePosMoved = vec3(0.0);\n\tmat2 rotMatrix;\n",particleAnimFrameClampVS:"\tfloat animFrame = min(floor(texCoordsAlphaLife.w * animTexParams.y) + animTexParams.x, animTexParams.z);\n",particleAnimFrameLoopVS:"\tfloat animFrame = floor(mod(texCoordsAlphaLife.w * animTexParams.y + animTexParams.x, animTexParams.z + 1.0));\n",particleAnimTexVS:"\tfloat animationIndex;\n\tif (animTexIndexParams.y == 1.0) {\n\t\tanimationIndex = floor((animTexParams.w + 1.0) * rndFactor3.z) * (animTexParams.z + 1.0);\n\t} else {\n\t\tanimationIndex = animTexIndexParams.x * (animTexParams.z + 1.0);\n\t}\n\tfloat atlasX = (animationIndex + animFrame) * animTexTilesParams.x;\n\tfloat atlasY = 1.0 - floor(atlasX + 1.0) * animTexTilesParams.y;\n\tatlasX = fract(atlasX);\n\ttexCoordsAlphaLife.xy *= animTexTilesParams.xy;\n\ttexCoordsAlphaLife.xy += vec2(atlasX, atlasY);\n",particleInputFloatPS:"void readInput(float uv) {\n\tvec4 tex = texture2D(particleTexIN, vec2(uv, 0.25));\n\tvec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.75));\n\tinPos = tex.xyz;\n\tinVel = tex2.xyz;\n\tinAngle = (tex.w < 0.0? -tex.w : tex.w) - 1000.0;\n\tinShow = tex.w >= 0.0;\n\tinLife = tex2.w;\n}\n",particleInputRgba8PS:"\n#define PI2 6.283185307179586\nuniform vec3 inBoundsSize;\nuniform vec3 inBoundsCenter;\nuniform float maxVel;\nfloat decodeFloatRG(vec2 rg) {\n\treturn rg.y*(1.0/255.0) + rg.x;\n}\nfloat decodeFloatRGBA( vec4 rgba ) {\n return dot( rgba, vec4(1.0, 1.0/255.0, 1.0/65025.0, 1.0/160581375.0) );\n}\nvoid readInput(float uv) {\n\tvec4 tex0 = texture2D(particleTexIN, vec2(uv, 0.125));\n\tvec4 tex1 = texture2D(particleTexIN, vec2(uv, 0.375));\n\tvec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.625));\n\tvec4 tex3 = texture2D(particleTexIN, vec2(uv, 0.875));\n\tinPos = vec3(decodeFloatRG(tex0.rg), decodeFloatRG(tex0.ba), decodeFloatRG(tex1.rg));\n\tinPos = (inPos - vec3(0.5)) * inBoundsSize + inBoundsCenter;\n\tinVel = tex2.xyz;\n\tinVel = (inVel - vec3(0.5)) * maxVel;\n\tinAngle = decodeFloatRG(tex1.ba) * PI2;\n\tinShow = tex2.a > 0.5;\n\tinLife = decodeFloatRGBA(tex3);\n\tfloat maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));\n\tfloat maxPosLife = lifetime+1.0;\n\tinLife = inLife * (maxNegLife + maxPosLife) - maxNegLife;\n}\n",particleOutputFloatPS:"void writeOutput() {\n\tif (gl_FragCoord.y<1.0) {\n\t\tgl_FragColor = vec4(outPos, (outAngle + 1000.0) * visMode);\n\t} else {\n\t\tgl_FragColor = vec4(outVel, outLife);\n\t}\n}\n",particleOutputRgba8PS:"uniform vec3 outBoundsMul;\nuniform vec3 outBoundsAdd;\nvec2 encodeFloatRG( float v ) {\n\tvec2 enc = vec2(1.0, 255.0) * v;\n\tenc = fract(enc);\n\tenc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n\treturn enc;\n}\nvec4 encodeFloatRGBA( float v ) {\n\tvec4 enc = vec4(1.0, 255.0, 65025.0, 160581375.0) * v;\n\tenc = fract(enc);\n\tenc -= enc.yzww * vec4(1.0/255.0,1.0/255.0,1.0/255.0,0.0);\n\treturn enc;\n}\nvoid writeOutput() {\n\toutPos = outPos * outBoundsMul + outBoundsAdd;\n\toutAngle = fract(outAngle / PI2);\n\toutVel = (outVel / maxVel) + vec3(0.5);\n\tfloat maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));\n\tfloat maxPosLife = lifetime+1.0;\n\toutLife = (outLife + maxNegLife) / (maxNegLife + maxPosLife);\n\tif (gl_FragCoord.y < 1.0) {\n\t\tgl_FragColor = vec4(encodeFloatRG(outPos.x), encodeFloatRG(outPos.y));\n\t} else if (gl_FragCoord.y < 2.0) {\n\t\tgl_FragColor = vec4(encodeFloatRG(outPos.z), encodeFloatRG(outAngle));\n\t} else if (gl_FragCoord.y < 3.0) {\n\t\tgl_FragColor = vec4(outVel, visMode*0.5+0.5);\n\t} else {\n\t\tgl_FragColor = encodeFloatRGBA(outLife);\n\t}\n}\n",particleUpdaterAABBPS:"uniform mat3 spawnBounds;\nuniform vec3 spawnPosInnerRatio;\nvec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {\n\tvec3 pos = inBounds - vec3(0.5);\n\tvec3 posAbs = abs(pos);\n\tvec3 maxPos = vec3(max(posAbs.x, max(posAbs.y, posAbs.z)));\n\tvec3 edge = maxPos + (vec3(0.5) - maxPos) * spawnPosInnerRatio;\n\tpos.x = edge.x * (maxPos.x == posAbs.x ? sign(pos.x) : 2.0 * pos.x);\n\tpos.y = edge.y * (maxPos.y == posAbs.y ? sign(pos.y) : 2.0 * pos.y);\n\tpos.z = edge.z * (maxPos.z == posAbs.z ? sign(pos.z) : 2.0 * pos.z);\n#ifndef LOCAL_SPACE\n\treturn emitterPos + spawnBounds * pos;\n#else\n\treturn spawnBounds * pos;\n#endif\n}\nvoid addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {\n\tlocalVelocity -= vec3(0, 0, initialVelocity);\n}\n",particleUpdaterEndPS:"\twriteOutput();\n}\n",particleUpdaterInitPS:"varying vec2 vUv0;\nuniform highp sampler2D particleTexIN;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\nuniform highp sampler2D internalTex3;\nuniform mat3 emitterMatrix, emitterMatrixInv;\nuniform vec3 emitterScale;\nuniform vec3 emitterPos, frameRandom, localVelocityDivMult, velocityDivMult;\nuniform float delta, rate, rateDiv, lifetime, numParticles, rotSpeedDivMult, radialSpeedDivMult, seed;\nuniform float startAngle, startAngle2;\nuniform float initialVelocity;\nuniform float graphSampleSize;\nuniform float graphNumSamples;\nvec3 inPos;\nvec3 inVel;\nfloat inAngle;\nbool inShow;\nfloat inLife;\nfloat visMode;\nvec3 outPos;\nvec3 outVel;\nfloat outAngle;\nbool outShow;\nfloat outLife;\n",particleUpdaterNoRespawnPS:"\tif (outLife >= lifetime) {\n\t\toutLife -= max(lifetime, (numParticles - 1.0) * particleRate);\n\t\tvisMode = -1.0;\n\t}\n",particleUpdaterOnStopPS:"\tvisMode = outLife < 0.0? -1.0: visMode;\n",particleUpdaterRespawnPS:"\tif (outLife >= lifetime) {\n\t\toutLife -= max(lifetime, (numParticles - 1.0) * particleRate);\n\t\tvisMode = 1.0;\n\t}\n\tvisMode = outLife < 0.0? 1.0: visMode;\n",particleUpdaterSpherePS:"uniform float spawnBoundsSphere;\nuniform float spawnBoundsSphereInnerRatio;\nvec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {\n\tfloat rnd4 = fract(rndFactor * 1000.0);\n\tvec3 norm = normalize(inBounds.xyz - vec3(0.5));\n\tfloat r = rnd4 * (1.0 - spawnBoundsSphereInnerRatio) + spawnBoundsSphereInnerRatio;\n#ifndef LOCAL_SPACE\n\treturn emitterPos + norm * r * spawnBoundsSphere;\n#else\n\treturn norm * r * spawnBoundsSphere;\n#endif\n}\nvoid addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {\n\tlocalVelocity += normalize(inBounds - vec3(0.5)) * initialVelocity;\n}\n",particleUpdaterStartPS:"float saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\nvec3 unpack3NFloats(float src) {\n\tfloat r = fract(src);\n\tfloat g = fract(src * 256.0);\n\tfloat b = fract(src * 65536.0);\n\treturn vec3(r, g, b);\n}\nvec3 tex1Dlod_lerp(highp sampler2D tex, vec2 tc, out vec3 w) {\n\tvec4 a = texture2D(tex, tc);\n\tvec4 b = texture2D(tex, tc + graphSampleSize);\n\tfloat c = fract(tc.x * graphNumSamples);\n\tvec3 unpackedA = unpack3NFloats(a.w);\n\tvec3 unpackedB = unpack3NFloats(b.w);\n\tw = mix(unpackedA, unpackedB, c);\n\treturn mix(a.xyz, b.xyz, c);\n}\n#define HASHSCALE4 vec4(1031, .1030, .0973, .1099)\nvec4 hash41(float p) {\n\tvec4 p4 = fract(vec4(p) * HASHSCALE4);\n\tp4 += dot(p4, p4.wzxy+19.19);\n\treturn fract(vec4((p4.x + p4.y)*p4.z, (p4.x + p4.z)*p4.y, (p4.y + p4.z)*p4.w, (p4.z + p4.w)*p4.x));\n}\nvoid main(void) {\n\tif (gl_FragCoord.x > numParticles) discard;\n\treadInput(vUv0.x);\n\tvisMode = inShow? 1.0 : -1.0;\n\tvec4 rndFactor = hash41(gl_FragCoord.x + seed);\n\tfloat particleRate = rate + rateDiv * rndFactor.x;\n\toutLife = inLife + delta;\n\tfloat nlife = clamp(outLife / lifetime, 0.0, 1.0);\n\tvec3 localVelocityDiv;\n\tvec3 velocityDiv;\n\tvec3 paramDiv;\n\tvec3 localVelocity = tex1Dlod_lerp(internalTex0, vec2(nlife, 0), localVelocityDiv);\n\tvec3 velocity =\t tex1Dlod_lerp(internalTex1, vec2(nlife, 0), velocityDiv);\n\tvec3 params =\t\ttex1Dlod_lerp(internalTex2, vec2(nlife, 0), paramDiv);\n\tfloat rotSpeed = params.x;\n\tfloat rotSpeedDiv = paramDiv.y;\n\tvec3 radialParams = tex1Dlod_lerp(internalTex3, vec2(nlife, 0), paramDiv);\n\tfloat radialSpeed = radialParams.x;\n\tfloat radialSpeedDiv = radialParams.y;\n\tbool respawn = inLife <= 0.0 || outLife >= lifetime;\n\tinPos = respawn ? calcSpawnPosition(rndFactor.xyz, rndFactor.x) : inPos;\n\tinAngle = respawn ? mix(startAngle, startAngle2, rndFactor.x) : inAngle;\n#ifndef LOCAL_SPACE\n\tvec3 radialVel = inPos - emitterPos;\n#else\n\tvec3 radialVel = inPos;\n#endif\n\tradialVel = (dot(radialVel, radialVel) > 1.0E-8) ? radialSpeed * normalize(radialVel) : vec3(0.0);\n\tradialVel += (radialSpeedDiv * vec3(2.0) - vec3(1.0)) * radialSpeedDivMult * rndFactor.xyz;\n\tlocalVelocity +=\t(localVelocityDiv * vec3(2.0) - vec3(1.0)) * localVelocityDivMult * rndFactor.xyz;\n\tvelocity +=\t\t (velocityDiv * vec3(2.0) - vec3(1.0)) * velocityDivMult * rndFactor.xyz;\n\trotSpeed +=\t\t (rotSpeedDiv * 2.0 - 1.0) * rotSpeedDivMult * rndFactor.y;\n\taddInitialVelocity(localVelocity, rndFactor.xyz);\n#ifndef LOCAL_SPACE\n\toutVel = emitterMatrix * localVelocity + (radialVel + velocity) * emitterScale;\n#else\n\toutVel = (localVelocity + radialVel) / emitterScale + emitterMatrixInv * velocity;\n#endif\n\toutPos = inPos + outVel * delta;\n\toutAngle = inAngle + rotSpeed * delta;\n",particle_billboardVS:"\tquadXY = rotate(quadXY, inAngle, rotMatrix);\n\tvec3 localPos = billboard(particlePos, quadXY);\n",particle_blendAddPS:"\tdBlendModeFogFactor = 0.0;\n\trgb *= saturate(gammaCorrectInput(max(a, 0.0)));\n\tif ((rgb.r + rgb.g + rgb.b) < 0.000001) discard;\n",particle_blendMultiplyPS:"\trgb = mix(vec3(1.0), rgb, vec3(a));\n\tif (rgb.r + rgb.g + rgb.b > 2.99) discard;\n",particle_blendNormalPS:"\tif (a < 0.01) discard;\n",particle_cpuVS:"attribute vec4 particle_vertexData;\nattribute vec4 particle_vertexData2;\nattribute vec4 particle_vertexData3;\nattribute float particle_vertexData4;\n#ifndef USE_MESH\n#define VDATA5TYPE vec2\n#else\n#define VDATA5TYPE vec4\n#endif\nattribute VDATA5TYPE particle_vertexData5;\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nuniform mat3 matrix_normal;\nuniform mat4 matrix_viewInverse;\nuniform float numParticles;\nuniform float lifetime;\nuniform float stretch;\nuniform float seed;\nuniform vec3 wrapBounds, emitterScale, faceTangent, faceBinorm;\nuniform sampler2D texLifeAndSourcePosOUT;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\nuniform vec3 emitterPos;\nvarying vec4 texCoordsAlphaLife;\nvec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix)\n{\n\tfloat c = cos(pRotation);\n\tfloat s = sin(pRotation);\n\tmat2 m = mat2(c, -s, s, c);\n\trotMatrix = m;\n\treturn m * quadXY;\n}\nvec3 billboard(vec3 InstanceCoords, vec2 quadXY)\n{\n\tvec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;\n\treturn pos;\n}\nvec3 customFace(vec3 InstanceCoords, vec2 quadXY)\n{\n\tvec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;\n\treturn pos;\n}\nvoid main(void)\n{\n\tvec3 particlePos = particle_vertexData.xyz;\n\tvec3 inPos = particlePos;\n\tvec3 vertPos = particle_vertexData3.xyz;\n\tvec3 inVel = vec3(particle_vertexData2.w, particle_vertexData3.w, particle_vertexData5.x);\n\tfloat id = floor(particle_vertexData4);\n\tfloat rndFactor = fract(sin(id + 1.0 + seed));\n\tvec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));\n#ifdef LOCAL_SPACE\n\tinVel = mat3(matrix_model) * inVel;\n#endif\n\tvec2 velocityV = normalize((mat3(matrix_view) * inVel).xy);\n\tvec2 quadXY = vertPos.xy;\n#ifdef USE_MESH\n\ttexCoordsAlphaLife = vec4(particle_vertexData5.zw, particle_vertexData2.z, particle_vertexData.w);\n#else\n\ttexCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, particle_vertexData2.z, particle_vertexData.w);\n#endif\n\tmat2 rotMatrix;\n\tfloat inAngle = particle_vertexData2.x;\n\tvec3 particlePosMoved = vec3(0.0);\n\tvec3 meshLocalPos = particle_vertexData3.xyz;\n",particle_cpu_endVS:"\tlocalPos *= particle_vertexData2.y * emitterScale;\n\tlocalPos += particlePos;\n\tgl_Position = matrix_viewProjection * vec4(localPos, 1.0);\n",particle_customFaceVS:"\tquadXY = rotate(quadXY, inAngle, rotMatrix);\n\tvec3 localPos = customFace(particlePos, quadXY);\n",particle_endPS:"\trgb = addFog(rgb);\n\trgb = toneMap(rgb);\n\trgb = gammaCorrectOutput(rgb);\n\tgl_FragColor = vec4(rgb, a);\n}\n",particle_endVS:"\tlocalPos *= scale * emitterScale;\n\tlocalPos += particlePos;\n\t#ifdef SCREEN_SPACE\n\tgl_Position = vec4(localPos.x, localPos.y, 0.0, 1.0);\n\t#else\n\tgl_Position = matrix_viewProjection * vec4(localPos.xyz, 1.0);\n\t#endif\n",particle_halflambertPS:"\tvec3 negNormal = normal*0.5+0.5;\n\tvec3 posNormal = -normal*0.5+0.5;\n\tnegNormal *= negNormal;\n\tposNormal *= posNormal;\n",particle_initVS:"attribute vec4 particle_vertexData;\n#ifdef USE_MESH\nattribute vec2 particle_uv;\n#endif\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\nuniform mat3 matrix_normal;\nuniform mat4 matrix_viewInverse;\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nuniform float numParticles, numParticlesPot;\nuniform float graphSampleSize;\nuniform float graphNumSamples;\nuniform float stretch;\nuniform vec3 wrapBounds;\nuniform vec3 emitterScale, emitterPos, faceTangent, faceBinorm;\nuniform float rate, rateDiv, lifetime, deltaRandomnessStatic, scaleDivMult, alphaDivMult, seed, delta;\nuniform sampler2D particleTexOUT, particleTexIN;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n#endif\nvarying vec4 texCoordsAlphaLife;\nvec3 inPos;\nvec3 inVel;\nfloat inAngle;\nbool inShow;\nfloat inLife;\n",particle_lambertPS:"\tvec3 negNormal = max(normal, vec3(0.0));\n\tvec3 posNormal = max(-normal, vec3(0.0));\n",particle_lightingPS:"\tvec3 light = negNormal.x*lightCube[0] + posNormal.x*lightCube[1] +\n\t\t\t\t\t\tnegNormal.y*lightCube[2] + posNormal.y*lightCube[3] +\n\t\t\t\t\t\tnegNormal.z*lightCube[4] + posNormal.z*lightCube[5];\n\trgb *= light;\n",particle_localShiftVS:"\tparticlePos = (matrix_model * vec4(particlePos, 1.0)).xyz;\n",particle_meshVS:"\tvec3 localPos = meshLocalPos;\n\tlocalPos.xy = rotate(localPos.xy, inAngle, rotMatrix);\n\tlocalPos.yz = rotate(localPos.yz, inAngle, rotMatrix);\n\tbillboard(particlePos, quadXY);\n",particle_normalVS:"\tNormal = normalize(localPos + matrix_viewInverse[2].xyz);\n",particle_normalMapPS:"\tvec3 normalMap = normalize(texture2D(normalMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y)).xyz * 2.0 - 1.0);\n\tvec3 normal = ParticleMat * normalMap;\n",particle_pointAlongVS:"\tinAngle = atan(velocityV.x, velocityV.y);\n",particle_softPS:"\tfloat depth = getLinearScreenDepth();\n\tfloat particleDepth = vDepth;\n\tfloat depthDiff = saturate(abs(particleDepth - depth) * softening);\n\ta *= depthDiff;\n",particle_softVS:"\tvDepth = getLinearDepth(localPos);\n",particle_stretchVS:"\tvec3 moveDir = inVel * stretch;\n\tvec3 posPrev = particlePos - moveDir;\n\tposPrev += particlePosMoved;\n\tvec2 centerToVertexV = normalize((mat3(matrix_view) * localPos).xy);\n\tfloat interpolation = dot(-velocityV, centerToVertexV) * 0.5 + 0.5;\n\tparticlePos = mix(particlePos, posPrev, interpolation);\n",particle_TBNVS:"\tmat3 rot3 = mat3(rotMatrix[0][0], rotMatrix[0][1], 0.0, rotMatrix[1][0], rotMatrix[1][1], 0.0, 0.0, 0.0, 1.0);\n\tParticleMat = mat3(-matrix_viewInverse[0].xyz, -matrix_viewInverse[1].xyz, matrix_viewInverse[2].xyz) * rot3;\n",particle_wrapVS:"\tvec3 origParticlePos = particlePos;\n\tparticlePos -= matrix_model[3].xyz;\n\tparticlePos = mod(particlePos, wrapBounds) - wrapBounds * 0.5;\n\tparticlePos += matrix_model[3].xyz;\n\tparticlePosMoved = particlePos - origParticlePos;\n",precisionTestPS:"void main(void) {\n\tgl_FragColor = vec4(2147483648.0);\n}\n",precisionTest2PS:"uniform sampler2D source;\nvec4 packFloat(float depth) {\n\tconst vec4 bit_shift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);\n\tvec4 res = mod(depth * bit_shift * vec4(255), vec4(256) ) / vec4(255);\n\tres -= res.xxyz * bit_mask;\n\treturn res;\n}\nvoid main(void) {\n\tfloat c = texture2D(source, vec2(0.0)).r;\n\tfloat diff = abs(c - 2147483648.0) / 2147483648.0;\n\tgl_FragColor = packFloat(diff);\n}\n",prefilterCubemapPS:"varying vec2 vUv0;\nuniform samplerCube source;\nuniform vec4 params;\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\nfloat rnd(vec2 uv) {\n\treturn fract(sin(dot(uv, vec2(12.9898, 78.233) * 2.0)) * 43758.5453);\n}\nconst float PI = 3.14159265358979;\nvec3 hemisphereSample_cos(vec2 uv, mat3 vecSpace, vec3 cubeDir, float gloss) {\n\tfloat phi = uv.y * 2.0 * PI;\n\tfloat cosTheta = sqrt(1.0 - uv.x);\n\tfloat sinTheta = sqrt(1.0 - cosTheta * cosTheta);\n\tvec3 sampleDir = vec3(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta);\n\treturn normalize(mix(vecSpace * sampleDir, cubeDir, params.y));\n}\nvec3 hemisphereSample_phong(vec2 uv, mat3 vecSpace, vec3 cubeDir, float specPow) {\n\tfloat phi = uv.y * 2.0 * PI;\n\tfloat cosTheta = pow(1.0 - uv.x, 1.0 / (specPow + 1.0));\n\tfloat sinTheta = sqrt(1.0 - cosTheta * cosTheta);\n\tvec3 sampleDir = vec3(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta);\n\treturn vecSpace * sampleDir;\n}\nmat3 matrixFromVector(vec3 n) {\n\tfloat a = 1.0 / (1.0 + n.z);\n\tfloat b = -n.x * n.y * a;\n\tvec3 b1 = vec3(1.0 - n.x * n.x * a, b, -n.x);\n\tvec3 b2 = vec3(b, 1.0 - n.y * n.y * a, -n.y);\n\treturn mat3(b1, b2, n);\n}\nvec4 encodeRGBM(vec3 color) {\n\tvec4 encoded;\n\tencoded.rgb = pow(color.rgb, vec3(0.5));\n\tencoded.rgb *= 1.0 / 8.0;\n\tencoded.a = saturate( max( max( encoded.r, encoded.g ), max( encoded.b, 1.0 / 255.0 ) ) );\n\tencoded.a = ceil(encoded.a * 255.0) / 255.0;\n\tencoded.rgb /= encoded.a;\n\treturn encoded;\n}\nvoid main(void) {\n\tvec2 st = vUv0 * 2.0 - 1.0;\n\tif (params.w==1.0 || params.w==3.0) {\n\t\tst = 2.0 * floor(gl_FragCoord.xy) / (params.z - 1.0) - 1.0;\n\t}\n\tfloat face = params.x;\n\tvec3 vec;\n\tif (face==0.0) {\n\t\tvec = vec3(1, -st.y, -st.x);\n\t} else if (face==1.0) {\n\t\tvec = vec3(-1, -st.y, st.x);\n\t} else if (face==2.0) {\n\t\tvec = vec3(st.x, 1, st.y);\n\t} else if (face==3.0) {\n\t\tvec = vec3(st.x, -1, -st.y);\n\t} else if (face==4.0) {\n\t\tvec = vec3(st.x, -st.y, 1);\n\t} else {\n\t\tvec = vec3(-st.x, -st.y, -1);\n\t}\n\tmat3 vecSpace = matrixFromVector(normalize(vec));\n\tvec3 color = vec3(0.0);\n\tconst int samples = $NUMSAMPLES;\n\tvec3 vect;\n\tfor(int i=0; i= 0.0 ? dTBN[1] : dTBN[0];\n\tvec3 anisotropicTangent = cross(anisotropicDirection, dViewDirW);\n\tvec3 anisotropicNormal = cross(anisotropicTangent, anisotropicDirection);\n\tvec3 bentNormal = normalize(mix(normalize(dNormalW), normalize(anisotropicNormal), anisotropy));\n\tdReflDirW = reflect(-dViewDirW, bentNormal);\n}\n",reflectionCCPS:"#ifdef CLEARCOAT\nuniform float material_clearCoatReflectivity;\nvoid addReflectionCC() {\n\tccReflection += vec4(calcReflection(ccReflDirW, ccGlossiness), material_clearCoatReflectivity);\n}\n#endif\n",reflectionCubePS:"uniform samplerCube texture_cubeMap;\nuniform float material_reflectivity;\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n\tvec3 lookupVec = fixSeams(cubeMapProject(tReflDirW));\n#ifndef RIGHT_HANDED_CUBEMAP\n\tlookupVec.x *= -1.0;\n#endif\n\treturn $textureCubeSAMPLE(texture_cubeMap, lookupVec).rgb;\n}\nvoid addReflection() {\n\tdReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionDpAtlasPS:"uniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\nvec2 getDpAtlasUv(vec2 uv, float mip) {\n\tvec4 rect;\n\tfloat sx = saturate(mip - 2.0);\n\trect.x = sx * 0.5;\n\tfloat t = mip - rect.x * 6.0;\n\tfloat i = 1.0 - rect.x;\n\trect.y = min(t * 0.5, 0.75) * i + rect.x;\n\tfloat st = saturate(t);\n\trect.z = (1.0 - st * 0.5) * i;\n\trect.w = rect.z * 0.5;\n\tfloat rcRectZ = 1.0 / rect.z;\n\tfloat scaleFactor = 0.00390625 * rcRectZ;\n\tvec2 scale = vec2(scaleFactor, scaleFactor * 2.0);\n\tuv = uv * (vec2(1.0) - scale) + scale * 0.5;\n\tuv = uv * rect.zw + rect.xy;\n\treturn uv;\n}\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n\tvec3 reflDir = normalize(cubeMapProject(tReflDirW));\n\tbool up = reflDir.y > 0.0;\n\tfloat scale = 0.90909090909090909090909090909091;\n\tvec3 reflDirWarp = reflDir.xzx * vec3(-0.25, 0.5, 0.25);\n\tfloat reflDirVer = abs(reflDir.y) + 1.0;\n\treflDirWarp /= reflDirVer;\n\treflDirWarp *= scale;\n\treflDirWarp = vec3(0.75, 0.5, 0.25) - reflDirWarp;\n\tvec2 tc = up? reflDirWarp.xy : reflDirWarp.zy;\n\tfloat bias = saturate(1.0 - tGlossiness) * 5.0;\n\tfloat mip = floor(bias);\n\tvec3 tex1 = $texture2DSAMPLE(texture_sphereMap, getDpAtlasUv(tc, mip)).rgb;\n\tmip = min(mip + 1.0, 5.0);\n\tvec3 tex2 = $texture2DSAMPLE(texture_sphereMap, getDpAtlasUv(tc, mip)).rgb;\n\ttex1 = mix(tex1, tex2, fract(bias));\n\ttex1 = processEnvironment(tex1);\n\treturn tex1;\n}\nvoid addReflection() {\n\tdReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionPrefilteredCubePS:"uniform samplerCube texture_prefilteredCubeMap128;\nuniform samplerCube texture_prefilteredCubeMap64;\nuniform samplerCube texture_prefilteredCubeMap32;\nuniform samplerCube texture_prefilteredCubeMap16;\nuniform samplerCube texture_prefilteredCubeMap8;\n#ifndef PMREM4\n#define PMREM4\nuniform samplerCube texture_prefilteredCubeMap4;\n#endif\nuniform float material_reflectivity;\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n\tvec3 refl = cubeMapProject(tReflDirW);\n#ifndef RIGHT_HANDED_CUBEMAP\n\trefl.x *= -1.0;\n#endif\n\tvec3 seam = calcSeam(refl);\n\tvec4 c0 = textureCube(texture_prefilteredCubeMap128, applySeam(refl, seam, 1.0 / 128.0));\n\tvec4 c1 = textureCube(texture_prefilteredCubeMap64, applySeam(refl, seam, 2.0 / 128.0));\n\tvec4 c2 = textureCube(texture_prefilteredCubeMap32, applySeam(refl, seam, 4.0 / 128.0));\n\tvec4 c3 = textureCube(texture_prefilteredCubeMap16, applySeam(refl, seam, 8.0 / 128.0));\n\tvec4 c4 = textureCube(texture_prefilteredCubeMap8, applySeam(refl, seam, 16.0 / 128.0));\n\tvec4 c5 = textureCube(texture_prefilteredCubeMap4, applySeam(refl, seam, 32.0 / 128.0));\n\tfloat bias = saturate(1.0 - tGlossiness) * 5.0;\n\tvec4 cubes0;\n\tvec4 cubes1;\n\tif (bias < 1.0) {\n\t\tcubes0 = c0;\n\t\tcubes1 = c1;\n\t} else if (bias < 2.0) {\n\t\tcubes0 = c1;\n\t\tcubes1 = c2;\n\t} else if (bias < 3.0) {\n\t\tcubes0 = c2;\n\t\tcubes1 = c3;\n\t} else if (bias < 4.0) {\n\t\tcubes0 = c3;\n\t\tcubes1 = c4;\n\t} else {\n\t\tcubes0 = c4;\n\t\tcubes1 = c5;\n\t}\n\tvec4 cubeFinal = mix(cubes0, cubes1, fract(bias));\n\treturn processEnvironment($DECODE(cubeFinal).rgb);\n}\nvoid addReflection() {\n\tdReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionPrefilteredCubeLodPS:"#ifndef PMREM4\n#define PMREM4\n#ifndef GL2\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nuniform samplerCube texture_prefilteredCubeMap128;\n#endif\nuniform float material_reflectivity;\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n\tfloat bias = saturate(1.0 - tGlossiness) * 5.0;\n\tvec3 fixedReflDir = fixSeams(cubeMapProject(tReflDirW), bias);\n#ifndef RIGHT_HANDED_CUBEMAP\n\tfixedReflDir.x *= -1.0;\n#endif\n\tvec3 refl = processEnvironment($DECODE( textureCubeLodEXT(texture_prefilteredCubeMap128, fixedReflDir, bias) ).rgb);\n\treturn refl;\n}\nvoid addReflection() {\n\tdReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionSpherePS:"#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nuniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n\tvec3 reflDirV = (mat3(matrix_view) * tReflDirW).xyz;\n\tfloat m = 2.0 * sqrt( dot(reflDirV.xy, reflDirV.xy) + (reflDirV.z+1.0)*(reflDirV.z+1.0) );\n\tvec2 sphereMapUv = reflDirV.xy / m + 0.5;\n\treturn $texture2DSAMPLE(texture_sphereMap, sphereMapUv).rgb;\n}\nvoid addReflection() {\n\tdReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",reflectionSphereLowPS:"uniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\nvec3 calcReflection(vec3 tReflDirW, float tGlossiness) {\n\tvec3 reflDirV = vNormalV;\n\tvec2 sphereMapUv = reflDirV.xy * 0.5 + 0.5;\n\treturn $texture2DSAMPLE(texture_sphereMap, sphereMapUv).rgb;\n}\nvoid addReflection() {\n\tdReflection += vec4(calcReflection(dReflDirW, dGlossiness), material_reflectivity);\n}\n",refractionPS:"uniform float material_refraction, material_refractionIndex;\nvec3 refract2(vec3 viewVec, vec3 Normal, float IOR) {\n\tfloat vn = dot(viewVec, Normal);\n\tfloat k = 1.0 - IOR * IOR * (1.0 - vn * vn);\n\tvec3 refrVec = IOR * viewVec - (IOR * vn + sqrt(k)) * Normal;\n\treturn refrVec;\n}\nvoid addRefraction() {\n\tvec3 tmp = dReflDirW;\n\tvec4 tmp2 = dReflection;\n\tdReflection = vec4(0.0);\n\tdReflDirW = refract2(-dViewDirW, dNormalW, material_refractionIndex);\n\taddReflection();\n\tdDiffuseLight = mix(dDiffuseLight, dReflection.rgb * dAlbedo, material_refraction);\n\tdReflDirW = tmp;\n\tdReflection = tmp2;\n}\n",reprojectPS:"\nvarying vec2 vUv0;\nuniform sampler2D sourceTex;\nuniform samplerCube sourceCube;\nuniform vec4 params;\nfloat targetFace() { return params.x; }\nfloat specularPower() { return params.y; }\nfloat sourceCubeSeamScale() { return params.z; }\nfloat targetCubeSeamScale() { return params.w; }\nfloat PI = 3.141592653589793;\nfloat saturate(float x) {\n\treturn clamp(x, 0.0, 1.0);\n}\nvec3 decodeLinear(vec4 source) {\n\treturn source.rgb;\n}\nvec4 encodeLinear(vec3 source) {\n\treturn vec4(source, 1.0);\n}\nvec3 decodeGamma(vec4 source) {\n\treturn pow(source.xyz, vec3(2.2));\n}\nvec4 encodeGamma(vec3 source) {\n\treturn vec4(pow(source + 0.0000001, vec3(1.0 / 2.2)), 1.0);\n}\nvec3 decodeRGBM(vec4 rgbm) {\n\tvec3 color = (8.0 * rgbm.a) * rgbm.rgb;\n\treturn color * color;\n}\nvec4 encodeRGBM(vec3 source) {\n\tvec4 result;\n\tresult.rgb = pow(source.rgb, vec3(0.5));\n\tresult.rgb *= 1.0 / 8.0;\n\tresult.a = saturate( max( max( result.r, result.g ), max( result.b, 1.0 / 255.0 ) ) );\n\tresult.a = ceil(result.a * 255.0) / 255.0;\n\tresult.rgb /= result.a;\n\treturn result;\n}\nvec3 decodeRGBE(vec4 source) {\n\tif (source.a == 0.0) {\n\t\treturn vec3(0.0, 0.0, 0.0);\n\t} else {\n\t\treturn source.xyz * pow(2.0, source.w * 255.0 - 128.0);\n\t}\n}\nvec4 encodeRGBE(vec3 source) {\n\tfloat maxVal = max(source.x, max(source.y, source.z));\n\tif (maxVal < 1e-32) {\n\t\treturn vec4(0, 0, 0, 0);\n\t} else {\n\t\tfloat e = ceil(log2(maxVal));\n\t\treturn vec4(source / pow(2.0, e), (e + 128.0) / 255.0);\n\t}\n}\nvec3 modifySeams(vec3 dir, float amount) {\n\tif (amount != 1.0) {\n\t\tvec3 adir = abs(dir);\n\t\tfloat M = max(max(adir.x, adir.y), adir.z);\n\t\tif (adir.x == M) {\n\t\t\tdir.y *= amount;\n\t\t\tdir.z *= amount;\n\t\t}\n\t\telse if (adir.y == M) {\n\t\t\tdir.x *= amount;\n\t\t\tdir.z *= amount;\n\t\t} else {\n\t\t\tdir.x *= amount;\n\t\t\tdir.y *= amount;\n\t\t}\n\t}\n\treturn dir;\n}\nvec2 toSpherical(vec3 dir) {\n\treturn vec2(atan(dir.z, dir.x), asin(dir.y));\n}\nvec3 fromSpherical(vec2 uv) {\n\treturn vec3(cos(uv.y) * cos(uv.x),\n\t\t\t\tsin(uv.y),\n\t\t\t\tcos(uv.y) * sin(uv.x));\n}\nvec4 sampleEquirect(vec2 sph) {\n\tvec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;\n\treturn texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n}\nvec4 sampleEquirect(vec3 dir) {\n\treturn sampleEquirect(toSpherical(dir));\n}\nvec4 sampleCubemap(vec3 dir) {\n\treturn textureCube(sourceCube, modifySeams(dir, sourceCubeSeamScale()));\n}\nvec4 sampleCubemap(vec2 sph) {\n\treturn sampleCubemap(fromSpherical(sph));\n}\nvec3 getDirectionEquirect() {\n\treturn fromSpherical((vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0) * vec2(PI, PI * 0.5));\n}\nfloat signNotZero(float k){\n\treturn(k >= 0.0) ? 1.0 : -1.0;\n}\nvec2 signNotZero(vec2 v) {\n\treturn vec2(signNotZero(v.x), signNotZero(v.y));\n}\nvec3 octDecode(vec2 o) {\n\tvec3 v = vec3(o.x, 1.0 - abs(o.x) - abs(o.y), o.y);\n\tif (v.y < 0.0) {\n\t\tv.xz = (1.0 - abs(v.zx)) * signNotZero(v.xz);\n\t}\n\treturn normalize(v);\n}\nvec3 getDirectionOctahedral() {\n\treturn octDecode(vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0);\n}\nvec2 octEncode(in vec3 v) {\n\tfloat l1norm = abs(v.x) + abs(v.y) + abs(v.z);\n\tvec2 result = v.xz * (1.0 / l1norm);\n\tif (v.y < 0.0) {\n\t\tresult = (1.0 - abs(result.yx)) * signNotZero(result.xy);\n\t}\n\treturn result;\n}\nvec4 sampleOctahedral(vec3 dir) {\n\tvec2 uv = octEncode(dir) * 0.5 + 0.5;\n\treturn texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n}\nvec4 sampleOctahedral(vec2 sph) {\n\treturn sampleOctahedral(fromSpherical(sph));\n}\nvec3 getDirectionCubemap() {\n\tvec2 st = vUv0 * 2.0 - 1.0;\n\tfloat face = targetFace();\n\tvec3 vec;\n\tif (face == 0.0) {\n\t\tvec = vec3(1, -st.y, -st.x);\n\t} else if (face == 1.0) {\n\t\tvec = vec3(-1, -st.y, st.x);\n\t} else if (face == 2.0) {\n\t\tvec = vec3(st.x, 1, st.y);\n\t} else if (face == 3.0) {\n\t\tvec = vec3(st.x, -1, -st.y);\n\t} else if (face == 4.0) {\n\t\tvec = vec3(st.x, -st.y, 1);\n\t} else {\n\t\tvec = vec3(-st.x, -st.y, -1);\n\t}\n\treturn normalize(modifySeams(vec, 1.0 / targetCubeSeamScale()));\n}\nmat3 matrixFromVector(vec3 n) {\n\tfloat a = 1.0 / (1.0 + n.z);\n\tfloat b = -n.x * n.y * a;\n\tvec3 b1 = vec3(1.0 - n.x * n.x * a, b, -n.x);\n\tvec3 b2 = vec3(b, 1.0 - n.y * n.y * a, -n.y);\n\treturn mat3(b1, b2, n);\n}\nmat3 matrixFromVectorSlow(vec3 n) {\n\tvec3 a = normalize(cross(n, vec3(0, 1, 0)));\n\tvec3 b = cross(n, a);\n\treturn mat3(a, b, n);\n}\nfloat rnd(int i) {\n\tfloat sini = sin(float(i));\n\tfloat cosi = cos(float(i));\n\treturn fract(sin(dot(vec2(sini, cosi), vec2(12.9898, 78.233) * 2.0)) * 43758.5453);\n}\nvec3 hemisphereSamplePhong(vec2 uv, float specPow) {\n\tfloat phi = uv.y * 2.0 * PI;\n\tfloat cosTheta = pow(1.0 - uv.x, 1.0 / (specPow + 1.0));\n\tfloat sinTheta = sqrt(1.0 - cosTheta * cosTheta);\n\treturn vec3(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta);\n}\nvec4 reproject() {\n\tif (NUM_SAMPLES <= 1) {\n\t\treturn ENCODE_FUNC(DECODE_FUNC(SOURCE_FUNC(TARGET_FUNC())));\n\t} else {\n\t\tvec2 sph = toSpherical(TARGET_FUNC());\n\t\tvec2 sphu = dFdx(sph);\n\t\tvec2 sphv = dFdy(sph);\n\t\tvec3 result = vec3(0.0);\n\t\tfor (float u = 0.0; u < NUM_SAMPLES_SQRT; ++u) {\n\t\t\tfor (float v = 0.0; v < NUM_SAMPLES_SQRT; ++v) {\n\t\t\t\tresult += DECODE_FUNC(SOURCE_FUNC(sph +\n\t\t\t\t\t\t\t\t\t\t\t\t sphu * (u / NUM_SAMPLES_SQRT - 0.5) +\n\t\t\t\t\t\t\t\t\t\t\t\t sphv * (v / NUM_SAMPLES_SQRT - 0.5)));\n\t\t\t}\n\t\t}\n\t\treturn ENCODE_FUNC(result / (NUM_SAMPLES_SQRT * NUM_SAMPLES_SQRT));\n\t}\n}\nvec4 prefilter() {\n\tvec3 vec = TARGET_FUNC();\n\tmat3 vecSpace = matrixFromVectorSlow(vec);\n\tvec3 result = vec3(0.0);\n\tfor (int i=0; i shadowCascadeDistances[int(maxCascades - 1.0)]) {\n\t\tdShadowCoord.z = -9999999.0;\n\t}\n}\n",shadowCommonPS:"void normalOffsetPointShadow(vec4 shadowParams) {\n\tfloat distScale = length(dLightDirW);\n\tvec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0) * distScale;\n\tvec3 dir = wPos - dLightPosW;\n\tdLightDirW = dir;\n}\n",shadowCoordPS:"void _getShadowCoordOrtho(mat4 shadowMatrix, vec3 shadowParams, vec3 wPos) {\n\tdShadowCoord = (shadowMatrix * vec4(wPos, 1.0)).xyz;\n\tdShadowCoord.z = saturate(dShadowCoord.z) - 0.0001;\n\t#ifdef SHADOWBIAS\n\tdShadowCoord.z += getShadowBias(shadowParams.x, shadowParams.z);\n\t#endif\n}\nvoid _getShadowCoordPersp(mat4 shadowMatrix, vec4 shadowParams, vec3 wPos) {\n\tvec4 projPos = shadowMatrix * vec4(wPos, 1.0);\n\tprojPos.xy /= projPos.w;\n\tdShadowCoord.xy = projPos.xy;\n\tdShadowCoord.z = length(dLightDirW) * shadowParams.w;\n\t#ifdef SHADOWBIAS\n\tdShadowCoord.z += getShadowBias(shadowParams.x, shadowParams.z);\n\t#endif\n}\nvoid getShadowCoordOrtho(mat4 shadowMatrix, vec3 shadowParams) {\n\t_getShadowCoordOrtho(shadowMatrix, shadowParams, vPositionW);\n}\nvoid getShadowCoordPersp(mat4 shadowMatrix, vec4 shadowParams) {\n\t_getShadowCoordPersp(shadowMatrix, shadowParams, vPositionW);\n}\nvoid getShadowCoordPerspNormalOffset(mat4 shadowMatrix, vec4 shadowParams) {\n\tfloat distScale = abs(dot(vPositionW - dLightPosW, dLightDirNormW));\n\tvec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0) * distScale;\n\t_getShadowCoordPersp(shadowMatrix, shadowParams, wPos);\n}\nvoid getShadowCoordOrthoNormalOffset(mat4 shadowMatrix, vec3 shadowParams) {\n\tvec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0);\n\t_getShadowCoordOrtho(shadowMatrix, shadowParams, wPos);\n}\n",shadowCoordPerspZbufferPS:"void _getShadowCoordPerspZbuffer(mat4 shadowMatrix, vec4 shadowParams, vec3 wPos) {\n\tvec4 projPos = shadowMatrix * vec4(wPos, 1.0);\n\tprojPos.xyz /= projPos.w;\n\tdShadowCoord = projPos.xyz;\n}\nvoid getShadowCoordPerspZbufferNormalOffset(mat4 shadowMatrix, vec4 shadowParams) {\n\tfloat distScale = abs(dot(vPositionW - dLightPosW, dLightDirNormW));\n\tvec3 wPos = vPositionW + dVertexNormalW * shadowParams.y * clamp(1.0 - dot(dVertexNormalW, -dLightDirNormW), 0.0, 1.0) * distScale;\n\t_getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, wPos);\n}\nvoid getShadowCoordPerspZbuffer(mat4 shadowMatrix, vec4 shadowParams) {\n\t_getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, vPositionW);\n}\n",shadowEVSMPS:"float VSM$(sampler2D tex, vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n\tvec3 moments = texture2D(tex, texCoords).xyz;\n\treturn calculateEVSM(moments, Z, vsmBias, exponent);\n}\nfloat getShadowVSM$(sampler2D shadowMap, vec3 shadowParams, float exponent) {\n\treturn VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, dShadowCoord.z, shadowParams.y, exponent);\n}\nfloat getShadowSpotVSM$(sampler2D shadowMap, vec4 shadowParams, float exponent) {\n\treturn VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, length(dLightDirW) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);\n}\n",shadowEVSMnPS:"float VSM$(sampler2D tex, vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n\tfloat pixelSize = 1.0 / resolution;\n\ttexCoords -= vec2(pixelSize);\n\tvec3 s00 = texture2D(tex, texCoords).xyz;\n\tvec3 s10 = texture2D(tex, texCoords + vec2(pixelSize, 0)).xyz;\n\tvec3 s01 = texture2D(tex, texCoords + vec2(0, pixelSize)).xyz;\n\tvec3 s11 = texture2D(tex, texCoords + vec2(pixelSize)).xyz;\n\tvec2 fr = fract(texCoords * resolution);\n\tvec3 h0 = mix(s00, s10, fr.x);\n\tvec3 h1 = mix(s01, s11, fr.x);\n\tvec3 moments = mix(h0, h1, fr.y);\n\treturn calculateEVSM(moments, Z, vsmBias, exponent);\n}\nfloat getShadowVSM$(sampler2D shadowMap, vec3 shadowParams, float exponent) {\n\treturn VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, dShadowCoord.z, shadowParams.y, exponent);\n}\nfloat getShadowSpotVSM$(sampler2D shadowMap, vec4 shadowParams, float exponent) {\n\treturn VSM$(shadowMap, dShadowCoord.xy, shadowParams.x, length(dLightDirW) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);\n}\n",shadowStandardPS:"vec3 lessThan2(vec3 a, vec3 b) {\n\treturn clamp((b - a)*1000.0, 0.0, 1.0);\n}\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n\tconst vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n\treturn dot(rgbaDepth, bitShift);\n}\n#endif\n#ifdef GL2\nfloat _getShadowPCF3x3(sampler2DShadow shadowMap, vec3 shadowParams) {\n\tfloat z = dShadowCoord.z;\n\tvec2 uv = dShadowCoord.xy * shadowParams.x;\n\tfloat shadowMapSizeInv = 1.0 / shadowParams.x;\n\tvec2 base_uv = floor(uv + 0.5);\n\tfloat s = (uv.x + 0.5 - base_uv.x);\n\tfloat t = (uv.y + 0.5 - base_uv.y);\n\tbase_uv -= vec2(0.5);\n\tbase_uv *= shadowMapSizeInv;\n\tfloat sum = 0.0;\n\tfloat uw0 = (3.0 - 2.0 * s);\n\tfloat uw1 = (1.0 + 2.0 * s);\n\tfloat u0 = (2.0 - s) / uw0 - 1.0;\n\tfloat u1 = s / uw1 + 1.0;\n\tfloat vw0 = (3.0 - 2.0 * t);\n\tfloat vw1 = (1.0 + 2.0 * t);\n\tfloat v0 = (2.0 - t) / vw0 - 1.0;\n\tfloat v1 = t / vw1 + 1.0;\n\tu0 = u0 * shadowMapSizeInv + base_uv.x;\n\tv0 = v0 * shadowMapSizeInv + base_uv.y;\n\tu1 = u1 * shadowMapSizeInv + base_uv.x;\n\tv1 = v1 * shadowMapSizeInv + base_uv.y;\n\tsum += uw0 * vw0 * texture(shadowMap, vec3(u0, v0, z));\n\tsum += uw1 * vw0 * texture(shadowMap, vec3(u1, v0, z));\n\tsum += uw0 * vw1 * texture(shadowMap, vec3(u0, v1, z));\n\tsum += uw1 * vw1 * texture(shadowMap, vec3(u1, v1, z));\n\tsum *= 1.0f / 16.0;\n\treturn sum;\n}\nfloat getShadowPCF3x3(sampler2DShadow shadowMap, vec3 shadowParams) {\n\treturn _getShadowPCF3x3(shadowMap, shadowParams);\n}\nfloat getShadowSpotPCF3x3(sampler2DShadow shadowMap, vec4 shadowParams) {\n\treturn _getShadowPCF3x3(shadowMap, shadowParams.xyz);\n}\n#else\nfloat _xgetShadowPCF3x3(mat3 depthKernel, sampler2D shadowMap, vec3 shadowParams) {\n\tmat3 shadowKernel;\n\tvec3 shadowCoord = dShadowCoord;\n\tvec3 shadowZ = vec3(shadowCoord.z);\n\tshadowKernel[0] = vec3(greaterThan(depthKernel[0], shadowZ));\n\tshadowKernel[1] = vec3(greaterThan(depthKernel[1], shadowZ));\n\tshadowKernel[2] = vec3(greaterThan(depthKernel[2], shadowZ));\n\tvec2 fractionalCoord = fract( shadowCoord.xy * shadowParams.x );\n\tshadowKernel[0] = mix(shadowKernel[0], shadowKernel[1], fractionalCoord.x);\n\tshadowKernel[1] = mix(shadowKernel[1], shadowKernel[2], fractionalCoord.x);\n\tvec4 shadowValues;\n\tshadowValues.x = mix(shadowKernel[0][0], shadowKernel[0][1], fractionalCoord.y);\n\tshadowValues.y = mix(shadowKernel[0][1], shadowKernel[0][2], fractionalCoord.y);\n\tshadowValues.z = mix(shadowKernel[1][0], shadowKernel[1][1], fractionalCoord.y);\n\tshadowValues.w = mix(shadowKernel[1][1], shadowKernel[1][2], fractionalCoord.y);\n\treturn dot( shadowValues, vec4( 1.0 ) ) * 0.25;\n}\nfloat _getShadowPCF3x3(sampler2D shadowMap, vec3 shadowParams) {\n\tvec3 shadowCoord = dShadowCoord;\n\tfloat xoffset = 1.0 / shadowParams.x;\n\tfloat dx0 = -xoffset;\n\tfloat dx1 = xoffset;\n\tmat3 depthKernel;\n\tdepthKernel[0][0] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx0, dx0)));\n\tdepthKernel[0][1] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx0, 0.0)));\n\tdepthKernel[0][2] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx0, dx1)));\n\tdepthKernel[1][0] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(0.0, dx0)));\n\tdepthKernel[1][1] = unpackFloat(texture2D(shadowMap, shadowCoord.xy));\n\tdepthKernel[1][2] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(0.0, dx1)));\n\tdepthKernel[2][0] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx1, dx0)));\n\tdepthKernel[2][1] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx1, 0.0)));\n\tdepthKernel[2][2] = unpackFloat(texture2D(shadowMap, shadowCoord.xy + vec2(dx1, dx1)));\n\treturn _xgetShadowPCF3x3(depthKernel, shadowMap, shadowParams);\n}\nfloat getShadowPCF3x3(sampler2D shadowMap, vec3 shadowParams) {\n\treturn _getShadowPCF3x3(shadowMap, shadowParams);\n}\nfloat getShadowSpotPCF3x3(sampler2D shadowMap, vec4 shadowParams) {\n\treturn _getShadowPCF3x3(shadowMap, shadowParams.xyz);\n}\n#endif\nfloat _getShadowPoint(samplerCube shadowMap, vec4 shadowParams, vec3 dir) {\n\tvec3 tc = normalize(dir);\n\tvec3 tcAbs = abs(tc);\n\tvec4 dirX = vec4(1,0,0, tc.x);\n\tvec4 dirY = vec4(0,1,0, tc.y);\n\tfloat majorAxisLength = tc.z;\n\tif ((tcAbs.x > tcAbs.y) && (tcAbs.x > tcAbs.z)) {\n\t\tdirX = vec4(0,0,1, tc.z);\n\t\tdirY = vec4(0,1,0, tc.y);\n\t\tmajorAxisLength = tc.x;\n\t} else if ((tcAbs.y > tcAbs.x) && (tcAbs.y > tcAbs.z)) {\n\t\tdirX = vec4(1,0,0, tc.x);\n\t\tdirY = vec4(0,0,1, tc.z);\n\t\tmajorAxisLength = tc.y;\n\t}\n\tfloat shadowParamsInFaceSpace = ((1.0/shadowParams.x) * 2.0) * abs(majorAxisLength);\n\tvec3 xoffset = (dirX.xyz * shadowParamsInFaceSpace);\n\tvec3 yoffset = (dirY.xyz * shadowParamsInFaceSpace);\n\tvec3 dx0 = -xoffset;\n\tvec3 dy0 = -yoffset;\n\tvec3 dx1 = xoffset;\n\tvec3 dy1 = yoffset;\n\tmat3 shadowKernel;\n\tmat3 depthKernel;\n\tdepthKernel[0][0] = unpackFloat(textureCube(shadowMap, tc + dx0 + dy0));\n\tdepthKernel[0][1] = unpackFloat(textureCube(shadowMap, tc + dx0));\n\tdepthKernel[0][2] = unpackFloat(textureCube(shadowMap, tc + dx0 + dy1));\n\tdepthKernel[1][0] = unpackFloat(textureCube(shadowMap, tc + dy0));\n\tdepthKernel[1][1] = unpackFloat(textureCube(shadowMap, tc));\n\tdepthKernel[1][2] = unpackFloat(textureCube(shadowMap, tc + dy1));\n\tdepthKernel[2][0] = unpackFloat(textureCube(shadowMap, tc + dx1 + dy0));\n\tdepthKernel[2][1] = unpackFloat(textureCube(shadowMap, tc + dx1));\n\tdepthKernel[2][2] = unpackFloat(textureCube(shadowMap, tc + dx1 + dy1));\n\tvec3 shadowZ = vec3(length(dir) * shadowParams.w + shadowParams.z);\n\tshadowKernel[0] = vec3(lessThan2(depthKernel[0], shadowZ));\n\tshadowKernel[1] = vec3(lessThan2(depthKernel[1], shadowZ));\n\tshadowKernel[2] = vec3(lessThan2(depthKernel[2], shadowZ));\n\tvec2 uv = (vec2(dirX.w, dirY.w) / abs(majorAxisLength)) * 0.5;\n\tvec2 fractionalCoord = fract( uv * shadowParams.x );\n\tshadowKernel[0] = mix(shadowKernel[0], shadowKernel[1], fractionalCoord.x);\n\tshadowKernel[1] = mix(shadowKernel[1], shadowKernel[2], fractionalCoord.x);\n\tvec4 shadowValues;\n\tshadowValues.x = mix(shadowKernel[0][0], shadowKernel[0][1], fractionalCoord.y);\n\tshadowValues.y = mix(shadowKernel[0][1], shadowKernel[0][2], fractionalCoord.y);\n\tshadowValues.z = mix(shadowKernel[1][0], shadowKernel[1][1], fractionalCoord.y);\n\tshadowValues.w = mix(shadowKernel[1][1], shadowKernel[1][2], fractionalCoord.y);\n\treturn 1.0 - dot( shadowValues, vec4( 1.0 ) ) * 0.25;\n}\nfloat getShadowPointPCF3x3(samplerCube shadowMap, vec4 shadowParams) {\n\treturn _getShadowPoint(shadowMap, shadowParams, dLightDirW);\n}\n",shadowStandardGL2PS:"float _getShadowPCF5x5(sampler2DShadow shadowMap, vec3 shadowParams) {\n\tfloat z = dShadowCoord.z;\n\tvec2 uv = dShadowCoord.xy * shadowParams.x;\n\tfloat shadowMapSizeInv = 1.0 / shadowParams.x;\n\tvec2 base_uv = floor(uv + 0.5);\n\tfloat s = (uv.x + 0.5 - base_uv.x);\n\tfloat t = (uv.y + 0.5 - base_uv.y);\n\tbase_uv -= vec2(0.5);\n\tbase_uv *= shadowMapSizeInv;\n\tfloat uw0 = (4.0 - 3.0 * s);\n\tfloat uw1 = 7.0;\n\tfloat uw2 = (1.0 + 3.0 * s);\n\tfloat u0 = (3.0 - 2.0 * s) / uw0 - 2.0;\n\tfloat u1 = (3.0 + s) / uw1;\n\tfloat u2 = s / uw2 + 2.0;\n\tfloat vw0 = (4.0 - 3.0 * t);\n\tfloat vw1 = 7.0;\n\tfloat vw2 = (1.0 + 3.0 * t);\n\tfloat v0 = (3.0 - 2.0 * t) / vw0 - 2.0;\n\tfloat v1 = (3.0 + t) / vw1;\n\tfloat v2 = t / vw2 + 2.0;\n\tfloat sum = 0.0;\n\tu0 = u0 * shadowMapSizeInv + base_uv.x;\n\tv0 = v0 * shadowMapSizeInv + base_uv.y;\n\tu1 = u1 * shadowMapSizeInv + base_uv.x;\n\tv1 = v1 * shadowMapSizeInv + base_uv.y;\n\tu2 = u2 * shadowMapSizeInv + base_uv.x;\n\tv2 = v2 * shadowMapSizeInv + base_uv.y;\n\tsum += uw0 * vw0 * texture(shadowMap, vec3(u0, v0, z));\n\tsum += uw1 * vw0 * texture(shadowMap, vec3(u1, v0, z));\n\tsum += uw2 * vw0 * texture(shadowMap, vec3(u2, v0, z));\n\tsum += uw0 * vw1 * texture(shadowMap, vec3(u0, v1, z));\n\tsum += uw1 * vw1 * texture(shadowMap, vec3(u1, v1, z));\n\tsum += uw2 * vw1 * texture(shadowMap, vec3(u2, v1, z));\n\tsum += uw0 * vw2 * texture(shadowMap, vec3(u0, v2, z));\n\tsum += uw1 * vw2 * texture(shadowMap, vec3(u1, v2, z));\n\tsum += uw2 * vw2 * texture(shadowMap, vec3(u2, v2, z));\n\tsum *= 1.0f / 144.0;\n\tsum = gammaCorrectInput(sum);\n\tsum = saturate(sum);\n\treturn sum;\n}\nfloat getShadowPCF5x5(sampler2DShadow shadowMap, vec3 shadowParams) {\n\treturn _getShadowPCF5x5(shadowMap, shadowParams);\n}\nfloat getShadowSpotPCF5x5(sampler2DShadow shadowMap, vec4 shadowParams) {\n\treturn _getShadowPCF5x5(shadowMap, shadowParams.xyz);\n}\n",shadowVSM8PS:"float calculateVSM8(vec3 moments, float Z, float vsmBias) {\n\tfloat VSMBias = vsmBias;\n\tfloat depthScale = VSMBias * Z;\n\tfloat minVariance1 = depthScale * depthScale;\n\treturn chebyshevUpperBound(moments.xy, Z, minVariance1, 0.1);\n}\nfloat decodeFloatRG(vec2 rg) {\n\treturn rg.y*(1.0/255.0) + rg.x;\n}\nfloat VSM8(sampler2D tex, vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n\tvec4 c = texture2D(tex, texCoords);\n\tvec3 moments = vec3(decodeFloatRG(c.xy), decodeFloatRG(c.zw), 0.0);\n\treturn calculateVSM8(moments, Z, vsmBias);\n}\nfloat getShadowVSM8(sampler2D shadowMap, vec3 shadowParams, float exponent) {\n\treturn VSM8(shadowMap, dShadowCoord.xy, shadowParams.x, dShadowCoord.z, shadowParams.y, 0.0);\n}\nfloat getShadowSpotVSM8(sampler2D shadowMap, vec4 shadowParams, float exponent) {\n\treturn VSM8(shadowMap, dShadowCoord.xy, shadowParams.x, length(dLightDirW) * shadowParams.w + shadowParams.z, shadowParams.y, 0.0);\n}\n",shadowVSM_commonPS:"float linstep(float a, float b, float v) {\n\treturn saturate((v - a) / (b - a));\n}\nfloat reduceLightBleeding(float pMax, float amount) {\n return linstep(amount, 1.0, pMax);\n}\nfloat chebyshevUpperBound(vec2 moments, float mean, float minVariance, float lightBleedingReduction) {\n\tfloat variance = moments.y - (moments.x * moments.x);\n\tvariance = max(variance, minVariance);\n\tfloat d = mean - moments.x;\n\tfloat pMax = variance / (variance + (d * d));\n\tpMax = reduceLightBleeding(pMax, lightBleedingReduction);\n\treturn (mean <= moments.x ? 1.0 : pMax);\n}\nfloat calculateEVSM(vec3 moments, float Z, float vsmBias, float exponent) {\n\tZ = 2.0 * Z - 1.0;\n\tfloat warpedDepth = exp(exponent * Z);\n\tmoments.xy += vec2(warpedDepth, warpedDepth*warpedDepth) * (1.0 - moments.z);\n\tfloat VSMBias = vsmBias;\n\tfloat depthScale = VSMBias * exponent * warpedDepth;\n\tfloat minVariance1 = depthScale * depthScale;\n\treturn chebyshevUpperBound(moments.xy, warpedDepth, minVariance1, 0.1);\n}\n",skinBatchConstVS:"attribute float vertex_boneIndices;\nuniform vec4 matrix_pose[BONE_LIMIT * 3];\nmat4 getBoneMatrix(const in float i) {\n\tvec4 v1 = matrix_pose[int(3.0 * i)];\n\tvec4 v2 = matrix_pose[int(3.0 * i + 1.0)];\n\tvec4 v3 = matrix_pose[int(3.0 * i + 2.0)];\n\treturn mat4(\n\t\tv1.x, v2.x, v3.x, 0,\n\t\tv1.y, v2.y, v3.y, 0,\n\t\tv1.z, v2.z, v3.z, 0,\n\t\tv1.w, v2.w, v3.w, 1\n\t);\n}\n",skinBatchTexVS:"attribute float vertex_boneIndices;\nuniform highp sampler2D texture_poseMap;\nuniform vec4 texture_poseMapSize;\nmat4 getBoneMatrix(const in float i) {\n\tfloat j = i * 3.0;\n\tfloat dx = texture_poseMapSize.z;\n\tfloat dy = texture_poseMapSize.w;\n\tfloat y = floor(j * dx);\n\tfloat x = j - (y * texture_poseMapSize.x);\n\ty = dy * (y + 0.5);\n\tvec4 v1 = texture2D(texture_poseMap, vec2(dx * (x + 0.5), y));\n\tvec4 v2 = texture2D(texture_poseMap, vec2(dx * (x + 1.5), y));\n\tvec4 v3 = texture2D(texture_poseMap, vec2(dx * (x + 2.5), y));\n\treturn mat4(\n\t\tv1.x, v2.x, v3.x, 0,\n\t\tv1.y, v2.y, v3.y, 0,\n\t\tv1.z, v2.z, v3.z, 0,\n\t\tv1.w, v2.w, v3.w, 1\n\t);\n}\n",skinConstVS:"attribute vec4 vertex_boneWeights;\nattribute vec4 vertex_boneIndices;\nuniform vec4 matrix_pose[BONE_LIMIT * 3];\nvoid getBoneMatrix(const in float i, out vec4 v1, out vec4 v2, out vec4 v3) {\n\tv1 = matrix_pose[int(3.0 * i)];\n\tv2 = matrix_pose[int(3.0 * i + 1.0)];\n\tv3 = matrix_pose[int(3.0 * i + 2.0)];\n}\nmat4 getSkinMatrix(const in vec4 indices, const in vec4 weights) {\n\tvec4 a1, a2, a3;\n\tgetBoneMatrix(indices.x, a1, a2, a3);\n\tvec4 b1, b2, b3;\n\tgetBoneMatrix(indices.y, b1, b2, b3);\n\tvec4 c1, c2, c3;\n\tgetBoneMatrix(indices.z, c1, c2, c3);\n\tvec4 d1, d2, d3;\n\tgetBoneMatrix(indices.w, d1, d2, d3);\n\tvec4 v1 = a1 * weights.x + b1 * weights.y + c1 * weights.z + d1 * weights.w;\n\tvec4 v2 = a2 * weights.x + b2 * weights.y + c2 * weights.z + d2 * weights.w;\n\tvec4 v3 = a3 * weights.x + b3 * weights.y + c3 * weights.z + d3 * weights.w;\n\tfloat one = dot(weights, vec4(1.0));\n\treturn mat4(\n\t\tv1.x, v2.x, v3.x, 0,\n\t\tv1.y, v2.y, v3.y, 0,\n\t\tv1.z, v2.z, v3.z, 0,\n\t\tv1.w, v2.w, v3.w, one\n\t);\n}\n",skinTexVS:"attribute vec4 vertex_boneWeights;\nattribute vec4 vertex_boneIndices;\nuniform highp sampler2D texture_poseMap;\nuniform vec4 texture_poseMapSize;\nvoid getBoneMatrix(const in float i, out vec4 v1, out vec4 v2, out vec4 v3) {\n\tfloat j = i * 3.0;\n\tfloat dx = texture_poseMapSize.z;\n\tfloat dy = texture_poseMapSize.w;\n\tfloat y = floor(j * dx);\n\tfloat x = j - (y * texture_poseMapSize.x);\n\ty = dy * (y + 0.5);\n\tv1 = texture2D(texture_poseMap, vec2(dx * (x + 0.5), y));\n\tv2 = texture2D(texture_poseMap, vec2(dx * (x + 1.5), y));\n\tv3 = texture2D(texture_poseMap, vec2(dx * (x + 2.5), y));\n}\nmat4 getSkinMatrix(const in vec4 indices, const in vec4 weights) {\n\tvec4 a1, a2, a3;\n\tgetBoneMatrix(indices.x, a1, a2, a3);\n\tvec4 b1, b2, b3;\n\tgetBoneMatrix(indices.y, b1, b2, b3);\n\tvec4 c1, c2, c3;\n\tgetBoneMatrix(indices.z, c1, c2, c3);\n\tvec4 d1, d2, d3;\n\tgetBoneMatrix(indices.w, d1, d2, d3);\n\tvec4 v1 = a1 * weights.x + b1 * weights.y + c1 * weights.z + d1 * weights.w;\n\tvec4 v2 = a2 * weights.x + b2 * weights.y + c2 * weights.z + d2 * weights.w;\n\tvec4 v3 = a3 * weights.x + b3 * weights.y + c3 * weights.z + d3 * weights.w;\n\tfloat one = dot(weights, vec4(1.0));\n\treturn mat4(\n\t\tv1.x, v2.x, v3.x, 0,\n\t\tv1.y, v2.y, v3.y, 0,\n\t\tv1.z, v2.z, v3.z, 0,\n\t\tv1.w, v2.w, v3.w, one\n\t);\n}\n",skyboxPS:"varying vec3 vViewDir;\nuniform samplerCube texture_cubeMap;\nvoid main(void) {\n\tgl_FragColor = textureCube(texture_cubeMap, fixSeams(vViewDir));\n}\n",skyboxVS:"attribute vec3 aPosition;\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nuniform mat4 matrix_projectionSkybox;\nvarying vec3 vViewDir;\nvoid main(void) {\n\tmat4 view = matrix_view;\n\tview[3][0] = view[3][1] = view[3][2] = 0.0;\n\tgl_Position = matrix_projectionSkybox * view * vec4(aPosition, 1.0);\n\tgl_Position.z = gl_Position.w - 0.00001;\n\tvViewDir = aPosition;\n}\n",skyboxHDRPS:"varying vec3 vViewDir;\nuniform samplerCube texture_cubeMap;\n#ifdef CUBEMAP_ROTATION\nuniform mat3 cubeMapRotationMatrix;\n#endif\nvoid main(void) {\n#ifdef CUBEMAP_ROTATION\n\tvec3 dir=vViewDir * cubeMapRotationMatrix;\n#else\n\tvec3 dir=vViewDir;\n#endif\n#ifndef RIGHT_HANDED_CUBEMAP\n\tdir.x *= -1.0;\n#endif\n\tvec3 color = processEnvironment($textureCubeSAMPLE(texture_cubeMap, fixSeamsStatic(dir, $FIXCONST)).rgb);\n\tcolor = toneMap(color);\n\tcolor = gammaCorrectOutput(color);\n\tgl_FragColor = vec4(color, 1.0);\n}\n",skyboxPrefilteredCubePS:"varying vec3 vViewDir;\nuniform samplerCube texture_cubeMap;\nvec3 fixSeamsStretch(vec3 vec, float mipmapIndex, float cubemapSize) {\n\tfloat scale = 1.0 - exp2(mipmapIndex) / cubemapSize;\n\tfloat M = max(max(abs(vec.x), abs(vec.y)), abs(vec.z));\n\tif (abs(vec.x) != M) vec.x *= scale;\n\tif (abs(vec.y) != M) vec.y *= scale;\n\tif (abs(vec.z) != M) vec.z *= scale;\n\treturn vec;\n}\nvoid main(void) {\n\tvec3 color = textureCubeRGBM(texture_cubeMap, fixSeamsStretch(vViewDir, 0.0, 128.0));\n\tcolor = toneMap(color);\n\tcolor = gammaCorrectOutput(color);\n\tgl_FragColor = vec4(color, 1.0);\n}\n",specularPS:"#ifdef MAPCOLOR\nuniform vec3 material_specular;\n#endif\n#ifdef MAPTEXTURE\nuniform sampler2D texture_specularMap;\n#endif\nvoid getSpecularity() {\n\tdSpecularity = vec3(1.0);\n\t#ifdef MAPCOLOR\n\tdSpecularity *= material_specular;\n\t#endif\n\t#ifdef MAPTEXTURE\n\tdSpecularity *= texture2D(texture_specularMap, $UV).$CH;\n\t#endif\n\t#ifdef MAPVERTEX\n\tdSpecularity *= saturate(vVertexColor.$VC);\n\t#endif\n}\n",specularAaNonePS:"float antiAliasGlossiness(float power) {\n\treturn power;\n}\n",specularAaToksvigPS:"float antiAliasGlossiness(float power) {\n\tfloat rlen = 1.0 / saturate(length(dNormalMap));\n\tfloat toksvig = 1.0 / (1.0 + power * (rlen - 1.0));\n\treturn power * mix(1.0, toksvig, material_bumpiness);\n}\n",specularAaToksvigFastPS:"float antiAliasGlossiness(float power) {\n\tfloat rlen = 1.0 / saturate(length(dNormalMap));\n\tfloat toksvig = 1.0 / (1.0 + power * (rlen - 1.0));\n\treturn power * toksvig;\n}\n",spotPS:"float getSpotEffect(vec3 lightSpotDirW, float lightInnerConeAngle, float lightOuterConeAngle) {\n\tfloat cosAngle = dot(dLightDirNormW, lightSpotDirW);\n\treturn smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle);\n}\n",startPS:"void main(void) {\n\tdDiffuseLight = vec3(0);\n\tdSpecularLight = vec3(0);\n\tdReflection = vec4(0);\n\tdSpecularity = vec3(0);\n\t#ifdef CLEARCOAT\n\tccSpecularLight = vec3(0);\n\tccReflection = vec4(0);\n\t#endif\n",startVS:"void main(void) {\n\tgl_Position = getPosition();\n",startNineSlicedPS:"\tnineSlicedUv = vUv0;\n\tnineSlicedUv.y = 1.0 - nineSlicedUv.y;\n",startNineSlicedTiledPS:"\tvec2 tileMask = step(vMask, vec2(0.99999));\n\tvec2 tileSize = 0.5 * (innerOffset.xy + innerOffset.zw);\n\tvec2 tileScale = vec2(1.0) / (vec2(1.0) - tileSize);\n\tvec2 clampedUv = mix(innerOffset.xy * 0.5, vec2(1.0) - innerOffset.zw * 0.5, fract((vTiledUv - tileSize) * tileScale));\n\tclampedUv = clampedUv * atlasRect.zw + atlasRect.xy;\n\tnineSlicedUv = vUv0 * tileMask + clampedUv * (vec2(1.0) - tileMask);\n\tnineSlicedUv.y = 1.0 - nineSlicedUv.y;\n",storeEVSMPS:"float exponent = VSM_EXPONENT;\ndepth = 2.0 * depth - 1.0;\ndepth = exp(exponent * depth);\ngl_FragColor = vec4(depth, depth*depth, 1.0, 1.0);\n",tangentBinormalVS:"vec3 getTangent() {\n\treturn normalize(dNormalMatrix * vertex_tangent.xyz);\n}\nvec3 getBinormal() {\n\treturn cross(vNormalW, vTangentW) * vertex_tangent.w;\n}\nvec3 getObjectSpaceUp() {\n\treturn normalize(dNormalMatrix * vec3(0, 1, 0));\n}\n",TBNPS:"void getTBN() {\n\tdTBN = mat3(normalize(dTangentW), normalize(dBinormalW), normalize(dVertexNormalW));\n}\n",TBNderivativePS:"uniform float tbnBasis;\nvoid getTBN() {\n\tvec2 uv = $UV;\n\tvec3 dp1 = dFdx( vPositionW );\n\tvec3 dp2 = dFdy( vPositionW );\n\tvec2 duv1 = dFdx( uv );\n\tvec2 duv2 = dFdy( uv );\n\tvec3 dp2perp = cross( dp2, dVertexNormalW );\n\tvec3 dp1perp = cross( dVertexNormalW, dp1 );\n\tvec3 T = dp2perp * duv1.x + dp1perp * duv2.x;\n\tvec3 B = dp2perp * duv1.y + dp1perp * duv2.y;\n\tfloat denom = max( dot(T,T), dot(B,B) );\n\tfloat invmax = (denom == 0.0) ? 0.0 : tbnBasis / sqrt( denom );\n\tdTBN = mat3(T * invmax, -B * invmax, dVertexNormalW );\n}\n",TBNfastPS:"void getTBN() {\n\tdTBN = mat3(dTangentW, dBinormalW, dVertexNormalW);\n}\n",TBNObjectSpacePS:"void getTBN() {\n\tvec3 B = cross(dVertexNormalW, vObjectSpaceUpW);\n\tvec3 T = cross(dVertexNormalW, B);\n\tif (dot(B,B)==0.0)\n\t{\n\t\tfloat major=max(max(dVertexNormalW.x, dVertexNormalW.y),dVertexNormalW.z);\n\t\tif (dVertexNormalW.x==major)\n\t\t{\n\t\t\tB=cross(dVertexNormalW, vec3(0,1,0));\n\t\t\tT=cross(dVertexNormalW, B);\n\t\t}\n\t\telse if (dVertexNormalW.y==major)\n\t\t{\n\t\t\tB=cross(dVertexNormalW, vec3(0,0,1));\n\t\t\tT=cross(dVertexNormalW, B);\n\t\t}\n\t\telse if (dVertexNormalW.z==major)\n\t\t{\n\t\t\tB=cross(dVertexNormalW, vec3(1,0,0));\n\t\t\tT=cross(dVertexNormalW, B);\n\t\t}\n\t}\n\tdTBN = mat3(normalize(T), normalize(B), normalize(dVertexNormalW));\n}\n",tonemappingAcesPS:"uniform float exposure;\nvec3 toneMap(vec3 color) {\n\tfloat tA = 2.51;\n\tfloat tB = 0.03;\n\tfloat tC = 2.43;\n\tfloat tD = 0.59;\n\tfloat tE = 0.14;\n\tvec3 x = color * exposure;\n\treturn (x*(tA*x+tB))/(x*(tC*x+tD)+tE);\n}\n",tonemappingAces2PS:"uniform float exposure;\nconst mat3 ACESInputMat = mat3(\n\t0.59719, 0.35458, 0.04823,\n\t0.07600, 0.90834, 0.01566,\n\t0.02840, 0.13383, 0.83777\n);\nconst mat3 ACESOutputMat = mat3(\n\t 1.60475, -0.53108, -0.07367,\n\t-0.10208, 1.10813, -0.00605,\n\t-0.00327, -0.07276, 1.07602\n);\nvec3 RRTAndODTFit(vec3 v) {\n\tvec3 a = v * (v + 0.0245786) - 0.000090537;\n\tvec3 b = v * (0.983729 * v + 0.4329510) + 0.238081;\n\treturn a / b;\n}\nvec3 toneMap(vec3 color) {\n\tcolor *= exposure;\n\tcolor = color * ACESInputMat;\n\tcolor = RRTAndODTFit(color);\n\tcolor = color * ACESOutputMat;\n\tcolor = clamp(color, 0.0, 1.0);\n\treturn color;\n}\n",tonemappingFilmicPS:"const float A = 0.15;\nconst float B = 0.50;\nconst float C = 0.10;\nconst float D = 0.20;\nconst float E = 0.02;\nconst float F = 0.30;\nconst float W = 11.2;\nuniform float exposure;\nvec3 uncharted2Tonemap(vec3 x) {\n return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\n}\nvec3 toneMap(vec3 color) {\n\tcolor = uncharted2Tonemap(color * exposure);\n\tvec3 whiteScale = 1.0 / uncharted2Tonemap(vec3(W,W,W));\n\tcolor = color * whiteScale;\n\treturn color;\n}\n",tonemappingHejlPS:"uniform float exposure;\nvec3 toneMap(vec3 color) {\n\tcolor *= exposure;\n\tconst float A = 0.22, B = 0.3, C = .1, D = 0.2, E = .01, F = 0.3;\n\tconst float Scl = 1.25;\n\tvec3 h = max( vec3(0.0), color - vec3(0.004) );\n\treturn (h*((Scl*A)*h+Scl*vec3(C*B,C*B,C*B))+Scl*vec3(D*E,D*E,D*E)) / (h*(A*h+vec3(B,B,B))+vec3(D*F,D*F,D*F)) - Scl*vec3(E/F,E/F,E/F);\n}\n",tonemappingLinearPS:"uniform float exposure;\nvec3 toneMap(vec3 color) {\n\treturn color * exposure;\n}\n",tonemappingNonePS:"vec3 toneMap(vec3 color) {\n\treturn color;\n}\n",transformVS:"#ifdef PIXELSNAP\nuniform vec4 uScreenSize;\n#endif\n#ifdef MORPHING\nuniform vec4 morph_weights_a;\nuniform vec4 morph_weights_b;\n#endif\n#ifdef MORPHING_TEXTURE_BASED\nuniform vec4 morph_tex_params;\nvec2 getTextureMorphCoords() {\n\tfloat vertexId = morph_vertex_id;\n\tvec2 textureSize = morph_tex_params.xy;\n\tvec2 invTextureSize = morph_tex_params.zw;\n\tfloat morphGridV = floor(vertexId * invTextureSize.x);\n\tfloat morphGridU = vertexId - (morphGridV * textureSize.x);\n\treturn (vec2(morphGridU, morphGridV) * invTextureSize) + (0.5 * invTextureSize);\n}\n#endif\n#ifdef MORPHING_TEXTURE_BASED_POSITION\nuniform highp sampler2D morphPositionTex;\n#endif\nmat4 getModelMatrix() {\n\t#ifdef DYNAMICBATCH\n\treturn getBoneMatrix(vertex_boneIndices);\n\t#elif defined(SKIN)\n\treturn matrix_model * getSkinMatrix(vertex_boneIndices, vertex_boneWeights);\n\t#elif defined(INSTANCING)\n\treturn mat4(instance_line1, instance_line2, instance_line3, instance_line4);\n\t#else\n\treturn matrix_model;\n\t#endif\n}\nvec4 getPosition() {\n\tdModelMatrix = getModelMatrix();\n\tvec3 localPos = vertex_position;\n\t#ifdef NINESLICED\n\tlocalPos.xz *= outerScale;\n\tvec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0));\n\tvec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0));\n\tlocalPos.xz += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;\n\tvTiledUv = (localPos.xz - outerScale + innerOffset.xy) * -0.5 + 1.0;\n\tlocalPos.xz *= -0.5;\n\tlocalPos = localPos.xzy;\n\t#endif\n\t#ifdef MORPHING\n\t#ifdef MORPHING_POS03\n\tlocalPos.xyz += morph_weights_a[0] * morph_pos0;\n\tlocalPos.xyz += morph_weights_a[1] * morph_pos1;\n\tlocalPos.xyz += morph_weights_a[2] * morph_pos2;\n\tlocalPos.xyz += morph_weights_a[3] * morph_pos3;\n\t#endif\n\t#ifdef MORPHING_POS47\n\tlocalPos.xyz += morph_weights_b[0] * morph_pos4;\n\tlocalPos.xyz += morph_weights_b[1] * morph_pos5;\n\tlocalPos.xyz += morph_weights_b[2] * morph_pos6;\n\tlocalPos.xyz += morph_weights_b[3] * morph_pos7;\n\t#endif\n\t#endif\n\t#ifdef MORPHING_TEXTURE_BASED_POSITION\n\tvec2 morphUV = getTextureMorphCoords();\n\tvec3 morphPos = texture2D(morphPositionTex, morphUV).xyz;\n\tlocalPos += morphPos;\n\t#endif\n\tvec4 posW = dModelMatrix * vec4(localPos, 1.0);\n\t#ifdef SCREENSPACE\n\tposW.zw = vec2(0.0, 1.0);\n\t#endif\n\tdPositionW = posW.xyz;\n\tvec4 screenPos;\n\t#ifdef UV1LAYOUT\n\tscreenPos = vec4(vertex_texCoord1.xy * 2.0 - 1.0, 0.5, 1);\n\t#else\n\t#ifdef SCREENSPACE\n\tscreenPos = posW;\n\t#else\n\tscreenPos = matrix_viewProjection * posW;\n\t#endif\n\t#ifdef PIXELSNAP\n\tscreenPos.xy = (screenPos.xy * 0.5) + 0.5;\n\tscreenPos.xy *= uScreenSize.xy;\n\tscreenPos.xy = floor(screenPos.xy);\n\tscreenPos.xy *= uScreenSize.zw;\n\tscreenPos.xy = (screenPos.xy * 2.0) - 1.0;\n\t#endif\n\t#endif\n\treturn screenPos;\n}\nvec3 getWorldPosition() {\n\treturn dPositionW;\n}\n",transformDeclVS:"attribute vec3 vertex_position;\nuniform mat4 matrix_model;\nuniform mat4 matrix_viewProjection;\nvec3 dPositionW;\nmat4 dModelMatrix;\n",uv0VS:"#ifdef NINESLICED\nvec2 getUv0() {\n\tvec2 uv = vertex_position.xz;\n\tvec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0));\n\tvec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0));\n\tuv += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;\n\tuv = uv * -0.5 + 0.5;\n\tuv = uv * atlasRect.zw + atlasRect.xy;\n\tvMask = vertex_texCoord0.xy;\n\treturn uv;\n}\n#else\nvec2 getUv0() {\n\treturn vertex_texCoord0;\n}\n#endif\n",uv1VS:"vec2 getUv1() {\n\treturn vertex_texCoord1;\n}\n",viewDirPS:"void getViewDir() {\n\tdViewDirW = normalize(view_position - vPositionW);\n}\n",viewNormalVS:"#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nvec3 getViewNormal() {\n\treturn mat3(matrix_view) * vNormalW;\n}\n"};function wi(e,t){return t||(t=Ti),1===e||2===e?t.gamma2_2PS?t.gamma2_2PS:Ti.gamma2_2PS:3===e?"#define HDR\n"+(t.gamma2_2PS?t.gamma2_2PS:Ti.gamma2_2PS):t.gamma1_0PS?t.gamma1_0PS:Ti.gamma1_0PS}function Mi(e,t){return t||(t=Ti),1===e?t.tonemappingFilmicPS?t.tonemappingFilmicPS:Ti.tonemappingFilmicPS:0===e?t.tonemappingLinearPS?t.tonemappingLinearPS:Ti.tonemappingLinearPS:2===e?t.tonemappingHejlPS?t.tonemappingHejlPS:Ti.tonemappingHejlPS:3===e?t.tonemappingAcesPS?t.tonemappingAcesPS:Ti.tonemappingAcesPS:4===e?t.tonemappingAces2PS?t.tonemappingAces2PS:Ti.tonemappingAces2PS:t.tonemapingNonePS?t.tonemapingNonePS:Ti.tonemappingNonePS}function Ai(e,t){return t||(t=Ti),"linear"===e?t.fogLinearPS?t.fogLinearPS:Ti.fogLinearPS:"exp"===e?t.fogExpPS?t.fogExpPS:Ti.fogExpPS:"exp2"===e?t.fogExp2PS?t.fogExp2PS:Ti.fogExp2PS:t.fogNonePS?t.fogNonePS:Ti.fogNonePS}function Ci(e,t){return t||(t=Ti),e.supportsBoneTextures?t.skinTexVS:"#define BONE_LIMIT "+e.getBoneLimit()+"\n"+t.skinConstVS}function Ei(e){var t="precision "+e.precision+" float;\n";return e.webgl2&&(t+="#ifdef GL2\nprecision "+e.precision+" sampler2DShadow;\n#endif\n"),t}function Pi(e){return e.webgl2?"#version 300 es\n":""}function Ii(){return"void main(void) {gl_FragColor = vec4(0.0);}"}function Ri(){return"void main(void)\n{\n"}function Li(){return"}\n"}var Di={vertex_position:ct,vertex_normal:ut,vertex_tangent:dt,vertex_texCoord0:gt,vertex_texCoord1:vt,vertex_texCoord2:yt,vertex_texCoord3:xt,vertex_texCoord4:bt,vertex_texCoord5:St,vertex_texCoord6:Tt,vertex_texCoord7:wt,vertex_color:mt,vertex_boneIndices:pt,vertex_boneWeights:ft};function ki(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.substr(r+1,s-(r+1)),o=Di[a];void 0!==o?t[a]=o:(t[a]="ATTR"+i,i++),n=e.indexOf("attribute",n+1)}return t}function Oi(e,t,i,n,s,r){var a=e.programLib._cache,o=a[n];if(void 0!==o)return o;i=Ei(e)+"\n"+(i||"void main(void) {gl_FragColor = vec4(0.0);}");var h=ki(t);return e.webgl2&&(t=Pi(e)+Ti.gles3VS+t,i=Pi(e)+Ti.gles3PS+i),a[n]=new Si(e,{attributes:h,vshader:t,fshader:(r||"")+i,useTransformFeedback:s}),a[n]}Ti.collectAttribs=ki,Ti.createShader=function(e,t,i,n){var s=Ti[t],r=Ei(e)+"\n"+Ti[i],a=ki(s);return e.webgl2&&(s=Pi(e)+Ti.gles3VS+s,r=Pi(e)+Ti.gles3PS+r),new Si(e,{attributes:a,vshader:s,fshader:r,useTransformFeedback:n})},Ti.createShaderFromCode=Oi;var Fi={generateKey:function(e){var t="basic";return e.fog&&(t+="_fog"),e.alphaTest&&(t+="_atst"),e.vertexColors&&(t+="_vcol"),e.diffuseMap&&(t+="_diff"),e.skin&&(t+="_skin"),e.screenSpace&&(t+="_ss"),e.useInstancing&&(t+="_inst"),e.useMorphPosition&&(t+="_morphp"),e.useMorphNormal&&(t+="_morphn"),e.useMorphTextureBased&&(t+="_morpht"),t+="_"+e.pass},createShaderDefinition:function(e,t){var i={vertex_position:ct};t.skin&&(i.vertex_boneWeights=ft,i.vertex_boneIndices=pt),t.vertexColors&&(i.vertex_color=mt),t.diffuseMap&&(i.vertex_texCoord0=gt);var n="";n+=Ti.transformDeclVS,t.skin?(n+=Ci(e),n+=Ti.transformSkinnedVS):n+=Ti.transformVS,t.vertexColors&&(n+="attribute vec4 vertex_color;\n",n+="varying vec4 vColor;\n"),t.diffuseMap&&(n+="attribute vec2 vertex_texCoord0;\n",n+="varying vec2 vUv0;\n"),2===t.pass&&(n+="varying float vDepth;\n",n+="#ifndef VIEWMATRIX\n",n+="#define VIEWMATRIX\n",n+="uniform mat4 matrix_view;\n",n+="#endif\n",n+="#ifndef CAMERAPLANES\n",n+="#define CAMERAPLANES\n",n+="uniform vec4 camera_params;\n\n",n+="#endif\n"),n+="void main(void)\n{\n",n+=" gl_Position = getPosition();\n",2===t.pass&&(n+=" vDepth = -(matrix_view * vec4(getWorldPosition(),1.0)).z * camera_params.x;\n"),t.vertexColors&&(n+=" vColor = vertex_color;\n"),t.diffuseMap&&(n+=" vUv0 = vertex_texCoord0;\n");var s=n+="}\n";return n=Ei(e),t.vertexColors?n+="varying vec4 vColor;\n":n+="uniform vec4 uColor;\n",t.diffuseMap&&(n+="varying vec2 vUv0;\n",n+="uniform sampler2D texture_diffuseMap;\n"),t.fog&&(n+=Ai(t.fog)),t.alphatest&&(n+=Ti.alphaTestPS),2===t.pass&&(n+="varying float vDepth;\n",n+=Ti.packDepthPS),n+="void main(void)\n{\n",t.vertexColors?n+=" gl_FragColor = vColor;\n":n+=" gl_FragColor = uColor;\n",t.diffuseMap&&(n+=" gl_FragColor *= texture2D(texture_diffuseMap, vUv0);\n"),t.alphatest&&(n+=" alphaTest(gl_FragColor.a);\n"),t.pass!==We&&(2===t.pass?n+=" gl_FragColor = packFloat(vDepth);\n":t.fog&&(n+=" glFragColor.rgb = addFog(gl_FragColor.rgb);\n")),{attributes:i,vshader:s,fshader:n+="}\n"}}},Bi={generateKey:function(e){var t="particle";for(var i in e)e.hasOwnProperty(i)&&(t+=e[i]);return t},_animTex:function(e){var t="";return t+=e.animTexLoop?Ti.particleAnimFrameLoopVS:Ti.particleAnimFrameClampVS,t+=Ti.particleAnimTexVS},createShaderDefinition:function(e,t){var i="",n=Ei(e)+"\n";n+="#define PARTICLE\n",e.webgl2&&(i+="#define GL2\n",n+="#define GL2\n"),i+="#define VERTEXSHADER\n",t.mesh&&(i+="#define USE_MESH\n"),t.localSpace&&(i+="#define LOCAL_SPACE\n"),t.screenSpace&&(i+="#define SCREEN_SPACE\n"),t.animTex&&(i+="\nuniform vec2 animTexTilesParams;\n"),t.animTex&&(i+="\nuniform vec4 animTexParams;\n"),t.animTex&&(i+="\nuniform vec2 animTexIndexParams;\n"),2===t.normal&&(i+="\nvarying mat3 ParticleMat;\n"),1===t.normal&&(i+="\nvarying vec3 Normal;\n"),t.soft&&(i+="\nvarying float vDepth;\n");var s=t.customFace?Ti.particle_customFaceVS:Ti.particle_billboardVS;return t.useCpu?(t.soft>0&&(i+=Ti.screenDepthPS),i+=Ti.particle_cpuVS,t.localSpace&&(i+=Ti.particle_localShiftVS),t.animTex&&(i+=this._animTex(t)),t.alignToMotion&&(i+=Ti.particle_pointAlongVS),i+=t.mesh?Ti.particle_meshVS:s,1===t.normal&&(i+=Ti.particle_normalVS),2===t.normal&&(i+=Ti.particle_TBNVS),t.stretch>0&&(i+=Ti.particle_stretchVS),i+=Ti.particle_cpu_endVS,t.soft>0&&(i+=Ti.particle_softVS)):(i+=Ti.particle_initVS,i+=t.pack8?Ti.particleInputRgba8PS:Ti.particleInputFloatPS,t.soft>0&&(i+=Ti.screenDepthPS),i+=Ti.particleVS,t.localSpace&&(i+=Ti.particle_localShiftVS),t.animTex&&(i+=this._animTex(t)),t.wrap&&(i+=Ti.particle_wrapVS),t.alignToMotion&&(i+=Ti.particle_pointAlongVS),i+=t.mesh?Ti.particle_meshVS:s,1===t.normal&&(i+=Ti.particle_normalVS),2===t.normal&&(i+=Ti.particle_TBNVS),t.stretch>0&&(i+=Ti.particle_stretchVS),i+=Ti.particle_endVS,t.soft>0&&(i+=Ti.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(t.gamma),n+=Mi(t.toneMap),"linear"===t.fog?n+=Ti.fogLinearPS:"exp"===t.fog?n+=Ti.fogExpPS:"exp2"===t.fog?n+=Ti.fogExp2PS:n+=Ti.fogNonePS,2===t.normal&&(n+="\nuniform sampler2D normalMap;\n"),t.soft>0&&(n+=Ti.screenDepthPS),n+=Ti.particlePS,t.soft>0&&(n+=Ti.particle_softPS),1===t.normal&&(n+="\nvec3 normal = Normal;\n"),2===t.normal&&(n+=Ti.particle_normalMapPS),t.normal>0&&(n+=t.halflambert?Ti.particle_halflambertPS:Ti.particle_lambertPS),t.normal>0&&(n+=Ti.particle_lightingPS),2===t.blend?n+=Ti.particle_blendNormalPS:1===t.blend?n+=Ti.particle_blendAddPS:5===t.blend&&(n+=Ti.particle_blendMultiplyPS),n+=Ti.particle_endPS,{attributes:ki(i),vshader:i,fshader:n}}},Ni={generateKey:function(e){return"skybox"+e.rgbm+" "+e.hdr+" "+e.fixSeams+e.toneMapping+e.gamma+e.useIntensity+e.useCubeMapRotation+e.useRightHandedCubeMap+e.mip},createShaderDefinition:function(e,t){var i=Ei(e);return i+=t.useCubeMapRotation?"#define CUBEMAP_ROTATION\n":"",i+=t.useRightHandedCubeMap?"#define RIGHT_HANDED_CUBEMAP\n":"",i+=t.mip?Ti.fixCubemapSeamsStretchPS:Ti.fixCubemapSeamsNonePS,i+=t.useIntensity?Ti.envMultiplyPS:Ti.envConstPS,i+=wi(t.gamma),i+=Mi(t.toneMapping),i+=Ti.rgbmPS,i+=Ti.skyboxHDRPS.replace(/\$textureCubeSAMPLE/g,t.rgbm?"textureCubeRGBM":t.hdr?"textureCube":"textureCubeSRGB").replace(/\$FIXCONST/g,1-1/[128,64,32,16,8,4,2][t.mip]+""),{attributes:{aPosition:ct},vshader:Ti.skyboxVS,fshader:i}}},zi=null,Ui=null,Vi=function(){function e(e,t){this.device=e,this.name=null,this._width=4,this._height=4,this._depth=1,this._format=7,this.type=Gt,this.projection=qt,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?Wt:Gt:t.hasOwnProperty("swizzleGGGR")&&(this.type=t.swizzleGGGR?Xt:Gt),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=jt:t.projection&&t.projection!==jt&&(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===et||this._format>=ot,this._invalid=!1,this._lockedLevel=-1,this._levels||(this._levels=this._cubemap?[[null,null,null,null,null,null]]:[null]),this.dirtyAll(),this._gpuSize=0}e.calcGpuSize=function(e,t,i,n,s,r){zi||((zi=[])[0]=1,zi[1]=1,zi[2]=2,zi[3]=2,zi[4]=2,zi[5]=2,zi[6]=4,zi[7]=4,zi[11]=8,zi[12]=8,zi[13]=16,zi[14]=16,zi[15]=4,zi[16]=4,zi[17]=4,zi[18]=4,zi[19]=4,zi[20]=4),Ui||((Ui=[])[21]=8,Ui[22]=8,Ui[24]=8,Ui[25]=8,Ui[26]=8,Ui[27]=8,Ui[8]=8,Ui[29]=8,Ui[23]=16,Ui[9]=16,Ui[10]=16,Ui[28]=16,Ui[30]=16);for(var a=zi.hasOwnProperty(n)?zi[n]:0,o=Ui.hasOwnProperty(n)?Ui[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!==ht&&n!==lt||(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)};var t=e.prototype;return t.destroy=function(){this.device&&this.device.destroyTexture(this),this.device=null,this._levels=this._cubemap?[[null,null,null,null,null,null]]:[null]},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 et:this._levels[e.level]=new Uint8Array(Math.floor((this._width+3)/4)*Math.floor((this._height+3)/4)*16*this._depth);break;case tt:this._levels[e.level]=new Uint16Array(this._width*this._height*this._depth*3);break;case nt:this._levels[e.level]=new Float32Array(this._width*this._height*this._depth*3);break;case it:this._levels[e.level]=new Uint16Array(this._width*this._height*this._depth*4);break;case st:this._levels[e.level]=new Float32Array(this._width*this._height*this._depth*4)}return this._levels[e.level]},t.setSource=function(e,t){var i;void 0===t&&(t=0);var n,s,r=!1;if(this._cubemap){if(e[0])for(n=e[0].width||0,s=e[0].height||0,i=0;i<6;i++){var a=e[i];if(!a||a.width!==n||a.height!==s||!this.device._isBrowserInterface(a)){r=!0;break}}else r=!0;if(!r)for(i=0;i<6;i++)this._levels[t][i]!==e[i]&&(this._levelsUpdated[t][i]=!0)}else this.device._isBrowserInterface(e)||(r=!0),r||(e!==this._levels[t]&&(this._levelsUpdated[t]=!0),n=e.width,s=e.height);if(r)if(this._width=4,this._height=4,this._cubemap)for(i=0;i<6;i++)this._levels[t][i]=null,this._levelsUpdated[t][i]=!0;else this._levels[t]=null,this._levelsUpdated[t]=!0;else 0===t&&(this._width=n,this._height=s),this._levels[t]=e;this._invalid===r&&r||(this._invalid=r,this.upload())},t.getSource=function(e){return void 0===e&&(e=0),this._levels[e]},t.unlock=function(){this.upload(),this._lockedLevel=-1},t.upload=function(){this._needsUpload=!0,this._needsMipmapsUpload=this._mipmaps},t.getDds=function(){for(var e,t,i=128,n=0;this._levels[n];){var s;if(this.cubemap)for(t=0;t<6;t++){if(!this._levels[n][t])return;if(!(s=this._levels[n][t].length))return;i+=s}else{if(!(s=this._levels[n].length))return;i+=s}i+=this._levels[n].length,n++}var r=new ArrayBuffer(i),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;for(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,n=0;n<11;n++)a[8+n]=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 c,u,d=128;if(this.cubemap)for(t=0;t<6;t++)for(n=0;n1){var r=65025*e%1;if(t[i+1]=Math.round(255*(s-ji*r)),n>2){var a=16581375*e%1;t[i+2]=Math.round(255*(r-ji*a)),n>3&&(t[i+3]=Math.round(255*a))}}}var Ki=function(){this.light=null,this.min=new me,this.max=new me},Zi=function(){function e(e,t,i){this.device=e,this.name="Untitled",this.reportCount=0,this._bounds=new Re,this.boundsMin=new me,this.boundsMax=new me,this.boundsDelta=new me,this._cells=new me,this._cellsLimit=new me,this.cells=t,this._maxCellLightCount=0,this._pixelsPerCellCount=0,this.maxCellLightCount=i,this._maxAttenuation=0,this._maxColorValue=0,this._usedLights=[],this._usedLights.push(new Ki),this.registerUniforms(e),this.initLightsTexture()}e.init=function(t){t.extTextureFloat?e.lightTextureFormat=e.FORMAT_FLOAT:e.lightTextureFormat=e.FORMAT_8BIT};var t=e.prototype;return t.destroy=function(){this.lightsTexture8&&(this.lightsTexture8.destroy(),this.lightsTexture8=null),this.lightsTextureFloat&&(this.lightsTextureFloat.destroy(),this.lightsTextureFloat=null),this.releaseClusterTexture()},t.releaseClusterTexture=function(){this.clusterTexture&&(this.clusterTexture.destroy(),this.clusterTexture=null)},t.registerUniforms=function(e){this._clusterWorldTextureId=e.scope.resolve("clusterWorldTexture"),this._clusterPixelsPerCellId=e.scope.resolve("clusterPixelsPerCell"),this._clusterTextureSizeId=e.scope.resolve("clusterTextureSize"),this._clusterTextureSizeData=new Float32Array(3),this._clusterBoundsMinId=e.scope.resolve("clusterBoundsMin"),this._clusterBoundsMinData=new Float32Array(3),this._clusterBoundsDeltaId=e.scope.resolve("clusterBoundsDelta"),this._clusterBoundsDeltaData=new Float32Array(3),this._clusterCellsCountByBoundsSizeId=e.scope.resolve("clusterCellsCountByBoundsSize"),this._clusterCellsCountByBoundsSizeData=new Float32Array(3),this._clusterCellsDotId=e.scope.resolve("clusterCellsDot"),this._clusterCellsDotData=new Float32Array(3),this._clusterCellsMaxId=e.scope.resolve("clusterCellsMax"),this._clusterCellsMaxData=new Float32Array(3),this._clusterCompressionLimit0Id=e.scope.resolve("clusterCompressionLimit0"),this._clusterCompressionLimit0Data=new Float32Array(2)},t.createTexture=function(e,t,i){return new Vi(this.device,{width:e,height:t,mipmaps:!1,format:i,addressU:1,addressV:1,type:Gt,magFilter:0,minFilter:0,anisotropy:1})},t.initLightsTexture=function(){this.maxLights=255;var t=4,i=0;e.lightTextureFormat===e.FORMAT_FLOAT?i=2:t=11,this.lights8=new Uint8ClampedArray(4*t*this.maxLights),this.lightsTexture8=this.createTexture(t,this.maxLights,7),this._lightsTexture8Id=this.device.scope.resolve("lightsTexture8"),i?(this.lightsFloat=new Float32Array(4*i*this.maxLights),this.lightsTextureFloat=this.createTexture(i,this.maxLights,st),this._lightsTextureFloatId=this.device.scope.resolve("lightsTextureFloat")):(this.lightsFloat=null,this.lightsTextureFloat=null,this._lightsTextureFloatId=void 0),this._lightsTextureInvSizeId=this.device.scope.resolve("lightsTextureInvSize"),this._lightsTextureInvSizeData=new Float32Array(4),this._lightsTextureInvSizeData[0]=i?1/this.lightsTextureFloat.width:0,this._lightsTextureInvSizeData[1]=i?1/this.lightsTextureFloat.height:0,this._lightsTextureInvSizeData[2]=1/this.lightsTexture8.width,this._lightsTextureInvSizeData[3]=1/this.lightsTexture8.height},t.getSpotDirection=function(e,t){t._node.getWorldTransform().getY(e).mulScalar(-1),e.normalize()},t.addLightData=function(t,i,n){var s=2===t._type,r=t._node.getPosition(),a=this.lights8,o=i*this.lightsTexture8.width*4;a[o+0]=s?255:0,a[o+1]=255*t._shape,a[o+2]=255*t._falloffMode,o+=4;var h=1/this._maxColorValue,l=n?t._linearFinalColor:t._finalColor;if(Yi(l[0]*h,a,o+0,2),Yi(l[1]*h,a,o+2,2),Yi(l[2]*h,a,o+4,2),o+=8,s&&(Yi(.499999*t._innerConeAngleCos+.5,a,o+0,2),Yi(.499999*t._outerConeAngleCos+.5,a,o+2,2)),o+=4,e.lightTextureFormat===e.FORMAT_FLOAT){var c=this.lightsFloat,u=i*this.lightsTextureFloat.width*4;c[u+0]=r.x,c[u+1]=r.y,c[u+2]=r.z,c[u+3]=t.attenuationEnd,s&&(this.getSpotDirection(Gi,t),c[u+4]=Gi.x,c[u+5]=Gi.y,c[u+6]=Gi.z)}else{var d=Gi.sub2(r,this.boundsMin).div(this.boundsDelta);Yi(d.x,a,o+0,4),Yi(d.y,a,o+4,4),Yi(d.z,a,o+8,4),Yi(t.attenuationEnd/this._maxAttenuation,a,o+12,4),o+=16,s&&(this.getSpotDirection(Gi,t),Yi(.499999*Gi.x+.5,a,o+0,4),Yi(.499999*Gi.y+.5,a,o+4,4),Yi(.499999*Gi.z+.5,a,o+8,4))}},t.updateCells=function(){if(this._cellsDirty){this._cellsDirty=!1;var e=this._cells.x,t=this._cells.y,i=this._cells.z,n=e*t*i,s=this._pixelsPerCellCount*n,r=Math.ceil(Math.sqrt(s));r=he.roundUp(r,this._pixelsPerCellCount);var a=Math.ceil(s/r);this._clusterCellsMaxData[0]=e,this._clusterCellsMaxData[1]=t,this._clusterCellsMaxData[2]=i,this._clusterCellsDotData[0]=this._pixelsPerCellCount,this._clusterCellsDotData[1]=e*i*this._pixelsPerCellCount,this._clusterCellsDotData[2]=e*this._pixelsPerCellCount,this.clusters=new Uint8ClampedArray(4*s),this.counts=new Int32Array(n),this._clusterTextureSizeData[0]=r,this._clusterTextureSizeData[1]=1/r,this._clusterTextureSizeData[2]=1/a,this.releaseClusterTexture(),this.clusterTexture=this.createTexture(r,a,7)}},t.uploadTextures=function(){var e=this.clusterTexture.lock();e.set(this.clusters),this.clusterTexture.unlock(),this.lightsTextureFloat&&((e=this.lightsTextureFloat.lock()).set(this.lightsFloat),this.lightsTextureFloat.unlock()),(e=this.lightsTexture8.lock()).set(this.lights8),this.lightsTexture8.unlock()},t.updateUniforms=function(){this._clusterWorldTextureId.setValue(this.clusterTexture),this._lightsTexture8Id.setValue(this.lightsTexture8),e.lightTextureFormat===e.FORMAT_FLOAT&&this._lightsTextureFloatId.setValue(this.lightsTextureFloat);var t=this.boundsDelta;this._clusterCellsCountByBoundsSizeData[0]=this._cells.x/t.x,this._clusterCellsCountByBoundsSizeData[1]=this._cells.y/t.y,this._clusterCellsCountByBoundsSizeData[2]=this._cells.z/t.z,this._clusterCellsCountByBoundsSizeId.setValue(this._clusterCellsCountByBoundsSizeData),this._clusterBoundsMinData[0]=this.boundsMin.x,this._clusterBoundsMinData[1]=this.boundsMin.y,this._clusterBoundsMinData[2]=this.boundsMin.z,this._clusterBoundsDeltaData[0]=t.x,this._clusterBoundsDeltaData[1]=t.y,this._clusterBoundsDeltaData[2]=t.z,this._clusterCompressionLimit0Data[0]=this._maxAttenuation,this._clusterCompressionLimit0Data[1]=this._maxColorValue,this._clusterPixelsPerCellId.setValue(this._pixelsPerCellCount),this._lightsTextureInvSizeId.setValue(this._lightsTextureInvSizeData),this._clusterTextureSizeId.setValue(this._clusterTextureSizeData),this._clusterBoundsMinId.setValue(this._clusterBoundsMinData),this._clusterBoundsDeltaId.setValue(this._clusterBoundsDeltaData),this._clusterCellsDotId.setValue(this._clusterCellsDotData),this._clusterCellsMaxId.setValue(this._clusterCellsMaxData),this._clusterCompressionLimit0Id.setValue(this._clusterCompressionLimit0Data)},t.evalLightCellMinMax=function(e,t,i){t.copy(e.min),t.sub(this.boundsMin),t.div(this.boundsDelta),t.mul2(t,this.cells),t.floor(),i.copy(e.max),i.sub(this.boundsMin),i.div(this.boundsDelta),i.mul2(i,this.cells),i.ceil(),t.max(me.ZERO),i.min(this._cellsLimit)},t.collectLights=function(e){for(var t=this._usedLights,i=1,n=0;n0){if(!(i1){t.copy(e[1].min),i.copy(e[1].max);for(var n=2;n=0&&!this.directionalLightsSet.has(s)){this.directionalLightsSet.add(s),this.directionalLights.push(s);var a=i.indexOf(s);this.directionalLightsIndices.push(a)}}},e}(),en=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&&this.cameras.sort((function(e,t){return e.priority-t.priority}));var c=[],u=0;for(e=0;e0&&s.layers.indexOf(n.id)>=0&&(c.push(n),m||n.id!==s.disablePostEffectsLayer||(m=!0,p&&(p.triggerPostprocess=!0)),(r=n.cameras.indexOf(s))>=0&&(p=this.addRenderAction(this._renderActions,u,n,i,r,d,m),u++,d=!1));f=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|=i.clearColorBuffer,p|=i.clearDepthBuffer,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},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;t0){if(mn[e]t.length){for(var i=t,n=i.charAt(i.length-1),s=mn[e]-i.length,r=0;r1&&(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"},_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")},_addVaryingIfNeeded:function(e,t,i){return e.indexOf(i)>=0?"varying "+t+" "+i+";\n":""},_getLightSourceShapeString:function(e){switch(e){case 1:return"Rect";case 2:return"Disk";case 3:return"Sphere";default:return""}},_vsAddTransformCode:function(e,t,i,n){return e+=i.transformVS},_vsAddBaseCode:function(e,t,i,n){return e+=i.baseVS,1!==n.nineSlicedMode&&2!==n.nineSlicedMode||(e+=i.baseNineSlicedVS),e},_fsAddBaseCode:function(e,t,i,n){return e+=i.basePS,1===n.nineSlicedMode?e+=i.baseNineSlicedPS:2===n.nineSlicedMode&&(e+=i.baseNineSlicedTiledPS),e},_fsAddStartCode:function(e,t,i,n){return e+=i.startPS,1===n.nineSlicedMode?e+=i.startNineSlicedPS:2===n.nineSlicedMode&&(e+=i.startNineSlicedTiledPS),e},createShaderDefinition:function(e,t){var i,n,s=t.lights.length>0;t.dirLightMap&&(s=!0),an.clusteredLightingEnabled&&(s=!0),0===t.shadingModel?(t.fresnelModel=0,t.specularAntialias=!1,t.prefilteredCubemap=!1,t.dpAtlas=!1,t.ambientSH=!1):t.fresnelModel=0===t.fresnelModel?2:t.fresnelModel;var r=(t.cubeMap||t.prefilteredCubemap&&t.useSpecular)&&!t.sphereMap&&!t.dpAtlas,a=t.sphereMap||r||t.dpAtlas,o=t.useTexCubeLod;t.cubeMap&&(t.sphereMap=null),t.dpAtlas&&(t.prefilteredCubemap=null),t.useSpecular||(t.specularMap=t.glossMap=null);var h=s||a||t.ambientSH||t.prefilteredCubemap||t.heightMap||t.enableGGXSpecular,l=t.pass>=3&&t.pass<=17;this.options=t;var c,u,d,f="",p="",m="",_=Ti,g={vertex_position:ct};if(t.chunks){var v,y={};for(n in _)_.hasOwnProperty(n)&&(t.chunks[n]?((d=t.chunks[n]).indexOf("vertex_normal")>=0&&(g.vertex_normal=ut),d.indexOf("vertex_tangent")>=0&&(g.vertex_tangent=dt),d.indexOf("vertex_texCoord0")>=0&&(g.vertex_texCoord0=gt),d.indexOf("vertex_texCoord1")>=0&&(g.vertex_texCoord1=vt),d.indexOf("vertex_color")>=0&&(g.vertex_color=mt),d.indexOf("vertex_boneWeights")>=0&&(g.vertex_boneWeights=ft),d.indexOf("vertex_boneIndices")>=0&&(g.vertex_boneIndices=pt),y[n]=d):y[n]=_[n]);for(n in t.chunks)(v=this._oldChunkToNew[n])&&(y[v.n]=v.f(t.chunks[n],v.n,n));_=y}f=this._vsAddBaseCode(f,e,_,t),p+=" vPositionW = getWorldPosition();\n",2===t.pass&&(f+="varying float vDepth;\n",f+="#ifndef VIEWMATRIX\n",f+="#define VIEWMATRIX\n",f+="uniform mat4 matrix_view;\n",f+="#endif\n",f+="#ifndef CAMERAPLANES\n",f+="#define CAMERAPLANES\n",f+="uniform vec4 camera_params;\n\n",f+="#endif\n",p+=" vDepth = -(matrix_view * vec4(vPositionW,1.0)).z * camera_params.x;\n"),t.useInstancing&&(g.instance_line1=yt,g.instance_line2=xt,g.instance_line3=bt,g.instance_line4=St,f+=_.instancingVS),h&&(g.vertex_normal=ut,p+=" vNormalW = getNormal();\n",t.sphereMap&&e.fragmentUniformsCount<=16&&(f+=_.viewNormalVS,p+=" vNormalV = getViewNormal();\n"),(t.heightMap||t.normalMap||t.enableGGXSpecular)&&t.hasTangents?(g.vertex_tangent=dt,f+=_.tangentBinormalVS,p+=" vTangentW = getTangent();\n",p+=" vBinormalW = getBinormal();\n"):t.enableGGXSpecular&&(f+=_.tangentBinormalVS,p+=" vObjectSpaceUpW = getObjectSpaceUp();\n"));var x,b,S,T,w=[],M=[];for(n in mn)if(b=n+"Map",t[n+"VertexColor"]&&(t[x=n+"VertexColorChannel"]=this._correctChannel(n,t[x])),t[b]){x=b+"Channel",S=b+"Transform",t[T=b+"Uv"]=Math.min(t[T],1),t[x]=this._correctChannel(n,t[x]);var A=t[T];w[A]=!0,M[A]=M[A]||t[b]&&!t[S]}for(t.forceUv1&&(w[1]=!0,M[1]=void 0===M[1]||M[1]),i=0;i<2;i++)w[i]&&(g["vertex_texCoord"+i]="TEXCOORD"+i,f+=_["uv"+i+"VS"],p+=" vec2 uv"+i+" = getUv"+i+"();\n"),M[i]&&(p+=" vUv"+i+" = uv"+i+";\n");var C=[f,m,p,[]];for(n in mn)t[b=n+"Map"]&&t[S=b+"Transform"]&&(T=b+"Uv",this._setMapTransform(C,n,t[S],t[T]));f=C[0],m=C[1],p=C[2],t.vertexColors&&(g.vertex_color=mt,p+=" vVertexColor = vertex_color;\n"),(t.useMorphPosition||t.useMorphNormal)&&(t.useMorphTextureBased?(f+="#define MORPHING_TEXTURE_BASED\n",t.useMorphPosition&&(f+="#define MORPHING_TEXTURE_BASED_POSITION\n"),t.useMorphNormal&&(f+="#define MORPHING_TEXTURE_BASED_NORMAL\n"),g.morph_vertex_id=Vt,f+="attribute float morph_vertex_id;\n"):(f+="#define MORPHING\n",t.useMorphPosition?(g.morph_pos0=kt,g.morph_pos1=Ot,g.morph_pos2=Ft,g.morph_pos3=Bt,f+="#define MORPHING_POS03\n",f+="attribute vec3 morph_pos0;\n",f+="attribute vec3 morph_pos1;\n",f+="attribute vec3 morph_pos2;\n",f+="attribute vec3 morph_pos3;\n"):t.useMorphNormal&&(g.morph_nrm0=kt,g.morph_nrm1=Ot,g.morph_nrm2=Ft,g.morph_nrm3=Bt,f+="#define MORPHING_NRM03\n",f+="attribute vec3 morph_nrm0;\n",f+="attribute vec3 morph_nrm1;\n",f+="attribute vec3 morph_nrm2;\n",f+="attribute vec3 morph_nrm3;\n"),t.useMorphNormal?(g.morph_nrm4=Nt,g.morph_nrm5=zt,g.morph_nrm6=Ut,g.morph_nrm7=Vt,f+="#define MORPHING_NRM47\n",f+="attribute vec3 morph_nrm4;\n",f+="attribute vec3 morph_nrm5;\n",f+="attribute vec3 morph_nrm6;\n",f+="attribute vec3 morph_nrm7;\n"):(g.morph_pos4=Nt,g.morph_pos5=zt,g.morph_pos6=Ut,g.morph_pos7=Vt,f+="#define MORPHING_POS47\n",f+="attribute vec3 morph_pos4;\n",f+="attribute vec3 morph_pos5;\n",f+="attribute vec3 morph_pos6;\n",f+="attribute vec3 morph_pos7;\n"))),t.skin?(g.vertex_boneWeights=ft,g.vertex_boneIndices=pt,f+=Ci(e,_),f+="#define SKIN\n"):t.useInstancing&&(f+="#define INSTANCING\n"),t.screenSpace&&(f+="#define SCREENSPACE\n"),t.pixelSnap&&(f+="#define PIXELSNAP\n"),f=this._vsAddTransformCode(f,e,_,t),h&&(f+=_.normalVS),f+="\n",f+=_.startVS,f+=p,f+=_.endVS;var E=f+="}",P=m;m="",m+=this._addVaryingIfNeeded(f,"vec4","vVertexColor"),m+=this._addVaryingIfNeeded(f,"vec3","vPositionW"),m+=this._addVaryingIfNeeded(f,"vec3","vNormalV"),m+=this._addVaryingIfNeeded(f,"vec3","vNormalW"),m+=this._addVaryingIfNeeded(f,"vec3","vTangentW"),m+=this._addVaryingIfNeeded(f,"vec3","vBinormalW"),m+=this._addVaryingIfNeeded(f,"vec3","vObjectSpaceUpW"),m+=this._addVaryingIfNeeded(f,"vec2","vUv0"),m+=this._addVaryingIfNeeded(f,"vec2","vUv1"),E=(m+=P)+E;var I="";if(e.webgl2?(I=Pi(e),_.extensionVS&&(I+=_.extensionVS+"\n"),E=I+_.gles3VS+E):(_.extensionVS&&(I=_.extensionVS+"\n"),E=I+E),t.forceFragmentPrecision&&"highp"!==t.forceFragmentPrecision&&"mediump"!==t.forceFragmentPrecision&&"lowp"!==t.forceFragmentPrecision&&(t.forceFragmentPrecision=null),t.forceFragmentPrecision&&("highp"===t.forceFragmentPrecision&&"highp"!==e.maxPrecision&&(t.forceFragmentPrecision="mediump"),"mediump"===t.forceFragmentPrecision&&"lowp"===e.maxPrecision&&(t.forceFragmentPrecision="lowp")),f="",e.webgl2&&(f+=Pi(e)),e.extStandardDerivatives&&!e.webgl2&&(f+="#extension GL_OES_standard_derivatives : enable\n\n"),_.extensionPS&&(f+=_.extensionPS+"\n"),e.webgl2&&(f+=_.gles3PS),f+=t.forceFragmentPrecision?"precision "+t.forceFragmentPrecision+" float;\n\n":Ei(e),t.pass===We)return f+="uniform vec4 uColor;\n",f+=m,t.alphaTest&&(f+="float dAlpha;\n",f+=this._addMap("opacity","opacityPS",t,_),f+=_.alphaTestPS),f+="void main(void)\n{\n",t.alphaTest&&(f+=" getOpacity();\n",f+=" alphaTest(dAlpha);\n"),f+=" gl_FragColor = uColor;\n",{attributes:g,vshader:E,fshader:f+="}\n"};if(2===t.pass)return f+="varying float vDepth;\n",f+=m,f+=_.packDepthPS,t.alphaTest&&(f+="float dAlpha;\n",f+=this._addMap("opacity","opacityPS",t,_),f+=_.alphaTestPS),f+="void main(void)\n{\n",t.alphaTest&&(f+=" getOpacity();\n",f+=" alphaTest(dAlpha);\n"),f+=" gl_FragColor = packFloat(vDepth);\n",{attributes:g,vshader:E,fshader:f+="}\n"};if(l){var R=t.pass-3,L=R-5*(c=Math.floor(R/5));return e.extStandardDerivatives&&!e.webgl2&&(f+="uniform vec2 polygonOffset;\n"),3===L?e.textureFloatHighPrecision?f+="#define VSM_EXPONENT 15.0\n\n":f+="#define VSM_EXPONENT 5.54\n\n":2===L&&(f+="#define VSM_EXPONENT 5.54\n\n"),0!==c&&(f+="uniform vec3 view_position;\n",f+="uniform float light_radius;\n"),f+=m,t.alphaTest&&(f+="float dAlpha;\n",f+=this._addMap("opacity","opacityPS",t,_),f+=_.alphaTestPS),0!==L||e.webgl2&&1!==c?1===L&&(f+="vec2 encodeFloatRG( float v ) {\n",f+=" vec2 enc = vec2(1.0, 255.0) * v;\n",f+=" enc = fract(enc);\n",f+=" enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n",f+=" return enc;\n",f+="}\n\n"):f+=_.packDepthPS,f+="void main(void)\n{\n",t.alphaTest&&(f+=" getOpacity();\n",f+=" alphaTest(dAlpha);\n"),f+=1===c||(1===L||2===L||3===L)&&0!==c?" float depth = min(distance(view_position, vPositionW) / light_radius, 0.99999);\n":" float depth = gl_FragCoord.z;\n",0!==L||e.webgl2&&1!==c?f+=0===L||4===L?" gl_FragColor = vec4(1.0);\n":1===L?" gl_FragColor = vec4(encodeFloatRG(depth), encodeFloatRG(depth*depth));\n":_.storeEVSMPS:e.extStandardDerivatives&&!e.webgl2?(f+=" float minValue = 2.3374370500153186e-10; //(1.0 / 255.0) / (256.0 * 256.0 * 256.0);\n",f+=" depth += polygonOffset.x * max(abs(dFdx(depth)), abs(dFdy(depth))) + minValue * polygonOffset.y;\n",f+=" gl_FragColor = packFloat(depth);\n"):f+=" gl_FragColor = packFloat(depth);\n",{attributes:g,vshader:E,fshader:f+="}\n"}}if(t.customFragmentShader)return{attributes:g,vshader:E,fshader:f+t.customFragmentShader,tag:1};f+=m,f=this._fsAddBaseCode(f,e,_,t),t.detailModes&&(f+=_.detailModesPS);var D=f;f="",t.clearCoat>0&&(f+="#define CLEARCOAT\n"),!1===t.opacityFadesSpecular&&(f+="uniform float material_alphaFade;\n");var k,O=0,F=[],B=!1,N=!1,z=!1,U=t.lights.some((function(e){return e._shape&&0!==e._shape}));7===e.areaLightLutFormat?(f+="#define AREA_R8_G8_B8_A8_LUTS\n",f+="#define AREA_LUTS_PRECISION lowp\n"):f+="#define AREA_LUTS_PRECISION highp\n",U&&(f+="#define AREA_LIGHTS\n",f+="uniform AREA_LUTS_PRECISION sampler2D areaLightsLutTex1;\n",f+="uniform AREA_LUTS_PRECISION sampler2D areaLightsLutTex2;\n");var V,G=0;for(i=0;i0?_.cubeMapProjectBoxPS:_.cubeMapProjectNonePS,f+=t.skyboxIntensity?_.envMultiplyPS:_.envConstPS),t.diffuseDetail&&(f+=this._addMap("diffuseDetail","diffuseDetailMapPS",t,_)),f+=this._addMap("diffuse","diffusePS",t,_),(3!==t.blendType||t.alphaTest||t.alphaToCoverage)&&(f+=this._addMap("opacity","opacityPS",t,_)),f+=this._addMap("emissive","emissivePS",t,_,t.emissiveFormat),s&&t.useSpecular||a){t.specularAntialias&&t.normalMap?t.normalizeNormalMap&&h?f+=_.specularAaToksvigPS:f+=_.specularAaToksvigFastPS:f+=_.specularAaNonePS;var q=t.useMetalness?"metalness":"specular";f+=this._addMap(q,q+"PS",t,_),f+=this._addMap("gloss","glossPS",t,_),2===t.fresnelModel&&(f+=_.fresnelSchlickPS)}if(t.clearCoat>0&&(f+=this._addMap("clearCoat","clearCoatPS",t,_),f+=this._addMap("clearCoatGloss","clearCoatGlossPS",t,_),f+=this._addMap("clearCoatNormal","clearCoatNormalPS",t,_)),t.heightMap){if(!t.normalMap){var j=this._getUvSourceExpression("heightMapTransform","heightMapUv",t);t.hasTangents||(V=V.replace(/\$UV/g,j)),f+=V}f+=this._addMap("height","parallaxPS",t,_)}var Y=t.aoMap||t.aoVertexColor;Y&&(f+=this._addMap("ao","aoPS",t,_),t.occludeSpecular&&(1===t.occludeSpecular?f+=t.occludeSpecularFloat?_.aoSpecOccSimplePS:_.aoSpecOccConstSimplePS:f+=t.occludeSpecularFloat?_.aoSpecOccPS:_.aoSpecOccConstPS));var K=t.rgbmReflection?"decodeRGBM":t.hdrReflection?"":"gammaCorrectInput";if(t.sphereMap){var Z=e.fragmentUniformsCount>16?_.reflectionSpherePS:_.reflectionSphereLowPS;f+=Z=Z.replace(/\$texture2DSAMPLE/g,t.rgbmReflection?"texture2DRGBM":t.hdrReflection?"texture2D":"texture2DSRGB")}else r?t.prefilteredCubemap?f+=o?_.reflectionPrefilteredCubeLodPS.replace(/\$DECODE/g,K):_.reflectionPrefilteredCubePS.replace(/\$DECODE/g,K):f+=_.reflectionCubePS.replace(/\$textureCubeSAMPLE/g,t.rgbmReflection?"textureCubeRGBM":t.hdrReflection?"textureCube":"textureCubeSRGB"):t.dpAtlas&&(f+=_.reflectionDpAtlasPS.replace(/\$texture2DSAMPLE/g,t.rgbmReflection?"texture2DRGBM":t.hdrReflection?"texture2D":"texture2DSRGB"));(r||t.sphereMap||t.dpAtlas)&&(t.clearCoat>0&&(f+=_.reflectionCCPS),t.refraction&&(f+=_.refractionPS)),O>0&&(B&&(f+=_.shadowCascadesPS),F[0]&&(f+=_.shadowStandardPS),F[4]&&(f+=_.shadowStandardGL2PS),N&&(f+=_.shadowVSM_commonPS,F[1]&&(f+=_.shadowVSM8PS),F[2]&&(f+=e.extTextureHalfFloatLinear?_.shadowEVSMPS.replace(/\$/g,"16"):_.shadowEVSMnPS.replace(/\$/g,"16")),F[3]&&(f+=e.extTextureFloatLinear?_.shadowEVSMPS.replace(/\$/g,"32"):_.shadowEVSMnPS.replace(/\$/g,"32"))),e.webgl2||e.extStandardDerivatives||(f+=_.biasConstPS),f+=_.shadowCoordPS+_.shadowCommonPS,z&&(f+=_.shadowCoordPerspZbufferPS)),t.enableGGXSpecular&&(f+="uniform float material_anisotropy;\n"),s&&(f+=_.lightDiffuseLambertPS,U&&(f+=_.ltc));var $=!1;t.useSpecular?(s&&(f+=0===t.shadingModel?_.lightSpecularPhongPS:t.enableGGXSpecular?_.lightSpecularAnisoGGXPS:_.lightSpecularBlinnPS),t.sphereMap||r||t.dpAtlas||t.fresnelModel>0?t.fresnelModel>0?t.conserveEnergy&&!U?f+=_.combineDiffuseSpecularPS:f+=_.combineDiffuseSpecularNoConservePS:f+=_.combineDiffuseSpecularOldPS:t.diffuseMap?f+=_.combineDiffuseSpecularNoReflPS:(f+=_.combineDiffuseSpecularNoReflSeparateAmbientPS,$=!0)):f+=_.combineDiffusePS,t.clearCoat>0&&(f+=_.combineClearCoatPS);var Q=!0;if(t.lightMap||t.lightVertexColor){var J=t.dirLightMap&&t.useSpecular?"lightmapDirPS":"lightmapSinglePS";f+=this._addMap("light",J,t,_,t.lightMapFormat),Q=t.lightMapWithoutAmbient}if(Q){var ee=t.rgbmAmbient?"decodeRGBM":t.hdrAmbient?"":"gammaCorrectInput";t.ambientSH?f+=_.ambientSHPS:t.prefilteredCubemap?f+=o?_.ambientPrefilteredCubeLodPS.replace(/\$DECODE/g,ee):_.ambientPrefilteredCubePS.replace(/\$DECODE/g,ee):f+=_.ambientConstantPS}t.ambientTint&&!$&&(f+="uniform vec3 material_ambient;\n"),t.alphaTest&&(f+=_.alphaTestPS),t.msdf&&(f+=_.msdfPS),h&&(f+=_.viewDirPS,t.useSpecular&&(f+=t.enableGGXSpecular?_.reflDirAnisoPS:_.reflDirPS));var te,ie=!1,ne=!1,se=!1,re=!1,ae=!1;an.clusteredLightingEnabled&&(re=!0,ie=!0,ne=!0,f+="\n#define CLUSTER_TEXTURE_"+(Zi.lightTextureFormat===Zi.FORMAT_FLOAT?"FLOAT":"8BIT")+"\n",f+=_.clusteredLightPS);t.twoSidedLighting&&(f+="uniform float twoSidedLightingNegScaleFactor;\n"),f=this._fsAddStartCode(f,e,_,t),h&&(t.hasTangents||!e.extStandardDerivatives||t.fastTbn?t.twoSidedLighting?f+=" dVertexNormalW = gl_FrontFacing ? vNormalW * twoSidedLightingNegScaleFactor : -vNormalW * twoSidedLightingNegScaleFactor;\n":f+=" dVertexNormalW = vNormalW;\n":t.twoSidedLighting?f+=" dVertexNormalW = normalize(gl_FrontFacing ? vNormalW * twoSidedLightingNegScaleFactor : -vNormalW * twoSidedLightingNegScaleFactor);\n":f+=" dVertexNormalW = normalize(vNormalW);\n",(t.heightMap||t.normalMap)&&t.hasTangents&&(t.twoSidedLighting?(f+=" dTangentW = gl_FrontFacing ? vTangentW * twoSidedLightingNegScaleFactor : -vTangentW * twoSidedLightingNegScaleFactor;\n",f+=" dBinormalW = gl_FrontFacing ? vBinormalW * twoSidedLightingNegScaleFactor : -vBinormalW * twoSidedLightingNegScaleFactor;\n"):(f+=" dTangentW = vTangentW;\n",f+=" dBinormalW = vBinormalW;\n")));var oe=!1;3!==t.blendType||t.alphaTest||t.alphaToCoverage?t.heightMap&&t.opacityMap?oe=!0:(f+=" getOpacity();\n",t.alphaTest&&(f+=" alphaTest(dAlpha);\n")):f+=" dAlpha = 1.0;\n";var he=!1;if(h&&(f+=" getViewDir();\n",(t.heightMap||t.normalMap||t.clearCoatNormalMap||t.enableGGXSpecular)&&(f+=" getTBN();\n"),t.heightMap&&(f+=" getParallax();\n"),oe&&(f+=" getOpacity();\n",t.alphaTest&&(f+=" alphaTest(dAlpha);\n")),f+=" getNormal();\n",t.useSpecular&&(t.enableGGXSpecular&&(f+=" getGlossiness();\n",he=!0),f+=" getReflDir();\n")),f+=" getAlbedo();\n",t.clearCoat>0&&(f+=" getClearCoat();\n",f+=" getClearCoatGlossiness();\n",f+=" getClearCoatNormal();\n"),(s&&t.useSpecular||a)&&(f+=" getSpecularity();\n",he||(f+=" getGlossiness();\n"),U&&(f+=" #ifdef AREA_LIGHTS\n",f+=" dSpecularityNoFres = dSpecularity;\n",f+=" #ifdef CLEARCOAT\n",f+=" ccSpecularityNoFres = ccSpecularity;\n",f+=" #endif\n",f+=" #endif\n"),t.fresnelModel>0&&(f+=" getFresnel();\n")),Q&&(f+=" addAmbient();\n"),t.ambientTint&&!$&&(f+=" dDiffuseLight *= material_ambient;\n"),Y&&!t.occludeDirect&&(f+=" applyAO();\n"),(t.lightMap||t.lightVertexColor)&&(f+=" addLightMap();\n"),s||a){(r||t.sphereMap||t.dpAtlas)&&(t.clearCoat>0&&(f+=" addReflectionCC();\n"),f+=" addReflection();\n"),U&&(f+=" ccReflection.rgb *= ccSpecularity;\n",f+=" dReflection.rgb *= dSpecularity;\n",f+=" dSpecularLight *= dSpecularity;\n",f+=" float roughness = max((1.0 - dGlossiness) * (1.0 - dGlossiness), 0.001);\n");var le="";for(an.clusteredLightingEnabled&&(ne=!0,ie=!0,f+=_.clusteredLightLoopPS),i=0;i 0.00001) {\n",2===c&&(te&&!k._cookieFalloff||(f+=" dAtten *= getSpotEffect(light"+i+"_direction, light"+i+"_innerConeAngle, light"+i+"_outerConeAngle);\n",re=!0))),f+=0!==G?0===c?" dAttenD = getLightDiffuse();\n":" dAttenD = get"+le+"LightDiffuse() * 16.0;\n":" dAtten *= getLightDiffuse();\n",k.castShadows&&!t.noShadow){var ce,ue=null;if(1===k._shadowType?(ue="VSM8",ce="0.0"):2===k._shadowType?(ue="VSM16",ce="5.54"):3===k._shadowType?(ue="VSM32",ce=e.textureFloatHighPrecision?"15.0":"5.54"):ue=4===k._shadowType?"PCF5x5":"PCF3x3",null!==ue)if(1===c)u="(light"+i+"_shadowMap, light"+i+"_shadowParams);\n",k._normalOffsetBias&&(f+=" normalOffsetPointShadow(light"+i+"_shadowParams);\n"),f+=" dAtten *= getShadowPoint"+ue+u;else{var de="light"+i+"_shadowMatrix",fe="light"+i+"_shadowParams";f+=this._nonPointShadowMapProjection(e,t.lights[i],de,fe,i),2===c&&(ue="Spot"+ue),f+=" dAtten *= getShadow"+ue+"(light"+i+"_shadowMap, light"+i+"_shadowParams"+(k._isVsm?", "+ce:"")+");\n"}}0!==G?t.conserveEnergy&&t.useSpecular?f+=" dDiffuseLight += mix((dAttenD * dAtten) * light"+i+"_color"+(te?" * dAtten3":"")+", vec3(0), dLTCSpecFres);\n":f+=" dDiffuseLight += (dAttenD * dAtten) * light"+i+"_color"+(te?" * dAtten3":"")+";\n":U&&t.conserveEnergy&&t.useSpecular?f+=" dDiffuseLight += mix(dAtten * light"+i+"_color"+(te?" * dAtten3":"")+", vec3(0), dSpecularity);\n":f+=" dDiffuseLight += dAtten * light"+i+"_color"+(te?" * dAtten3":"")+";\n",0!==G?(t.clearCoat>0&&(f+=" ccSpecularLight += ccLTCSpecFres * get"+le+"LightSpecularCC() * dAtten * light"+i+"_color"+(te?" * dAtten3":"")+";\n"),t.useSpecular&&(f+=" dSpecularLight += dLTCSpecFres * get"+le+"LightSpecular() * dAtten * light"+i+"_color"+(te?" * dAtten3":"")+";\n")):U?(t.clearCoat>0&&(f+=" ccSpecularLight += ccSpecularity * getLightSpecularCC() * dAtten * light"+i+"_color"+(te?" * dAtten3":"")+";\n"),t.useSpecular&&(f+=" dSpecularLight += dSpecularity * getLightSpecular() * dAtten * light"+i+"_color"+(te?" * dAtten3":"")+";\n")):(t.clearCoat>0&&(f+=" ccSpecularLight += getLightSpecularCC() * dAtten * light"+i+"_color"+(te?" * dAtten3":"")+";\n"),t.useSpecular&&(f+=" dSpecularLight += getLightSpecular() * dAtten * light"+i+"_color"+(te?" * dAtten3":"")+";\n")),0!==c&&(f+=" }\n"),f+="\n"}U&&(t.clearCoat>0&&(f+=" ccSpecularity = 1.0;\n"),t.useSpecular&&(f+=" dSpecularity = vec3(1);\n")),(r||t.sphereMap||t.dpAtlas)&&t.refraction&&(f+=" addRefraction();\n")}f+="\n",Y&&(t.occludeDirect&&(f+=" applyAO();\n"),t.occludeSpecular&&(f+=" occludeSpecular();\n")),!1===t.opacityFadesSpecular&&(2!==t.blendType&&4!==t.blendType||(f+="float specLum = dot((dSpecularLight + dReflection.rgb * dReflection.a) * dSpecularity, vec3( 0.2126, 0.7152, 0.0722 ));\n",f+="#ifdef CLEARCOAT\n specLum += dot(ccSpecularLight * ccSpecularity + ccReflection.rgb * ccReflection.a * ccSpecularity, vec3( 0.2126, 0.7152, 0.0722 ));\n#endif\n",f+="dAlpha = clamp(dAlpha + gammaCorrectInput(specLum), 0.0, 1.0);\n"),f+="dAlpha *= material_alphaFade;\n"),f+=_.endPS,2===t.blendType||6===t.blendType||t.alphaToCoverage?f+=_.outputAlphaPS:4===t.blendType?f+=_.outputAlphaPremulPS:f+=_.outputAlphaOpaquePS,t.msdf&&(f+=" gl_FragColor = applyMsdf(gl_FragColor);\n"),f+="\n",f+="}\n",ie&&(f=_.lightDirPointPS+f),ne&&(f=_.falloffLinearPS+f),se&&(f=_.falloffInvSquaredPS+f),re&&(f=_.spotPS+f),ae&&(f=_.cookiePS+f);var pe="";return f.includes("dReflection")&&(pe+="vec4 dReflection;\n"),f.includes("dTBN")&&(pe+="mat3 dTBN;\n"),f.includes("dAlbedo")&&(pe+="vec3 dAlbedo;\n"),f.includes("dEmission")&&(pe+="vec3 dEmission;\n"),f.includes("dNormalW")&&(pe+="vec3 dNormalW;\n"),f.includes("dVertexNormalW")&&(pe+="vec3 dVertexNormalW;\n"),f.includes("dTangentW")&&(pe+="vec3 dTangentW;\n"),f.includes("dBinormalW")&&(pe+="vec3 dBinormalW;\n"),f.includes("dViewDirW")&&(pe+="vec3 dViewDirW;\n"),f.includes("dReflDirW")&&(pe+="vec3 dReflDirW;\n"),f.includes("dDiffuseLight")&&(pe+="vec3 dDiffuseLight;\n"),f.includes("dSpecularLight")&&(pe+="vec3 dSpecularLight;\n"),f.includes("dLightDirNormW")&&(pe+="vec3 dLightDirNormW;\n"),f.includes("dLightDirW")&&(pe+="vec3 dLightDirW;\n"),f.includes("dLightPosW")&&(pe+="vec3 dLightPosW;\n"),f.includes("dShadowCoord")&&(pe+="vec3 dShadowCoord;\n"),f.includes("dNormalMap")&&(pe+="vec3 dNormalMap;\n"),f.includes("dSpecularity")&&(pe+="vec3 dSpecularity;\n"),f.includes("dSpecularityNoFres")&&(pe+="vec3 dSpecularityNoFres;\n"),f.includes("dUvOffset")&&(pe+="vec2 dUvOffset;\n"),f.includes("dGlossiness")&&(pe+="float dGlossiness;\n"),f.includes("dAlpha")&&(pe+="float dAlpha;\n"),f.includes("dAtten")&&(pe+="float dAtten;\n"),f.includes("dAttenD")&&(pe+="float dAttenD;\n"),f.includes("dAtten3")&&(pe+="vec3 dAtten3;\n"),f.includes("dAo")&&(pe+="float dAo;\n"),f.includes("dMsdf")&&(pe+="vec4 dMsdf;\n"),f.includes("ccReflection")&&(pe+="vec4 ccReflection;\n"),f.includes("ccNormalW")&&(pe+="vec3 ccNormalW;\n"),f.includes("ccReflDirW")&&(pe+="vec3 ccReflDirW;\n"),f.includes("ccSpecularLight")&&(pe+="vec3 ccSpecularLight;\n"),f.includes("ccSpecularity")&&(pe+="float ccSpecularity;\n"),f.includes("ccSpecularityNoFres")&&(pe+="float ccSpecularityNoFres;\n"),f.includes("ccGlossiness")&&(pe+="float ccGlossiness;\n"),{attributes:g,vshader:E,fshader:f=D+pe+f,tag:1}}},gn={begin:Ri,dummyFragmentCode:Ii,end:Li,fogCode:Ai,gammaCode:wi,precisionCode:Ei,skinCode:Ci,tonemapCode:Mi,versionCode:Pi,basic:Fi,particle:Bi,skybox:Ni,standard:_n};function vn(e,t,i,n){var s=t.fixCubemapSeams?Ti.fixCubemapSeamsStretchPS:Ti.fixCubemapSeamsNonePS,r=Oi(e,Ti.fullscreenQuadVS,s+Ti.genParaboloidPS,"genParaboloid"),a=e.scope.resolve("source"),o=e.scope.resolve("params"),h=new Float32Array(4),l=t.width,c=t.format;l=2*Math.max(l,8);var u=new Vi(e,{type:t.type,format:c,width:2*l,height:l,mipmaps:!1});u.name="paraboloid";var d=new Qn({colorBuffer:u,depth:!1});return h[0]=i,h[1]=n?-1:1,a.setValue(t),o.setValue(h),bi(e,d,r),u}function yn(e,t){e.x=.5*he.clamp(t-2,0,1);var i=t-6*e.x,n=1-e.x;return e.y=Math.min(.5*i,.75)*n+e.x,e.z=(1-.5*he.clamp(i,0,1))*n,e.w=.5*e.z,1/e.z}var xn=0,bn=function(){function e(){this.name="Untitled",this.id=xn++,this._shader=null,this.variants={},this.parameters={},this.alphaTest=0,this.alphaToCoverage=!1,this.blend=!1,this.blendSrc=1,this.blendDst=0,this.blendEquation=0,this.separateAlphaBlend=!1,this.blendSrcAlpha=1,this.blendDstAlpha=0,this.blendAlphaEquation=0,this.cull=1,this.depthTest=!0,this.depthWrite=!0,this.stencilFront=null,this.stencilBack=null,this.depthBias=0,this.slopeDepthBias=0,this.redWrite=!0,this.greenWrite=!0,this.blueWrite=!0,this.alphaWrite=!0,this.meshInstances=[],this._shaderVersion=0,this._scene=null,this._dirtyBlend=!1,this.dirty=!0}var t=e.prototype;return t._cloneInternal=function(e){e.name=this.name,e.shader=this.shader,e.alphaTest=this.alphaTest,e.alphaToCoverage=this.alphaToCoverage,e.blend=this.blend,e.blendSrc=this.blendSrc,e.blendDst=this.blendDst,e.blendEquation=this.blendEquation,e.separateAlphaBlend=this.separateAlphaBlend,e.blendSrcAlpha=this.blendSrcAlpha,e.blendDstAlpha=this.blendDstAlpha,e.blendAlphaEquation=this.blendAlphaEquation,e.cull=this.cull,e.depthTest=this.depthTest,e.depthWrite=this.depthWrite,e.depthBias=this.depthBias,e.slopeDepthBias=this.slopeDepthBias,this.stencilFront&&(e.stencilFront=this.stencilFront.clone()),this.stencilBack&&(this.stencilFront===this.stencilBack?e.stencilBack=e.stencilFront:e.stencilBack=this.stencilBack.clone()),e.redWrite=this.redWrite,e.greenWrite=this.greenWrite,e.blueWrite=this.blueWrite,e.alphaWrite=this.alphaWrite},t.clone=function(){var t=new e;return this._cloneInternal(t),t},t._updateMeshInstanceKeys=function(){var e,t=this.meshInstances;for(e=0;e0,e.forceFragmentPrecision=t.forceFragmentPrecision||"",e.chunks=t.chunks||"",e.blendType=t.blendType,e.forceUv1=t.forceUv1,e.screenSpace=i&&0!=(i&ze),e.skin=i&&0!=(2&i),e.useInstancing=i&&0!=(32&i),e.useMorphPosition=i&&0!=(i&Ue),e.useMorphNormal=i&&0!=(i&Ve),e.useMorphTextureBased=i&&0!=(i&Ge),e.nineSlicedMode=t.nineSlicedMode||0},Sn.prototype._updateUVOptions=function(e,t,i,n){var s=!1,r=!1,a=!1;for(var o in i&&(s=0!=(4&i),r=0!=(8&i),a=0!=(16&i)),e.vertexColors=!1,this._mapXForms=[],mn)this._updateTexOptions(e,t,o,s,r,a,n);this._mapXForms=null},Sn.prototype._updateMinOptions=function(e,t){e.opacityTint=1!==t.opacity&&3!==t.blendType,e.lights=[]},Sn.prototype._updateMaterialOptions=function(e,t){var i=1===t.diffuse.r&&1===t.diffuse.g&&1===t.diffuse.b||!t.diffuseTint&&(t.diffuseMap||t.diffuseVertexColor)?0:3,n=!1,s=!!(t.useMetalness||t.specularMap||t.sphereMap||t.cubeMap||t.dpAtlas);(s=(s=(s=s||!!t.useMetalness||!(0===t.specular.r&&0===t.specular.g&&0===t.specular.b))||t.enableGGXSpecular)||t.clearCoat>0)&&(!t.specularTint&&(t.specularMap||t.specularVertexColor)||t.useMetalness||(n=1!==t.specular.r||1!==t.specular.g||1!==t.specular.b));var r=t.emissiveMap?0:3;r||(r=(r=(1!==t.emissive.r||1!==t.emissive.g||1!==t.emissive.b||1!==t.emissiveIntensity)&&t.emissiveTint)?3:1!==t.emissiveIntensity?1:0);var a=!!t.normalMap&&(t.normalMap.format===et||t.normalMap.type===Xt);e.opacityTint=1!==t.opacity&&3!==t.blendType?1:0,e.blendMapsWithColors=!0,e.ambientTint=t.ambientTint,e.diffuseTint=i,e.specularTint=n?3:0,e.metalnessTint=t.useMetalness&&t.metalness<1?1:0,e.glossTint=1,e.emissiveTint=r,e.alphaToCoverage=t.alphaToCoverage,e.normalizeNormalMap=t.normalizeNormalMap,e.sphereMap=!!t.sphereMap,e.cubeMap=!!t.cubeMap,e.dpAtlas=!!t.dpAtlas,e.ambientSH=!!t.ambientSH,e.useSpecular=s,e.emissiveFormat=t.emissiveMap?t.emissiveMap.type===Wt?1:t.emissiveMap.format===st?2:0:null,e.lightMapFormat=t.lightMap?t.lightMap.type===Wt?1:t.lightMap.format===st?2:0:null,e.specularAntialias=t.specularAntialias&&!!t.normalMap&&!!t.normalMap.mipmaps&&!a,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=a,e.fastTbn=t.fastTbn,e.cubeMapProjection=t.cubeMapProjection,e.customFragmentShader=t.customFragmentShader,e.refraction=!!t.refraction,e.useMetalness=t.useMetalness,e.enableGGXSpecular=t.enableGGXSpecular,e.msdf=!!t.msdfMap,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},Sn.prototype._updateEnvOptions=function(e,t,i,n){var s,r=n&&n.type===Wt||t.cubeMap&&t.cubeMap.type===Wt||t.dpAtlas&&t.dpAtlas.type===Wt,a=n&&(n.type===Wt||n.format===st)||t.cubeMap&&(t.cubeMap.type===Wt||t.cubeMap.format===st)||t.dpAtlas&&(t.dpAtlas.type===Wt||t.dpAtlas.format===st),o=n&&!t.cubeMap&&!t.sphereMap&&!t.dpAtlas&&n.type===Wt||t.cubeMap&&t.cubeMap.type===Wt||t.sphereMap&&t.sphereMap.type===Wt||t.dpAtlas&&t.dpAtlas.type===Wt,h=!(!n||t.cubeMap||t.sphereMap||t.dpAtlas)&&(n.type===Wt||n.format===st)||t.cubeMap&&(t.cubeMap.type===Wt||t.cubeMap.format===st)||t.sphereMap&&(t.sphereMap.type===Wt||t.sphereMap.format===st)||t.dpAtlas&&(t.dpAtlas.type===Wt||t.dpAtlas.format===st);t.useSkybox&&i._skyboxPrefiltered&&(s=i._skyboxPrefiltered[0]),e.fog=t.useFog?i.fog:"none",e.gamma=t.useGammaTonemap?i.gammaCorrection:0,e.toneMap=t.useGammaTonemap?i.toneMapping:-1,e.rgbmAmbient=r,e.hdrAmbient=a,e.rgbmReflection=o,e.hdrReflection=h,e.useRgbm=o||r||t.emissiveMap&&t.emissiveMap.type===Wt||t.lightMap&&t.lightMap.type===Wt,e.fixSeams=n?n.fixCubemapSeams:!!t.cubeMap&&t.cubeMap.fixCubemapSeams,e.prefilteredCubemap=!!n,e.skyboxIntensity=n&&s&&n===s&&1!==i.skyboxIntensity,e.useCubeMapRotation=!t.cubeMap&&!t.prefilteredCubeMap128&&t.useSkybox&&i&&i.skyboxRotation&&!i.skyboxRotation.equals(Me.IDENTITY),e.useRightHandedCubeMap=t.cubeMap?t.cubeMap._isRenderTarget:!t.prefilteredCubeMap128&&t.useSkybox&&i&&i._skyboxIsRenderTarget},Sn.prototype._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!=(i&Be)&&(e.lightMapFormat=1,e.lightMap=!0,e.lightMapChannel="rgb",e.lightMapUv=1,e.lightMapTransform=0,e.lightMapWithoutAmbient=!t.lightMap,e.useRgbm=!0,0!=(i&Ne)&&(e.dirLightMap=!0))),t.useLighting){var r=[],a=i?i>>16:1;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)},Sn.prototype._updateTexOptions=function(e,t,i,n,s,r,a){var o=i+"Map",h=i+"VertexColor",l=i+"VertexColorChannel",c=o+"Channel",u=o+"Transform",d=o+"Uv";"light"!==i&&(e[o]=!1,e[c]="",e[u]=0,e[d]=0),e[h]=!1,e[l]="";var f="opacity"===i;if(f&&3===t.blendType&&0===t.alphaTest&&!t.alphaToCoverage)return e;if((!a||f)&&("height"!==i&&t[h]&&r&&(e[h]=t[h],e[l]=t[l],e.vertexColors=!0),t[o])){var p=!0;0!==t[d]||n||(p=!1),1!==t[d]||s||(p=!1),p&&(e[o]=!!t[o],e[u]=this._getMapTransformID(t.getUniform(u),t[d]),e[c]=t[c],e[d]=t[d])}},Sn.prototype._collectLights=function(e,t,i,n,s){var r,a;for(a=0;a0&&(this._setParameter("material_clearCoat",this.clearCoat),this._setParameter("material_clearCoatGlossiness",this.clearCoatGlossiness),this._setParameter("material_clearCoatReflectivity",this.clearCoat),this._setParameter("material_clearCoatBumpiness",this.clearCoatBumpiness)),this._setParameter("material_shininess",n("shininess")),this.emissiveMap&&!this.emissiveTint||this._setParameter("material_emissive",n("emissive")),this.emissiveMap&&this._setParameter("material_emissiveIntensity",this.emissiveIntensity),this.refraction>0&&(this._setParameter("material_refraction",this.refraction),this._setParameter("material_refractionIndex",this.refractionIndex)),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")),mn)this._updateMap(s);this.ambientSH&&this._setParameter("ambientSH[0]",this.ambientSH),this.normalMap&&this._setParameter("material_bumpiness",this.bumpiness),this.normalMap&&this.normalDetailMap&&this._setParameter("material_normalDetailMapBumpiness",this.normalDetailMapBumpiness),this.heightMap&&this._setParameter("material_heightMapFactor",n("heightMapFactor")),this.cubeMap&&this._setParameter("texture_cubeMap",this.cubeMap),this.sphereMap&&this._setParameter("texture_sphereMap",this.sphereMap),this.dpAtlas&&this._setParameter("texture_sphereMap",this.dpAtlas),this._setParameter("material_reflectivity",this.reflectivity),this._processParameters("_activeParams"),this._dirtyShader&&(this.shader=null,this.clearVariants())},i.updateLightingUniforms=function(e,t){var i,n,s,r,a,o;this.useSkybox&&(i=t._skyboxPrefiltered[0],n=t._skyboxPrefiltered[1],s=t._skyboxPrefiltered[2],r=t._skyboxPrefiltered[3],a=t._skyboxPrefiltered[4],o=t._skyboxPrefiltered[5]);var h=this.prefilteredCubeMap128||i,l=this.prefilteredCubeMap64||n,c=this.prefilteredCubeMap32||s,u=this.prefilteredCubeMap16||r,d=this.prefilteredCubeMap8||a,f=this.prefilteredCubeMap4||o;if(h){var p=h&&l&&c&&u&&d&&f,m=!e.extTextureLod&&p,_=m?h.sh||is(e,u):null;if(m&&_){if(!h.dpAtlas){var g=[h,l,c,u,d,f];h.dpAtlas=function(e,t,i){var n,s=new ve,r=new Float32Array(4),a=2*t[0].width*2,o=Oi(e,Ti.fullscreenQuadVS,Ti.dpAtlasQuadPS,"dpAtlasQuad"),h=e.scope.resolve("source"),l=e.scope.resolve("params"),c=new Vi(e,{type:t[0].type,format:t[0].format,width:a,height:a,mipmaps:!1});c.name="paraboloid";for(var u,d=new Qn({colorBuffer:c,depth:!1}),f=(a+2)/a-1,p=0;p<6;p++)n=vn(e,t[p],p,i),h.setValue(n),u=yn(s,p),r[0]=u*f,r[1]=2*r[0],r[0]+=1,r[1]+=1,l.setValue(r),s.x*=a,s.y*=a,s.z*=a,s.w*=a,bi(e,d,o,s);return c}(e,g),h.sh=_}this.dpAtlas=h.dpAtlas,this.ambientSH=h.sh,this._setParameter("ambientSH[0]",this.ambientSH),this._setParameter("texture_sphereMap",this.dpAtlas)}else e.useTexCubeLod?h._levels.length<6?p?this._setParameter("texture_prefilteredCubeMap128",h):console.log("Can't use prefiltered cubemap: "+p+", "+e.useTexCubeLod+", "+h._levels):this._setParameter("texture_prefilteredCubeMap128",h):p?(this._setParameter("texture_prefilteredCubeMap128",h),this._setParameter("texture_prefilteredCubeMap64",l),this._setParameter("texture_prefilteredCubeMap32",c),this._setParameter("texture_prefilteredCubeMap16",u),this._setParameter("texture_prefilteredCubeMap8",d),this._setParameter("texture_prefilteredCubeMap4",f)):console.log("Can't use prefiltered cubemap: "+p+", "+e.useTexCubeLod+", "+h._levels);this.useSkybox&&!t.skyboxRotation.equals(Me.IDENTITY)&&t._skyboxRotationMat3&&this._setParameter("cubeMapRotationMatrix",t._skyboxRotationMat3.data)}this._processParameters("_activeLightingParams")},i.updateShader=function(e,t,i,n,s,r){this.updateLightingUniforms(e,t);var a=this.prefilteredCubeMap128||this.useSkybox&&t._skyboxPrefiltered[0],o=s>1&&s<=We,h=o?_n.optionsContextMin:_n.optionsContext;o?this.shaderOptBuilder.updateMinRef(h,e,t,this,i,n,s,r,a):this.shaderOptBuilder.updateRef(h,e,t,this,i,n,s,r,a),this.onUpdateShader&&(h=this.onUpdateShader(h));var l=e.getProgramLibrary();this.shader=l.getProgram("standard",h),i||(this.clearVariants(),this.variants[0]=this.shader),this._dirtyShader=!1},i.destroy=function(){for(var t in this._assetReferences)this._assetReferences[t]._unbind();this._assetReferences=null,this._validator=null,e.prototype.destroy.call(this)},t}(bn);Rn.TEXTURE_PARAMETERS=An,Rn.CUBEMAP_PARAMETERS=Cn;var Ln=function(e,t){Pn[e]=t},Dn=function(e){var t=e.name,i="_"+t,n=e.defaultValue,s=e.dirtyShaderFunc||null,r=e.getUniformFunc||null,a=n&&n.clone?{equals:function(e,t){return e.equals(t)},clone:function(e){return e.clone()},copy:function(e,t){return e.copy(t)}}:{equals:function(e,t){return e===t},clone:function(e){return e},copy:function(e,t){return t}},o=e.default instanceof ue;Object.defineProperty(Rn.prototype,t,{get:function(){return o&&(this._dirtyShader=!0),this[i]},set:function(e){var t=this[i];a.equals(t,e)||(this._dirtyShader||(this._dirtyShader=!s||s(t,e)),this[i]=a.copy(t,e))}}),En[t]={value:function(){return a.clone(n)}},r&&Ln(t,r)};function kn(e,t,i,n,s,r){mn[e]=i,Dn({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)}}),Dn({name:e+"MapTiling",defaultValue:new ge(1,1)}),Dn({name:e+"MapOffset",defaultValue:new ge(0,0)}),Dn({name:e+"MapRotation",defaultValue:0}),Dn({name:e+"MapUv",defaultValue:t}),i>0&&Dn({name:e+"MapChannel",defaultValue:n||(i>1?"rgb":"g")}),s&&(Dn({name:e+"VertexColor",defaultValue:!1}),i>0&&Dn({name:e+"VertexColorChannel",defaultValue:n||(i>1?"rgb":"g")})),r&&Dn({name:e+"Mode",defaultValue:"mul"});var a=e+"MapTiling",o=e+"MapOffset",h=e+"MapRotation",l=e+"MapTransform";Ln(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*he.DEG_TO_RAD),d=Math.sin(r*he.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 On(e,t,i){var n=e+"Intensity";Dn({name:e,defaultValue:t,getUniformFunc:function(t,s,r){var a=t._allocUniform(e,(function(){return new Float32Array(3)})),o=t[e],h=i?t[n]:1;return t.useGammaTonemap&&r.gammaCorrection?(a[0]=Math.pow(o.r,2.2)*h,a[1]=Math.pow(o.g,2.2)*h,a[2]=Math.pow(o.b,2.2)*h):(a[0]=o.r*h,a[1]=o.g*h,a[2]=o.b*h),a}}),i&&Dn({name:n,defaultValue:1})}function Fn(e,t,i){Dn({name:""+e,defaultValue:t,dirtyShaderFunc:function(e,t){return(0===e||1===e)!=(0===t||1===t)},getUniformFunc:i})}function Bn(e,t){Dn({name:e,defaultValue:null,dirtyShaderFunc:function(e,t){return!!e==!!t},getUniformFunc:t})}function Nn(e,t){Object.defineProperty(Rn.prototype,t,{get:function(){return this[e]},set:function(t){this[e]=t}})}function zn(e,t){Dn({name:e,defaultValue:t})}On("ambient",new ue(.7,.7,.7)),On("diffuse",new ue(1,1,1)),On("specular",new ue(0,0,0)),On("emissive",new ue(0,0,0),!0),Fn("shininess",25,(function(e,t,i){return 0===e.shadingModel?Math.pow(2,.01*e.shininess*11):.01*e.shininess})),Fn("heightMapFactor",1,(function(e,t,i){return.025*e.heightMapFactor})),Fn("opacity",1),Fn("alphaFade",1),Fn("alphaTest",0),Fn("bumpiness",1),Fn("normalDetailMapBumpiness",1),Fn("reflectivity",1),Fn("occludeSpecularIntensity",1),Fn("refraction",0),Fn("refractionIndex",1/1.5),Fn("metalness",1),Fn("anisotropy",0),Fn("clearCoat",0),Fn("clearCoatGlossiness",1),Fn("clearCoatBumpiness",1),Fn("aoUvSet",0,null),Bn("ambientSH"),Bn("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})),Object.defineProperty(Rn.prototype,"chunks",{get:function(){return this._dirtyShader=!0,this._chunks},set:function(e){this._dirtyShader=!0,this._chunks=e}}),zn("ambientTint",!1),zn("diffuseTint",!1),zn("specularTint",!1),zn("emissiveTint",!1),zn("fastTbn",!1),zn("specularAntialias",!1),zn("useMetalness",!1),zn("enableGGXSpecular",!1),zn("occludeDirect",!1),zn("normalizeNormalMap",!0),zn("conserveEnergy",!0),zn("opacityFadesSpecular",!0),zn("occludeSpecular",1),zn("shadingModel",1),zn("fresnelModel",2),zn("cubeMapProjection",0),zn("customFragmentShader",null),zn("forceFragmentPrecision",null),zn("useFog",!0),zn("useLighting",!0),zn("useGammaTonemap",!0),zn("useSkybox",!0),zn("forceUv1",!1),zn("pixelSnap",!1),zn("twoSidedLighting",!1),zn("nineSlicedMode",void 0),kn("diffuse",0,3,"",!0),kn("specular",0,3,"",!0),kn("emissive",0,3,"",!0),kn("normal",0,-1,"",!1),kn("metalness",0,1,"",!0),kn("gloss",0,1,"",!0),kn("opacity",0,1,"a",!0),kn("height",0,1,"",!1),kn("ao",0,1,"",!0),kn("light",1,3,"",!0),kn("msdf",0,3,"",!1),kn("diffuseDetail",0,3,"",!1,!0),kn("normalDetail",0,-1,"",!1),kn("clearCoat",0,1,"",!0),kn("clearCoatGloss",0,1,"",!0),kn("clearCoatNormal",0,-1,"",!1),Bn("cubeMap"),Bn("sphereMap"),Bn("dpAtlas"),Bn("prefilteredCubeMap128"),Bn("prefilteredCubeMap64"),Bn("prefilteredCubeMap32"),Bn("prefilteredCubeMap16"),Bn("prefilteredCubeMap8"),Bn("prefilteredCubeMap4"),Nn("diffuseTint","diffuseMapTint"),Nn("specularTint","specularMapTint"),Nn("emissiveTint","emissiveMapTint"),Nn("aoVertexColor","aoMapVertexColor"),Nn("diffuseVertexColor","diffuseMapVertexColor"),Nn("specularVertexColor","specularMapVertexColor"),Nn("emissiveVertexColor","emissiveMapVertexColor"),Nn("metalnessVertexColor","metalnessMapVertexColor"),Nn("glossVertexColor","glossMapVertexColor"),Nn("opacityVertexColor","opacityMapVertexColor"),Nn("lightVertexColor","lightMapVertexColor");var Un=function(){function e(e){this._device=e,this._cache={},this._generators={},this._isClearingCache=!1,this._precached=!1,this._programsCollection=[],this._defaultStdMatOption={},this._defaultStdMatOptionMin={};var t=new Rn;t.shaderOptBuilder.updateRef(this._defaultStdMatOption,e,{},t,null,[],0,null,null),t.shaderOptBuilder.updateMinRef(this._defaultStdMatOptionMin,e,{},t,null,[],3,null,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.getProgram=function(e,t){var i=this._generators[e];if(void 0===i)return null;var n=this._device,s=i.generateKey(t),r=this._cache[s];if(!r){var a;t.lights&&(a=t.lights,t.lights=a.map((function(e){var t=e.clone?e.clone():e;return t.key=e.key,t}))),this.storeNewProgram(e,t),t.lights&&(t.lights=a),this._precached&&console.warn("ProgramLibrary#getProgram: Cache miss for shader",e,"key",s,"after shaders precaching");var o=i.createShaderDefinition(n,t);r=this._cache[s]=new Si(n,o)}return r},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&&e<=We?this._defaultStdMatOptionMin:this._defaultStdMatOption},t.precompile=function(e){if(e)for(var t=new Array(e.length),i=0;it||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}function Kn(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 Zn=function(e){function t(t,i){var n;(n=e.call(this)||this).canvas=t,n._enableAutoInstancing=!1,n.autoInstancingMaxObjects=16384,n.defaultFramebuffer=null,n._maxPixelRatio=1,n._width=0,n._height=0,n.updateClientRect(),n.shaders=[],n.buffers=[],n.textures=[],n.targets=[],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")};var r=!i||void 0===i.preferWebGl2||i.preferWebGl2?["webgl2","webgl","experimental-webgl"]:["webgl","experimental-webgl"],a=null;(i=i||{}).stencil=!0;for(var o=0;o0,n.useTexCubeLod=n.extTextureLod&&n.maxTextures<16;var _=n.vertexUniformsCount;_-=16,_-=8,_-=1,_-=16,n.boneLimit=Math.floor(_/3),n.boneLimit=Math.min(n.boneLimit,128),"Mali-450 MP"===n.unmaskedRenderer&&(n.boneLimit=34),n._drawCallsPerFrame=0,n._shaderSwitchesPerFrame=0,n._primsPerFrame=[];for(var g=0;g<=6;g++)n._primsPerFrame[g]=0;return n._renderTargetCreationTime=0,n._vram={tex:0,vb:0,ib:0},n._shaderStats={vsCompiled:0,fsCompiled:0,linked:0,materialShaders:0,compileTime:0},n.constantTexSource=n.scope.resolve("source"),n.extTextureFloat?n.webgl2?n.textureFloatRenderable=!!n.extColorBufferFloat:n.textureFloatRenderable=Kn(a,a.FLOAT):n.textureFloatRenderable=!1,n.extColorBufferHalfFloat?n.textureHalfFloatRenderable=!!n.extColorBufferHalfFloat:n.extTextureHalfFloat?n.webgl2?n.textureHalfFloatRenderable=!!n.extColorBufferFloat:n.textureHalfFloatRenderable=Kn(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.grabPassAvailable=!0,n.grabPassAlpha=i.alpha,n.createGrabPass(),si.init(Q(n)),n.areaLightLutFormat=7,n.extTextureHalfFloat&&n.textureHalfFloatUpdatable&&n.extTextureHalfFloatLinear?n.areaLightLutFormat=it:n.extTextureFloat&&n.extTextureFloatLinear&&(n.areaLightLutFormat=st),n}Z(t,e);var i=t.prototype;return i.destroy=function(){var e=this.gl;this.destroyGrabPass(),this.webgl2&&this.feedback&&e.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.scope=null,this.canvas=null,this.gl=null},i.toJSON=function(e){},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,t=this.gl,i={};t.getSupportedExtensions().forEach((function(e){i[e]=!0}));var n=function(){for(var e=0;e0;){var i=this.textures[0];this.destroyTexture(i),i.dirtyAll()}for(var n,s=ee(this.buffers);!(n=s()).done;){n.value.loseContext()}for(var r,a=ee(this.targets);!(r=a()).done;){r.value.loseContext()}},i.restoreContext=function(){this.initializeExtensions(),this.initializeCapabilities(),this.initializeRenderState(),this.initializeContextCaches();for(var e,t=ee(this.shaders);!(e=t()).done;){var i=e.value;this.compileAndLinkShader(i)}for(var n,s=ee(this.buffers);!(n=s()).done;){n.value.unlock()}this.createGrabPass()},i.createGrabPass=function(){if(!this.grabPassTexture){var e=new Vi(this,{format:!1===this.grabPassAlpha?6:7,minFilter:1,magFilter:1,addressU:1,addressV:1,mipmaps:!1});e.name="texture_grabPass";var t=this.scope.resolve(e.name);t.setValue(e);var i=new Qn({colorBuffer:e,depth:!1});this.grabPassRenderTarget=i,this.grabPassTextureId=t,this.grabPassTexture=e}},i.updateGrabPass=function(){var e=this.gl;if(!this.grabPassAvailable)return!1;var t=this.renderTarget,i=t&&t._glResolveFrameBuffer,n=this.grabPassTexture,s=this.width,r=this.height;if(this.webgl2&&!this._tempMacChromeBlitFramebufferWorkaround&&s===n._width&&r===n._height){i&&t.resolve(!0);var a=t?t._glFrameBuffer:null,o=t?t._glResolveFrameBuffer||t._glFrameBuffer:null;this.initRenderTarget(this.grabPassRenderTarget);var h=this.grabPassRenderTarget._glFrameBuffer;e.bindFramebuffer(e.READ_FRAMEBUFFER,o),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,h),e.blitFramebuffer(0,0,s,r,0,0,s,r,e.COLOR_BUFFER_BIT,e.NEAREST),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,a)}else{i&&(t.resolve(!0),e.bindFramebuffer(e.FRAMEBUFFER,t._glResolveFrameBuffer));var l=n._glFormat;e.copyTexImage2D(e.TEXTURE_2D,0,l,0,0,s,r,0),n._width=s,n._height=r,i&&e.bindFramebuffer(e.FRAMEBUFFER,t._glFrameBuffer)}return!0},i.destroyGrabPass=function(){this.grabPassRenderTarget.destroy(),this.grabPassRenderTarget=null,this.grabPassTextureId=null,this.grabPassTexture.destroy(),this.grabPassTexture=null},i.updateClientRect=function(){this.clientRect=this.canvas.getBoundingClientRect()},i.setViewport=function(e,t,i,n){this.vx===e&&this.vy===t&&this.vw===i&&this.vh===n||(this.gl.viewport(e,t,i,n),this.vx=e,this.vy=t,this.vw=i,this.vh=n)},i.setScissor=function(e,t,i,n){this.sx===e&&this.sy===t&&this.sw===i&&this.sh===n||(this.gl.scissor(e,t,i,n),this.sx=e,this.sy=t,this.sw=i,this.sh=n)},i.getProgramLibrary=function(){return this.programLib},i.setProgramLibrary=function(e){this.programLib=e},i.setFramebuffer=function(e){this.activeFramebuffer!==e&&(this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,e),this.activeFramebuffer=e)},i._checkFbo=function(){var e=this.gl;switch(e.checkFramebufferStatus(e.FRAMEBUFFER)){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:console.error("ERROR: FRAMEBUFFER_INCOMPLETE_ATTACHMENT");break;case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:console.error("ERROR: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT");break;case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:console.error("ERROR: FRAMEBUFFER_INCOMPLETE_DIMENSIONS");break;case e.FRAMEBUFFER_UNSUPPORTED:console.error("ERROR: FRAMEBUFFER_UNSUPPORTED");break;case e.FRAMEBUFFER_COMPLETE:}},i.copyRenderTarget=function(e,t,i,n){var s=this.gl;if(!this.webgl2&&n)return!1;if(i)if(t){if(!e._colorBuffer||!t._colorBuffer)return!1;if(e._colorBuffer._format!==t._colorBuffer._format)return!1}else if(!e._colorBuffer)return!1;if(n){if(!e._depthBuffer||!t._depthBuffer)return!1;if(e._depthBuffer._format!==t._depthBuffer._format)return!1}if(this.webgl2&&t){var r=this.renderTarget;this.renderTarget=t,this.updateBegin(),s.bindFramebuffer(s.READ_FRAMEBUFFER,e?e._glFrameBuffer:null),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,t._glFrameBuffer);var a=e?e.width:t.width,o=e?e.height:t.height;s.blitFramebuffer(0,0,a,o,0,0,a,o,(i?s.COLOR_BUFFER_BIT:0)|(n?s.DEPTH_BUFFER_BIT:0),s.NEAREST),this.renderTarget=r,s.bindFramebuffer(s.FRAMEBUFFER,r?r._glFrameBuffer:null)}else{var h=this.getCopyShader();this.constantTexSource.setValue(e._colorBuffer),bi(this,t,h)}return!0},i.initRenderTarget=function(e){if(!e._glFrameBuffer){e._device=this;var t=this.gl;e._glFrameBuffer=t.createFramebuffer(),this.setFramebuffer(e._glFrameBuffer);var i=e._colorBuffer;i&&(i._glTexture||(i._width=Math.min(i.width,this.maxRenderBufferSize),i._height=Math.min(i.height,this.maxRenderBufferSize),this.setTexture(i,0)),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,i._cubemap?t.TEXTURE_CUBE_MAP_POSITIVE_X+e._face:t.TEXTURE_2D,i._glTexture,0));var n=e._depthBuffer;if(n&&this.webgl2)n._glTexture||(n._width=Math.min(n.width,this.maxRenderBufferSize),n._height=Math.min(n.height,this.maxRenderBufferSize),this.setTexture(n,0)),e._stencil?t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,n._cubemap?t.TEXTURE_CUBE_MAP_POSITIVE_X+e._face:t.TEXTURE_2D,e._depthBuffer._glTexture,0):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,n._cubemap?t.TEXTURE_CUBE_MAP_POSITIVE_X+e._face:t.TEXTURE_2D,e._depthBuffer._glTexture,0);else if(e._depth){e._samples>1&&this.webgl2||(e._glDepthBuffer||(e._glDepthBuffer=t.createRenderbuffer()),t.bindRenderbuffer(t.RENDERBUFFER,e._glDepthBuffer),e._stencil?(t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,e._glDepthBuffer)):(t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_COMPONENT16,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,e._glDepthBuffer)),t.bindRenderbuffer(t.RENDERBUFFER,null))}this.webgl2&&e._samples>1&&(e._glResolveFrameBuffer=e._glFrameBuffer,e._glFrameBuffer=t.createFramebuffer(),this.setFramebuffer(e._glFrameBuffer),i&&(e._glMsaaColorBuffer||(e._glMsaaColorBuffer=t.createRenderbuffer()),t.bindRenderbuffer(t.RENDERBUFFER,e._glMsaaColorBuffer),t.renderbufferStorageMultisample(t.RENDERBUFFER,e._samples,i._glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,e._glMsaaColorBuffer)),e._depth&&(e._glMsaaDepthBuffer||(e._glMsaaDepthBuffer=t.createRenderbuffer()),t.bindRenderbuffer(t.RENDERBUFFER,e._glMsaaDepthBuffer),e._stencil?(t.renderbufferStorageMultisample(t.RENDERBUFFER,e._samples,t.DEPTH24_STENCIL8,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,e._glMsaaDepthBuffer)):(t.renderbufferStorageMultisample(t.RENDERBUFFER,e._samples,t.DEPTH_COMPONENT32F,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,e._glMsaaDepthBuffer)))),this.targets.push(e)}},i.getCopyShader=function(){return this._copyShader||(this._copyShader=Oi(this,Ti.fullscreenQuadVS,Ti.outputTex2DPS,"outputTex2D")),this._copyShader},i.updateBegin=function(){if(this.boundVao=null,this._tempEnableSafariTextureUnitWorkaround)for(var e=0;e1&&t.autoResolve&&t.resolve()}},i.initializeTexture=function(e){var t,i=this.gl;switch(e._glTexture=i.createTexture(),e._glTarget=e._cubemap?i.TEXTURE_CUBE_MAP:e._volume?i.TEXTURE_3D:i.TEXTURE_2D,e._format){case 0:e._glFormat=i.ALPHA,e._glInternalFormat=i.ALPHA,e._glPixelType=i.UNSIGNED_BYTE;break;case 1:e._glFormat=i.LUMINANCE,e._glInternalFormat=i.LUMINANCE,e._glPixelType=i.UNSIGNED_BYTE;break;case 2:e._glFormat=i.LUMINANCE_ALPHA,e._glInternalFormat=i.LUMINANCE_ALPHA,e._glPixelType=i.UNSIGNED_BYTE;break;case 3:e._glFormat=i.RGB,e._glInternalFormat=i.RGB,e._glPixelType=i.UNSIGNED_SHORT_5_6_5;break;case 4:e._glFormat=i.RGBA,e._glInternalFormat=i.RGBA,e._glPixelType=i.UNSIGNED_SHORT_5_5_5_1;break;case 5:e._glFormat=i.RGBA,e._glInternalFormat=i.RGBA,e._glPixelType=i.UNSIGNED_SHORT_4_4_4_4;break;case 6:e._glFormat=i.RGB,e._glInternalFormat=this.webgl2?i.RGB8:i.RGB,e._glPixelType=i.UNSIGNED_BYTE;break;case 7:e._glFormat=i.RGBA,e._glInternalFormat=this.webgl2?i.RGBA8:i.RGBA,e._glPixelType=i.UNSIGNED_BYTE;break;case 8:t=this.extCompressedTextureS3TC,e._glFormat=i.RGB,e._glInternalFormat=t.COMPRESSED_RGB_S3TC_DXT1_EXT;break;case 9:t=this.extCompressedTextureS3TC,e._glFormat=i.RGBA,e._glInternalFormat=t.COMPRESSED_RGBA_S3TC_DXT3_EXT;break;case et:t=this.extCompressedTextureS3TC,e._glFormat=i.RGBA,e._glInternalFormat=t.COMPRESSED_RGBA_S3TC_DXT5_EXT;break;case ot:t=this.extCompressedTextureETC1,e._glFormat=i.RGB,e._glInternalFormat=t.COMPRESSED_RGB_ETC1_WEBGL;break;case ht:t=this.extCompressedTexturePVRTC,e._glFormat=i.RGB,e._glInternalFormat=t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;break;case lt:t=this.extCompressedTexturePVRTC,e._glFormat=i.RGBA,e._glInternalFormat=t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;break;case 26:t=this.extCompressedTexturePVRTC,e._glFormat=i.RGB,e._glInternalFormat=t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;break;case 27:t=this.extCompressedTexturePVRTC,e._glFormat=i.RGBA,e._glInternalFormat=t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;break;case 22:t=this.extCompressedTextureETC,e._glFormat=i.RGB,e._glInternalFormat=t.COMPRESSED_RGB8_ETC2;break;case 23:t=this.extCompressedTextureETC,e._glFormat=i.RGBA,e._glInternalFormat=t.COMPRESSED_RGBA8_ETC2_EAC;break;case 28:t=this.extCompressedTextureASTC,e._glFormat=i.RGBA,e._glInternalFormat=t.COMPRESSED_RGBA_ASTC_4x4_KHR;break;case 29:t=this.extCompressedTextureATC,e._glFormat=i.RGB,e._glInternalFormat=t.COMPRESSED_RGB_ATC_WEBGL;break;case 30:t=this.extCompressedTextureATC,e._glFormat=i.RGBA,e._glInternalFormat=t.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL;break;case tt:t=this.extTextureHalfFloat,e._glFormat=i.RGB,this.webgl2?(e._glInternalFormat=i.RGB16F,e._glPixelType=i.HALF_FLOAT):(e._glInternalFormat=i.RGB,e._glPixelType=t.HALF_FLOAT_OES);break;case it:t=this.extTextureHalfFloat,e._glFormat=i.RGBA,this.webgl2?(e._glInternalFormat=i.RGBA16F,e._glPixelType=i.HALF_FLOAT):(e._glInternalFormat=i.RGBA,e._glPixelType=t.HALF_FLOAT_OES);break;case nt:e._glFormat=i.RGB,this.webgl2?e._glInternalFormat=i.RGB32F:e._glInternalFormat=i.RGB,e._glPixelType=i.FLOAT;break;case st:e._glFormat=i.RGBA,this.webgl2?e._glInternalFormat=i.RGBA32F:e._glInternalFormat=i.RGBA,e._glPixelType=i.FLOAT;break;case 15:e._glFormat=i.RED,e._glInternalFormat=i.R32F,e._glPixelType=i.FLOAT;break;case rt:this.webgl2?(e._glFormat=i.DEPTH_COMPONENT,e._glInternalFormat=i.DEPTH_COMPONENT32F,e._glPixelType=i.FLOAT):(e._glFormat=i.DEPTH_COMPONENT,e._glInternalFormat=i.DEPTH_COMPONENT,e._glPixelType=i.UNSIGNED_SHORT);break;case at:e._glFormat=i.DEPTH_STENCIL,e._glInternalFormat=i.DEPTH24_STENCIL8,e._glPixelType=i.UNSIGNED_INT_24_8;break;case 18:e._glFormat=i.RGB,e._glInternalFormat=i.R11F_G11F_B10F,e._glPixelType=i.UNSIGNED_INT_10F_11F_11F_REV;break;case 19:e._glFormat=i.RGB,e._glInternalFormat=i.SRGB8,e._glPixelType=i.UNSIGNED_BYTE;break;case 20:e._glFormat=i.RGBA,e._glInternalFormat=i.SRGB8_ALPHA8,e._glPixelType=i.UNSIGNED_BYTE}this.textures.push(e)},i.destroyTexture=function(e){if(e._glTexture){var t=this.textures.indexOf(e);-1!==t&&this.textures.splice(t,1),this.scope.removeValue(e);for(var i=0;ithis.maxCubeMapSize||o.height>this.maxCubeMapSize)&&(o=Yn(o,this.maxCubeMapSize),0===s&&(e._width=o.width,e._height=o.height)),this.setUnpackFlipY(!1),this.setUnpackPremultiplyAlpha(e._premultiplyAlpha),t.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+a,s,e._glInternalFormat,e._glFormat,e._glPixelType,o)}}else for(n=1/Math.pow(2,s),a=0;a<6;a++)if(e._levelsUpdated[0][a]){var h=i[a];e._compressed?t.compressedTexImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+a,s,e._glInternalFormat,Math.max(e._width*n,1),Math.max(e._height*n,1),0,h):(this.setUnpackFlipY(!1),this.setUnpackPremultiplyAlpha(e._premultiplyAlpha),t.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+a,s,e._glInternalFormat,Math.max(e._width*n,1),Math.max(e._height*n,1),0,e._glFormat,e._glPixelType,h))}}else e._volume?(n=1/Math.pow(2,s),e._compressed?t.compressedTexImage3D(t.TEXTURE_3D,s,e._glInternalFormat,Math.max(e._width*n,1),Math.max(e._height*n,1),Math.max(e._depth*n,1),0,i):(this.setUnpackFlipY(!1),this.setUnpackPremultiplyAlpha(e._premultiplyAlpha),t.texImage3D(t.TEXTURE_3D,s,e._glInternalFormat,Math.max(e._width*n,1),Math.max(e._height*n,1),Math.max(e._depth*n,1),0,e._glFormat,e._glPixelType,i))):(this._isBrowserInterface(i)?(i instanceof HTMLImageElement&&(i.width>this.maxTextureSize||i.height>this.maxTextureSize)&&(i=Yn(i,this.maxTextureSize),0===s&&(e._width=i.width,e._height=i.height)),this.setUnpackFlipY(e._flipY),this.setUnpackPremultiplyAlpha(e._premultiplyAlpha),t.texImage2D(t.TEXTURE_2D,s,e._glInternalFormat,e._glFormat,e._glPixelType,i)):(n=1/Math.pow(2,s),e._compressed?t.compressedTexImage2D(t.TEXTURE_2D,s,e._glInternalFormat,Math.max(e._width*n,1),Math.max(e._height*n,1),0,i):(this.setUnpackFlipY(!1),this.setUnpackPremultiplyAlpha(e._premultiplyAlpha),t.texImage2D(t.TEXTURE_2D,s,e._glInternalFormat,Math.max(e._width*n,1),Math.max(e._height*n,1),0,e._glFormat,e._glPixelType,i))),e._mipmapsUploaded=0!==s);s++}else s++;if(e._needsUpload)if(e._cubemap)for(var l=0;l<6;l++)e._levelsUpdated[0][l]=!1;else e._levelsUpdated[0]=!1;!e._compressed&&e._mipmaps&&e._needsMipmapsUpload&&(e.pot||this.webgl2)&&1===e._levels.length&&(t.generateMipmap(e._glTarget),e._mipmapsUploaded=!0),e._gpuSize&&(this._vram.tex-=e._gpuSize),e._gpuSize=e.gpuSize,this._vram.tex+=e._gpuSize}},i.activeTexture=function(e){this.textureUnit!==e&&(this.gl.activeTexture(this.gl.TEXTURE0+e),this.textureUnit=e)},i.bindTexture=function(e){var t=e._glTarget,i=e._glTexture,n=this.textureUnit,s=this.targetToSlot[t];this.textureUnits[n][s]!==i&&(this.gl.bindTexture(t,i),this.textureUnits[n][s]=i)},i.bindTextureOnUnit=function(e,t){var i=e._glTarget,n=e._glTexture,s=this.targetToSlot[i];this.textureUnits[t][s]!==n&&(this.activeTexture(t),this.gl.bindTexture(i,n),this.textureUnits[t][s]=n)},i.setTextureParameters=function(e){var t=this.gl,i=e._parameterFlags,n=e._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._glTexture||this.initializeTexture(e),e._parameterFlags>0||e._needsUpload||e._needsMipmapsUpload||e===this.grabPassTexture)?(this.activeTexture(t),this.bindTexture(e),e._parameterFlags&&(this.setTextureParameters(e),e._parameterFlags=0),e===this.grabPassTexture&&this.updateGrabPass()||!e._needsUpload&&!e._needsMipmapsUpload||(this.uploadTexture(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,w,M,t):u.drawElements(b,S,w,M)}else{var A=e.base;t>0?u.drawArraysInstanced(b,A,S,t):u.drawArrays(b,A,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=null==(e=e||t).flags?t.flags:e.flags;if(0!==i){var n=this.gl;if(1&i){var s=null==e.color?t.color:e.color;this.setClearColor(s[0],s[1],s[2],s[3])}if(2&i){var r=null==e.depth?t.depth:e.depth;this.setClearDepth(r),this.depthWrite||n.depthMask(!0)}if(4&i){var a=null==e.stencil?t.stencil:e.stencil;this.setClearStencil(a)}n.clear(this.glClearFlag[i]),2&i&&(this.depthWrite||n.depthMask(!1))}},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){e===this.clearRed&&t===this.clearGreen&&i===this.clearBlue&&n===this.clearAlpha||(this.gl.clearColor(e,t,i,n),this.clearRed=e,this.clearGreen=t,this.clearBlue=i,this.clearAlpha=n)},i.setClearStencil=function(e){e!==this.clearStencil&&(this.gl.clearStencil(e),this.clearStencil=e)},i.setRenderTarget=function(e){this.renderTarget=e},i.getRenderTarget=function(){return this.renderTarget},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.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.setIndexBuffer=function(e){this.indexBuffer=e},i.setVertexBuffer=function(e){e&&this.vertexBuffers.push(e)},i.compileShaderSource=function(e,t){var i=this.gl,n=t?this.vertexShaderCache[e]:this.fragmentShaderCache[e];return n||(n=i.createShader(t?i.VERTEX_SHADER:i.FRAGMENT_SHADER),i.shaderSource(n,e),i.compileShader(n),t?this.vertexShaderCache[e]=n:this.fragmentShaderCache[e]=n),n},i.compileAndLinkShader=function(e){var t=this.gl,i=e.definition,n=i.attributes,s=this.compileShaderSource(i.vshader,!0),r=this.compileShaderSource(i.fshader,!1),a=t.createProgram();if(t.attachShader(a,s),t.attachShader(a,r),this.webgl2&&i.useTransformFeedback){var o=[];for(var h in n)n.hasOwnProperty(h)&&o.push("out_"+h);t.transformFeedbackVaryings(a,o,t.INTERLEAVED_ATTRIBS)}var l={};for(var c in n)if(n.hasOwnProperty(c)){var u=n[c],d=ei[u];l[d]=c,t.bindAttribLocation(a,d,c)}t.linkProgram(a),e._glVertexShader=s,e._glFragmentShader=r,e._glProgram=a},i.createShader=function(e){this.compileAndLinkShader(e),this.shaders.push(e)},i.destroyShader=function(e){var t=this.shaders.indexOf(e);-1!==t&&this.shaders.splice(t,1),e._glProgram&&(this.gl.deleteProgram(e._glProgram),e._glProgram=null,this.removeShaderFromCache(e))},i._addLineNumbers=function(e){if(!e)return"";for(var t=e.split("\n"),i=0,n=t.length;it)if(ArrayBuffer.isView(e))e=e.subarray(0,t),i.set(e);else for(var n=0;n0){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>T&&(r.y=T),r.z>w&&(r.z=w),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 ps(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 vi(this.vertexBuffer).readData(e,t));return i},i.setPositions=function(e,t,i){void 0===t&&(t=fs.DEFAULT_COMPONENTS_POSITION),this.setVertexStream(ct,e,t,i,6,!1)},i.setNormals=function(e,t,i){void 0===t&&(t=fs.DEFAULT_COMPONENTS_NORMAL),this.setVertexStream(ut,e,t,i,6,!1)},i.setUvs=function(e,t,i,n){void 0===i&&(i=fs.DEFAULT_COMPONENTS_UV),this.setVertexStream(_t+e,t,i,n,6,!1)},i.setColors=function(e,t,i){void 0===t&&(t=fs.DEFAULT_COMPONENTS_COLORS),this.setVertexStream(mt,e,t,i,6,!1)},i.setColors32=function(e,t){this.setVertexStream(mt,e,fs.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(ct,e)},i.getNormals=function(e){return this.getVertexStream(ut,e)},i.getUvs=function(e,t){return this.getVertexStream(_t+e,t)},i.getColors=function(e){return this.getVertexStream(mt,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 si(this.device,t,e)},i._updateVertexBuffer=function(){if(!this.vertexBuffer){var e=this._geometryData.maxVertices,t=this._buildVertexFormat(e);this.vertexBuffer=new ii(this.device,t,e,this._geometryData.verticesUsage)}var i=new vi(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 rs(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 Jt[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 rs(this.vertexBuffer.device,e,t.length);new Jt[p.format](p.storage).set(t),p.unlock(),this.primitive[1]={type:1,base:0,count:t.length,indexed:!0},this.indexBuffer[1]=p},Y(t,[{key:"aabb",get:function(){return this._aabb},set:function(e){this._aabb=e}}]),t}(us),_s=4/64,gs=.875,vs=[];function ys(e,t){var i,n,s,r,a=t.length/3,o=e.length/3,h=new me,l=new me,c=new me,u=new me,d=new me,f=new me,p=[];for(r=0;r0)for(a=0;a<=n;a++)for(o=0;o<=s;o++){_=o/s*2*Math.PI-Math.PI,v=Math.sin(_),g=Math.cos(_),p=new me(v*e,-i/2,g*e),f=new me(v*t,i/2,g*t),A.lerp(p,f,a/n),C.sub2(f,p).normalize(),m=new me(g,0,-v),E.cross(m,C).normalize(),P.push(A.x,A.y,A.z),I.push(E.x,E.y,E.z),u=o/s,d=a/n,R.push(u,1-d);var k=d;d=u,u=(u=k)*gs+_s,d=d*gs+_s,u/=3,L.push(u,1-d),a0)for(a=0;a1&&D.push(M,M+a,M+a-1);if(M+=s,t>0)for(a=0;a1&&D.push(M,M+a-1,M+a)}return{positions:P,normals:I,uvs:R,uvs1:L,indices:D}}function ws(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=Ts(i,i,n,s,r,!1);return a&&(o.tangents=xs(o.positions,o.normals,o.uvs,o.indices)),bs(e,o.positions,o)}function Ms(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=Ts(i,i,n-2*i,s,r,!0);return a&&(o.tangents=xs(o.positions,o.normals,o.uvs,o.indices)),bs(e,o.positions,o)}function As(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=Ts(i,n,s,r,a,!1);return o&&(h.tangents=xs(h.positions,h.normals,h.uvs,h.indices)),bs(e,h.positions,h)}function Cs(e,t){var i,n,s,r,a,o,h,l,c,u,d,f,p,m,_=t&&void 0!==t.radius?t.radius:.5,g=t&&void 0!==t.latitudeBands?t.latitudeBands:16,v=t&&void 0!==t.longitudeBands?t.longitudeBands:16,y=!(!t||void 0===t.calculateTangents)&&t.calculateTangents,x=[],b=[],S=[],T=[];for(n=0;n<=g;n++)for(s=n*Math.PI/g,r=Math.sin(s),a=Math.cos(s),i=0;i<=v;i++)o=2*i*Math.PI/v-Math.PI/2,h=Math.sin(o),u=Math.cos(o)*r,d=a,f=h*r,p=1-i/v,m=1-n/g,x.push(u*_,d*_,f*_),b.push(u,d,f),S.push(p,1-m);for(n=0;n=0;i--)this.matrices[i].mulAffine2(ks,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=0?e.insertChild(this,t):e.addChild(this))},i.setLocalEulerAngles=function(e,t,i){e instanceof me?this.localRotation.setFromEulerAngles(e.x,e.y,e.z):this.localRotation.setFromEulerAngles(e,t,i),this._dirtyLocal||this._dirtifyLocal()},i.setLocalPosition=function(e,t,i){e instanceof me?this.localPosition.copy(e):this.localPosition.set(e,t,i),this._dirtyLocal||this._dirtifyLocal()},i.setLocalRotation=function(e,t,i,n){e instanceof Me?this.localRotation.copy(e):this.localRotation.set(e,t,i,n),this._dirtyLocal||this._dirtifyLocal()},i.setLocalScale=function(e,t,i){e instanceof me?this.localScale.copy(e):this.localScale.set(e,t,i),this._dirtyLocal||this._dirtifyLocal()},i._dirtifyLocal=function(){this._dirtyLocal||(this._dirtyLocal=!0,this._dirtyWorld||this._dirtifyWorld())},i._unfreezeParentToRoot=function(){for(var e=this._parent;e;)e._frozen=!1,e=e._parent},i._dirtifyWorld=function(){this._dirtyWorld||this._unfreezeParentToRoot(),this._dirtifyWorldInternal()},i._dirtifyWorldInternal=function(){if(!this._dirtyWorld){this._frozen=!1,this._dirtyWorld=!0;for(var e=0;e>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 or(e,t,i,n){return(15&e)<<27|(3===t?1:0)<<26|(i?1:0)<<25|(33554431&n)<<0}function hr(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 _r=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 Ds(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(),T=p[0].drawOrder;h.copy(p[0].aabb);var w=mr(p[0]),M=p[0].mesh.vertexBuffer.format.batchingHash,A=p[0].mesh.primitive[0].indexed;c=null;for(var C=1;C=a){f=f.concat(p.slice(C));break}if(_!==E.material||g!==E.layer||M!==E.mesh.vertexBuffer.format.batchingHash||A!==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(w===mr(E))if(lr(y,E.parameters)){var P=E._staticLightList;if(b&&P){if(!cr(b,P)){m(E);continue}}else if(b||P){m(E);continue}n&&c&&c.intersects(E.aabb)&&E.drawOrder!==T?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===ct)for(var M=0;M0&&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 I=new ar(r,p,this.rootNode);I.castShadow=h.origMeshInstances[0].castShadow,I.parameters=h.origMeshInstances[0].parameters,I.isStatic=h.origMeshInstances[0].isStatic,I.layer=h.origMeshInstances[0].layer,I._staticLightList=h.origMeshInstances[0]._staticLightList,I._shaderDefs=h.origMeshInstances[0]._shaderDefs,I.cull=h.origMeshInstances[0].cull;var R=this._batchGroups[i];if(R&&R._ui&&(I.cull=!1),t){for(var L=[],D=0;D0&&this.generate(this._dirtyGroups);for(var e=0;es&&(s=a)}return Cr.min=n,Cr.max=s,Cr}function Pr(e,t){return Math.exp(-e*e/(2*t*t))}var Ir=new Re,Rr=new we,Lr=new we,Dr=new Float32Array(2),kr={x:1,y:1,z:0,w:0},Or={r:1,g:2,b:3,a:4},Fr=new me,Br=new we;function Nr(e){var t=e.material,i=e.skinInstance?10:0,n=0;if(t.opacityMap){var s=t.opacityMapChannel;s&&(n=Or[s])}return i+n}var zr=function(){function e(e){this.device=e.device,this.forwardRenderer=e;var t=this.device.scope;this.sourceId=t.resolve("source"),this.pixelOffsetId=t.resolve("pixelOffset"),this.weightId=t.resolve("weight[0]"),this.blurVsmShaderCode=[Ti.blurVSMPS,"#define GAUSS\n"+Ti.blurVSMPS];var i="#define PACKED\n";this.blurPackedVsmShaderCode=[i+this.blurVsmShaderCode[0],i+this.blurVsmShaderCode[1]],this.blurVsmShader=[{},{}],this.blurPackedVsmShader=[{},{}],this.blurVsmWeights={},this.shadowMapLightRadiusId=t.resolve("light_radius"),this.shadowMapCache=new wr}var t=e.prototype;return t.destroy=function(){this.shadowMapCache.destroy(),this.shadowMapCache=null},e.createShadowCamera=function(e,t,i,n){var s=new br;switch(s.node=new Js("ShadowCamera"),s.aspectRatio=1,i){case 1:s.node.setRotation(Mr[n]),s.fov=90,s.projection=0;break;case 2:s.projection=0;break;case 0:s.projection=1}var r=4===t||0===t&&e.webgl2;return 1===i&&(r=!1),s.clearColor=t>=1&&t<=3?new ue(0,0,0,0):new ue(1,1,1,1),s.clearColorBuffer=!r,s.clearDepthBuffer=!0,s.clearStencilBuffer=!1,s},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(Fr.dot(v)*x)/x,S=Math.ceil(Fr.dot(g)*x)/x,T=v.mulScalar(b),w=g.mulScalar(S),M=Fr.dot(y),A=y.mulScalar(M);Fr.add2(T,w).add(A),o.setPosition(Fr),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.applyVsmBlur(e,t)}},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;rC&&(C=b),S>E&&(E=S),T>P&&(P=T);$[c=6*o]=w,$[c+1]=M,$[c+2]=A,$[c+3]=C,$[c+4]=E,$[c+5]=P}for(l=0;l=I.x&&$[c+1]<=R.y&&$[c+4]>=I.y&&$[c+2]<=R.z&&$[c+5]>=I.z&&(K[o]|=U,L=!0);if(L){for(O={},o=0;o<_;o++)a=3*o+x,O[F=K[o]]||(O[F]=[]),(B=O[F]).push(p[a]),B.push(p[a+1]),B.push(p[a+2]);for(F in O){B=O[F];var J=new rs(t,D.format,B.length,D.usage);for((2===J.bytesPerIndex?new Uint16Array(J.lock()):new Uint32Array(J.lock())).set(B),J.unlock(),w=Number.MAX_VALUE,M=Number.MAX_VALUE,A=Number.MAX_VALUE,C=-Number.MAX_VALUE,E=-Number.MAX_VALUE,P=-Number.MAX_VALUE,o=0;oC&&(C=b),S>E&&(E=S),T>P&&(P=T);X.set(w,M,A),q.set(C,E,P);var ee=new Re;ee.setMinMax(X,q);var te=new ms(t);te.vertexBuffer=k,te.indexBuffer[0]=J,te.primitive[0].type=4,te.primitive[0].base=0,te.primitive[0].count=B.length,te.primitive[0].indexed=!0,te.aabb=ee;var ie=new ar(te,u.material,u.node);for(ie.isStatic=u.isStatic,ie.visible=u.visible,ie.layer=u.layer,ie.castShadow=u.castShadow,ie._receiveShadow=u._receiveShadow,ie.cull=u.cull,ie.pick=u.pick,ie.mask=u.mask,ie.parameters=u.parameters,ie._shaderDefs=u._shaderDefs,ie._staticSource=u,u._staticLightList?ie._staticLightList=u._staticLightList:ie._staticLightList=[],o=0;o0&&(this._instancedDrawCalls++,e.setVertexBuffer(Hr.vertexBuffer),e.draw(i.primitive[n],Hr.count),Hr.vertexBuffer===Ma))return this._removedByInstancing+=Hr.count,t.instancingData=null,Hr.count-1}else Xr=t.node.worldTransform,this.modelMatrixId.setValue(Xr.data),s&&(qr=t.node.normalMatrix,t.node._dirtyNormal&&(Xr.invertTo3x3(qr),qr.transpose(),t.node._dirtyNormal=!1),this.normalMatrixId.setValue(qr.data)),e.draw(i.primitive[n]);return 0},t.drawInstance2=function(e,t,i,n){if(Hr=t.instancingData){if(Hr.count>0&&(this._instancedDrawCalls++,e.draw(i.primitive[n],Hr.count,!0),Hr.vertexBuffer===Ma))return this._removedByInstancing+=Hr.count,t.instancingData=null,Hr.count-1}else e.draw(i.primitive[n],void 0,!0);return 0},t.renderShadows=function(e,t){var i=this.device;i.grabPassAvailable=!1;for(var n=0;n0&&n.cull<3){i.flipFaces&&(r*=-1),t&&(r*=-1);var a=i.node.worldTransform;a.getX(xa),a.getY(ba),a.getZ(Sa),xa.cross(xa,ba),xa.dot(Sa)<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(xa),o.getY(ba),o.getZ(Sa),xa.cross(xa,ba),xa.dot(Sa)<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;i0&&this.renderShadows(r.directionalLights,c.camera),o.enabled&&e.subLayerEnabled[a]){if(c&&c.frameBegin(r.renderTarget),!h&&o.onPreRenderOpaque?o.onPreRenderOpaque(l):h&&o.onPreRenderTransparent&&o.onPreRenderTransparent(l),o._preRenderCalledForCameras&1<=0&&a._shaderVersion!==i&&(a.updateShader!==bn.prototype.updateShader&&(a.clearVariants(),a.shader=null),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(Ia);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;s=1?(a[0]=Math.pow(t,2.2)*s,a[1]=Math.pow(i,2.2)*s,a[2]=Math.pow(n,2.2)*s):(a[0]=Math.pow(r[0],2.2),a[1]=Math.pow(r[1],2.2),a[2]=Math.pow(r[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|Na[this._cookieChannel.charAt(0)]<<18|(this._cookieTransform?1:0)<<12|this._shape<<10|this.numCascades-1<<8;3===this._cookieChannel.length&&(e|=Na[this._cookieChannel.charAt(1)]<<16,e|=Na[this._cookieChannel.charAt(2)]<<14),e!==this.key&&null!==this._scene&&this.layersDirty(),this.key=e},Y(e,[{key:"numCascades",get:function(){return this.cascades.length},set:function(e){this.cascades&&this.numCascades==e||(this.cascades=za[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:"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:"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))}},{key:"outerConeAngle",get:function(){return this._outerConeAngle},set:function(e){this._outerConeAngle!==e&&(this._outerConeAngle=e,this._outerConeAngleCos=Math.cos(e*Math.PI/180))}},{key:"intensity",get:function(){return this._intensity},set:function(e){this._intensity!==e&&(this._intensity=e,this._updateFinalColor())}},{key:"cookieMatrix",get:function(){return this._cookieMatrix||(this._cookieMatrix=new we),this._cookieMatrix}},{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&&t.push(new Ha(e,l))}}for(var d=0;d0){var c=1===t?2:1;this.setLightmaping(o,!1,c),this.initBake(i),this.bakeInternal(c,o,h);var u=1===t?192:Be;this.setLightmaping(o,!0,c,u),this.finishBake(o)}var d=ie();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(n[0].aabb);for(var s=1;sf)return!1;this.morphTextureWidth=p,this.morphTextureHeight=m;var _=!1,g=3,v=he.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&&(n(s,r),s=0,r=!0))}(s>0||0===a&&!this.zeroTextures)&&n(s,r)},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.absWeight=P)&&this.calcSpawnPosition(i,n,s,r,A);var k=I>0&&I0&&(1===f.emitterShape?(io.copy(no).mulScalar(2).sub(me.ONE).normalize(),ao.add(io.mulScalar(f.initialVelocity))):ao.add(me.FORWARD.mulScalar(f.initialVelocity))),ro.x+=(oo.x-ro.x)*no.x,ro.y+=(oo.y-ro.y)*no.y,ro.z+=(oo.z-ro.z)*no.z,g+=(v-g)*no.y,L=(L+1e4*C%1*(y-L))*Qa,D=1e3*C%1*(b-x),f.meshInstance.node&&(f.localSpace?(ao.x/=Ya.x,ao.y/=Ya.y,ao.z/=Ya.z):Ja.transformPoint(ao,ao)),f.localSpace?(eo.transformPoint(ro,ro),ao.add(ro).add(lo)):(ao.add(ro.mul(Ya)),ao.add(lo.mul(Ya))),fo.copy(ao),co.copy(so).add(ao.mulScalar(a)),uo.copy(co),i[4*A]=uo.x,i[4*A+1]=uo.y,i[4*A+2]=uo.z,i[4*A+3]+=g*a,f.wrap&&f.wrapBounds&&(f.localSpace||uo.sub(r),uo.x=go(uo.x,f.wrapBounds.x)-.5*f.wrapBounds.x,uo.y=go(uo.y,f.wrapBounds.y)-.5*f.wrapBounds.y,uo.z=go(uo.z,f.wrapBounds.z)-.5*f.wrapBounds.z,f.localSpace||uo.add(r)),f.sort>0&&(1===f.sort?(po.copy(uo).sub(T),f.particleDistance[A]=-(po.x*po.x+po.y*po.y+po.z*po.z)):2===f.sort?f.particleDistance[A]=I:3===f.sort&&(f.particleDistance[A]=-I))),o?I<0&&(i[4*A+3+2*f.numParticlesPot*4]=-1):(I>=P&&(I-=Math.max(P,(f.numParticles-1)*E),i[4*A+3+2*f.numParticlesPot*4]=f.loop?1:-1),I<0&&f.loop&&(i[4*A+3+2*f.numParticlesPot*4]=1)),i[4*A+3+2*f.numParticlesPot*4]<0&&(k=!1),i[4*A+3+4*f.numParticlesPot]=I;for(var O=0;O0&&f.camera){var V=f.useMesh?6:4,G=f.particleDistance;for(u=0;ut.maxTextureSize&&(console.warn("WARNING: can't create more than "+t.maxTextureSize+" particles on this device."),this.numParticles=t.maxTextureSize),zo("rate",1),zo("rate2",this.rate),zo("lifetime",50),zo("emitterExtents",new me(0,0,0)),zo("emitterExtentsInner",new me(0,0,0)),zo("emitterRadius",0),zo("emitterRadiusInner",0),zo("emitterShape",0),zo("initialVelocity",1),zo("wrap",!1),zo("localSpace",!1),zo("screenSpace",!1),zo("wrapBounds",null),zo("colorMap",e.DEFAULT_PARAM_TEXTURE),zo("normalMap",null),zo("loop",!0),zo("preWarm",!1),zo("sort",0),zo("mode",0),zo("scene",null),zo("lighting",!1),zo("halfLambert",!1),zo("intensity",1),zo("stretch",0),zo("alignToMotion",!1),zo("depthSoftening",0),zo("mesh",null),zo("particleNormal",new me(0,1,0)),zo("orientation",0),zo("depthWrite",!1),zo("noFog",!1),zo("blendType",2),zo("node",null),zo("startAngle",0),zo("startAngle2",this.startAngle),zo("animTilesX",1),zo("animTilesY",1),zo("animStartFrame",0),zo("animNumFrames",1),zo("animNumAnimations",1),zo("animIndex",0),zo("randomizeAnimIndex",!1),zo("animSpeed",1),zo("animLoop",!0),this._gpuUpdater=new To(this,n),this._cpuUpdater=new yo(this),this.constantLightCube=n.scope.resolve("lightCube[0]"),this.emitterPosUniform=new Float32Array(3),this.wrapBoundsUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),zo("colorGraph",Lo),zo("colorGraph2",this.colorGraph),zo("scaleGraph",Io),zo("scaleGraph2",this.scaleGraph),zo("alphaGraph",Io),zo("alphaGraph2",this.alphaGraph),zo("localVelocityGraph",Ro),zo("localVelocityGraph2",this.localVelocityGraph),zo("velocityGraph",Ro),zo("velocityGraph2",this.velocityGraph),zo("rotationSpeedGraph",Po),zo("rotationSpeedGraph2",this.rotationSpeedGraph),zo("radialSpeedGraph",Po),zo("radialSpeedGraph2",this.radialSpeedGraph),this.lightCube=new Float32Array(18),this.lightCubeDir=new Array(6),this.lightCubeDir[0]=new me(-1,0,0),this.lightCubeDir[1]=new me(1,0,0),this.lightCubeDir[2]=new me(0,-1,0),this.lightCubeDir[3]=new me(0,1,0),this.lightCubeDir[4]=new me(0,0,-1),this.lightCubeDir[5]=new me(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=!1,this.pack8=!0,this.localBounds=new Re,this.worldBoundsNoTrail=new Re,this.worldBoundsTrail=[new Re,new Re],this.worldBounds=new Re,this.worldBoundsSize=new me,this.prevWorldBoundsSize=new me,this.prevWorldBoundsCenter=new me,this.prevEmitterExtents=this.emitterExtents,this.prevEmitterRadius=this.emitterRadius,this.worldBoundsMul=new me,this.worldBoundsAdd=new me,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()}e.staticInit=function(t){if(!e.DEFAULT_PARAM_TEXTURE){for(var i=16,n=new Float32Array(1024),s=0;s=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?we.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(){var e,t,i,n,s,r,a=Number.MAX_VALUE,o=Number.MAX_VALUE,h=Number.MAX_VALUE,l=-Number.MAX_VALUE,c=-Number.MAX_VALUE,u=-Number.MAX_VALUE,d=0,f=0,p=this.lifetime/this.precision,m=[this.qVelocity,this.qVelocity2],_=[this.qLocalVelocity,this.qLocalVelocity2],g=[0,0],v=[0,0],y=[0,0],x=[0,0],b=[0,0];for(e=0;e0||i.maxVertexTextures<=1||i.fragmentUniformsCount<64||i.forceCpuParticles||!i.extTextureFloat,this._destroyResources(),this.pack8=(this.pack8||!i.textureFloatRenderable)&&!this.useCpu,Do=this.useCpu||this.pack8?4:2,this.useMesh=!1,this.mesh)&&(this.numParticles*this.mesh.vertexBuffer.numVertices>65535?console.warn("WARNING: particle system can't render mesh particles because numParticles * numVertices is more than 65k. Reverting to quad particles."):this.useMesh=!0);this.numParticlesPot=he.nextPowerOfTwo(this.numParticles),this.rebuildGraphs(),this.calculateLocalBounds(),this.resetWorldBounds(),this.node&&(this.worldBounds.setFromTransformedAabb(this.localBounds,this.localSpace?we.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 n=0;n=1&&(this.animTilesX>1||this.animTilesY>1)&&(this.colorMap&&this.colorMap!==e.DEFAULT_PARAM_TEXTURE||this.normalMap)},t.rebuildGraphs=function(){var e,t=this.precision,i=this.graphicsDevice;for(this.qLocalVelocity=this.localVelocityGraph.quantize(t),this.qVelocity=this.velocityGraph.quantize(t),this.qColor=this.colorGraph.quantizeClamped(t,0,1),this.qRotSpeed=this.rotationSpeedGraph.quantize(t),this.qScale=this.scaleGraph.quantize(t),this.qAlpha=this.alphaGraph.quantize(t),this.qRadialSpeed=this.radialSpeedGraph.quantize(t),this.qLocalVelocity2=this.localVelocityGraph2.quantize(t),this.qVelocity2=this.velocityGraph2.quantize(t),this.qColor2=this.colorGraph2.quantizeClamped(t,0,1),this.qRotSpeed2=this.rotationSpeedGraph2.quantize(t),this.qScale2=this.scaleGraph2.quantize(t),this.qAlpha2=this.alphaGraph2.quantize(t),this.qRadialSpeed2=this.radialSpeedGraph2.quantize(t),e=0;e0&&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?we.IDENTITY:this.node.getWorldTransform()).transformVector(this.particleNormal).normalize();var n=new me(1,0,0);1===Math.abs(n.dot(i))&&n.set(0,0,1);var s=(new me).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,i,n,s=e*this.numParticleVerts,r=e*this.numParticleIndices;if(void 0===this.vertexBuffer||this.vertexBuffer.getNumVertices()!==s){this.useCpu?(t=[{semantic:At,components:4,type:6},{semantic:Ct,components:4,type:6},{semantic:Et,components:4,type:6},{semantic:Pt,components:1,type:6},{semantic:It,components:this.useMesh?4:2,type:6}],i=new si(this.graphicsDevice,t),this.vertexBuffer=new ii(this.graphicsDevice,i,s,1),this.indexBuffer=new rs(this.graphicsDevice,1,r)):(t=[{semantic:At,components:4,type:6}],this.useMesh&&t.push({semantic:Ct,components:2,type:6}),i=new si(this.graphicsDevice,t),this.vertexBuffer=new ii(this.graphicsDevice,i,s,1),this.indexBuffer=new rs(this.graphicsDevice,1,r));var a,o,h,l,c=new Float32Array(this.vertexBuffer.lock());if(this.useMesh){o=(a=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}();Ho.DEFAULT_PARAM_TEXTURE=null;var Xo=function(){function e(){}return e.createTexture=function(e,t,i){var n=new Vi(e,{width:i,height:i,format:t,addressU:1,addressV:1,type:Gt,magFilter:1,minFilter:0,anisotropy:1});return n.name="AreaLightLUT",n},e.setUniforms=function(e,t,i){e.scope.resolve("areaLightsLutTex1").setValue(t),e.scope.resolve("areaLightsLutTex2").setValue(i)},e.createPlaceholder=function(t){var i=e.createTexture(t,7,2);i.lock().fill(0),i.unlock(),e.setUniforms(t,i,i)},e.set=function(t,i){function n(t,i,n){var s=e.createTexture(t,n,64);return s.lock().set(i),s.unlock(),s.upload(),s}function s(e,t,i){for(var n=e.length,s=new Float32Array(n),r=0;rthis.numLinesAllocated;)this.vb&&(this.vb.destroy(),this.vb=null),this.numLinesAllocated*=2;this.vertexFormat=t,this.vb||(this.vb=new ii(e,t,2*this.numLinesAllocated,1),this.mesh.vertexBuffer=this.vb,this.vbRam=new DataView(this.vb.lock()),this.meshInstance||(qo.worldTransform=we.IDENTITY,qo._dirtyWorld=qo._dirtyNormal=!1,this.meshInstance=new ar(this.mesh,this.material,qo),this.meshInstance.cull=!1))},t.addLines=function(e,t){for(var i,n=!!t.length,s=2*this.linesUsed*this.vertexFormat.size,r=0;r0&&(this.vb.setData(this.vbRam.buffer),this.mesh.primitive[0].count=2*this.linesUsed,e[0]=this.meshInstance,this.layer.addMeshInstances(e,!0),this.linesUsed=0)},e}(),Yo=function(){function e(e){this.lineVertexFormat=new si(e,[{semantic:ct,components:3,type:6},{semantic:mt,components:4,type:1,normalize:!0}]),this.device=e,this.lineBatches=[],this.layers=[],this.layerToBatch={},this.quadMesh=null,this.textureShader=null,this.depthTextureShader=null,this.cubeLocalPos=null,this.cubeWorldPos=null,this.meshInstanceArray=[],this.usedGraphNodes=[],this.freeGraphNodes=[]}e.getTextureVS=function(){return"\n attribute vec2 aPosition;\n uniform mat4 matrix_model;\n varying vec2 uv0;\n void main(void) {\n gl_Position = matrix_model * vec4(aPosition, 0, 1);\n uv0 = aPosition.xy + 0.5;\n uv0.y = 1.0 - uv0.y;\n }\n "};var t=e.prototype;return t.getTextureShader=function(){if(!this.textureShader){var t={attributes:{aPosition:ct},vshader:e.getTextureVS(),fshader:"\n precision lowp float;\n varying vec2 uv0;\n uniform sampler2D colorMap;\n void main (void) {\n gl_FragColor = vec4(texture2D(colorMap, uv0).xyz, 1);\n }\n "};this.textureShader=new Si(this.device,t)}return this.textureShader},t.getDepthTextureShader=function(){if(!this.depthTextureShader){var t=this.device.webgl2?"#define GL2":"",i={attributes:{aPosition:ct},vshader:e.getTextureVS(),fshader:"\n precision "+this.device.precision+" float;\n "+t+"\n "+Ti.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=new Si(this.device,i)}return this.depthTextureShader},t.getQuadMesh=function(){if(!this.quadMesh){var e=new si(this.device,[{semantic:ct,components:3,type:6}]),t=new ii(this.device,e,4),i=new vi(t);i.element.POSITION.set(-.5,-.5,0),i.next(),i.element.POSITION.set(.5,-.5,0),i.next(),i.element.POSITION.set(-.5,.5,0),i.next(),i.element.POSITION.set(.5,.5,0),i.end(),this.quadMesh=new ms(this.device),this.quadMesh.vertexBuffer=t,this.quadMesh.primitive[0].type=5,this.quadMesh.primitive[0].base=0,this.quadMesh.primitive[0].count=4,this.quadMesh.primitive[0].indexed=!1}return this.quadMesh},t.renderMesh=function(e,t,i,n,s){if(!n){var r=this.getGraphNode(t);(n=new ar(i,e,r)).cull=!1}this.addLayer(s.layer),s.mask&&(n.mask=s.mask),this.meshInstanceArray[0]=n,s.layer.addMeshInstances(this.meshInstanceArray,!0)},t.renderWireCube=function(e,t,i){if(!this.cubeLocalPos){var n=.5;this.cubeLocalPos=[new me(-n,-n,-n),new me(-n,n,-n),new me(n,n,-n),new me(n,-n,-n),new me(-n,-n,n),new me(-n,n,n),new me(n,n,n),new me(n,-n,n)],this.cubeWorldPos=[new me,new me,new me,new me,new me,new me,new me,new me];var s=this.cubeWorldPos;this.cubePositions=[s[0],s[1],s[1],s[2],s[2],s[3],s[3],s[0],s[4],s[5],s[5],s[6],s[6],s[7],s[7],s[4],s[0],s[4],s[1],s[5],s[2],s[6],s[3],s[7]]}for(var r=this.cubeLocalPos,a=this.cubeWorldPos,o=0;o<8;o++)e.transformPoint(r[o],a[o]);this.prepareLineBatch(i.layer,i.depthTest,void 0,this.cubePositions.length).addLines(this.cubePositions,t)},t.renderWireSphere=function(e,t,i,n){if(!this.spherePoints){this.spherePoints=[];for(var s=0;s<120;s++)this.spherePoints.push(new me)}for(var r=this.spherePoints,a=2*Math.PI/20,o=0,h=0;h<20;h++){var l=Math.sin(o),c=Math.cos(o);o+=a;var u=Math.sin(o),d=Math.cos(o);r[6*h].set(e.x+t*l,e.y,e.z+t*c),r[6*h+1].set(e.x+t*u,e.y,e.z+t*d),r[6*h+2].set(e.x+t*l,e.y+t*c,e.z),r[6*h+3].set(e.x+t*u,e.y+t*d,e.z),r[6*h+4].set(e.x,e.y+t*l,e.z+t*c),r[6*h+5].set(e.x,e.y+t*u,e.z+t*d)}this.prepareLineBatch(n.layer,n.depthTest,void 0,r.length).addLines(r,i)},t.getGraphNode=function(e){var t=null;return t=this.freeGraphNodes.length>0?this.freeGraphNodes.pop():new Js,this.usedGraphNodes.push(t),t.worldTransform=e,t._dirtyWorld=t._dirtyNormal=!1,t},t.addLayer=function(e){this.layers.indexOf(e)<0&&this.layers.push(e)},t.getLayerIdx=function(e){return this.layerToBatch[e.id]},t.addLayerIdx=function(e,t){this.layerToBatch[t.id]=e},t.finalize=function(){for(var e=0;e=0},i.getModels=function(e){return this._models},Y(t,[{key:"fog",get:function(){return this._fog},set:function(e){e!==this._fog&&(this._fog=e,this.updateShaders=!0)}},{key:"gammaCorrection",get:function(){return this._gammaCorrection},set:function(e){e!==this._gammaCorrection&&(this._gammaCorrection=e,this.updateShaders=!0)}},{key:"toneMapping",get:function(){return this._toneMapping},set:function(e){e!==this._toneMapping&&(this._toneMapping=e,this.updateShaders=!0)}},{key:"skybox",get:function(){return this._skyboxCubeMap},set:function(e){this._skyboxCubeMap=e,this._resetSkyboxModel(),this.updateShaders=!0}},{key:"skyboxIntensity",get:function(){return this._skyboxIntensity},set:function(e){this._skyboxIntensity=e,this._resetSkyboxModel(),this.updateShaders=!0}},{key:"skyboxRotation",get:function(){return this._skyboxRotation},set:function(e){this._skyboxRotation.equals(e)||(this._skyboxRotation.copy(e),this._resetSkyboxModel(),this.updateShaders=!0)}},{key:"skyboxMip",get:function(){return this._skyboxMip},set:function(e){this._skyboxMip=e,this._resetSkyboxModel(),this.updateShaders=!0}},{key:"skyboxPrefiltered128",get:function(){return this._skyboxPrefiltered[0]},set:function(e){this._skyboxPrefiltered[0]!==e&&(this._skyboxPrefiltered[0]=e,this.updateShaders=!0)}},{key:"skyboxPrefiltered64",get:function(){return this._skyboxPrefiltered[1]},set:function(e){this._skyboxPrefiltered[1]!==e&&(this._skyboxPrefiltered[1]=e,this.updateShaders=!0)}},{key:"skyboxPrefiltered32",get:function(){return this._skyboxPrefiltered[2]},set:function(e){this._skyboxPrefiltered[2]!==e&&(this._skyboxPrefiltered[2]=e,this.updateShaders=!0)}},{key:"skyboxPrefiltered16",get:function(){return this._skyboxPrefiltered[3]},set:function(e){this._skyboxPrefiltered[3]!==e&&(this._skyboxPrefiltered[3]=e,this.updateShaders=!0)}},{key:"skyboxPrefiltered8",get:function(){return this._skyboxPrefiltered[4]},set:function(e){this._skyboxPrefiltered[4]!==e&&(this._skyboxPrefiltered[4]=e,this.updateShaders=!0)}},{key:"skyboxPrefiltered4",get:function(){return this._skyboxPrefiltered[5]},set:function(e){this._skyboxPrefiltered[5]!==e&&(this._skyboxPrefiltered[5]=e,this.updateShaders=!0)}},{key:"drawCalls",get:function(){var e=this.layers._meshInstances;return e.length||(this.layers._update(),e=this.layers._meshInstances),e},set:function(e){}},{key:"layers",get:function(){return this._layers},set:function(e){var t=this._layers;this._layers=e,this.fire("set:layers",t,e)}},{key:"defaultMaterial",get:function(){return bn.defaultMaterial},set:function(e){bn.defaultMaterial=e}}]),t}(_);function Zo(){return!("undefined"==typeof AudioContext&&"undefined"==typeof webkitAudioContext)}var $o=function(){function e(e,t,i){if(void 0===i&&(i={}),this.volume=void 0===i.volume?1:i.volume,this.loop=void 0!==i.loop&&i.loop,this.pitch=void 0===i.pitch?1:i.pitch,this.sound=t,this.paused=!1,this.suspended=!1,this.manager=e,this.source=null,Zo()){this.startTime=0,this.startOffset=0;var n=e.context;this.gain=n.createGain()}else t.audio&&(this.source=t.audio.cloneNode(!1),this.source.pause())}var t=e.prototype;return t.getVolume=function(){return this.volume},t.getLoop=function(){return this.loop},t.setLoop=function(e){this.loop=e,this.source&&(this.source.loop=e)},t.getPitch=function(){return this.pitch},t.onManagerVolumeChange=function(){this.setVolume(this.getVolume())},t.onManagerSuspend=function(){this.isPlaying()&&!this.suspended&&(this.suspended=!0,this.pause())},t.onManagerResume=function(){this.suspended&&(this.suspended=!1,this.unpause())},e}();Zo()?Object.assign($o.prototype,{play:function(){if(this.source)throw new Error("Call stop() before calling play()");this._createSource(),this.source&&(this.startTime=this.manager.context.currentTime,this.source.start(0,this.startOffset%this.source.buffer.duration),this.setVolume(this.volume),this.setLoop(this.loop),this.setPitch(this.pitch),this.manager.on("volumechange",this.onManagerVolumeChange,this),this.manager.on("suspend",this.onManagerSuspend,this),this.manager.on("resume",this.onManagerResume,this),this.manager.suspended&&this.onManagerSuspend())},pause:function(){this.source&&(this.paused=!0,this.startOffset+=this.manager.context.currentTime-this.startTime,this.source.stop(0),this.source=null)},unpause:function(){!this.source&&this.paused?(this._createSource(),this.source&&(this.startTime=this.manager.context.currentTime,this.source.start(0,this.startOffset%this.source.buffer.duration),this.setVolume(this.volume),this.setLoop(this.loop),this.setPitch(this.pitch),this.paused=!1)):console.warn("Call pause() before unpausing.")},stop:function(){this.source&&(this.source.stop(0),this.source=null),this.manager.off("volumechange",this.onManagerVolumeChange,this),this.manager.off("suspend",this.onManagerSuspend,this),this.manager.off("resume",this.onManagerResume,this)},setVolume:function(e){e=he.clamp(e,0,1),this.volume=e,this.gain&&(this.gain.gain.value=e*this.manager.volume)},setPitch:function(e){this.pitch=e,this.source&&(this.source.playbackRate.value=e)},isPlaying:function(){return!this.paused&&this.source.playbackState===this.source.PLAYING_STATE},getDuration:function(){return this.source?this.source.buffer.duration:0},_createSource:function(){var e=this.manager.context;this.sound.buffer&&(this.source=e.createBufferSource(),this.source.buffer=this.sound.buffer,this.source.connect(this.gain),this.gain.connect(e.destination),this.loop||(this.source.onended=this.pause.bind(this)))}}):Object.assign($o.prototype,{play:function(){this.source&&(this.paused=!1,this.setVolume(this.volume),this.setLoop(this.loop),this.setPitch(this.pitch),this.source.play()),this.manager.on("volumechange",this.onManagerVolumeChange,this),this.manager.on("suspend",this.onManagerSuspend,this),this.manager.on("resume",this.onManagerResume,this),this.manager.suspended&&this.onManagerSuspend()},pause:function(){this.source&&(this.paused=!0,this.source.pause())},unpause:function(){this.source&&(this.paused=!1,this.source.play())},stop:function(){this.source&&this.source.pause(),this.manager.off("volumechange",this.onManagerVolumeChange,this),this.manager.off("suspend",this.onManagerSuspend,this),this.manager.off("resume",this.onManagerResume,this)},setVolume:function(e){e=he.clamp(e,0,1),this.volume=e,this.source&&(this.source.volume=e*this.manager.volume)},setPitch:function(e){this.pitch=e,this.source&&(this.source.playbackRate=e)},getDuration:function(){return this.source&&!isNaN(this.source.duration)?this.source.duration:0},isPlaying:function(){return!this.source.paused}});var Qo="linear",Jo="inverse",eh="exponential",th=function(e){function t(t,i,n){var s;return(s=e.call(this,t,i,n)||this).position=new me,s.velocity=new me,Zo()?s.panner=t.context.createPanner():(s.maxDistance=1e4,s.minDistance=1,s.rollOffFactor=1,s.distanceModel=Jo),s}Z(t,e);var i=t.prototype;return i.getPosition=function(){return this.position},i.getVelocity=function(){return this.velocity},t}($o);if(Zo())Object.assign(th.prototype,{setPosition:function(e){this.position.copy(e),this.panner.setPosition(e.x,e.y,e.z)},setVelocity:function(e){this.velocity.copy(e),this.panner.setVelocity(e.x,e.y,e.z)},getMaxDistance:function(){return this.panner.maxDistance},setMaxDistance:function(e){this.panner.maxDistance=e},getMinDistance:function(){return this.panner.refDistance},setMinDistance:function(e){this.panner.refDistance=e},getRollOffFactor:function(){return this.panner.rolloffFactor},setRollOffFactor:function(e){this.panner.rolloffFactor=e},getDistanceModel:function(){return this.pannel.distanceModel},setDistanceModel:function(e){this.panner.distanceModel=e},_createSource:function(){var e=this.manager.context;this.source=e.createBufferSource(),this.source.buffer=this.sound.buffer,this.source.connect(this.panner),this.panner.connect(this.gain),this.gain.connect(e.destination),this.loop||(this.source.onended=this.pause.bind(this))}});else{var ih=new me;Object.assign(th.prototype,{setPosition:function(e){if(this.position.copy(e),this.source){var t=function(e,t,i,n,s,r){var a=(ih=ih.sub2(e,t)).length();if(an)return 0;var o=0;return r===Qo?o=1-s*(a-i)/(n-i):r===Jo?o=i/(i+s*(a-i)):r===eh&&(o=Math.pow(a/i,-s)),he.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}},setVelocity:function(e){this.velocity.copy(e)},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 nh=function(){function e(e){this._manager=e,this.position=new me,this.velocity=new me,this.orientation=new we}var t=e.prototype;return t.getPosition=function(){return this.position},t.setPosition=function(e){this.position.copy(e);var t=this.listener;t&&t.setPosition(e.x,e.y,e.z)},t.getVelocity=function(){return this.velocity},t.setVelocity=function(e){this.velocity.copy(e);var t=this.listener;t&&t.setPosition(e.x,e.y,e.z)},t.setOrientation=function(e){this.orientation.copy(e);var t=this.listener;t&&t.setOrientation(-e.data[8],-e.data[9],-e.data[10],e.data[4],e.data[5],e.data[6])},t.getOrientation=function(){return this.orientation},Y(e,[{key:"listener",get:function(){var e=this._manager.context;return e?e.listener:null}}]),e}(),sh=function(e){function t(t){var i;return(i=e.call(this)||this)._context=null,i._forceWebAudioApi=t.forceWebAudioApi,i._resumeContext=null,i._unlock=null,Zo()||i._forceWebAudioApi?(i._resumeContext=function(){window.removeEventListener("mousedown",i._resumeContext),window.removeEventListener("touchend",i._resumeContext),i.context&&i.context.resume()},window.addEventListener("mousedown",i._resumeContext),window.addEventListener("touchend",i._resumeContext),D.ios&&(i._unlock=function(){window.removeEventListener("touchend",i._unlock);var e=i.context;if(e){var t=e.createBuffer(1,1,44100),n=e.createBufferSource();n.buffer=t,n.connect(e.destination),n.start(0),n.disconnect()}},window.addEventListener("touchend",i._unlock))):console.warn("No support for 3D audio found"),i.listener=new nh(Q(i)),i._volume=1,i.suspended=!1,i}Z(t,e);var i=t.prototype;return i.suspend=function(){this.suspended=!0,this.fire("suspend")},i.resume=function(){this.suspended=!1,this.fire("resume")},i.destroy=function(){this._resumeContext&&(window.removeEventListener("mousedown",this._resumeContext),window.removeEventListener("touchend",this._resumeContext)),this._unlock&&window.removeEventListener("touchend",this._unlock),this.fire("destroy"),this._context&&this._context.close&&(this._context.close(),this._context=null)},i.playSound=function(e,t){t=t||{};var i=null;return $o&&(i=new $o(this,e,t)).play(),i},i.playSound3d=function(e,t,i){i=i||{};var n=null;return th&&((n=new th(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},Y(t,[{key:"volume",get:function(){return this._volume},set:function(e){e=he.clamp(e,0,1),this._volume=e,this.fire("volumechange",e)}},{key:"context",get:function(){return this._context||(Zo()||this._forceWebAudioApi)&&("undefined"!=typeof AudioContext?this._context=new AudioContext:"undefined"!=typeof webkitAudioContext&&(this._context=new webkitAudioContext)),this._context}}]),t}(_),rh=function(e,t,i,n){this.time=e,this.position=t,this.rotation=i,this.scale=n},ah=function(){this._name="",this._keys=[]},oh=function(){function e(){this.name="",this.duration=0,this._nodes=[],this._nodeDict={}}var t=e.prototype;return t.getNode=function(e){return this._nodeDict[e]},t.addNode=function(e){this._nodes.push(e),this._nodeDict[e._name]=e},Y(e,[{key:"nodes",get:function(){return this._nodes}}]),e}(),hh=function(e,t,i){this.device=e,this.inverseBindPose=t,this.boneNames=i},lh=function(e){function t(){var t;return(t=e.call(this)||this)._meshes=null,t}Z(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;t0&&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}(),mh="en-US",_h={en:"en-US",es:"en-ES",zh:"zh-CN","zh-HK":"zh-TW","zh-TW":"zh-HK","zh-MO":"zh-HK",fr:"fr-FR",de:"de-DE",it:"it-IT",ru:"ru-RU",ja:"ja-JP"},gh={};function vh(e,t){for(var i=0,n=e.length;i=0&&e<=1?0:1})),vh(["fr","pt"],(function(e){return e>=0&&e<2?0:1})),vh(["da"],(function(e){return 1===e||!Number.isInteger(e)&&e>=0&&e<=1?0:1})),vh(["de","en","it","el","es","tr","fi","sv","nb","no","ur"],(function(e){return 1===e?0:1})),vh(["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})),vh(["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})),vh(["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 bh=gh[yh(mh)];function Sh(e){return gh[e]||bh}var Th,wh=new RegExp("^\\s*(?:(?:[a-z]+[a-z0-9\\-\\+\\.]*:)?//|data:|blob:)","i"),Mh=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}(),Ah=-1,Ch={pvr:"extCompressedTexturePVRTC",dxt:"extCompressedTextureS3TC",etc2:"extCompressedTextureETC",etc1:"extCompressedTextureETC1",basis:"canvas"},Eh=["pvr","dxt","etc2","etc1","basis"],Ph=function(e){function t(t,i,n,s,r){var a;return(a=e.call(this)||this)._id=Ah--,a.name=t||"",a.type=i,a.tags=new te(Q(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}Z(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&&!wh.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=y.getDirectory(this.file.url);return y.join(t,e)},i.getLocalizedAssetId=function(e){return e=xh(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.resource?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)},Y(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)||tn(),r=null==s?void 0:s.graphicsDevice;if(r)for(var a=function(i,n){var a=Eh[i];if(e.variants[a]&&r[Ch[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=Eh.length;o0&&o(n,Float32Array,1),s.length>0&&o(s,Uint16Array,65535),r.length>0&&o(r,Uint8Array,255)}(y),y.unlock(),y},Wh=new we,Hh=new me,Xh=function(e,t,i,n,s,r,a){var o=[];return t.primitives.forEach((function(h){var l,c,u,d=null,f=!0;if(h.hasOwnProperty("extensions")){var p=h.extensions;if(p.hasOwnProperty("KHR_draco_mesh_compression")){var m=window.DracoDecoderModule;if(m){var _=p.KHR_draco_mesh_compression;if(_.hasOwnProperty("attributes")){var g=n[_.bufferView],v=new m.DecoderBuffer;v.Init(g,g.length);var y,x,b=new m.Decoder,S=b.GetEncodedGeometryType(v);switch(S){case m.POINT_CLOUD:l=0,y=new m.PointCloud,x=b.DecodeBufferToPointCloud(v,y);break;case m.TRIANGULAR_MESH:l=4,y=new m.Mesh,x=b.DecodeBufferToMesh(v,y);break;case m.INVALID_GEOMETRY_TYPE:}if(!x||!x.ok()||0==y.ptr)return void s("Failed to decode draco compressed asset: "+(x?x.error_msg():"Mesh asset - invalid draco compressed geometry type: "+S));var T=y.num_faces();if(S===m.TRIANGULAR_MESH){var w=y.num_points()>65535,M=(u=3*T)*(w?4:2),A=m._malloc(M);w?(b.GetTrianglesUInt32Array(y,M,A),d=new Uint32Array(m.HEAPU32.buffer,A,u).slice()):(b.GetTrianglesUInt16Array(y,M,A),d=new Uint16Array(m.HEAPU16.buffer,A,u).slice()),m._free(A)}c=function(e,t,i,n,s,r,a){var o=t.num_points(),h=function(e){var i,r,a,h,l=n.GetAttributeByUniqueId(t,e),c=o*l.num_components();switch(l.data_type()){case s.DT_UINT8:h=1,a=1,i=s._malloc(c*a),n.GetAttributeDataArrayForAllPoints(t,l,s.DT_UINT8,c*a,i),r=new Uint8Array(s.HEAPU8.buffer,i,c).slice();break;case s.DT_UINT16:h=3,a=2,i=s._malloc(c*a),n.GetAttributeDataArrayForAllPoints(t,l,s.DT_UINT16,c*a,i),r=new Uint16Array(s.HEAPU16.buffer,i,c).slice();break;case s.DT_FLOAT32:default:h=6,a=4,i=s._malloc(c*a),n.GetAttributeDataArrayForAllPoints(t,l,s.DT_FLOAT32,c*a,i),r=new Float32Array(s.HEAPF32.buffer,i,c).slice()}return s._free(i),{values:r,numComponents:l.num_components(),componentSizeInBytes:a,storageType:h,normalized:l.normalized()}},l={},c=i.attributes;for(var u in c)if(c.hasOwnProperty(u)&&Oh.hasOwnProperty(u)){var d=Oh[u],f=h(c[u]),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(ut)||Uh(l,r),Gh(e,l,a)}(e,y,_,b,m,d,r),m.destroy(y),m.destroy(b),m.destroy(v),f=!1}}}}c||(d=h.hasOwnProperty("indices")?Bh(i[h.indices],n,!0):null,c=function(e,t,i,n,s,r,a){var o={},h=[];for(var l in t)t.hasOwnProperty(l)&&Oh.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=Bh(p,s),_=s[p.bufferView],g=Oh[f],v=Lh(p.type)*kh(p.componentType),y=_.hasOwnProperty("byteStride")?_.byteStride:v;d[g]={buffer:m.buffer,size:v,offset:m.byteOffset,stride:y,count:p.count,components:Lh(p.type),type:Dh(p.componentType),normalize:p.normalized}}d.hasOwnProperty(ut)||Uh(d,i),u=Gh(e,d,r),a[c]=u}return u}(e,h.attributes,d,i,n,r,a),l=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:return 4;case 5:return 5;case 6:return 6;default:return 4}}(h));var C=null;if(c){if((C=new ms(e)).vertexBuffer=c,C.primitive[0].type=l,C.primitive[0].base=0,C.primitive[0].indexed=null!==d,null!==d){var E;2!==(E=d instanceof Uint8Array?0:d instanceof Uint16Array?1:2)||e.extUintElement||(E=1,d=new Uint16Array(d));var P=new rs(e,E,d.length,0,d);C.indexBuffer[0]=P,C.primitive[0].count=d.length}else C.primitive[0].count=c.numVertices;C.materialIndex=h.material;var I=i[h.attributes.POSITION];if(C.aabb=zh(I),f&&h.hasOwnProperty("targets")){var R=[];h.targets.forEach((function(e,s){var r={};e.hasOwnProperty("POSITION")&&(I=i[e.POSITION],r.deltaPositions=Nh(I,n),r.deltaPositionsType=6,r.aabb=zh(I)),e.hasOwnProperty("NORMAL")&&(I=i[e.NORMAL],r.deltaNormals=Nh(I,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.push(new $a(r))})),C.morph=new ja(R,e)}}o.push(C)})),o},qh=function(e,t,i){var n,s,r=["#ifdef MAPFLOAT","uniform float material_shininess;","#endif","","#ifdef MAPTEXTURE","uniform sampler2D texture_glossMap;","#endif","","void getGlossiness() {"," dGlossiness = 1.0;","","#ifdef MAPFLOAT"," dGlossiness *= material_shininess;","#endif","","#ifdef MAPTEXTURE"," dGlossiness *= texture2D(texture_glossMap, $UV).$CH;","#endif","","#ifdef MAPVERTEX"," dGlossiness *= saturate(vVertexColor.$VC);","#endif",""," dGlossiness = 1.0 - dGlossiness;",""," dGlossiness += 0.0000001;","}"].join("\n"),a=["#ifdef MAPCOLOR","uniform vec3 material_specular;","#endif","","#ifdef MAPTEXTURE","uniform sampler2D texture_specularMap;","#endif","","void getSpecularity() {"," dSpecularity = vec3(1.0);",""," #ifdef MAPCOLOR"," dSpecularity *= material_specular;"," #endif",""," #ifdef MAPTEXTURE"," vec3 srgb = texture2D(texture_specularMap, $UV).$CH;"," dSpecularity *= vec3(pow(srgb.r, 2.2), pow(srgb.g, 2.2), pow(srgb.b, 2.2));"," #endif",""," #ifdef MAPVERTEX"," dSpecularity *= saturate(vVertexColor.$VC);"," #endif","}"].join("\n"),o=["#ifdef MAPFLOAT","uniform float material_clearCoatGlossiness;","#endif","","#ifdef MAPTEXTURE","uniform sampler2D texture_clearCoatGlossMap;","#endif","","void getClearCoatGlossiness() {"," ccGlossiness = 1.0;","","#ifdef MAPFLOAT"," ccGlossiness *= material_clearCoatGlossiness;","#endif","","#ifdef MAPTEXTURE"," ccGlossiness *= texture2D(texture_clearCoatGlossMap, $UV).$CH;","#endif","","#ifdef MAPVERTEX"," ccGlossiness *= saturate(vVertexColor.$VC);","#endif",""," ccGlossiness = 1.0 - ccGlossiness;",""," ccGlossiness += 0.0000001;","}"].join("\n"),h=[0,0],l=[1,1],c=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")&&(Wh.data.set(e.matrix),Wh.getTranslation(Hh),i.setLocalPosition(Hh),Wh.getEulerAngles(Hh),i.setLocalEulerAngles(Hh),Wh.getScale(Hh),i.setLocalScale(Hh)),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},Yh=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*he.RAD_TO_DEG,n.aspectRatio&&(s.aspectRatioMode=1,s.aspectRatio=n.aspectRatio));var r=new Og(e.name);return r.addComponent("camera",s),r},Kh=function(e,t){var i={enabled:!1,type:"point"===e.type?"omni":e.type,color:e.hasOwnProperty("color")?new ue(e.color):ue.WHITE,range:e.hasOwnProperty("range")?e.range:Number.MAX_VALUE,falloffMode:1,intensity:e.hasOwnProperty("intensity")?he.clamp(e.intensity,0,2):1};e.hasOwnProperty("spot")&&(i.innerConeAngle=e.spot.hasOwnProperty("innerConeAngle")?e.spot.innerConeAngle*he.RAD_TO_DEG:0,i.outerConeAngle=e.spot.hasOwnProperty("outerConeAngle")?e.spot.outerConeAngle*he.RAD_TO_DEG:Math.PI/4);var n=new Og(t.name);return n.rotateLocal(90,0,0),n.addComponent("light",i),n},Zh=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=Bh(i[d],n,!0),p=[];for(a=0;a0){var s=i&&i.camera&&i.camera.preprocess,r=i&&i.camera&&i.camera.process||Yh,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=$h(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||qh,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,t,i,n,s){if(!t.hasOwnProperty("meshes")||0===t.meshes.length||!t.hasOwnProperty("accessors")||0===t.accessors.length||!t.hasOwnProperty("bufferViews")||0===t.bufferViews.length)return[];var r={};return t.meshes.map((function(a){return Xh(e,a,t.accessors,i,n,s,r)}))}(e,t,i,r,h),_=Zh(e,t,l,i),g=[],v=0;vi.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})},nl=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;c0,maxRetries:this.maxRetries};(e.load.startsWith("blob:")||e.load.startsWith("data:"))&&(".glb"===y.getExtension(e.original).toLowerCase()?i.responseType=le.ResponseType.ARRAY_BUFFER:i.responseType=le.ResponseType.JSON),ce.get(e.load,i,(function(i,n){i?t("Error loading animation resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){if(".glb"===y.getExtension(e).toLowerCase()){var i=sl.parse("filename.glb",t,null);if(i){var n=i.animations;return i.destroy(),n}return null}return this["_parseAnimationV"+t.animation.version](t)},t._parseAnimationV3=function(e){var t=e.animation,i=new oh;i.name=t.name,i.duration=t.duration;for(var n=0;n0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=le.ResponseType.JSON),ce.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 uh(1,e)})),r=t.outputs.map((function(e){return new uh(e.components,e.data)})),a=t.curves.map((function(e){return new ch([e.path],e.inputIndex,e.outputIndex,e.interpolation)}));return new fh(i,n,s,r,a)},e}(),ol=function(){function e(e){var t;if(this._layers=[],this._parameters={},Array.isArray(e.layers))this._layers=e.layers;else for(var i in e.layers){var n=e.layers[i],s={name:n.name,states:[],transitions:[]};for(t=0;t0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=le.ResponseType.JSON),ce.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 ol(t)},e}(),ll=function(){function e(e){e instanceof Audio?this.audio=e:this.buffer=e}return Y(e,[{key:"duration",get:function(){var e=0;return this.buffer?e=this.buffer.duration:this.audio&&(e=this.audio.duration),e||0}}]),e}(),cl=function(){if("undefined"==typeof window)return!1;var e=window.navigator.userAgent,t=e.indexOf("MSIE ");if(t>0)return parseInt(e.substring(t+5,e.indexOf(".",t)),10);if(e.indexOf("Trident/")>0){var i=e.indexOf("rv:");return parseInt(e.substring(i+3,e.indexOf(".",i)),10)}return!1}(),ul={".ogg":"audio/ogg",".mp3":"audio/mpeg",".wav":"audio/x-wav",".mp4a":"audio/mp4",".m4a":"audio/mp4",".mp4":"audio/mp4",".aac":"audio/aac"},dl=function(){function e(e){this.manager=e,this.maxRetries=0}var t=e.prototype;return t._isSupported=function(e){var t=y.getExtension(e);return!!ul[t]},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 ll(e))}),i)}else i(null)},t.open=function(e,t){return t},t._createSound=function(e,t,i){if(Zo()){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=le.ResponseType.ARRAY_BUFFER),ce.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")}cl&&document.body.appendChild(r);r.onerror=function(){r.onerror=null,cl&&document.body.removeChild(r),i()},r.addEventListener("canplaythrough",(function e(){r.removeEventListener("canplaythrough",e),cl&&document.body.removeChild(r),t(r)})),r.src=e}},e}(),fl=function(){function e(){this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),ce.get(e.load,{responseType:le.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}(),pl=function(){function e(e){this._blobUrls={};for(var t=0,i=e.length;t=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 _l=null;var gl=function(){function e(e){this._requestId=0,this._pendingRequests={},this._filenamePrefix=e,this._worker=new Worker(function(){if(!_l){var e="("+ml.toString()+")(true)\n\n",t=new Blob([e],{type:"application/javascript"});_l=URL.createObjectURL(t)}return _l}()),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,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(D.workers)i._worker||(i._worker=new gl(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 Th(e).untar(i._assets.prefix);t(null,n)}},t.open=function(e,t){return new pl(t)},t.patch=function(e,t){},e}(),yl=function(e){function t(t,i){var n;return(n=e.call(this)||this).skin=t,n.skinInstance=i,n}return Z(t,e),t}(us),xl=function(){function e(){}return e.createCachedSkinedInstance=function(t,i,n){var s=e.getCachedSkinInstance(t,i);return s||((s=new Os(t)).resolve(i,n),e.addCachedSkinInstance(t,i,s)),s},e.getCachedSkinInstance=function(t,i){var n=null,s=e._skinInstanceCache.get(i);if(s){var r=s.find((function(e){return e.skin===t}));r&&(r.incRefCount(),n=r.skinInstance)}return n},e.addCachedSkinInstance=function(t,i,n){var s=e._skinInstanceCache.get(i);s||(s=[],e._skinInstanceCache.set(i,s));var r=s.find((function(e){return e.skin===t}));r||(r=new yl(t,n),s.push(r)),r.incRefCount()},e.removeCachedSkinInstance=function(t){if(t){var i=t.rootBone;if(i){var n=e._skinInstanceCache.get(i);if(n){var s=n.findIndex((function(e){return e.skinInstance===t}));if(s>=0){var r=n[s];r.decRefCount(),0===r.getRefCount()&&(n.splice(s,1),n.length||e._skinInstanceCache.delete(i),t&&(t.destroy(),r.skinInstance=null))}}}}},e}();xl._skinInstanceCache=new Map;var bl=function(){function e(e){this.data=e,this._model=null,this.renders=[],this.materials=[],this.textures=[],this.animations=[],this.registry=null,this._defaultMaterial=null,this._assetName=null,this._assets=null}e.createAsset=function(e,t,i,n){var s=new Ph(e+"/"+t+"/"+n,t,{url:""});return s.resource=i,s.loaded=!0,s};var t=e.prototype;return t.instantiateModelEntity=function(e){var t=new Og;return t.addComponent("model",Object.assign({type:"asset",asset:this.model},e)),t},t.instantiateRenderEntity=function(t){for(var i,n=this._defaultMaterial,s=[],r=function(e,t,i,r,a,o){var h=void 0===i.materialIndex?n:r[i.materialIndex],l=new ar(i,h);return i.morph&&(l.morphInstance=new Ka(i.morph)),o.hasOwnProperty("skin")&&s.push({meshInstance:l,rootBone:e,entity:t}),l},a=function e(i,n,s){var a=new Og;n._cloneInternal(a),i||(i=a);for(var o=null,h=0;h=0?e.split("?")[0]:e},t.load=function(e,t,i){var n=this;"string"==typeof e&&(e={load:e,original:e}),Ph.fetchArrayBuffer(e.load,(function(s,r){s?t(s):sl.parseAsync(n._getUrlWithoutParams(e.original),y.extractPath(e.load),r,n._device,i.registry,i.options,(function(e,i){e?t(e):t(null,new bl(i))}))}),i,this.maxRetries)},t.open=function(e,t,i){return t},t.patch=function(e,t){var i=e.resource,n=i&&i.data;if(n){var s,r=function(i,n,s){var r=bl.createAsset(e.name,i,n,s);return t.add(r),r},a=[];for(s=0;s0,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 wl=function(){function e(e,t,i){this._device=e,this._registry=t,this._loader=i}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?Wt:Gt: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){var u=[n._levels[r]];if(0===r&&this._device.useTexCubeLod)for(s=1;s>r),cubemap:!0,type:c()||n.type,width:n.width>>r,height:n.height>>r,format:n.format,levels:u,fixCubemapSeams:!0,addressU:1,addressV:1});l[r+1]=d}var f=i.slice(1);if(e.loaded&&this.cmpArrays(f,o.slice(1)))l[0]=h[0]||null;else if(-1===f.indexOf(null)){var p=f.map((function(e){return e.resource})),m=[];for(s=0;s0,maxRetries:this.maxRetries},(function(i,s){if(i)t("Error loading font resource: "+e.original+" ["+i+"]");else{var r=Pl(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=Pl(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)}))},Bl=function(){function e(e){this._app=e,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){Fl(e,this.maxRetries,t)},t.open=function(e,t){this._app.systems.script.preloading=!0;var i=new Ol(this._app,!1).parse(t);return this._app.systems.script.preloading=!1,i},e}(),Nl=function(){function e(){this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),ce.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}(),zl=function(){function 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};e.load.startsWith("blob:")&&(i.responseType=le.ResponseType.JSON),ce.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}(),Ul=function(){function e(e,t,i,n,s){this.propertyName=e,this.parent=t,this._scope=s,this._registry=i,this.id=null,this.url=null,this.asset=null,this._onAssetLoad=n.load,this._onAssetAdd=n.add,this._onAssetRemove=n.remove,this._onAssetUnload=n.unload}var t=e.prototype;return t._bind=function(){this.id&&(this._onAssetLoad&&this._registry.on("load:"+this.id,this._onLoad,this),this._onAssetAdd&&this._registry.once("add:"+this.id,this._onAdd,this),this._onAssetRemove&&this._registry.on("remove:"+this.id,this._onRemove,this),this._onAssetUnload&&this._registry.on("unload:"+this.id,this._onUnload,this)),this.url&&(this._onAssetLoad&&this._registry.on("load:url:"+this.url,this._onLoad,this),this._onAssetAdd&&this._registry.once("add:url:"+this.url,this._onAdd,this),this._onAssetRemove&&this._registry.on("remove:url:"+this.url,this._onRemove,this))},t._unbind=function(){this.id&&(this._onAssetLoad&&this._registry.off("load:"+this.id,this._onLoad,this),this._onAssetAdd&&this._registry.off("add:"+this.id,this._onAdd,this),this._onAssetRemove&&this._registry.off("remove:"+this.id,this._onRemove,this),this._onAssetUnload&&this._registry.off("unload:"+this.id,this._onUnload,this)),this.url&&(this._onAssetLoad&&this._registry.off("load:"+this.url,this._onLoad,this),this._onAssetAdd&&this._registry.off("add:"+this.url,this._onAdd,this),this._onAssetRemove&&this._registry.off("remove:"+this.url,this._onRemove,this))},t._onLoad=function(e){this._onAssetLoad.call(this._scope,this.propertyName,this.parent,e)},t._onAdd=function(e){this.asset=e,this._onAssetAdd.call(this._scope,this.propertyName,this.parent,e)},t._onRemove=function(e){this._onAssetRemove.call(this._scope,this.propertyName,this.parent,e),this.asset=null},t._onUnload=function(e){this._onAssetUnload.call(this._scope,this.propertyName,this.parent,e)},Y(e,[{key:"id",get:function(){return this._id},set:function(e){if(this.url)throw Error("Can't set id and url");this._unbind(),this._id=e,this.asset=this._registry.get(this._id),this._bind()}},{key:"url",get:function(){return this._url},set:function(e){if(this.id)throw Error("Can't set id and url");this._unbind(),this._url=e,this.asset=this._registry.getByUrl(this._url),this._bind()}}]),e}();function Vl(){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]),shadingModel:this._createEnumValidator([0,1])}}Vl.prototype.setInvalid=function(e,t){this.valid=!1,this.removeInvalid&&delete t[e]},Vl.prototype.validate=function(e){var t,i,n=Mn,s="path"===e.mappingFormat;for(var r in e)if(t=n[r])if(t.startsWith("enum")){var a=t.split(":")[1];this.enumValidators[a]&&(this.enumValidators[a](e[r])||this.setInvalid(r,e))}else if("number"===t)"number"!=typeof e[r]&&this.setInvalid(r,e);else if("boolean"===t)"boolean"!=typeof e[r]&&this.setInvalid(r,e);else if("string"===t)"string"!=typeof e[r]&&this.setInvalid(r,e);else if("vec2"===t)e[r]instanceof Array&&2===e[r].length||this.setInvalid(r,e);else if("rgb"===t)e[r]instanceof Array&&3===e[r].length||this.setInvalid(r,e);else if("texture"===t)s?"string"==typeof e[r]||e[null===r]||e[r]instanceof Vi||this.setInvalid(r,e):"number"!=typeof e[r]&&null!==e[r]&&(e[r]instanceof Vi||this.setInvalid(r,e));else if("boundingbox"===t)e[r].center&&e[r].center instanceof Array&&3===e[r].center.length||this.setInvalid(r,e),e[r].halfExtents&&e[r].halfExtents instanceof Array&&3===e[r].halfExtents.length||this.setInvalid(r,e);else if("cubemap"===t)"number"!=typeof e[r]&&null!==e[r]&&void 0!==e[r]&&(e[r]instanceof Vi&&e[r].cubemap||this.setInvalid(r,e));else if("chunks"===t){var o=Object.keys(e[r]);for(i=0;i=0}};var Gl=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 Rn;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=K({},t.chunks)),t){var n=Mn[i],s=t[i];if("vec2"===n)e[i]=new ge(s[0],s[1]);else if("rgb"===n)e[i]=new ue(s[0],s[1],s[2]);else if("texture"===n)s instanceof Vi?e[i]=s:e[i]instanceof Vi&&"number"==typeof s&&s>0||(e[i]=null);else if("cubemap"===n)s instanceof Vi?e[i]=s:e[i]instanceof Vi&&"number"==typeof s&&s>0||(e[i]=null);else if("boundingbox"===n){var r=new me(s.center[0],s.center[1],s.center[2]),a=new me(s.halfExtents[0],s.halfExtents[1],s.halfExtents[2]);e[i]=new Re(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 Vi(this._device,{width:2,height:2,format:7}),this._placeholderTextures[t].name="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=Wl[e];return this._placeholderTextures[t]},t._assignPlaceholderTexture=function(e,t){t.resource[e]=this._getPlaceholderTexture(e,t)},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],7===i.length&&(t.resource.prefilteredCubeMap128=i[1],t.resource.prefilteredCubeMap64=i[2],t.resource.prefilteredCubeMap32=i[3],t.resource.prefilteredCubeMap16=i[4],t.resource.prefilteredCubeMap8=i[5],t.resource.prefilteredCubeMap4=i[6])},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=An;for(i=0;i0){var u=i.blendIndices.data[4*l+c],d=!0;for(r=0;rn)return!1;for(s=0;s=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===m.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===m.originalMesh&&(u.splice(r,1),t&&t.splice(r,1))}!function(e){var t,i=e.vertices,n=e.skins,s=e.meshes,r=e.meshInstances;for(t=0;t0&&Yl(s,null,this._device.getBoneLimit());for(i=0;i0&&(h>65535&&this._device.extUintElement?(s=new rs(this._device,2,a),r=new Uint32Array(s.lock())):(s=new rs(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"===y.getExtension(e.original).toLowerCase()?i.responseType=le.ResponseType.ARRAY_BUFFER:i.responseType=le.ResponseType.JSON),ce.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?console.assert("Script Ordering Error. Contact support@playcanvas.com"):e._types.push(t)};var t=e.prototype;return t.load=function(t,i){"string"==typeof t&&(t={load:t,original:t});var n=this;oc.app=this._app,this._loadScript(t.load,function(t,s,r){if(t)i(t);else if(oc.legacy){var a=null;e._types.length&&(a=e._types.pop()),a?this._scripts[s]=a:a=null,i(null,a,r)}else{for(var o={},h=0;h0,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}(),cc=[0,0,1,0,0,1,0,0,1,0,0,1],uc=[0,1,3,2,3,1],dc=function(e){function t(t,i){var n;return(n=e.call(this)||this)._device=t,n._pixelsPerUnit=i&&void 0!==i.pixelsPerUnit?i.pixelsPerUnit:1,n._renderMode=i&&void 0!==i.renderMode?i.renderMode:0,n._atlas=i&&void 0!==i.atlas?i.atlas:null,n._frameKeys=i&&void 0!==i.frameKeys?i.frameKeys:null,n._meshes=[],n._updatingProperties=!1,n._meshesDirty=!1,n._atlas&&n._frameKeys&&n._createMeshes(),n}Z(t,e);var i=t.prototype;return i._createMeshes=function(){for(var e=this._meshes.length,t=0;t0,maxRetries:this.maxRetries},(function(e,i){e?t(e):t(null,i)}))},t.open=function(e,t){var i=new dc(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,fc,e),this._assets.on("load:"+e.data.textureAtlasAsset,fc,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,mc,e),this._assets.on("add:"+e.data.textureAtlasAsset,mc,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,fc,e),this._assets.off("add:"+n.textureAtlasAsset,mc,e))},e}(),gc=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 Ol(this._app,!0);this._templateRoot=e.parse(this._data)},e}(),vc=function(){function e(e){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};ce.get(e.load,i,(function(i,n){i?t("Error requesting template: "+e.original):t(i,n)}))},t.open=function(e,t){return new gc(this._app,t)},e}(),yc=function(){function e(){this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),ce.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}(),xc=function(e){function t(){var t;return(t=e.call(this)||this)._texture=null,t._frames=null,t}Z(t,e);var i=t.prototype;return i.setFrame=function(e,t){var i=this._frames[e];i?(i.rect.copy(t.rect),i.pivot.copy(t.pivot),i.border.copy(t.border)):(i={rect:t.rect.clone(),pivot:t.pivot.clone(),border:t.border.clone()},this._frames[e]=i),this.fire("set:frame",e.toString(),i)},i.removeFrame=function(e){var t=this._frames[e];t&&(delete this._frames[e],this.fire("remove:frame",e.toString(),t))},i.destroy=function(){this._texture&&this._texture.destroy()},Y(t,[{key:"texture",get:function(){return this._texture},set:function(e){this._texture=e,this.fire("set:texture",e)}},{key:"frames",get:function(){return this._frames},set:function(e){this._frames=e,this.fire("set:frames",e)}}]),t}(_),bc={repeat:0,clamp:1,mirror:2},Sc={nearest:0,linear:1,nearest_mip_nearest:2,linear_mip_nearest:4,nearest_mip_linear:3,linear_mip_linear:5},Tc=/^data\.frames\.(\d+)$/,wc=function(){function e(e){this._loader=e,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"!==y.getExtension(e.original))return n.load(e,t);ce.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 xc;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){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!==Sc[e.data.minfilter]&&(i.minFilter=Sc[e.data.minfilter]),e.data.hasOwnProperty("magfilter")&&i.magFilter!==Sc[e.data.magfilter]&&(i.magFilter=Sc[e.data.magfilter]),e.data.hasOwnProperty("addressu")&&i.addressU!==bc[e.data.addressu]&&(i.addressU=bc[e.data.addressu]),e.data.hasOwnProperty("addressv")&&i.addressV!==bc[e.data.addressv]&&(i.addressV=bc[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?Wt:Gt;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 ve(a.rect),pivot:new ge(a.pivot),border:new ve(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 ve(n.rect),pivot:new ge(n.pivot),border:new ve(n.border)};e.resource.frames=s}else{var a=t.match(Tc);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 ve(i.rect),pivot:new ge(i.pivot),border:new ve(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}();function Mc(){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,T=27,w=28,M=29,A=30,C=7,E=3,P=5,I=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 T;case l:return w;case c:return M;case u:return A;case d:return C;case f:return E;case p:return P}},R=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},k=function(){return"undefined"!=typeof performance?performance.now():0},O=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&&++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};ce.get(e,s,(function(e,t){e?n(e):createImageBitmap(t,{premultiplyAlpha:"none"}).then((function(e){n(null,e)})).catch((function(e){n(e)}))}))},e}(),zc=[1481919403,3140563232,169478669],Uc={33776:8,33778:9,33779:et,36196:ot,37492:22,37496:23,35840:26,35841:ht,35842:27,35843:lt,32849:6,32856:7,35905:19,35907:20,35898:18,34843:tt,34842:it};var Vc=function(){function e(e){this.maxRetries=0}var t=e.prototype;return t.load=function(e,t,i){Ph.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 Vi(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(zc[0]!==t[0]||zc[1]!==t[1]||zc[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=Uc[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}(),Gc=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.readU8=function(){return this.dataView.getUint8(this.offset++)},t.readU16=function(){return this.dataView.getUint16(this._inc(2),!0)},t.readU32=function(){return this.dataView.getUint32(this._inc(4),!0)},t.readU64=function(){return this.dataView.getBigUint64(this._inc(8),!0)},t.readU32be=function(){return this.dataView.getUint32(this._inc(4),!1)},t.readArray=function(e){for(var t=0;t=e.byteLength);){var i=String.fromCharCode(this.readU8());if("\n"===i)break;t+=i}return t},Y(e,[{key:"remainingBytes",get:function(){return this.dataView.byteLength-this.offset}}]),e}(),Wc=166,Hc=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;Ph.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 Vi(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 Gc(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;l32767)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 this._error("radiance has invalid scanline data"),null;for(c=e.readU8(),o=0;ot)return this._error("radiance has invalid scanline data"),null;for(o=0;o=0?e.split("?")[0]:e},t._getParser=function(e){var t=y.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 Vi(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!==st||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=Yc[n.minfilter]),n.hasOwnProperty("magfilter")&&(i.magFilter=Yc[n.magfilter]),i.cubemap||(n.hasOwnProperty("addressu")&&(i.addressU=jc[n.addressu]),n.hasOwnProperty("addressv")&&(i.addressV=jc[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=Kc[n.type]:n.hasOwnProperty("rgbm")&&n.rgbm?i.type=Wt:e.file&&0!=(8&e.file.opt)&&(i.type=Xt)}},Y(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}(),Qc=function(){function e(e){void 0===e&&(e=null),this._index={},this._key=e}var t=e.prototype;return t.addItem=function(e){for(var t,i=ee(e.tags._list);!(t=i()).done;){var n=t.value;this.add(n,e)}},t.removeItem=function(e){for(var t,i=ee(e.tags._list);!(t=i()).done;){var n=t.value;this.remove(n,e)}},t.add=function(e,t){this._index[e]&&-1!==this._index[e].list.indexOf(t)||(this._index[e]||(this._index[e]={list:[]},this._key&&(this._index[e].keys={})),this._index[e].list.push(t),this._key&&(this._index[e].keys[t[this._key]]=t))},t.remove=function(e,t){if(this._index[e]&&(!this._key||this._index[e].keys[t[this._key]])){var i=this._index[e].list.indexOf(t);-1!==i&&(this._index[e].list.splice(i,1),this._key&&delete this._index[e].keys[t[this._key]],0===this._index[e].list.length&&delete this._index[e])}},t.find=function(e){for(var t,i,n,s,r,a=this,o={},h=[],l=function(e,t){return a._index[e].list.length-a._index[t].list.length},c=0;c0?i[0]:null},t}(_),eu=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;tthis.views.length)for(var r=0;r<=s-this.views.length;r++){var a=this.viewsPool.pop();a||(a={viewport:new ve,projMat:new we,viewMat:new we,viewOffMat:new we,viewInvMat:new we,viewInvOffMat:new we,projViewOffMat:new we,viewMat3:new _e,position:new Float32Array(3),rotation:new Me}),this.views.push(a)}else if(s<=this.views.length)for(var o=0;o=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,s=i._data,r=i._components,a=this._p0*r;if(0===t)for(n=0;nthis.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},Y(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}(),id=function(){function e(e){this._binder=e,this._clips=[],this._inputs=[],this._outputs=[],this._targets={}}e._dot=function(e,t){for(var i=e.length,n=0,s=0;s0){i=1/Math.sqrt(i);for(var n=t.length,s=0;s0&&(a=1/Math.sqrt(a)),s=0;s0;)this.removeClip(0)},t.findClip=function(e){for(var t=this._clips,i=0;i0&&c._update(t),f>=1)for(n=0;n0)for(n=0;n0){return e.createAnimTarget((function(e){for(var t=0;tc)for(this._time=this.looping?0:c,t=0;t=0?1:-1;for(t=0;t=0;f+=d)if(a=s[f],o=s[f+1],a.time<=this._time&&o.time>=this._time){h=(this._time-a.time)/(o.time-a.time),r._pos.lerp(a.position,o.position,h),r._quat.slerp(a.rotation,o.rotation,h),r._scale.lerp(a.scale,o.scale,h),r._written=!0,this._currKeyIndices[n]=f,u=!0;break}(1===s.length||!u&&0===this._time&&this.looping)&&(r._pos.copy(s[0].position),r._quat.copy(s[0].rotation),r._scale.copy(s[0].scale),r._written=!0)}}},t.blend=function(e,t,i){for(var n=this._interpolatedKeys.length,s=0;s0&&i.prevAnim,i.blending&&(i.blend=0,i.blendSpeed=1/t),i.skeleton&&(i.blending?(i.fromSkel.animation=n,i.fromSkel.addTime(i.skeleton._time),i.toSkel.animation=s):i.skeleton.animation=s),i.animEvaluator){var r=i.animEvaluator;if(i.blending)for(;r.clips.length>1;)r.removeClip(0);else i.animEvaluator.removeClips();var a=new td(i.animations[i.currAnim],0,1,!0,i.loop);a.name=i.currAnim,a.blendWeight=i.blending?0:1,a.reset(),i.animEvaluator.addClip(a)}}i.playing=!0}}},i.getAnimation=function(e){return this.data.animations[e]},i.setModel=function(e){var t=this.data;e!==t.model&&(this._resetAnimationController(),t.model=e,t.animations&&t.currAnim&&t.animations[t.currAnim]&&this.play(t.currAnim))},i._resetAnimationController=function(){var e=this.data;e.skeleton=null,e.fromSkel=null,e.toSkel=null,e.animEvaluator=null},i._createAnimationController=function(){var e=this.data,t=e.model,i=e.animations,n=!1,s=!1;for(var r in i){if(i.hasOwnProperty(r))i[r].constructor===fh?s=!0:n=!0}var a=t.getGraph();n?(e.fromSkel=new ad(a),e.toSkel=new ad(a),e.skeleton=new ad(a),e.skeleton.looping=e.loop,e.skeleton.setGraph(a)):s&&(e.animEvaluator=new id(new sd(this.entity)))},i.loadAnimationAssets=function(e){if(e&&e.length){var t,i=this,n=this.system.app.assets,s=e.length,r=function(e){if(e.resources.length>1)for(var t=0;t1){if(n&&n.length>1)for(s=0;s1)for(s=0;s1)for(s=0;s1)for(var t=0;t0)return t[t.length-1].time}return 0},set:function(e){var t=this.data;if(t.skeleton){var i=t.skeleton;i.currentTime=e,i.addTime(0),i.updateGraph()}if(t.animEvaluator)for(var n=t.animEvaluator,s=0;s=1&&(s.blend=1)),s.playing){var r=s.skeleton;if(null!==r&&null!==s.model){if(s.blending)r.blend(s.fromSkel,s.toSkel,s.blend);else{var a=e*s.speed;r.addTime(a),(s.speed>0&&r._time===r._animation.duration&&!s.loop||s.speed<0&&0===r._time&&!s.loop)&&(s.playing=!1)}s.blending&&1===s.blend&&(r.animation=s.toSkel._animation),r.updateGraph()}}var o=s.animEvaluator;if(o){for(var h=0;h1&&(o.clips[1].blendWeight=s.blend),o.update(e)}s.blending&&1===s.blend&&(s.blending=!1)}}},t}($u);Zu._buildAccessors(od.prototype,ld);var ud=function(){function e(e,t,i,n,s){void 0===s&&(s=1),this._state=e,this._parent=t,this._name=i,Array.isArray(n)?(this._point=new ge(n[0],n[1]),this._pointLength=this._point.length()):(this._point=n,this._pointLength=n),this._speed=s,this._weightedSpeed=1,this._weight=1,this._animTrack=null}return Y(e,[{key:"parent",get:function(){return this._parent}},{key:"name",get:function(){return this._name}},{key:"path",get:function(){return this._parent?this._parent.path+"."+this._name:this._name}},{key:"point",get:function(){return this._point}},{key:"pointLength",get:function(){return this._pointLength}},{key:"weight",get:function(){return this._parent?this._parent.weight*this._weight:this._weight},set:function(e){this._weight=e}},{key:"normalizedWeight",get:function(){var e=this._state.totalWeight;return 0===e?0:this.weight/e}},{key:"speed",get:function(){return this._weightedSpeed*this._speed}},{key:"absoluteSpeed",get:function(){return Math.abs(this._speed)}},{key:"weightedSpeed",get:function(){return this._weightedSpeed},set:function(e){this._weightedSpeed=e}},{key:"animTrack",get:function(){return this._animTrack},set:function(e){this._animTrack=e}}]),e}(),dd=function(e){function t(t,i,n,s,r,a,o,h,l){var c;(c=e.call(this,t,i,n,s)||this)._parameters=r,c._parameterValues=new Array(r.length),c._children=[],c._findParameter=l,c._syncAnimations=!1!==o,c._pointCache={};for(var u=0;u=0)this._animationList[n].animTrack=t;else{var s=this._getNodeFromPath(e);s.animTrack=t,this._animationList.push(s)}},Y(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!==ud?this._blendTree.getNodeCount():1}},{key:"playable",get:function(){return-1!==Nd.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(){var e,t=0;for(e=0;et&&(t=i.animTrack.duration)}return t}}]),e}(),Ud=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?gd: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 Y(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}(),Vd=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}))).sort((function(e,t){return e.priority"+t]=i),i},t._transitionHasConditionsMet=function(e){for(var t=!0,i=0;in.value;break;case Td:t=t&&s.value=n.value;break;case Md:t=t&&s.value<=n.value;break;case Ad:t=t&&s.value===n.value;break;case Cd:t=t&&s.value!==n.value}if(!t)return t}return t},t._findTransition=function(e,t){var i=[];if(e&&t)i.concat(this._findTransitionsBetweenStates(e,t));else if(this._isTransitioning)switch(this._transitionInterruptionSource){case vd:i=(i=i.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(Bd));break;case yd:i=(i=i.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Bd));break;case xd:i=(i=(i=i.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Bd));break;case bd:i=(i=(i=i.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(Bd))}else i=(i=i.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Bd));if((i=i.filter(function(e){if(e.to===this.activeStateName)return!1;if(e.hasExitTime){var t=this._getActiveStateProgressForTime(this._timeInStateBefore),i=this._getActiveStateProgressForTime(this._timeInState);if(e.exitTime<1&&this.activeState.loop&&(t-=Math.floor(t),i-=Math.floor(i)),!(e.exitTime>t&&e.exitTime<=i))return null}return this._transitionHasConditionsMet(e)}.bind(this))).length>0){var n=i[0];if(n.to===Fd){var s=this._findTransitionsFromState(Od)[0];n.to=s.to}return n}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 Ud({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 zd(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===Nd.indexOf(e)){var t=this._findState(e);if(t)return 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=Od,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=this._currTransitionTime/this._totalTransitionTime,a=0;a1){var h=t.length>2?this._resolvePath(e,t.slice(0,-1)):e,l=t[t.length-2];return function(e){n[s]=i(e),h[l]=n}}return function(e){n[s]=i(e)}},i._createAnimTargetForProperty=function(e,i,n){if(this.handlers&&"weights"===i[0])return this.handlers.weights(e);if(this.handlers&&"material"===i[0]&&2===i.length){var s=i[1];if(s.indexOf("Map")===s.length-3)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 ge:r=this._setter(e,i,t._packVec2),a="vector",o=2;break;case me:r=this._setter(e,i,t._packVec3),a="vector",o=3;break;case ve:r=this._setter(e,i,t._packVec4),a="vector",o=4;break;case ue:r=this._setter(e,i,t._packColor),a="vector",o=4;break;case Me:r=this._setter(e,i,t._packQuat),a="quaternion",o=4;break;default:return null}return-1!==i.indexOf("material")?new nd((function(t){r(t),e.material.update()}),a,o,n):new nd(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}(Zu),Zd=function(){this.enabled=!0},$d=["enabled"],Qd=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="anim",i.ComponentType=Kd,i.DataType=Zd,i.schema=$d,i.on("beforeremove",i.onBeforeRemove,Q(i)),$u.bind("animationUpdate",i.onAnimationUpdate,Q(i)),i}Z(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){e.prototype.initializeComponentData.call(this,t,i,$d);var s=["animationAssets","stateGraph","layers"];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.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={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};this.addComponent(t,i)},i.onBeforeRemove=function(e,t){t.onBeforeRemove()},t}($u);Zu._buildAccessors(Kd.prototype,$d);var Jd=function(e){function t(){return e.apply(this,arguments)||this}Z(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}(Zu),ef=function(){this.enabled=!0},tf=["enabled"],nf=function(e){function t(t,i){var n;return(n=e.call(this,t)||this).id="audiolistener",n.ComponentType=Jd,n.DataType=ef,n.schema=tf,n.manager=i,n.current=null,$u.bind("update",n.onUpdate,Q(n)),n}Z(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)}},t}($u);Zu._buildAccessors(Jd.prototype,tf);var sf=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this).on("set_assets",n.onSetAssets,Q(n)),n.on("set_loop",n.onSetLoop,Q(n)),n.on("set_volume",n.onSetVolume,Q(n)),n.on("set_pitch",n.onSetPitch,Q(n)),n.on("set_minDistance",n.onSetMinDistance,Q(n)),n.on("set_maxDistance",n.onSetMaxDistance,Q(n)),n.on("set_rollOffFactor",n.onSetRollOffFactor,Q(n)),n.on("set_distanceModel",n.onSetDistanceModel,Q(n)),n.on("set_3d",n.onSet3d,Q(n)),n}Z(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=[],r=i.length;if(t&&t.length)for(n=0;n1e-5){var i=this._tweenInfo.lerpColor;i.lerp(this._tweenInfo.from,this._tweenInfo.to,t),this._applyTintImmediately(new ue(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}(Zu);var gf,vf=function(){this.enabled=!0,this.active=!0,this.imageEntity=null,this.hitPadding=new ve,this.transitionMode=0,this.hoverTint=new ue(.75,.75,.75),this.pressedTint=new ue(.5,.5,.5),this.inactiveTint=new ue(.25,.25,.25),this.fadeDuration=0,this.hoverSpriteAsset=null,this.hoverSpriteFrame=0,this.pressedSpriteAsset=null,this.pressedSpriteFrame=0,this.inactiveSpriteAsset=null,this.inactiveSpriteFrame=0},yf=["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"],xf=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="button",i.ComponentType=_f,i.DataType=vf,i.schema=yf,i.on("beforeremove",i._onRemoveComponent,Q(i)),$u.bind("update",i.onUpdate,Q(i)),i}Z(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){e.prototype.initializeComponentData.call(this,t,i,yf)},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()},t}($u);Zu._buildAccessors(_f.prototype,yf);var bf=function(e,t){this.effect=e,this.inputTarget=t,this.outputTarget=null,this.name=e.constructor.name},Sf=function(){function e(e,t){var i=this;this.app=e,this.camera=t,this.destinationRenderTarget=null,this.effects=[],this.enabled=!1,this.depthTarget=null,this.renderTargetScale=1,this.resizeTimeout=null,this.resizeLast=0,this._resizeTimeoutCallback=function(){i.resizeRenderTargets()},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*this.renderTargetScale),s=Math.floor(i.w*this.app.graphicsDevice.height*this.renderTargetScale),r=new Vi(this.app.graphicsDevice,{format:e,width:n,height:s,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1});return r.name=t,r},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),a=this.app.graphicsDevice.supportsStencil,o=e?i.samples:1;return new Qn({colorBuffer:r,depth:e,stencil:a,samples:o})},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.setRenderTargetScale=function(e){this.renderTargetScale=e,this.resizeRenderTargets()},t.addEffect=function(e){var t=this.effects,i=0===t.length,n=this._createOffscreenTarget(i,e.hdr),s=new bf(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){var t,i,n=-1;for(t=0,i=this.effects.length;t=0&&(n>0?this.effects[n-1].outputTarget=n+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[n].inputTarget),this.effects.splice(n,1)),this.enabled&&e.needsDepthBuffer&&this._releaseDepthMap(),0===this.effects.length&&this.disable()},t._requestDepthMaps=function(){for(var e=0,t=this.effects.length;e100?this.resizeRenderTargets():this.resizeTimeout=setTimeout(this._resizeTimeoutCallback,100))},t.resizeRenderTargets=function(){this.resizeTimeout&&(clearTimeout(this.resizeTimeout),this.resizeTimeout=null),this.resizeLast=ie();for(var e=this.camera.rect,t=Math.floor(e.z*this.app.graphicsDevice.width*this.renderTargetScale),i=Math.floor(e.w*this.app.graphicsDevice.height*this.renderTargetScale),n=this.effects,s=0,r=n.length;s=0&&(this.cameras.splice(t,1),this.sortCamerasByPriority())},i.sortCamerasByPriority=function(){this.cameras.sort((function(e,t){return e.priority-t.priority}))},t}($u);Zu._buildAccessors(wf.prototype,Af);var Ef,Pf,If,Rf=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._compoundParent=null,n.entity.on("insert",n._onInsert,Q(n)),n.on("set_type",n.onSetType,Q(n)),n.on("set_halfExtents",n.onSetHalfExtents,Q(n)),n.on("set_radius",n.onSetRadius,Q(n)),n.on("set_height",n.onSetHeight,Q(n)),n.on("set_axis",n.onSetAxis,Q(n)),n.on("set_asset",n.onSetAsset,Q(n)),n.on("set_renderAsset",n.onSetRenderAsset,Q(n)),n.on("set_model",n.onSetModel,Q(n)),n.on("set_render",n.onSetRender,Q(n)),n}Z(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,s=this.system.app.assets;t&&(n=s.get(t))&&n.off("remove",this.onAssetRemoved,this),i&&(i instanceof Ph&&(this.data.asset=i.id),(n=s.get(this.data.asset))&&(n.off("remove",this.onAssetRemoved,this),n.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,s=this.system.app.assets;t&&(n=s.get(t))&&n.off("remove",this.onRenderAssetRemoved,this),i&&(i instanceof Ph&&(this.data.renderAsset=i.id),(n=s.get(this.data.renderAsset))&&(n.off("remove",this.onRenderAssetRemoved,this),n.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}(),zf=new we,Uf=new me,Vf=new Me,Gf=new Js,Wf=["enabled","type","halfExtents","radius","axis","height","asset","renderAsset","shape","model","render"],Hf=function(){function e(e){this.system=e}var t=e.prototype;return t.beforeInitialize=function(e,t){t.shape=null,t.model=new Za,t.model.graph=new Js},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 Nf(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){var i=this.system.app;e.rigidbody&&e.rigidbody.body&&e.rigidbody.disableSimulation(),e.trigger&&(e.trigger.destroy(),delete e.trigger),i.scene.containsModel(t.model)&&(i.root.removeChild(t.model.graph),i.scene.removeModel(t.model))},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}(),Xf=function(e){function t(){return e.apply(this,arguments)||this}return Z(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}(Hf),qf=function(e){function t(){return e.apply(this,arguments)||this}return Z(t,e),t.prototype.createPhysicalShape=function(e,t){if("undefined"!=typeof Ammo)return new Ammo.btSphereShape(t.radius)},t}(Hf),jf=function(e){function t(){return e.apply(this,arguments)||this}return Z(t,e),t.prototype.createPhysicalShape=function(e,t){var i=null,n=void 0!==t.axis?t.axis:1,s=t.radius||.5,r=Math.max((t.height||2)-2*s,0);if("undefined"!=typeof Ammo)switch(n){case 0:i=new Ammo.btCapsuleShapeX(s,r);break;case 1:i=new Ammo.btCapsuleShape(s,r);break;case 2:i=new Ammo.btCapsuleShapeZ(s,r)}return i},t}(Hf),Yf=function(e){function t(){return e.apply(this,arguments)||this}return Z(t,e),t.prototype.createPhysicalShape=function(e,t){var i=null,n=null,s=void 0!==t.axis?t.axis:1,r=void 0!==t.radius?t.radius:.5,a=void 0!==t.height?t.height:1;if("undefined"!=typeof Ammo)switch(s){case 0:i=new Ammo.btVector3(.5*a,r,r),n=new Ammo.btCylinderShapeX(i);break;case 1:i=new Ammo.btVector3(r,.5*a,r),n=new Ammo.btCylinderShape(i);break;case 2:i=new Ammo.btVector3(r,r,.5*a),n=new Ammo.btCylinderShapeZ(i)}return i&&Ammo.destroy(i),n},t}(Hf),Kf=function(e){function t(){return e.apply(this,arguments)||this}return Z(t,e),t.prototype.createPhysicalShape=function(e,t){var i=null,n=void 0!==t.axis?t.axis:1,s=void 0!==t.radius?t.radius:.5,r=void 0!==t.height?t.height:1;if("undefined"!=typeof Ammo)switch(n){case 0:i=new Ammo.btConeShapeX(s,r);break;case 1:i=new Ammo.btConeShape(s,r);break;case 2:i=new Ammo.btConeShapeZ(s,r)}return i},t}(Hf),Zf=function(e){function t(){return e.apply(this,arguments)||this}Z(t,e);var i=t.prototype;return i.beforeInitialize=function(e,t){},i.createAmmoMesh=function(e,t,i){var n,s;if(this.system._triMeshCache[e.id])n=this.system._triMeshCache[e.id];else{var r,a,o=e.vertexBuffer,h=o.getFormat();for(s=0;s=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?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"\\":switch(this._next(),this._cur){case"[":this._store();break;default:this._output("\\")}break;default:this._store()}},t._tag=function(){for(;;)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(op)},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 cp(e,t){for(var i in t)if(t.hasOwnProperty(i)){var n=t[i];n instanceof Object?(e.hasOwnProperty(i)||(e[i]={}),cp(e[i],t[i])):e[i]=n}}function up(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,T,w,M=0,A=0,C=1;function E(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;)mp.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 P=!0;P;){for(P=!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,C=this._fontSize/32,M=this._fontMinY*C,A=this._fontMaxY*C,b=0;b=r?null:this._symbols[b+1],mp.test(y))_++,(!this._wrapLines||this._maxLines<0||c0){var U=this._font.data.kerning;if(U){var V=U[H.getCodePoint(this._symbols[b-1])||0];V&&(z=V[H.getCodePoint(this._symbols[b])||0]||0)}}D=x.scale||1,B=C*((x.width+x.height)/2)/D,F=(x.xadvance+z)*C,k=(x.xoffset-z)*C,O=x.yoffset*C}else console.error("Couldn't substitute missing character: '"+y+"'");var G=_p.test(y),W=this._meshInfo[x&&x.map||0],X=a+this._spacing*F;if(X>v&&m>0&&!G&&(this._maxLines<0||cthis._element.calculatedWidth&&($=Math.floor(this._element.fontSize*this._element.calculatedWidth/(this.width||1e-4)),($=he.clamp($,i,n))!==this._element.fontSize)){this._fontSize=$,P=!0;break}if(this.height=Math.max(this.height,A-(o+M)),this._shouldAutoFitHeight()&&this.height>this._element.calculatedHeight&&($=he.clamp(this._fontSize-1,i,n))!==this._element.fontSize){this._fontSize=$,P=!0;break}a+=this._spacing*F,G||(l=a),(this._isWordBoundary(y)||this._isValidNextChar(w)&&(this._isNextCJKBoundary(y,w)||this._isNextCJKWholeWord(w)))&&(p++,u=l,d=b+1),m++;var ne=this._getUv(y);if(W.uvs[4*T*2+0]=ne[0],W.uvs[4*T*2+1]=1-ne[1],W.uvs[4*T*2+2]=ne[2],W.uvs[4*T*2+3]=1-ne[1],W.uvs[4*T*2+4]=ne[2],W.uvs[4*T*2+5]=1-ne[3],W.uvs[4*T*2+6]=ne[0],W.uvs[4*T*2+7]=1-ne[3],this._symbolColors){var se=3*this._symbolColors[b];I=this._colorPalette[se],R=this._colorPalette[se+1],L=this._colorPalette[se+2]}W.colors[4*T*4+0]=I,W.colors[4*T*4+1]=R,W.colors[4*T*4+2]=L,W.colors[4*T*4+3]=255,W.colors[4*T*4+4]=I,W.colors[4*T*4+5]=R,W.colors[4*T*4+6]=L,W.colors[4*T*4+7]=255,W.colors[4*T*4+8]=I,W.colors[4*T*4+9]=R,W.colors[4*T*4+10]=L,W.colors[4*T*4+11]=255,W.colors[4*T*4+12]=I,W.colors[4*T*4+13]=R,W.colors[4*T*4+14]=L,W.colors[4*T*4+15]=255,W.quad++}}P||f=be?(Se.element.POSITION.set(0,0,0),Se.element.TEXCOORD0.set(0,0),Se.element.COLOR.set(0,0,0,0)):(Se.element.POSITION.set(this._meshInfo[b].positions[3*Te+0],this._meshInfo[b].positions[3*Te+1],this._meshInfo[b].positions[3*Te+2]),Se.element.TEXCOORD0.set(this._meshInfo[b].uvs[2*Te+0],this._meshInfo[b].uvs[2*Te+1]),Se.element.COLOR.set(this._meshInfo[b].colors[4*Te+0],this._meshInfo[b].colors[4*Te+1],this._meshInfo[b].colors[4*Te+2],this._meshInfo[b].colors[4*Te+3])),Se.next();Se.end(),this._meshInfo[b].meshInstance.mesh.aabb.compute(this._meshInfo[b].positions),this._meshInfo[b].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 ge?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&&this.system.app.batcher.insert(Ds.ELEMENT,this.batchGroupId,this.entity),this.fire("enableelement")},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._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&&this.system.app.batcher.remove(Ds.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(){var e,t,i=this.entity._children;for(e=0,t=i.length;e=0&&this._addedModels.splice(i,1);for(var n=0;ni||f>n||p16777215&&(e=16777215),this._drawOrder=(t<<24)+e,this.fire("set:draworder",this._drawOrder)}}),Object.defineProperty(Lp.prototype,"_absLeft",{get:function(){return this._localAnchor.x+this._margin.x}}),Object.defineProperty(Lp.prototype,"_absRight",{get:function(){return this._localAnchor.z-this._margin.z}}),Object.defineProperty(Lp.prototype,"_absTop",{get:function(){return this._localAnchor.w-this._margin.w}}),Object.defineProperty(Lp.prototype,"_absBottom",{get:function(){return this._localAnchor.y+this._margin.y}}),Object.defineProperty(Lp.prototype,"margin",{get:function(){return this._margin},set:function(e){this._margin.copy(e),this._calculateSize(!0,!0),this.fire("set:margin",this._margin)}}),Object.defineProperty(Lp.prototype,"left",{get:function(){return this._margin.x},set:function(e){this._margin.x=e;var t=this.entity.getLocalPosition(),i=this._absRight,n=this._localAnchor.x+e;this._setWidth(i-n),t.x=e+this._calculatedWidth*this._pivot.x,this.entity.setLocalPosition(t)}}),Object.defineProperty(Lp.prototype,"right",{get:function(){return this._margin.z},set:function(e){this._margin.z=e;var t=this.entity.getLocalPosition(),i=this._absLeft,n=this._localAnchor.z-e;this._setWidth(n-i),t.x=this._localAnchor.z-this._localAnchor.x-e-this._calculatedWidth*(1-this._pivot.x),this.entity.setLocalPosition(t)}}),Object.defineProperty(Lp.prototype,"top",{get:function(){return this._margin.w},set:function(e){this._margin.w=e;var t=this.entity.getLocalPosition(),i=this._absBottom,n=this._localAnchor.w-e;this._setHeight(n-i),t.y=this._localAnchor.w-this._localAnchor.y-e-this._calculatedHeight*(1-this._pivot.y),this.entity.setLocalPosition(t)}}),Object.defineProperty(Lp.prototype,"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)}}),Object.defineProperty(Lp.prototype,"width",{get:function(){return this._width},set:function(e){this._width=e,this._hasSplitAnchorsX||this._setCalculatedWidth(e,!0),this.fire("set:width",this._width)}}),Object.defineProperty(Lp.prototype,"height",{get:function(){return this._height},set:function(e){this._height=e,this._hasSplitAnchorsY||this._setCalculatedHeight(e,!0),this.fire("set:height",this._height)}}),Object.defineProperty(Lp.prototype,"calculatedWidth",{get:function(){return this._calculatedWidth},set:function(e){this._setCalculatedWidth(e,!0)}}),Object.defineProperty(Lp.prototype,"calculatedHeight",{get:function(){return this._calculatedHeight},set:function(e){this._setCalculatedHeight(e,!0)}}),Object.defineProperty(Lp.prototype,"pivot",{get:function(){return this._pivot},set:function(e){var t=this._pivot.x,i=this._pivot.y;e instanceof ge?this._pivot.set(e.x,e.y):this._pivot.set(e[0],e[1]);var n=this._margin.x+this._margin.z,s=this._pivot.x-t;this._margin.x+=n*s,this._margin.z-=n*s;var r=this._margin.y+this._margin.w,a=this._pivot.y-i;this._margin.y+=r*a,this._margin.w-=r*a,this._anchorDirty=!0,this._cornersDirty=!0,this._worldCornersDirty=!0,this._calculateSize(!1,!1),this._flagChildrenAsDirty(),this.fire("set:pivot",this._pivot)}}),Object.defineProperty(Lp.prototype,"anchor",{get:function(){return this._anchor},set:function(e){e instanceof ve?this._anchor.set(e.x,e.y,e.z,e.w):this._anchor.set(e[0],e[1],e[2],e[3]),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)}}),Object.defineProperty(Lp.prototype,"_hasSplitAnchorsX",{get:function(){return Math.abs(this._anchor.x-this._anchor.z)>.001}}),Object.defineProperty(Lp.prototype,"_hasSplitAnchorsY",{get:function(){return Math.abs(this._anchor.y-this._anchor.w)>.001}}),Object.defineProperty(Lp.prototype,"aabb",{get:function(){return this._image?this._image.aabb:this._text?this._text.aabb:null}}),Object.defineProperty(Lp.prototype,"screenCorners",{get:function(){if(!this._cornersDirty||!this.screen)return this._screenCorners;var e=this.entity.parent&&this.entity.parent.element&&this.entity.parent.element.screenCorners[0];this._screenCorners[0].set(this._absLeft,this._absBottom,0),this._screenCorners[1].set(this._absRight,this._absBottom,0),this._screenCorners[2].set(this._absRight,this._absTop,0),this._screenCorners[3].set(this._absLeft,this._absTop,0);for(var t=this.screen.screen.screenSpace,i=0;i<4;i++)this._screenTransform.transformPoint(this._screenCorners[i],this._screenCorners[i]),t&&this._screenCorners[i].mulScalar(this.screen.screen.scale),e&&this._screenCorners[i].add(e);return this._cornersDirty=!1,this._canvasCornersDirty=!0,this._worldCornersDirty=!0,this._screenCorners}}),Object.defineProperty(Lp.prototype,"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}}),Object.defineProperty(Lp.prototype,"worldCorners",{get:function(){if(!this._worldCornersDirty)return this._worldCorners;if(this.screen){var e=this.screenCorners;if(!this.screen.screen.screenSpace){Ep.copy(this.screen.screen._screenMatrix),Ep.data[13]=-Ep.data[13],Ep.mul2(this.screen.getWorldTransform(),Ep);for(var t=0;t<4;t++)Ep.transformPoint(e[t],this._worldCorners[t])}}else{var i=this.entity.getLocalPosition();Ep.setTranslate(-i.x,-i.y,-i.z),Pp.setTRS(me.ZERO,this.entity.getLocalRotation(),this.entity.getLocalScale()),Ip.setTranslate(i.x,i.y,i.z);var n=this.entity.parent?this.entity.parent:this.entity;Rp.copy(n.getWorldTransform()),Rp.mul(Ip).mul(Pp).mul(Ep),Ap.set(i.x-this.pivot.x*this.calculatedWidth,i.y-this.pivot.y*this.calculatedHeight,i.z),Rp.transformPoint(Ap,this._worldCorners[0]),Ap.set(i.x+(1-this.pivot.x)*this.calculatedWidth,i.y-this.pivot.y*this.calculatedHeight,i.z),Rp.transformPoint(Ap,this._worldCorners[1]),Ap.set(i.x+(1-this.pivot.x)*this.calculatedWidth,i.y+(1-this.pivot.y)*this.calculatedHeight,i.z),Rp.transformPoint(Ap,this._worldCorners[2]),Ap.set(i.x-this.pivot.x*this.calculatedWidth,i.y+(1-this.pivot.y)*this.calculatedHeight,i.z),Rp.transformPoint(Ap,this._worldCorners[3])}return this._worldCornersDirty=!1,this._worldCorners}}),Object.defineProperty(Lp.prototype,"textWidth",{get:function(){return this._text?this._text.width:0}}),Object.defineProperty(Lp.prototype,"textHeight",{get:function(){return this._text?this._text.height:0}}),Object.defineProperty(Lp.prototype,"useInput",{get:function(){return this._useInput},set:function(e){this._useInput!==e&&(this._useInput=e,this.system.app.elementInput?e?this.enabled&&this.entity.enabled&&this.system.app.elementInput.addElement(this):this.system.app.elementInput.removeElement(this):!0===this._useInput&&console.warn("Elements will not get any input events because this.system.app.elementInput is not created"),this.fire("set:useInput",e))}}),Object.defineProperty(Lp.prototype,"batchGroupId",{get:function(){return this._batchGroupId},set:function(e){this._batchGroupId!==e&&(this.entity.enabled&&this._batchGroupId>=0&&this.system.app.batcher.remove(Ds.ELEMENT,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&this.system.app.batcher.insert(Ds.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)}}),Object.defineProperty(Lp.prototype,"maskedBy",{get:function(){return this._maskedBy}});var Dp=function(e){Object.defineProperty(Lp.prototype,e,{get:function(){return this._text?this._text[e]:this._image?this._image[e]:null},set:function(t){this._text?this._text[e]=t:this._image&&(this._image[e]=t)}})};Dp("fontSize"),Dp("minFontSize"),Dp("maxFontSize"),Dp("maxLines"),Dp("autoFitWidth"),Dp("autoFitHeight"),Dp("color"),Dp("font"),Dp("fontAsset"),Dp("spacing"),Dp("lineHeight"),Dp("wrapLines"),Dp("lines"),Dp("alignment"),Dp("autoWidth"),Dp("autoHeight"),Dp("rtlReorder"),Dp("unicodeConverter"),Dp("text"),Dp("key"),Dp("texture"),Dp("textureAsset"),Dp("material"),Dp("materialAsset"),Dp("sprite"),Dp("spriteAsset"),Dp("spriteFrame"),Dp("pixelsPerUnit"),Dp("opacity"),Dp("rect"),Dp("mask"),Dp("outlineColor"),Dp("outlineThickness"),Dp("shadowColor"),Dp("shadowOffset"),Dp("enableMarkup"),Dp("rangeStart"),Dp("rangeEnd");var kp=function(){this.enabled=!0},Op=["enabled"],Fp=function(e){function t(t){var i;(i=e.call(this,t)||this).id="element",i.ComponentType=Lp,i.DataType=kp,i.schema=Op,i._unicodeConverter=null,i._rtlReorder=null,i._defaultTexture=new Vi(t.graphicsDevice,{width:1,height:1,format:7}),i._defaultTexture.name="element-system";var n=i._defaultTexture.lock(),s=new Uint8Array(4);return s[0]=255,s[1]=255,s[2]=255,s[3]=255,n.set(s),i._defaultTexture.unlock(),i.defaultImageMaterial=null,i.defaultImage9SlicedMaterial=null,i.defaultImage9TiledMaterial=null,i.defaultImageMaskMaterial=null,i.defaultImage9SlicedMaskMaterial=null,i.defaultImage9TiledMaskMaterial=null,i.defaultScreenSpaceImageMaterial=null,i.defaultScreenSpaceImage9SlicedMaterial=null,i.defaultScreenSpaceImage9TiledMaterial=null,i.defaultScreenSpaceImageMask9SlicedMaterial=null,i.defaultScreenSpaceImageMask9TiledMaterial=null,i.defaultScreenSpaceImageMaskMaterial=null,i.defaultTextMaterial=null,i.defaultBitmapTextMaterial=null,i.defaultScreenSpaceTextMaterial=null,i.defaultScreenSpaceBitmapTextMaterial=null,i.defaultImageMaterials=[],i.on("beforeremove",i.onRemoveComponent,Q(i)),i}Z(t,e);var i=t.prototype;return i.destroy=function(){this._defaultTexture.destroy()},i.initializeComponentData=function(t,i,n){t._beingInitialized=!0,void 0!==i.anchor&&(i.anchor instanceof ve?t.anchor.copy(i.anchor):t.anchor.set(i.anchor[0],i.anchor[1],i.anchor[2],i.anchor[3])),void 0!==i.pivot&&(i.pivot instanceof ge?t.pivot.copy(i.pivot):t.pivot.set(i.pivot[0],i.pivot[1]));var s,r=Math.abs(t.anchor.x-t.anchor.z)>.001,a=Math.abs(t.anchor.y-t.anchor.w)>.001,o=!1;void 0!==i.margin&&(i.margin instanceof ve?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),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===tp?(void 0!==i.rect&&(t.rect=i.rect),void 0!==i.color&&((s=i.color)instanceof ue||(s=new ue(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===ip&&(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 ue||(s=new ue(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===tp&&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,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){return e?t?(this.defaultScreenSpaceTextMaterial||(this.defaultScreenSpaceTextMaterial=new Rn,this.defaultScreenSpaceTextMaterial.name="defaultScreenSpaceTextMaterial",this.defaultScreenSpaceTextMaterial.msdfMap=this._defaultTexture,this.defaultScreenSpaceTextMaterial.useLighting=!1,this.defaultScreenSpaceTextMaterial.useGammaTonemap=!1,this.defaultScreenSpaceTextMaterial.useFog=!1,this.defaultScreenSpaceTextMaterial.useSkybox=!1,this.defaultScreenSpaceTextMaterial.diffuse.set(0,0,0),this.defaultScreenSpaceTextMaterial.emissive.set(1,1,1),this.defaultScreenSpaceTextMaterial.opacity=.5,this.defaultScreenSpaceTextMaterial.blendType=4,this.defaultScreenSpaceTextMaterial.depthWrite=!1,this.defaultScreenSpaceTextMaterial.depthTest=!1,this.defaultScreenSpaceTextMaterial.emissiveVertexColor=!0,this.defaultScreenSpaceTextMaterial.update()),this.defaultScreenSpaceTextMaterial):(this.defaultScreenSpaceBitmapTextMaterial||(this.defaultScreenSpaceBitmapTextMaterial=new Rn,this.defaultScreenSpaceBitmapTextMaterial.name="defaultScreenSpaceBitmapTextMaterial",this.defaultScreenSpaceBitmapTextMaterial.emissive.set(.5,.5,.5),this.defaultScreenSpaceBitmapTextMaterial.emissiveMap=this._defaultTexture,this.defaultScreenSpaceBitmapTextMaterial.emissiveTint=!0,this.defaultScreenSpaceBitmapTextMaterial.opacity=.5,this.defaultScreenSpaceBitmapTextMaterial.opacityMap=this._defaultTexture,this.defaultScreenSpaceBitmapTextMaterial.opacityMapChannel="a",this.defaultScreenSpaceBitmapTextMaterial.useLighting=!1,this.defaultScreenSpaceBitmapTextMaterial.useGammaTonemap=!1,this.defaultScreenSpaceBitmapTextMaterial.useFog=!1,this.defaultScreenSpaceBitmapTextMaterial.useSkybox=!1,this.defaultScreenSpaceBitmapTextMaterial.diffuse.set(0,0,0),this.defaultScreenSpaceBitmapTextMaterial.blendType=4,this.defaultScreenSpaceBitmapTextMaterial.depthWrite=!1,this.defaultScreenSpaceBitmapTextMaterial.depthTest=!1,this.defaultScreenSpaceBitmapTextMaterial.emissiveVertexColor=!0,this.defaultScreenSpaceBitmapTextMaterial.update()),this.defaultScreenSpaceBitmapTextMaterial):t?(this.defaultTextMaterial||(this.defaultTextMaterial=new Rn,this.defaultTextMaterial.name="defaultTextMaterial",this.defaultTextMaterial.msdfMap=this._defaultTexture,this.defaultTextMaterial.useLighting=!1,this.defaultTextMaterial.useGammaTonemap=!1,this.defaultTextMaterial.useFog=!1,this.defaultTextMaterial.useSkybox=!1,this.defaultTextMaterial.diffuse.set(0,0,0),this.defaultTextMaterial.emissive.set(1,1,1),this.defaultTextMaterial.opacity=.5,this.defaultTextMaterial.blendType=4,this.defaultTextMaterial.depthWrite=!1,this.defaultTextMaterial.emissiveVertexColor=!0,this.defaultTextMaterial.update()),this.defaultTextMaterial):(this.defaultBitmapTextMaterial||(this.defaultBitmapTextMaterial=new Rn,this.defaultBitmapTextMaterial.name="defaultBitmapTextMaterial",this.defaultBitmapTextMaterial.emissive.set(.5,.5,.5),this.defaultBitmapTextMaterial.emissiveTint=!0,this.defaultBitmapTextMaterial.emissiveMap=this._defaultTexture,this.defaultBitmapTextMaterial.opacity=.5,this.defaultBitmapTextMaterial.opacityMap=this._defaultTexture,this.defaultBitmapTextMaterial.opacityMapChannel="a",this.defaultBitmapTextMaterial.useLighting=!1,this.defaultBitmapTextMaterial.useGammaTonemap=!1,this.defaultBitmapTextMaterial.useFog=!1,this.defaultBitmapTextMaterial.useSkybox=!1,this.defaultBitmapTextMaterial.diffuse.set(0,0,0),this.defaultBitmapTextMaterial.blendType=4,this.defaultBitmapTextMaterial.depthWrite=!1,this.defaultBitmapTextMaterial.emissiveVertexColor=!0,this.defaultBitmapTextMaterial.update()),this.defaultBitmapTextMaterial)},i._createBaseImageMaterial=function(){var e=new Rn;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}($u);Zu._buildAccessors(Lp.prototype,Op);var Bp="free",Np="limited",zp="locked",Up=["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"],Vp=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=zp,n._linearLimitsX=new ge(0,0),n._linearSpringX=!1,n._linearStiffnessX=0,n._linearDampingX=1,n._linearEquilibriumX=0,n._linearMotionY=zp,n._linearLimitsY=new ge(0,0),n._linearSpringY=!1,n._linearStiffnessY=0,n._linearDampingY=1,n._linearEquilibriumY=0,n._linearMotionZ=zp,n._linearLimitsZ=new ge(0,0),n._linearSpringZ=!1,n._linearStiffnessZ=0,n._linearDampingZ=1,n._linearEquilibriumZ=0,n._angularMotionX=zp,n._angularLimitsX=new ge(0,0),n._angularSpringX=!1,n._angularStiffnessX=0,n._angularDampingX=1,n._angularEquilibriumX=0,n._angularMotionY=zp,n._angularLimitsY=new ge(0,0),n._angularSpringY=!1,n._angularStiffnessY=0,n._angularDampingY=1,n._angularEquilibriumY=0,n._angularMotionZ=zp,n._angularLimitsZ=new ge(0,0),n._angularSpringZ=!1,n._angularEquilibriumZ=0,n._angularDampingZ=1,n._angularStiffnessZ=0,n.on("set_enabled",n._onSetEnabled,Q(n)),n}Z(t,e);var i=t.prototype;return i._convertTransform=function(e,t){var i=e.getTranslation(),n=new Me;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===Np?(t=this._angularLimitsX.x*he.DEG_TO_RAD,s=this._angularLimitsX.y*he.DEG_TO_RAD):this._angularMotionX===Bp?(t=1,s=0):t=s=0,this._angularMotionY===Np?(i=this._angularLimitsY.x*he.DEG_TO_RAD,r=this._angularLimitsY.y*he.DEG_TO_RAD):this._angularMotionY===Bp?(i=1,r=0):i=r=0,this._angularMotionZ===Np?(n=this._angularLimitsZ.x*he.DEG_TO_RAD,a=this._angularLimitsZ.y*he.DEG_TO_RAD):this._angularMotionZ===Bp?(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===Np?(t=this._linearLimitsX.x,s=this._linearLimitsX.y):this._linearMotionX===Bp?(t=1,s=0):t=s=0,this._linearMotionY===Np?(i=this._linearLimitsY.x,r=this._linearLimitsY.y):this._linearMotionY===Bp?(i=1,r=0):i=r=0,this._linearMotionZ===Np?(n=this._linearLimitsZ.x,a=this._linearLimitsZ.y):this._linearMotionZ===Bp?(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 we,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=ee(Up);!(t=i()).done;){var n=t.value;e.hasOwnProperty(n)&&(e[n]instanceof ge?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")},Y(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}(Zu),Gp={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(Vp.prototype,n,{get:function(){return this[s]},set:function(e){this[s]!==e&&(this[s]=e,this._constraint[Gp[t]](r,e))}})}))}))}));var Wp=function(){this.enabled=!0},Hp=["enabled"],Xp=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="joint",i.app=t,i.ComponentType=Vp,i.DataType=Wp,i.schema=Hp,i}return Z(t,e),t.prototype.initializeComponentData=function(e,t,i){e.initFromData(t)},t}($u);Zu._buildAccessors(Vp.prototype,Hp);var qp=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 Z(t,e),t}(Zu);function jp(e){var t="_"+e;Object.defineProperty(qp.prototype,e,{get:function(){return this[t]},set:function(e){this[t]!==e&&(this[t]=e,this.fire("resize"))}})}jp("minWidth"),jp("minHeight"),jp("maxWidth"),jp("maxHeight"),jp("fitWidthProportion"),jp("fitHeightProportion"),jp("excludeFromLayout");var Yp=function(){this.enabled=!0},Kp=["enabled"],Zp=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="layoutchild",i.ComponentType=qp,i.DataType=Yp,i.schema=Kp,i}Z(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}($u);Zu._buildAccessors(qp.prototype,Kp);var $p={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"}},Qp={0:1,1:0},Jp={minWidth:0,minHeight:0,maxWidth:Number.POSITIVE_INFINITY,maxHeight:Number.POSITIVE_INFINITY,width:null,height:null,fitWidthProportion:0,fitHeightProportion:0},em="NONE",tm="APPLY_STRETCHING",im="APPLY_SHRINKING",nm=new ge;function sm(e){var t,i=$p[e],n=$p[Qp[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 em;case 1:return t=i?im:em;case 3:return t=i?im:em;default:throw new Error("Unrecognized fitting mode: "+e)}}function l(e,i){return _(e,i.size)+(e.length-1)*t.spacing[i.axis]}function c(e,t,i){for(var n=v(e,i.maxSize),s=g(e,i.fittingProportion),r=b(s,n),a=nm[i.axis]-t,o=0;o=0;--n)i[t[n]]=i[t[n+1]]+e[t[n]];return i}return function(e,d){e=e.filter(o),t=d,nm.x=t.containerSize.x-t.padding.x-t.padding.z,nm.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>nm[i.axis]&&0!==n[n.length-1].length&&(r=h,n.push([])),n[n.length-1].push(e[o]),a&&r>nm[i.axis]&&o!==e.length-1&&(r=0,n.push([]))}return n}(e)),m=function(e,i){var s,r,a,o=[],d=[];for(r=0;ra.largestSize[n.size]&&(a.largestElement=a[s],a.largestSize=f)}o.push(a.largestElement),d.push(a.largestSize)}var p=l(d,n),m=h(t[n.fitting],p,nm[n.axis]);m===tm?c(d,p,n):m===im&&u(d,p,n);for(r=0;r0;){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()},t}($u);Zu._buildAccessors(lm.prototype,dm);var pm=[],mm=[],_m=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}Z(t,e);var i=t.prototype;return i.addLightToLayers=function(){for(var e,t=0;t=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,t=0;t=0&&e.batcher.insert(Ds.MODEL,this.batchGroupId,this.entity)},i.onDisable=function(){var e=this.system.app,t=e.scene;t.off("set:layers",this.onLayersChanged,this),t.layers&&(t.layers.off("add",this.onLayerAdded,this),t.layers.off("remove",this.onLayerRemoved,this)),this._batchGroupId>=0&&e.batcher.remove(Ds.MODEL,this.batchGroupId,this.entity),this._model&&this.removeModelFromLayers()},i.hide=function(){if(this._model){var e,t,i=this._model.meshInstances;for(e=0,t=i.length;e=0&&t.remove(Ds.MODEL,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&t.insert(Ds.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 Ph&&(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&&e.batcher.insert(Ds.RENDER,this.batchGroupId,this.entity)},i.onDisable=function(){var e=this.system.app,t=e.scene;t.off("set:layers",this.onLayersChanged,this),t.layers&&(t.layers.off("add",this.onLayerAdded,this),t.layers.off("remove",this.onLayerRemoved,this)),this._batchGroupId>=0&&e.batcher.remove(Ds.RENDER,this.batchGroupId,this.entity),this.removeFromLayers()},i.hide=function(){if(this._meshInstances)for(var e=0;e=0&&t.remove(Ds.RENDER,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&t.insert(Ds.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(t=e.length;t=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 ms||(s=null),this.emitter=new Ho(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,this.psys=new Za,this.psys.graph=this.entity,this.psys.emitter=this.emitter,this.psys.meshInstances=[this.emitter.meshInstance],e.model=this.psys,this.emitter.psys=this.psys,e.autoPlay||(this.pause(),this.emitter.meshInstance.visible=!1)}e.model&&this.emitter.colorMap&&this.addModelToLayers(),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.data.model&&(this.removeModelFromLayers(),this.data.depthSoftening&&this._releaseDepth()),this.emitter&&(this.emitter.camera=null)},i.onBeforeRemove=function(){this.enabled&&(this.enabled=!1);var e=this.data;e.model&&(this.entity.removeChild(e.model.getGraph()),e.model.destroy(),e.model=null),this.emitter&&(this.emitter.destroy(),this.emitter=null);for(var t=0;tc.fixedTimeStep&&(t=Math.floor(c.simTime/c.fixedTimeStep),c.simTime-=t*c.fixedTimeStep),t){for(t=Math.min(t,c.maxSubSteps),i=0;ithis._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}(),jm=function(e){function t(t,i){var n;return n=e.call(this,t,i)||this,"undefined"==typeof Ammo||zm||(zm=new Ammo.btTransform,Um=new Ammo.btVector3,Vm=new Ammo.btVector3,Gm=new Ammo.btQuaternion,Wm=new Ammo.btVector3(0,0,0)),n._angularDamping=0,n._angularFactor=new me(1,1,1),n._angularVelocity=new me,n._body=null,n._friction=.5,n._group=2,n._linearDamping=0,n._linearFactor=new me(1,1,1),n._linearVelocity=new me,n._mask=Bf,n._mass=1,n._restitution=0,n._rollingFriction=0,n._simulationEnabled=!1,n._type=Df,n}Z(t,e);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===kf?this._mass:0;this._getEntityTransform(zm);var n=this.system.createBody(i,e,zm);if(n.setRestitution(this._restitution),n.setFriction(this._friction),n.setRollingFriction(this._rollingFriction),n.setDamping(this._linearDamping,this._angularDamping),this._type===kf){var s=this._linearFactor;Um.setValue(s.x,s.y,s.z),n.setLinearFactor(Um);var r=this._angularFactor;Um.setValue(r.x,r.y,r.z),n.setAngularFactor(Um)}else this._type===Of&&(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 kf:this.system._dynamic.push(this),t.forceActivationState(1),this.syncEntityToBody();break;case Of:this.system._kinematic.push(this),t.forceActivationState(4);break;case Df: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(),Um.setValue(e,t,i),void 0!==n?(Vm.setValue(n,s,r),a.applyForce(Um,Vm)):a.applyForce(Um,Wm))},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(),Um.setValue(e,t,i),n.applyTorque(Um))},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(),Um.setValue(e,t,i),void 0!==n?(Vm.setValue(n,s,r),a.applyImpulse(Um,Vm)):a.applyImpulse(Um,Wm))},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(),Um.setValue(e,t,i),n.applyTorqueImpulse(Um))},i.isStatic=function(){return this._type===Df},i.isStaticOrKinematic=function(){return this._type===Df||this._type===Of},i.isKinematic=function(){return this._type===Of},i._getEntityTransform=function(e){var t=this.entity,i=t.getPosition(),n=t.getRotation();Um.setValue(i.x,i.y,i.z),Gm.setValue(n.x,n.y,n.z,n.w),e.setOrigin(Um),e.setRotation(Gm)},i.syncEntityToBody=function(){var e=this._body;if(e){if(this._getEntityTransform(zm),e.setWorldTransform(zm),this._type===Of){var t=e.getMotionState();t&&t.setWorldTransform(zm)}e.activate()}},i._updateDynamic=function(){var e=this._body;if(e.isActive()){var t=e.getMotionState();if(t){t.getWorldTransform(zm);var i=zm.getOrigin(),n=zm.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(zm),e.setWorldTransform(zm))},i.teleport=function(){arguments.length<3?(arguments[0]&&this.entity.setPosition(arguments[0]),arguments[1]&&(arguments[1]instanceof Me?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()},Y(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===kf&&(Um.setValue(e.x,e.y,e.z),this._body.setAngularFactor(Um)))}},{key:"angularVelocity",get:function(){if(this._body&&this._type===kf){var e=this._body.getAngularVelocity();this._angularVelocity.set(e.x(),e.y(),e.z())}return this._angularVelocity},set:function(e){this._body&&this._type===kf&&(this._body.activate(),Um.setValue(e.x,e.y,e.z),this._body.setAngularVelocity(Um),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===kf&&(Um.setValue(e.x,e.y,e.z),this._body.setLinearFactor(Um)))}},{key:"linearVelocity",get:function(){if(this._body&&this._type===kf){var e=this._body.getLinearVelocity();this._linearVelocity.set(e.x(),e.y(),e.z())}return this._linearVelocity},set:function(e){this._body&&this._type===kf&&(this._body.activate(),Um.setValue(e.x,e.y,e.z),this._body.setLinearVelocity(Um),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===kf)){var t=this.enabled&&this.entity.enabled;t&&this.disableSimulation(),this._body.getCollisionShape().calculateLocalInertia(e,Um),this._body.setMassProps(e,Um),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 kf:this._group=1,this._mask=Ff;break;case Of:this._group=4,this._mask=Ff;break;case Df:default:this._group=2,this._mask=Bf}this.createBody()}}}]),t}(Zu),Ym=function(){this.enabled=!0},Km={},Zm={},$m=function(e,t,i){this.entity=e,this.point=t,this.normal=i},Qm=function(e,t,i){0===arguments.length?(this.a=null,this.b=null,this.localPointA=new me,this.localPointB=new me,this.pointA=new me,this.pointB=new me,this.normal=new me):(this.a=e,this.b=t,this.localPointA=i.localPoint,this.localPointB=i.localPointOther,this.pointA=i.point,this.pointB=i.pointOther,this.normal=i.normal)},Jm=function(e,t,i,n,s){void 0===e&&(e=new me),void 0===t&&(t=new me),void 0===i&&(i=new me),void 0===n&&(n=new me),void 0===s&&(s=new me),this.localPoint=e,this.localPointOther=t,this.point=i,this.pointOther=n,this.normal=s},e_=function(e,t){this.other=e,this.contacts=t},t_=["enabled"],i_=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="rigidbody",i._stats=t.stats.frame,i.ComponentType=jm,i.DataType=Ym,i.contactPointPool=null,i.contactResultPool=null,i.singleContactResultPool=null,i.schema=t_,i.maxSubSteps=10,i.fixedTimeStep=1/60,i.gravity=new me(0,-9.81,0),i._dynamic=[],i._kinematic=[],i._triggers=[],i._compounds=[],i.on("beforeremove",i.onBeforeRemove,Q(i)),i.on("remove",i.onRemove,Q(i)),i}Z(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)}Hm=new Ammo.btVector3,Xm=new Ammo.btVector3,this.contactPointPool=new qm(Jm,1),this.contactResultPool=new qm(e_,1),this.singleContactResultPool=new qm(Qm,1),$u.bind("update",this.onUpdate,this)}else $u.unbind("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=[];Hm.setValue(e.x,e.y,e.z),Xm.setValue(t.x,t.y,t.z);var n=new Ammo.AllHitsRayResultCallback(Hm,Xm);if(this.dynamicsWorld.rayTest(Hm,Xm,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),T=this._hasContactEvent(u),w=this.hasEvent("contact");if(w||S||T){for(var M=0;M=0&&i!==e.element.drawOrder&&this.system.app.batcher.markGroupDirty(e.element._batchGroupId)}e.particlesystem&&(e.particlesystem.drawOrder=t++);for(var n=e.children,s=0;s255&&(e=255),this._priority=e}}]),t}(Zu),o_=function(){this.enabled=!0},h_=["enabled"],l_=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="screen",i.ComponentType=a_,i.DataType=o_,i.schema=h_,i.windowResolution=new ge,i._drawOrderSyncQueue=new X,i.app.graphicsDevice.on("resizecanvas",i._onResize,Q(i)),$u.bind("update",i._onUpdate,Q(i)),i.on("beforeremove",i.onRemoveComponent,Q(i)),i}Z(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 ge?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 ge?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(){this.off(),this.app.graphicsDevice.off("resizecanvas",this._onResize,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=3&&i.length<=4){for(s=0;si.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}console.warn("script '"+r+"' is already added to entity '"+this.entity.name+"'")}else this._scriptsIndex[r]={awaiting:!0,ind:this._scripts.length},console.warn("script '"+r+"' is not found, awaiting it to be added to registry");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,n,s=this.entity.script;for(var r in e._scriptsIndex){var a=this.system.app.scripts.get(r);if(a){var o=e._scriptsIndex[r];if(o&&o.instance){var h=s[r].__attributesRaw,l=s[r].__attributes;if(h||l){var c=!!h,u=o.instance.__attributes;for(var d in u)if(u[d]){var f=a.attributes.get(d);if(f)if("entity"===f.type)this._resolveEntityScriptAttribute(f,d,u[d],c,h||l,t);else if("json"===f.type&&Array.isArray(f.schema)){var p=u[d],m=h?h[d]:l[d];for(i=0;i=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)},Y(t,[{key:"enabled",get:function(){return this._enabled},set:function(e){var t=this._enabled;this._enabled=e,this.fire("set","enabled",t,e)}},{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(!f_.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)}}}]),t}(Zu);p_.scriptMethods={initialize:"initialize",postInitialize:"postInitialize",update:"update",postUpdate:"postUpdate",swap:"swap"};var m_=function(){this.enabled=!0},__=0,g_=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="script",i.ComponentType=p_,i.DataType=m_,i._components=new q({sortBy:"_executionOrder"}),i._enabledComponents=new q({sortBy:"_executionOrder"}),i.preloading=!0,i.on("beforeremove",i._onBeforeRemove,Q(i)),$u.bind("initialize",i._onInitialize,Q(i)),$u.bind("postInitialize",i._onPostInitialize,Q(i)),$u.bind("update",i._onUpdate,Q(i)),$u.bind("postUpdate",i._onPostUpdate,Q(i)),i}Z(t,e);var i=t.prototype;return i.initializeComponentData=function(e,t){if(e._executionOrder=__++,this._components.append(e),__>Number.MAX_SAFE_INTEGER&&this._resetExecutionOrder(),e.enabled=!t.hasOwnProperty("enabled")||!!t.enabled,e.enabled&&e.entity.enabled&&this._enabledComponents.append(e),t.hasOwnProperty("order")&&t.hasOwnProperty("scripts")){e._scriptsData=t.scripts;for(var i=0;i=0&&t._onBeforeRemove(),this._removeComponentFromEnabled(t),this._components.remove(t)},t}($u),v_=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this).on("set_scripts",n.onSetScripts,Q(n)),n}Z(t,e);var i=t.prototype;return i.send=function(e,t){var i,n=Array.prototype.slice.call(arguments,2),s=this.entity.script.instances;if(s&&s[e]&&(i=s[e].instance[t]))return i.apply(s[e].instance,n)},i.onEnable=function(){this.data.areScriptsLoaded&&!this.system.preloading&&(this.data.initialized?this.system._enableScriptComponent(this):this.system._initializeScriptComponent(this),this.data.postInitialized||this.system._postInitializeScriptComponent(this))},i.onDisable=function(){this.system._disableScriptComponent(this)},i.onSetScripts=function(e,t,i){if(!this.system._inTools||this.runInTools){if(this._updateScriptAttributes(t,i))return;this.enabled&&this.system._disableScriptComponent(this),this.system._destroyScriptComponent(this),this.data.areScriptsLoaded=!1;var n=i.map((function(e){return e.url}));if(this._loadFromCache(n))return;this._loadScripts(n)}},i._updateScriptAttributes=function(e,t){var i=!0;if(e.length!==t.length)i=!1;else{var n,s=t.length;for(n=0;n=0&&this.instancesWithUpdate.splice(t,1),s.fixedUpdate&&(t=this.instancesWithFixedUpdate.indexOf(s))>=0&&this.instancesWithFixedUpdate.splice(t,1),s.postUpdate&&(t=this.instancesWithPostUpdate.indexOf(s))>=0&&this.instancesWithPostUpdate.splice(t,1),s.toolsUpdate&&(t=this.instancesWithToolsUpdate.indexOf(s))>=0&&this.instancesWithToolsUpdate.splice(t,1),e.instances[n].instance===e[n]&&delete e[n],delete e.instances[n]}},i._postInitializeScriptComponent=function(e){this._callInstancesMethod(e,S_),e.data.postInitialized=!0},i._updateInstances=function(e,t,i){for(var n,s=0,r=t.length;s0){var i=L_.sub(I_).dot(D_)/t,n=I_.add(R_.mulScalar(i));return k_.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?(E_.x=e.x*t,E_.y=e.y*t):e.changedTouches?(E_.x=e.changedTouches[0].x*t,E_.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?(I_.set(E_.x,-E_.y,0),R_.set(0,0,-1)):(P_.copy(this._dragCamera.screenToWorld(E_.x,E_.y,1)),I_.copy(this._dragCamera.entity.getPosition()),R_.copy(P_).sub(I_).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){if(this._element&&this._isDragging&&this.enabled&&this._element.enabled&&this._element.entity.enabled){var t=this._screenToLocal(e);if(this._dragStartMousePosition&&t){if(this._deltaMousePosition.copy(t).sub(this._dragStartMousePosition),this._deltaHandlePosition.copy(this._dragStartHandlePosition).add(this._deltaMousePosition),this._axis){var i=this._element.entity.getLocalPosition(),n=O_[this._axis];this._deltaHandlePosition[n]=i[n]}this._element.entity.setLocalPosition(this._deltaHandlePosition),this.fire("drag:move",this._deltaHandlePosition)}}},i.destroy=function(){this._toggleLifecycleListeners("off"),this._toggleDragListeners("off")},Y(t,[{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"isDragging",get:function(){return this._isDragging}}]),t}(_),B_="mouse",N_="keyboard",z_="gamepad",U_="mousedown",V_="mousemove",G_="mouseup",W_="mousewheel",H_=new ge,X_=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._viewportReference=new hf(Q(n),"viewportEntity",{"element#gain":n._onViewportElementGain,"element#resize":n._onSetContentOrViewportSize}),n._contentReference=new hf(Q(n),"contentEntity",{"element#gain":n._onContentElementGain,"element#lose":n._onContentElementLose,"element#resize":n._onSetContentOrViewportSize}),n._scrollbarUpdateFlags={},n._scrollbarReferences={},n._scrollbarReferences[0]=new hf(Q(n),"horizontalScrollbarEntity",{"scrollbar#set:value":n._onSetHorizontalScrollbarValue,"scrollbar#gain":n._onHorizontalScrollbarGain}),n._scrollbarReferences[1]=new hf(Q(n),"verticalScrollbarEntity",{"scrollbar#set:value":n._onSetVerticalScrollbarValue,"scrollbar#gain":n._onVerticalScrollbarGain}),n._prevContentSizes={},n._prevContentSizes[0]=null,n._prevContentSizes[1]=null,n._scroll=new ge,n._velocity=new me,n._dragStartPosition=new me,n._disabledContentInput=!1,n._disabledContentInputEntities=[],n._toggleLifecycleListeners("on",t),n._toggleElementListeners("on"),n}Z(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](W_,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 F_(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=!1;n|=this._updateAxis(e,"x",0),(n|=this._updateAxis(t,"y",1))&&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 he.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:he.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 H_.x=0===t?0:e.x/t,H_.y=0===i?0:e.y/-i,H_},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,i;return t=this._getMaxScrollValue(0),(i=this._toOvershoot(e.x,0))>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=he.clamp(this._scroll.x+i,0,this._getMaxScrollValue(0)),r=he.clamp(this._scroll.y+n,0,this._getMaxScrollValue(1));this.scroll=new ge(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);var n,s,r=i.children;for(n=0,s=r.length;n1e-5&&(this.data.value=he.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=he.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}(Zu),Z_=function(){this.enabled=!0},$_=[{name:"enabled",type:"boolean"},{name:"orientation",type:"number"},{name:"value",type:"number"},{name:"handleSize",type:"number"},{name:"handleEntity",type:"entity"}],Q_=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="scrollbar",i.ComponentType=K_,i.DataType=Z_,i.schema=$_,i.on("beforeremove",i._onRemoveComponent,Q(i)),i}Z(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){e.prototype.initializeComponentData.call(this,t,i,$_)},i._onRemoveComponent=function(e,t){t.onRemove()},t}($u);Zu._buildAccessors(K_.prototype,$_);function J_(e,t){return e%t||0}var eg=function(e){function t(t,i,n){var s;return(s=e.call(this)||this)._manager=t,s._volume=void 0!==n.volume?he.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=!1,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.source=null,s._onPlayCallback=n.onPlay,s._onPauseCallback=n.onPause,s._onResumeCallback=n.onResume,s._onStopCallback=n.onStop,s._onEndCallback=n.onEnd,Zo()?(s._startedAt=0,s._currentTime=0,s._currentOffset=0,s._inputNode=null,s._connectorNode=null,s._firstNode=null,s._lastNode=null,s._initializeNodes(),s._endedHandler=s._onEnded.bind(Q(s))):(s._isReady=!1,s._loadedMetadataHandler=s._onLoadedMetadata.bind(Q(s)),s._timeUpdateHandler=s._onTimeUpdate.bind(Q(s)),s._endedHandler=s._onEnded.bind(Q(s)),s._createSource()),s}Z(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?this._suspendEndEvent=!1:(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())},Y(t,[{key:"loop",get:function(){return this._loop},set:function(e){this._loop=!!e,this.source&&(this.source.loop=this._loop)}},{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:"duration",get:function(){return this._sound?this._duration?J_(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:"isPlaying",get:function(){return 0===this._state}},{key:"isPaused",get:function(){return 1===this._state}},{key:"isStopped",get:function(){return 2===this._state}},{key:"isSuspended",get:function(){return this._suspended}}]),t}(_);Zo()?(Object.assign(eg.prototype,{_initializeNodes:function(){this.gain=this._manager.context.createGain(),this._inputNode=this.gain,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination)},play:function(){2!==this._state&&this.stop(),this.source||this._createSource();var e=J_(this._startOffset,this.duration);return e=J_(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._state=0,this._playWhenLoaded=!1,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._manager.suspended&&this._onManagerSuspend(),this._suspendInstanceEvents||this._onPlay(),!0},pause:function(){return this._playWhenLoaded=!1,!(0!==this._state||!this.source)&&(this._updateCurrentTime(),this._state=1,this._suspendEndEvent=!0,this.source.stop(0),this.source=null,this._startOffset=null,this._suspendInstanceEvents||this._onPause(),!0)},resume:function(){if(1!==this._state)return!1;this.source||this._createSource();var e=this.currentTime;return null!==this._startOffset&&(e=J_(this._startOffset,this.duration),e=J_(this._startTime+e,this._sound.duration),this._startOffset=null),this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._state=0,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},stop:function(){return this._playWhenLoaded=!1,!(2===this._state||!this.source)&&(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=!0,0===this._state&&this.source.stop(0),this.source=null,this._state=2,this._suspendInstanceEvents||this._onStop(),!0)},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")},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)},getExternalNodes:function(){return[this._firstNode,this._lastNode]},_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=J_(this._startTime,this.source.buffer.duration),this._duration&&(this.source.loopEnd=Math.max(this.source.loopStart,J_(this._startTime+this._duration,this.source.buffer.duration)))),this.source},_updateCurrentTime:function(){this._currentTime=J_((this._manager.context.currentTime-this._startedAt)*this._pitch+this._currentOffset,this.duration)},_onManagerDestroy:function(){this.source&&0===this._state&&(this.source.stop(0),this.source=null)}}),Object.defineProperty(eg.prototype,"volume",{get:function(){return this._volume},set:function(e){e=he.clamp(e,0,1),this._volume=e,this.gain&&(this.gain.gain.value=e*this._manager.volume)}}),Object.defineProperty(eg.prototype,"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)}}),Object.defineProperty(eg.prototype,"sound",{get:function(){return this._sound},set:function(e){this._sound=e,2!==this._state?this.stop():this._createSource()}}),Object.defineProperty(eg.prototype,"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}})):(Object.assign(eg.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=!0,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=!0,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=J_(this._startOffset,this.duration);e=J_(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>J_(this._startTime+this._duration,this.source.duration)&&(this.loop?this.source.currentTime=J_(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(eg.prototype,"volume",{get:function(){return this._volume},set:function(e){e=he.clamp(e,0,1),this._volume=e,this.source&&(this.source.volume=e*this._manager.volume)}}),Object.defineProperty(eg.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(eg.prototype,"sound",{get:function(){return this._sound},set:function(e){this.stop(),this._sound=e}}),Object.defineProperty(eg.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=J_(this._startTime+J_(e,this.duration),this._sound.duration),this._startOffset=null))}}));var tg=function(e){function t(t,i,n){var s;return s=e.call(this,t,i,n)||this,n=n||{},s._position=new me,n.position&&(s.position=n.position),s._velocity=new me,n.velocity&&(s.velocity=n.velocity),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:Qo,s}return Z(t,e),t}(eg);if(Zo())Object.assign(tg.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)}}),Object.defineProperty(tg.prototype,"position",{get:function(){return this._position},set:function(e){this._position.copy(e),this.panner.setPosition(e.x,e.y,e.z)}}),Object.defineProperty(tg.prototype,"velocity",{get:function(){return this._velocity},set:function(e){this._velocity.copy(e),this.panner.setVelocity(e.x,e.y,e.z)}}),Object.defineProperty(tg.prototype,"maxDistance",{get:function(){return this.panner.maxDistance},set:function(e){this.panner.maxDistance=e}}),Object.defineProperty(tg.prototype,"refDistance",{get:function(){return this.panner.refDistance},set:function(e){this.panner.refDistance=e}}),Object.defineProperty(tg.prototype,"rollOffFactor",{get:function(){return this.panner.rolloffFactor},set:function(e){this.panner.rolloffFactor=e}}),Object.defineProperty(tg.prototype,"distanceModel",{get:function(){return this.panner.distanceModel},set:function(e){this.panner.distanceModel=e}});else{var ig=new me;Object.defineProperty(tg.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=(ig=ig.sub2(e,t)).length();if(an)return 0;var o=0;return r===Qo?o=1-s*(a-i)/(n-i):r===Jo?o=i/(i+s*(a-i)):r===eh&&(o=Math.pow(a/i,-s)),he.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(tg.prototype,"velocity",{get:function(){return this._velocity},set:function(e){this._velocity.copy(e)}}),Object.defineProperty(tg.prototype,"maxDistance",{get:function(){return this._maxDistance},set:function(e){this._maxDistance=e}}),Object.defineProperty(tg.prototype,"refDistance",{get:function(){return this._refDistance},set:function(e){this._refDistance=e}}),Object.defineProperty(tg.prototype,"rollOffFactor",{get:function(){return this._rollOffFactor},set:function(e){this._rollOffFactor=e}}),Object.defineProperty(tg.prototype,"distanceModel",{get:function(){return this._distanceModel},set:function(e){this._distanceModel=e}})}var ng={volume:0,pitch:0,loop:!1,startTime:0,duration:0,position:new me,maxDistance:0,refDistance:0,rollOffFactor:0,distanceModel:0,onPlay:null,onPause:null,onResume:null,onStop:null,onEnd:null},sg=function(e){function t(t,i,n){var s;return(s=e.call(this)||this)._component=t,s._assets=t.system.app.assets,s._manager=t.system.manager,s.name=i||"Untitled",n=n||{},s._volume=void 0!==n.volume?he.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 Ph&&(s._asset=s._asset.id),s._onInstancePlayHandler=s._onInstancePlay.bind(Q(s)),s._onInstancePauseHandler=s._onInstancePause.bind(Q(s)),s._onInstanceResumeHandler=s._onInstanceResume.bind(Q(s)),s._onInstanceStopHandler=s._onInstanceStop.bind(Q(s)),s._onInstanceEndHandler=s._onInstanceEnd.bind(Q(s)),s.instances=[],s}Z(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,i=this._slots;if(i)for(t in i)i[t].stop();var n={};for(t in e)e[t]instanceof sg?n[e[t].name]=e[t]:e[t].name&&(n[e[t].name]=new sg(this,e[t].name,e[t]));this._slots=n,this.enabled&&this.entity.enabled&&this.onEnable()}}]),t}(Zu);function ag(e,t){Object.defineProperty(rg.prototype,e,{get:function(){return this[t]},set:function(i){this[t]=i;var n=this._slots;for(var s in n){var r=n[s];if(!r.overlap)for(var a=r.instances,o=0,h=a.length;on||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=he.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))},Y(t,[{key:"spriteAsset",get:function(){return this._spriteAsset},set:function(e){var t=this._component.system.app.assets,i=e;if(e instanceof Ph&&(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:"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:"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:"isPlaying",get:function(){return this._playing}},{key:"isPaused",get:function(){return this._paused}},{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:"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}(_),pg="texture_emissiveMap",mg="texture_opacityMap",_g="material_emissive",gg="material_opacity",vg=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._type=ug,n._material=t.defaultMaterial,n._color=new ue(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 ge(1,1),n._outerScaleUniform=new Float32Array(2),n._innerOffset=new ve,n._innerOffsetUniform=new Float32Array(4),n._atlasRect=new ve,n._atlasRectUniform=new Float32Array(4),n._batchGroupId=-1,n._batchGroup=null,n._node=new Js,n._model=new Za,n._model.graph=n._node,n._meshInstance=null,i.addChild(n._model.graph),n._model._entity=i,n._updateAabbFunc=n._updateAabb.bind(Q(n)),n._addedModel=!1,n._autoPlayClip=null,n._clips={},n._defaultClip=new fg(Q(n),{name:n.entity.name,fps:0,loop:!1,spriteAsset:null}),n._currentClip=n._defaultClip,n}Z(t,e);var i=t.prototype;return i.onEnable=function(){var e=this.system.app,t=e.scene;t.on("set:layers",this._onLayersChanged,this),t.layers&&(t.layers.on("add",this._onLayerAdded,this),t.layers.on("remove",this._onLayerRemoved,this)),this._showModel(),this._autoPlayClip&&this._tryAutoPlay(),this._batchGroupId>=0&&e.batcher.insert(Ds.SPRITE,this._batchGroupId,this.entity)},i.onDisable=function(){var e=this.system.app,t=e.scene;t.off("set:layers",this._onLayersChanged,this),t.layers&&(t.layers.off("add",this._onLayerAdded,this),t.layers.off("remove",this._onLayerRemoved,this)),this.stop(),this._hideModel(),this._batchGroupId>=0&&e.batcher.remove(Ds.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){var e,t,i=[this._meshInstance];for(e=0,t=this._layers.length;e=0&&this.system.app.batcher.remove(Ds.SPRITE,t,this.entity),this.entity.enabled&&e>=0?this.system.app.batcher.insert(Ds.SPRITE,e,this.entity):t>=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 fg?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}(Zu),yg=function(){this.enabled=!0},xg=["enabled"],bg=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="sprite",i.ComponentType=vg,i.DataType=yg,i.schema=xg,i._defaultTexture=null,i._defaultMaterial=null,i._default9SlicedMaterialSlicedMode=null,i._default9SlicedMaterialTiledMode=null,$u.bind("update",i.onUpdate,Q(i)),i.on("beforeremove",i.onBeforeRemove,Q(i)),i}Z(t,e);var i=t.prototype;return i.destroy=function(){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 ue?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()},Y(t,[{key:"defaultMaterial",get:function(){if(!this._defaultMaterial){var e=new Vi(this.app.graphicsDevice,{width:1,height:1,format:7}),t=new Uint8Array(e.lock());t[0]=t[1]=t[2]=t[3]=255,e.name="sprite",e.unlock();var i=new Rn;i.diffuse.set(0,0,0),i.emissive.set(.5,.5,.5),i.emissiveMap=e,i.emissiveMapTint=!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}($u);Zu._buildAccessors(vg.prototype,xg);var Sg=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._oldState=!0,n._size=new me,n.on("set_enabled",n._onSetEnabled,Q(n)),n}Z(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")},Y(t,[{key:"size",get:function(){return this._size},set:function(e){e instanceof me?this._size.copy(e):e instanceof Array&&e.length>=3&&this.size.set(e[0],e[1],e[2])}}]),t}(Zu),Tg=function(){this.enabled=!0},wg=["enabled"],Mg=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="zone",i.ComponentType=Sg,i.DataType=Tg,i.schema=wg,i.on("beforeremove",i._onBeforeRemove,Q(i)),i}Z(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 me?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}($u);Zu._buildAccessors(Sg.prototype,wg);var Ag=function(){function e(e){this.frame={fps:0,ms:0,dt:0,updateStart:0,updateTime:0,renderStart:0,renderTime:0,physicsStart:0,physicsTime:0,cullTime:0,sortTime:0,skinTime:0,morphTime:0,instancingTime:0,triangles:0,otherPrimitives:0,shaders:0,materials:0,cameras:0,shadowMapUpdates:0,shadowMapTime:0,depthMapTime:0,forwardTime:0,lightClustersTime:0,lightClusters:0,_timeToCountFrames:0,_fpsAccum:0},this.drawCalls={forward:0,depth:0,shadow:0,immediate:0,misc:0,total:0,skinned:0,instanced:0,removedByInstancing:0},this.misc={renderTargetCreationTime:0},this.particles={updatesPerFrame:0,_updatesPerFrame:0,frameTime:0,_frameTime:0},this.shaders=e._shaderStats,this.vram=e._vram,Object.defineProperty(this.vram,"totalUsed",{get:function(){return this.tex+this.vb+this.ib}}),Object.defineProperty(this.vram,"geom",{get:function(){return this.vb+this.ib}})}return Y(e,[{key:"scene",get:function(){return tn().scene._stats}},{key:"lightmapper",get:function(){return tn().lightmapper._stats}},{key:"batcher",get:function(){return tn().batcher._stats}}]),e}(),Cg=function(){function e(e,t){this.name=e,this.url=t,this.data=null,this._loading=!1,this._onLoadedCallbacks=[]}return Y(e,[{key:"loaded",get:function(){return!!this.data}},{key:"loading",get:function(){return this._loading}}]),e}(),Eg=function(){function e(e){this._app=e,this._list=[],this._index={},this._urlIndex={}}var t=e.prototype;return t.destroy=function(){this._app=null},t.list=function(){return this._list},t.add=function(e,t){if(this._index.hasOwnProperty(e))return!1;var i=new Cg(e,t),n=this._list.push(i);return this._index[i.name]=n-1,this._urlIndex[i.url]=n-1,!0},t.find=function(e){return this._index.hasOwnProperty(e)?this._list[this._index[e]]:null},t.findByUrl=function(e){return this._urlIndex.hasOwnProperty(e)?this._list[this._urlIndex[e]]:null},t.remove=function(e){if(this._index.hasOwnProperty(e)){var t=this._index[e],i=this._list[t];for(delete this._urlIndex[i.url],delete this._index[e],this._list.splice(t,1),t=0;t0&&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 s=new an(this.graphicsDevice,"application"),r={};for(var a in e.layers){var o=e.layers[a];o.id=parseInt(a,10),o.enabled=1!==o.id,r[a]=new ka(o)}for(i=0,n=e.layerOrder.length;i0,o.tags.add(a.tags),a.i18n)for(var h in a.i18n)o.addLocalizedAssetId(h,a.i18n[h]);this.assets.add(o)}},n._getScriptReferences=function(e){var t,i,n=[];e.settings.priority_scripts&&(n=e.settings.priority_scripts);var s=[],r={};for(t=0;tn._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.instancingTime=this.renderer._instancingTime,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===ru&&(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(){if(this._allowResize&&!this.xr.active&&this._resolutionMode===ou){var e=this.graphicsDevice.canvas;this.graphicsDevice.resizeCanvas(e.clientWidth,e.clientHeight)}},n.onLibrariesLoaded=function(){this._librariesLoaded=!0,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){if(e){var t=this.graphicsDevice;e.ready((function(e){Xo.set(t,e.resource)})),this.assets.load(e)}},n.setSkybox=function(e){if(e){if(this._skyboxLast===e.id)return void(0!==this.scene.skyboxMip||e.loadFaces?this._onSkyboxChange(e):this._skyboxLoad(e));this._skyboxLast&&(this.assets.off("add:"+this._skyboxLast,this.setSkybox,this),this.assets.off("load:"+this._skyboxLast,this._onSkyboxChange,this),this.assets.off("remove:"+this._skyboxLast,this._skyboxRemove,this)),this._skyboxLast=e.id,this.assets.on("load:"+e.id,this._onSkyboxChange,this),this.assets.once("remove:"+e.id,this._skyboxRemove,this),e.resource&&this.scene.setSkybox(e.resources),this._skyboxLoad(e)}else{if(!this._skyboxLast)return;this._skyboxRemove({id:this._skyboxLast})}},n.enableVr=function(){this.vr||(this.vr=new cu(this))},n.disableVr=function(){this.vr&&(this.vr.destroy(),this.vr=null)},n._onSkyboxChange=function(e){this.scene.setSkybox(e.resources)},n._skyboxLoad=function(e){0===this.scene.skyboxMip&&(e.loadFaces=!0),this.assets.load(e),this._onSkyboxChange(e)},n._skyboxRemove=function(e){this._skyboxLast&&(this.assets.off("add:"+e.id,this.setSkybox,this),this.assets.off("load:"+e.id,this._onSkyboxChange,this),this.assets.off("remove:"+e.id,this._skyboxRemove,this),this.scene.setSkybox(null),this._skyboxLast=null)},n._firstBake=function(){this.lightmapper.bake(null,this.scene.lightmapMode)},n._firstBatch=function(){this.batcher.generate()},n._processTimestamp=function(e){return e},n._preRenderImmediate=function(){this._immediateData.finalize()},n._postRenderImmediate=function(){this._immediateData.clear()},n._initImmediate=function(){this._immediateData||(this._immediateData=new Yo(this.graphicsDevice),this.on("prerender",this._preRenderImmediate,this),this.on("postrender",this._postRenderImmediate,this))},n._addLines=function(e,t,i){var n=i&&i.layer?i.layer:this.scene.layers.getLayerById(3),s=!i||void 0===i.depthTest||i.depthTest,r=i&&i.mask?i.mask:void 0;this._initImmediate(),this._immediateData.prepareLineBatch(n,s,r,e.length/2).addLines(e,t)},n.renderLine=function(e,t,i){var n,s=i,r=arguments[3],a=arguments[4];r instanceof ue?(s=r,"number"==typeof a?(Rg||(console.warn("lineBatch argument is deprecated for renderLine. Use options.layer instead"),Rg=!0),n=1===a?{layer:this.scene.layers.getLayerById(3),depthTest:!1}:{layer:this.scene.layers.getLayerById(3),depthTest:!0}):n=a):"number"==typeof r?(Rg||(console.warn("lineBatch argument is deprecated for renderLine. Use options.layer instead"),Rg=!0),s=i,n=1===r?{layer:this.scene.layers.getLayerById(3),depthTest:!1}:{layer:this.scene.layers.getLayerById(3),depthTest:!0}):r&&(n=r),this._addLines([e,t],[i,s],n)},n.renderLines=function(e,t,i){i?"number"==typeof i&&(Rg||(console.warn("lineBatch argument is deprecated for renderLine. Use options.layer instead"),Rg=!0),i=1===i?{layer:this.scene.layers.getLayerById(3),depthTest:!1}:{layer:this.scene.layers.getLayerById(3),depthTest:!0}):i={layer:this.scene.layers.getLayerById(3),depthTest:!0},!t.length||e.length===t.length?e.length%2==0?this._addLines(e,t,i):console.error("renderLines: array length is not divisible by 2"):console.error("renderLines: position/color arrays have different lengths")},n._getDefaultImmediateOptions=function(e){return void 0===e&&(e=!1),{layer:this.scene.layers.getLayerById(3),depthTest:e}},n.renderWireCube=function(e,t,i){void 0===i&&(i=this._getDefaultImmediateOptions(!0)),this._initImmediate(),this._immediateData.renderWireCube(e,t,i)},n.renderWireSphere=function(e,t,i,n){void 0===n&&(n=this._getDefaultImmediateOptions(!0)),this._initImmediate(),this._immediateData.renderWireSphere(e,t,i,n)},n.renderMeshInstance=function(e,t){void 0===t&&(t=this._getDefaultImmediateOptions(!0)),this._initImmediate(),this._immediateData.renderMesh(null,null,null,e,t)},n.renderMesh=function(e,t,i,n){void 0===n&&(n=this._getDefaultImmediateOptions(!0)),this._initImmediate(),this._immediateData.renderMesh(t,i,e,null,n)},n.renderQuad=function(e,t,i){void 0===i&&(i=this._getDefaultImmediateOptions()),this._initImmediate(),this._immediateData.renderMesh(t,e,this._immediateData.getQuadMesh(),null,i)},n.renderTexture=function(e,t,i,n,s,r,a){this._initImmediate();var o=new we;o.setTRS(new me(e,t,0),Me.IDENTITY,new me(i,n,0)),r||((r=new bn).setParameter("colorMap",s),r.shader=this._immediateData.getTextureShader(),r.update()),this.renderQuad(o,r,a)},n.renderDepthTexture=function(e,t,i,n,s){this._initImmediate();var r=new bn;r.shader=this._immediateData.getDepthTextureShader(),r.update(),this.renderTexture(e,t,i,n,null,r,s)},n.destroy=function(){if(this._inFrameUpdate)this._destroyRequested=!0;else{var e,t,n=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);var s=this.systems.list;for(e=0,t=s.length;e>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 an("picker"),this.layerComp.pushOpaque(this.layer)},t.prepare=function(e,t,i){e instanceof br&&(e=e.node.camera),i instanceof ka&&(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;cUg?Ug:i.width||512,r=i.height>Ug?Ug:i.height||512,a=document.createElement("canvas");a.height=r,a.width=s;var o=new Vi(n.app.graphicsDevice,{format:7,mipmaps:!0});return o.name="font",o.setSource(a),o.minFilter=5,o.magFilter=1,o.addressU=1,o.addressV=1,n.textures=[o],n.chars="",n.data={},n}Z(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;eM&&(M=this.fontSize*this.fontSize/A,c.font=this.fontWeight+" "+M.toString()+"px "+this.fontName,A=this.fontSize),this.renderCharacter(c,d,S+x,T+b,r);var C=this.padding+(this.glyphSize-A)/2,E=-this.padding+g[d].descent-_,P=A;if(this._addChar(this.data,d,w,S,T,v,y,C,E,P,t-1,n,s),(S+=v)+v>n&&(S=0,(T+=y)+y>s))if(this.textures[t-1].upload(),T=0,++t>p){(i=document.createElement("canvas")).height=s,i.width=n,c=this._getAndClearContext(i,o);var I=new Vi(this.app.graphicsDevice,{format:7,mipmaps:!0});I.name="font-atlas",I.setSource(i),I.minFilter=5,I.magFilter=1,I.addressU=1,I.addressV=1,this.textures.push(I)}else i=this.textures[t-1].getSource(),c=this._getAndClearContext(i,o)}if(this.textures[t-1].upload(),t=0&&(this._count++,this.fire("progress",e)),this._count===this._total&&setTimeout((function(){t._loadingComplete(t._failed)}),0)},i._onError=function(e,t){var i=this;this._assets.indexOf(t)>=0&&(this._count++,this._failed.push(t)),this._count===this._total&&setTimeout((function(){i._loadingComplete(i._failed)}),0)},i._onAddAsset=function(e){var t,i=this._waitingAssets.indexOf(e);i>=0&&this._waitingAssets.splice(i,1),this._assets.push(e);var n=this._assets.length;for(t=0;t0?this.wheelDelta=1:i.deltaY<0&&(this.wheelDelta=-1)),nv()?(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},ov=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(Q(i)),i._downHandler=i._handleDown.bind(Q(i)),i._moveHandler=i._handleMove.bind(Q(i)),i._wheelHandler=i._handleWheel.bind(Q(i)),i._contextMenuHandler=function(e){e.preventDefault()},i._target=null,i._attached=!1,i.attach(t),i}Z(t,e),t.isPointerLocked=function(){return nv()};var i=t.prototype;return i.attach=function(e){if(this._target=e,!this._attached){this._attached=!0;var t=!!D.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=!!D.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 av(this,e);t.event&&this.fire(G_,t)},i._handleDown=function(e){this._buttons[e.button]=!0;var t=new av(this,e);t.event&&this.fire(U_,t)},i._handleMove=function(e){var t=new av(this,e);t.event&&(this.fire(V_,t),this._lastX=t.x,this._lastY=t.y)},i._handleWheel=function(e){var t=new av(this,e);t.event&&this.fire(W_,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}(_),hv=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(e),this._mouse&&this._mouse.update(e),this._gamepads&&this._gamepads.update(e),this._axesValues={},this._axes)this._axesValues[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._actions[e]?this._actions[e].push({type:N_,keys:t}):this._actions[e]=[{type:N_,keys:t}]},t.registerMouse=function(e,t){if(this._mouse||this._enableMouse(),void 0===t)throw new Error("Invalid button");this._actions[e]?this._actions[e].push({type:B_,button:t}):this._actions[e]=[{type:B_,button:-t}]},t.registerPadButton=function(e,t,i){if(void 0===i)throw new Error("Invalid button");this._actions[e]?this._actions[e].push({type:z_,button:i,pad:t}):this._actions[e]=[{type:z_,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(V_,(function(e){n._axesValues[t][i]=e.dx/10}));break;case"mousey":n._mouse.on(V_,(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;var t,i=0,n=this._actions[e].length;for(i=0;iMath.abs(t)&&(t=s)}else this._axesValues[e]&&Math.abs(this._axesValues[e][i])>Math.abs(t)&&(t=this._axesValues[e][i])}return t},t._enableMouse=function(){if(this._mouse=new ov,!this._element)throw new Error("Controller must be attached to an Element");this._mouse.attach(this._element)},t._enableKeyboard=function(){if(this._keyboard=new iv,!this._element)throw new Error("Controller must be attached to an Element");this._keyboard.attach(this._element)},e}(),lv=new me,cv=new me,uv=new qe,dv=new qe,fv=new qe;uv.end=new me,dv.end=new me,fv.end=new me;var pv=new me,mv=new me,_v=new me,gv=new me,vv=new me,yv=new me,xv=new me,bv=new ge,Sv=new me,Tv=new me,wv=new me,Mv=new me,Av=new me,Cv=new me,Ev=new me,Pv=new me,Iv=new ve;function Rv(e,t,i){return xv.cross(e,t).dot(i)}var Lv=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}(),Dv=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,ov.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 Z(t,e),t}(Lv),kv=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 Z(t,e),t}(Lv),Ov=function(e){function t(t,i,n,s){var r;return(r=e.call(this,t,i,n)||this).inputSource=s,r}return Z(t,e),t}(Lv),Fv=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,D.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=!!D.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&&D.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=!!D.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&&(ov.isPointerLocked()||(this._calcMouseCoords(e),null!==sv&&this._onElementMouseEvent("mouseup",e)))},t._handleDown=function(e){this._enabled&&(ov.isPointerLocked()||(this._calcMouseCoords(e),null!==sv&&this._onElementMouseEvent("mousedown",e)))},t._handleMove=function(e){this._enabled&&(this._calcMouseCoords(e),null!==sv&&(this._onElementMouseEvent("mousemove",e),this._lastX=sv,this._lastY=rv))},t._handleWheel=function(e){this._enabled&&(this._calcMouseCoords(e),null!==sv&&this._onElementMouseEvent("mousewheel",e))},t._determineTouchedElements=function(e){var t,i,n,s={},r=this.app.systems.camera.cameras;for(t=r.length-1;t>=0;t--){var a=r[t],o=0;for(i=0,n=e.changedTouches.length;i=0;d--){this._getTargetElement(t[d],u.x,u.y)===o&&(this._clickedEntities[o.entity.getGuid()]||(this._fireEvent("click",new kv(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._getTargetElement(s,sv,rv)));a--);i&&(this._fireEvent(e,new Dv(t,i,s,sv,rv,this._lastX,this._lastY)),this._hoveredElement=i,"mousedown"===e&&(this._pressedElement=i)),n!==this._hoveredElement&&(n&&this._fireEvent("mouseleave",new Dv(t,n,s,sv,rv,this._lastX,this._lastY)),this._hoveredElement&&this._fireEvent("mouseenter",new Dv(t,this._hoveredElement,s,sv,rv,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 Dv(t,this._hoveredElement,s,sv,rv,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(fv,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 Ov(i,a,r,t)),s&&this._fireEvent("selectenter",new Ov(i,s,r,t))),"selectstart"===e&&(this._selectedPressedElements[t.id]=s,s&&this._fireEvent("selectstart",new Ov(i,s,r,t)));var l=this._selectedPressedElements[t.id];!t.elementInput&&l&&(delete this._selectedPressedElements[t.id],a&&this._fireEvent("selectend",new Ov(i,a,r,t))),"selectend"===e&&t.elementInput&&(delete this._selectedPressedElements[t.id],a&&this._fireEvent("selectend",new Ov(i,a,r,t)),l&&l===a&&this._fireEvent("click",new Ov(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);e.clientX=i+this._target.clientWidth||e.clientY=n+this._target.clientHeight?(sv=null,rv=null):(sv=e.clientX-i,rv=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._getTargetElement=function(e,t,i){var n,s,r=null;this._elements.sort(this._sortHandler);for(var a=0,o=this._elements.length;a=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,lv),i.screenToWorld(d,f,i.farClip,cv),n.origin.copy(lv),n.direction.set(0,0,-1),n.end.copy(cv),!0)},t._checkElement=function(e,t,i){var n;if(t.maskedBy&&!this._checkElement(e,t.maskedBy.element,i))return!1;n=i?this._calculateScaleToScreen(t):t.entity.getWorldTransform().getScale();var s=this._buildHitCorners(t,i?t.screenCorners:t.worldCorners,n.x,n.y);return!!function(e,t,i){if(pv.sub2(t,e),mv.sub2(i[0],e),_v.sub2(i[1],e),gv.sub2(i[2],e),yv.cross(gv,pv),mv.dot(yv)>=0){if(-_v.dot(yv)<0)return!1;if(Rv(pv,_v,mv)<0)return!1}else{if(vv.sub2(i[3],e),vv.dot(yv)<0)return!1;if(Rv(pv,mv,vv)<0)return!1}return!(pv.sub2(i[0],i[2]).lengthSq()<1e-8||pv.sub2(i[1],i[3]).lengthSq()<1e-8)}(e.origin,e.end,s)},Y(e,[{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"app",get:function(){return this._app||tn()},set:function(e){this._app=e}}]),e}(),Bv={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"]}},Nv={"Product: 0268":"PS3"},zv=function(){function e(){this.gamepadsSupported=!!navigator.getGamepads||!!navigator.webkitGetGamepads,this.current=[],this.previous=[],this.deadZone=.25}var t=e.prototype;return t.update=function(){var e,t,i,n,s;for(e=0,i=this.current.length;e0&&(e.length=0),this.gamepadsSupported){var t,i=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads(),n=i.length;for(t=0;t=0)return Bv[Nv[t]];return Bv.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)128){var A=Math.round(Math.log2(128)),C=Math.round(Math.log2(y))-A;for(o=0;o1&&f){b[l]=b[l-2];continue}for(o=0;o<7;o++)for(h=0;h<6;h++)a=new Qn({colorBuffer:b[l][o],face:h,depth:!1}),v[0]=h,v[1]=l<0?R:S[o],v[2]=T[o],v[3]=f?3:l,_.setValue(0===o?i:0===n?b[0][o-1]:b[-1][o-1]),g.setValue(v),bi(t,a,p),r&&Jn(t,a,h)}if(e.filtered=b[0],r&&e.singleFilteredFixed){for(I=[i].concat(e.filteredFixed),(u=new Vi(t,{cubemap:!0,type:d,fixCubemapSeams:!0,format:x,width:128,height:128,addressU:1,addressV:1})).name="prefiltered-cube",o=0;o