/** * @license * PlayCanvas Engine v2.8.2 revision 9dcece8 (RELEASE) * Copyright 2011-2025 PlayCanvas Ltd. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var e,t,n;function i(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?!!t[Symbol.hasInstance](e):e instanceof t}e=this,t=function(e){var t,n,r,s,a,o,l,u,c,h,f,d,p,m,_,v,g,y,S,x,b,T,E,w,A,C,P,I,L,D,R,M,O,k,N,F,B,U,V,z,G="undefined"!=typeof document?document.currentScript:null;function H(e,t,n){e.prototype[t]||Object.defineProperty(e.prototype,t,{value:n,configurable:true,enumerable:false,writable:true});}if(H(Array,"fill",function(e){if(this==null)throw TypeError("this is null or not defined");for(var t=Object(this),n=t.length>>>0,i=arguments[1],r=0|i,s=r<0?Math.max(n+r,0):Math.min(r,n),a=arguments[2],o=void 0===a?n:0|a,l=o<0?Math.max(n+o,0):Math.min(o,n);s>>0;if("function"!=typeof e)throw TypeError("predicate must be a function");for(var i=arguments[1],r=0;r>>0;if("function"!=typeof e)throw TypeError("predicate must be a function");for(var i=arguments[1],r=0;r0)-(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 TypeError("Cannot convert undefined or null to object");for(var n=Object(e),i=1;ie.length)&&(t=e.length);for(var n=0,i=Array(t);nthis.length)&&(t=this.length),this.substring(t-e.length,t)===e}),H(String,"includes",function(e,t){return "number"!=typeof t&&(t=0),!(t+e.length>this.length)&&-1!==this.indexOf(e,t)}),H(String,"startsWith",function(e,t){var n=t>0?0|t:0;return this.substring(n,n+e.length)===e}),H(String,"trimEnd",function(){return this.replace(RegExp(/[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/.source+"$","g"),"")});for(var Y,q=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array],K=function(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return (n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return X(e,void 0);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return X(e,void 0)}}(e))){n&&(e=n);var i=0;return function(){return i>=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(q);!(Y=K()).done;){var Z=Y.value;H(Z,"fill",Array.prototype.fill),H(Z,"join",Array.prototype.join);}var Q="GpuTimings",J="2.8.2",$="9dcece8";function ee(e,t){for(var n in t){var i=t[n];Array.isArray(i)?e[n]=ee([],i):i&&(void 0===i?"undefined":i&&"undefined"!=typeof Symbol&&i.constructor===Symbol?"symbol":typeof i)=="object"?e[n]=ee({},i):e[n]=i;}return e}var et={create:function(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return ("x"===e?t:3&t|8).toString(16)})}},en={delimiter:"/",join:function(){for(var e=arguments.length,t=Array(e),n=0;n0){s=s.slice(0,s.length-2);continue}a>0&&s.push(en.delimiter),s.push(i[a]);}return r=s.join(""),t||r[0]!==en.delimiter||(r=r.slice(1)),n&&r[r.length-1]!==en.delimiter&&(r+=en.delimiter),r},split:function(e){var t=e.lastIndexOf(en.delimiter);return -1!==t?[e.substring(0,t),e.substring(t+1)]:["",e]},getBasename:function(e){return en.split(e)[1]},getDirectory:function(e){return en.split(e)[0]},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="",n=e.split("/"),i=0;if(n.length>1)if(en.isRelativePath(e))if("."===n[0])for(i=0;i0),eu="browser"===er&&(!!navigator.getGamepads||!!navigator.webkitGetGamepads),ec="undefined"!=typeof Worker,eh=function(){var e=false;try{var t=Object.defineProperty({},"passive",{get:function(){return e=!0,!1}});window.addEventListener("testpassive",null,t),window.removeEventListener("testpassive",null,t);}catch(e){}return e}(),ef={name:es,environment:er,global:null!=(u=null!=(l=null!=(o="undefined"!=typeof globalThis&&globalThis)?o:"browser"===er&&window)?l:"node"===er&&global)?u:"worker"===er&&self,browser:"browser"===er,worker:"worker"===er,desktop:["windows","osx","linux","cros"].includes(es),mobile:["android","ios"].includes(es),ios:"ios"===es,android:"android"===es,xbox:eo,gamepads:eu,touch:el,workers:ec,passiveEvents:eh,browserName:ea},ed="abcdefghijklmnopqrstuvwxyz",ep="ABCDEFGHIJKLMNOPQRSTUVWXYZ";function em(e,t){ void 0===t&&(t=0);var n=e.length;if(t<0||t>=n)return null;var i=e.charCodeAt(t);if(n>1&&i>=55296&&i<=56319){var r=e.charCodeAt(t+1);if(r>=56320&&r<=57343)return {code:(i-55296)*1024+r-56320+65536,long:true}}return {code:i,long:false}}function e_(e,t,n){if(!e)return false;var i=em(e);if(i){var r=i.code;return r>=t&&r<=n}return false}var ev={ASCII_LOWERCASE:ed,ASCII_UPPERCASE:ep,ASCII_LETTERS:ed+ep,format:function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),i=1;i65535?String.fromCharCode(((e-=65536)>>10)+55296,e%1024+56320):String.fromCharCode(e)}).join("")}},eg=function(){function e(e,t,n,i,r){ void 0===r&&(r=false),this._removed=false,this.handler=e,this.name=t,this.callback=n,this.scope=i,this._once=r;}var t,n=e.prototype;return n.off=function(){this._removed||this.handler.offByHandle(this);},n.on=function(e,t,n){return void 0===n&&(n=this),this.handler._addCallback(e,t,n,false)},n.once=function(e,t,n){return void 0===n&&(n=this),this.handler._addCallback(e,t,n,true)},n.toJSON=function(e){},t=[{key:"removed",get:function(){return this._removed},set:function(e){e&&(this._removed=true);}}],function(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var ex=function(){function e(){this._callbacks=new Map,this._callbackActive=new Map;}var t=e.prototype;return t.initEventHandler=function(){this._callbacks=new Map,this._callbackActive=new Map;},t._addCallback=function(e,t,n,i){if(this._callbacks.has(e)||this._callbacks.set(e,[]),this._callbackActive.has(e)){var r=this._callbackActive.get(e);r&&r===this._callbacks.get(e)&&this._callbackActive.set(e,r.slice());}var s=new eg(this,e,t,n,i);return this._callbacks.get(e).push(s),s},t.on=function(e,t,n){return void 0===n&&(n=this),this._addCallback(e,t,n,false)},t.once=function(e,t,n){return void 0===n&&(n=this),this._addCallback(e,t,n,true)},t.off=function(e,t,n){if(e)this._callbackActive.has(e)&&this._callbackActive.get(e)===this._callbacks.get(e)&&this._callbackActive.set(e,this._callbackActive.get(e).slice());else for(var i,r=eS(this._callbackActive);!(i=r()).done;){var s=i.value,a=s[0],o=s[1];this._callbacks.has(a)&&this._callbacks.get(a)===o&&this._callbackActive.set(a,o.slice());}if(e)if(t){var l=this._callbacks.get(e);if(!l)return this;for(var u=0;ut&&(this._index[e]=n-1);}return true}return false},t.list=function(){return this._list},t.clear=function(){for(var e in this._list.length=0,this._index)delete this._index[e];},e}();function eT(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?!!t[Symbol.hasInstance](e):i(e,t)}var eE=function(){function e(){}return e.loadScript=function(e,t){var n=document.createElement("script");n.setAttribute("src",e),n.onload=function(){t(null);},n.onerror=function(){t("Failed to load script='"+e+"'");},document.body.appendChild(n);},e.loadWasm=function(t,n,i){var r=e.wasmSupported()&&n.glueUrl&&n.wasmUrl?n.glueUrl:n.fallbackUrl;r?e.loadScript(r,function(e){if(e)i(e,null);else {var r=window[t];window[t]=void 0,r({locateFile:function(){return n.wasmUrl},onAbort:function(){i("wasm module aborted.");}}).then(function(e){i(null,e);});}}):i("No supported wasm modules found.",null);},e.getModule=function(t){return e.modules.hasOwnProperty(t)||(e.modules[t]={config:null,initializing:false,instance:null,callbacks:[]}),e.modules[t]},e.initialize=function(t,n){if(!n.initializing){var i=n.config;(i.glueUrl||i.wasmUrl||i.fallbackUrl)&&(n.initializing=true,e.loadWasm(t,i,function(e,t){e?i.errorHandler&&i.errorHandler(e):(n.instance=t,n.callbacks.forEach(function(e){e(t);}));}));}},e}();eE.modules={},t=function(){try{var e;if(("undefined"==typeof WebAssembly?"undefined":(e=WebAssembly)&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e)=="object"&&"function"==typeof WebAssembly.instantiate){var t=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(eT(t,WebAssembly.Module))return eT(new WebAssembly.Instance(t),WebAssembly.Instance)}}catch(e){}return false},r=n={},eE.wasmSupported=function(){return r===n&&(r=t()),r};var ew=function(){function e(){}return e.setConfig=function(e,t){var n=eE.getModule(e);n.config=t,n.callbacks.length>0&&eE.initialize(e,n);},e.getConfig=function(e){var t,n;return null==(n=eE.modules)||null==(t=n[e])?void 0:t.config},e.getInstance=function(e,t){var n=eE.getModule(e);n.instance?t(n.instance):(n.callbacks.push(t),n.config&&eE.initialize(e,n));},e}(),eA=function(){function e(e){this.offset=0,this.arraybuffer=e,this.dataView=new DataView(e);}var t,n=e.prototype;return n.reset=function(e){ void 0===e&&(e=0),this.offset=e;},n.skip=function(e){this.offset+=e;},n.align=function(e){this.offset=this.offset+e-1&~(e-1);},n._inc=function(e){return this.offset+=e,this.offset-e},n.readChar=function(){return String.fromCharCode(this.dataView.getUint8(this.offset++))},n.readChars=function(e){for(var t="",n=0;n=e.byteLength);){var n=String.fromCharCode(this.readU8());if("\n"===n)break;t+=n;}return t},t=[{key:"remainingBytes",get:function(){return this.dataView.byteLength-this.offset}}],function(e,t){for(var n=0;ns&&(r=t-1);return i},t._doSort=function(e,t){var n=this._sortBy;return e[n]-t[n]},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 eP(e,t){return (eP=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var eI=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this)||this)._index={},n._list=[],n._parent=t,n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&eP(t,e);var n,r=t.prototype;return r.add=function(){for(var e=arguments.length,t=Array(e),n=0;ne.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(t=i()).done;){var r=t.value.split("=");e[r[0]]=r[1];}return e},t.setQuery=function(e){var t="";for(var n in e)e.hasOwnProperty(n)&&(""!==t&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));this.query=t;},e}(),eO=function(){function e(){}return e.set=function(e,t){},e.get=function(t){return e._traceChannels.has(t)},e}();eO._traceChannels=new Set,eO.stack=false;var ek={DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,clamp:function(e,t,n){return e>=n?n: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,n){return e.length&&(n=e[2],t=e[1],e=e[0]),e<<16|t<<8|n},bytesToInt32:function(e,t,n,i){return e.length&&(i=e[3],n=e[2],t=e[1],e=e[0]),(e<<24|t<<16|n<<8|i)>>>0},lerp:function(e,t,n){return e+(t-e)*ek.clamp(n,0,1)},lerpAngle:function(e,t,n){return t-e>180&&(t-=360),t-e<-180&&(t+=360),ek.lerp(e,t,ek.clamp(n,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},nearestPowerOfTwo:function(e){return Math.pow(2,Math.round(Math.log2(e)))},random:function(e,t){return Math.random()*(t-e)+e},smoothstep:function(e,t,n){return n<=e?0:n>=t?1:(n=(n-e)/(t-e))*n*(3-2*n)},smootherstep:function(e,t,n){return n<=e?0:n>=t?1:(n=(n-e)/(t-e))*n*n*(n*(6*n-15)+10)},roundUp:function(e,t){return 0===t?e:Math.ceil(e/t)*t},between:function(e,t,n,i){var r=Math.min(t,n),s=Math.max(t,n);return i?e>=r&&e<=s:e>r&&e7?t=ek.intToBytes32(n):(t=ek.intToBytes24(n))[3]=255,this.set(t[0]/255,t[1]/255,t[2]/255,t[3]/255),this},t.fromArray=function(e,t){var n,i,r,s;return void 0===t&&(t=0),this.r=null!=(n=e[t])?n:this.r,this.g=null!=(i=e[t+1])?i:this.g,this.b=null!=(r=e[t+2])?r:this.b,this.a=null!=(s=e[t+3])?s:this.a,this},t.toString=function(e,t){var n=this.r,i=this.g,r=this.b,s=this.a;if(t||n>1||i>1||r>1)return n.toFixed(3)+", "+i.toFixed(3)+", "+r.toFixed(3)+", "+s.toFixed(3);var a="#"+(0x1000000+(Math.round(255*n)<<16)+(Math.round(255*i)<<8)+Math.round(255*r)).toString(16).slice(1);if(true===e){var o=Math.round(255*s).toString(16);this.a<16/255?a+="0"+o:a+=o;}return a},t.toArray=function(e,t,n){return void 0===e&&(e=[]),void 0===t&&(t=0),void 0===n&&(n=true),e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,n&&(e[t+3]=this.a),e},e}();eN.BLACK=Object.freeze(new eN(0,0,0,1)),eN.BLUE=Object.freeze(new eN(0,0,1,1)),eN.CYAN=Object.freeze(new eN(0,1,1,1)),eN.GRAY=Object.freeze(new eN(.5,.5,.5,1)),eN.GREEN=Object.freeze(new eN(0,1,0,1)),eN.MAGENTA=Object.freeze(new eN(1,0,1,1)),eN.RED=Object.freeze(new eN(1,0,0,1)),eN.WHITE=Object.freeze(new eN(1,1,1,1)),eN.YELLOW=Object.freeze(new eN(1,1,0,1));var eF=function(){function e(e,t){ void 0===t&&(t=0),this._left=-1/0,this._right=1/0,this._recip=0,this._p0=0,this._p1=0,this._m0=0,this._m1=0,this._curve=e,this._reset(t);}var t=e.prototype;return t.evaluate=function(e,t){ void 0===t&&(t=false),(t||e=this._right)&&this._reset(e);var n,i=this._curve.type;if(5===i)n=this._p0;else {var r=0===this._recip?0:(e-this._left)*this._recip;n=0===i?ek.lerp(this._p0,this._p1,r):1===i?ek.lerp(this._p0,this._p1,r*r*(3-2*r)):this._evaluateHermite(this._p0,this._p1,this._m0,this._m1,r);}return n},t._reset=function(e){var t=this._curve.keys,n=t.length;if(n)if(e=t[n-1][0])this._left=t[n-1][0],this._right=1/0,this._recip=0,this._p0=this._p1=t[n-1][1],this._m0=this._m1=0;else {for(var i=0;e>=t[i+1][0];)i++;this._left=t[i][0],this._right=t[i+1][0];var r=1/(this._right-this._left);this._recip=isFinite(r)?r:0,this._p0=t[i][1],this._p1=t[i+1][1],4===this._curve.type&&this._calcTangents(t,i);}else this._left=-1/0,this._right=1/0,this._recip=0,this._p0=this._p1=this._m0=this._m1=0;},t._calcTangents=function(e,t){var n,i,r=e[t],s=e[t+1];if(n=0===t?[e[0][0]+(e[0][0]-e[1][0]),e[0][1]+(e[0][1]-e[1][1])]:e[t-1],i=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*(s[0]-r[0])/(s[0]-n[0]),o=2*(s[0]-r[0])/(i[0]-r[0]);this._m0=this._curve.tension*(isFinite(a)?a:0)*(s[1]-n[1]),this._m1=this._curve.tension*(isFinite(o)?o:0)*(i[1]-r[1]);}else {var l=(s[0]-r[0])/(r[0]-n[0]),u=(s[0]-r[0])/(i[0]-s[0]),c=r[1]+(n[1]-r[1])*(isFinite(l)?l:0),h=s[1]+(i[1]-s[1])*(isFinite(u)?u:0),f=this._curve.tension;this._m0=f*(s[1]-c),this._m1=f*(h-r[1]);}},t._evaluateHermite=function(e,t,n,i,r){var s=r*r,a=r+r,o=1-r,l=o*o;return (1+a)*l*e+r*l*n+s*(3-a)*t+s*(r-1)*i},e}(),eB=function(){function e(e){if(this.keys=[],this.type=1,this.tension=.5,this._eval=new eF(this),e)for(var t=0;te);r++);var s=[e,t];return this.keys.splice(r,0,s),s},n.get=function(e){return this.keys[e]},n.sort=function(){this.keys.sort(function(e,t){return e[0]-t[0]});},n.value=function(e){return this._eval.evaluate(e,true)},n.closest=function(e){for(var t=this.keys,n=t.length,i=2,r=null,s=0;s=a)i=a,r=t[s];else break}return r},n.clone=function(){var e=new this.constructor;return e.keys=this.keys.map(function(e){return [].concat(e)}),e.type=this.type,e.tension=this.tension,e},n.quantize=function(e){var t=new Float32Array(e=Math.max(e,2)),n=1/(e-1);t[0]=this._eval.evaluate(0,true);for(var i=1;i1)for(var i=0;i>16&32768,i=t>>12&2047,r=t>>23&255;return r<103?n:r>142?(n|=31744,n|=+(255!==r)&&8388607&t):r<113?(i|=2048,n|=(i>>114-r)+(i>>113-r&1)):(n|=r-112<<10|i>>1,n+=1&i)},e.float2RGBA8=function(e,t){eV[0]=e;var n=ez[0];t.r=(n>>24&255)/255,t.g=(n>>16&255)/255,t.b=(n>>8&255)/255,t.a=(255&n)/255;},e}(),eH=function(){function e(){}return e.concentric=function(e,t){var n=[];n.push(0,0);for(var i=2*Math.PI/e/t,r=1;r<=e;r++)for(var s=r/e,a=Math.max(1,Math.floor(2*Math.PI*s/i)),o=2*Math.PI/a,l=0;l0){var n=1/Math.sqrt(t);this.x=e.x*n,this.y=e.y*n,this.z=e.z*n;}return this},t.floor=function(e){return void 0===e&&(e=this),this.x=Math.floor(e.x),this.y=Math.floor(e.y),this.z=Math.floor(e.z),this},t.ceil=function(e){return void 0===e&&(e=this),this.x=Math.ceil(e.x),this.y=Math.ceil(e.y),this.z=Math.ceil(e.z),this},t.round=function(e){return void 0===e&&(e=this),this.x=Math.round(e.x),this.y=Math.round(e.y),this.z=Math.round(e.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,n){return this.x=e,this.y=t,this.z=n,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.fromArray=function(e,t){var n,i,r;return void 0===t&&(t=0),this.x=null!=(n=e[t])?n:this.x,this.y=null!=(i=e[t+1])?i:this.y,this.z=null!=(r=e[t+2])?r:this.z,this},t.toString=function(){return "["+this.x+", "+this.y+", "+this.z+"]"},t.toArray=function(e,t){return void 0===e&&(e=[]),void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e},e}();eW.ZERO=Object.freeze(new eW(0,0,0)),eW.HALF=Object.freeze(new eW(.5,.5,.5)),eW.ONE=Object.freeze(new eW(1,1,1)),eW.UP=Object.freeze(new eW(0,1,0)),eW.DOWN=Object.freeze(new eW(0,-1,0)),eW.RIGHT=Object.freeze(new eW(1,0,0)),eW.LEFT=Object.freeze(new eW(-1,0,0)),eW.FORWARD=Object.freeze(new eW(0,0,-1)),eW.BACK=Object.freeze(new eW(0,0,1));var ej=function(){function e(){this.data=new Float32Array(9),this.data[0]=this.data[4]=this.data[8]=1;}var t=e.prototype;return t.clone=function(){return new this.constructor().copy(this)},t.copy=function(e){var t=e.data,n=this.data;return n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=t[3],n[4]=t[4],n[5]=t[5],n[6]=t[6],n[7]=t[7],n[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.getX=function(e){return void 0===e&&(e=new eW),e.set(this.data[0],this.data[1],this.data[2])},t.getY=function(e){return void 0===e&&(e=new eW),e.set(this.data[3],this.data[4],this.data[5])},t.getZ=function(e){return void 0===e&&(e=new eW),e.set(this.data[6],this.data[7],this.data[8])},t.equals=function(e){var t=this.data,n=e.data;return t[0]===n[0]&&t[1]===n[1]&&t[2]===n[2]&&t[3]===n[3]&&t[4]===n[4]&&t[5]===n[5]&&t[6]===n[6]&&t[7]===n[7]&&t[8]===n[8]},t.isIdentity=function(){var e=this.data;return 1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&1===e[4]&&0===e[5]&&0===e[6]&&0===e[7]&&1===e[8]},t.setIdentity=function(){var e=this.data;return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,this},t.toString=function(){return "["+this.data.join(", ")+"]"},t.transpose=function(e){ void 0===e&&(e=this);var t,n=e.data,i=this.data;return n===i?(t=n[1],i[1]=n[3],i[3]=t,t=n[2],i[2]=n[6],i[6]=t,t=n[5],i[5]=n[7],i[7]=t):(i[0]=n[0],i[1]=n[3],i[2]=n[6],i[3]=n[1],i[4]=n[4],i[5]=n[7],i[6]=n[2],i[7]=n[5],i[8]=n[8]),this},t.setFromMat4=function(e){var t=e.data,n=this.data;return n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=t[4],n[4]=t[5],n[5]=t[6],n[6]=t[8],n[7]=t[9],n[8]=t[10],this},t.setFromQuat=function(e){var t=e.x,n=e.y,i=e.z,r=e.w,s=t+t,a=n+n,o=i+i,l=t*s,u=t*a,c=t*o,h=n*a,f=n*o,d=i*o,p=r*s,m=r*a,_=r*o,v=this.data;return v[0]=1-(h+d),v[1]=u+_,v[2]=c-m,v[3]=u-_,v[4]=1-(l+d),v[5]=f+p,v[6]=c+m,v[7]=f-p,v[8]=1-(l+h),this},t.invertMat4=function(e){var t=e.data,n=t[0],i=t[1],r=t[2],s=t[4],a=t[5],o=t[6],l=t[8],u=t[9],c=t[10],h=c*a-o*u,f=-c*s+o*l,d=u*s-a*l,p=n*h+i*f+r*d;if(0===p)this.setIdentity();else {var m=1/p,_=this.data;_[0]=h*m,_[1]=(-c*i+r*u)*m,_[2]=(o*i-r*a)*m,_[3]=f*m,_[4]=(c*n-r*l)*m,_[5]=(-o*n+r*s)*m,_[6]=d*m,_[7]=(-u*n+i*l)*m,_[8]=(a*n-i*s)*m;}return this},t.transformVector=function(e,t){ void 0===t&&(t=new eW);var n=this.data,i=e.x,r=e.y,s=e.z;return t.x=i*n[0]+r*n[3]+s*n[6],t.y=i*n[1]+r*n[4]+s*n[7],t.z=i*n[2]+r*n[5]+s*n[8],t},e}();ej.IDENTITY=Object.freeze(new ej),ej.ZERO=Object.freeze(new ej().set([0,0,0,0,0,0,0,0,0]));var eX=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.addScaled=function(e,t){return this.x+=e.x*t,this.y+=e.y*t,this},t.clone=function(){return new this.constructor(this.x,this.y)},t.copy=function(e){return this.x=e.x,this.y=e.y,this},t.cross=function(e){return this.x*e.y-this.y*e.x},t.distance=function(e){var t=this.x-e.x,n=this.y-e.y;return Math.sqrt(t*t+n*n)},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.equalsApprox=function(e,t){return void 0===t&&(t=1e-6),Math.abs(this.x-e.x)0){var n=1/Math.sqrt(t);this.x=e.x*n,this.y=e.y*n;}return this},t.rotate=function(e){var t=Math.atan2(this.x,this.y)+e*ek.DEG_TO_RAD,n=Math.sqrt(this.x*this.x+this.y*this.y);return this.x=Math.sin(t)*n,this.y=Math.cos(t)*n,this},t.angle=function(){return Math.atan2(this.x,this.y)*ek.RAD_TO_DEG},t.angleTo=function(e){return Math.atan2(this.x*e.y+this.y*e.x,this.x*e.x+this.y*e.y)*ek.RAD_TO_DEG},t.floor=function(e){return void 0===e&&(e=this),this.x=Math.floor(e.x),this.y=Math.floor(e.y),this},t.ceil=function(e){return void 0===e&&(e=this),this.x=Math.ceil(e.x),this.y=Math.ceil(e.y),this},t.round=function(e){return void 0===e&&(e=this),this.x=Math.round(e.x),this.y=Math.round(e.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.fromArray=function(e,t){var n,i;return void 0===t&&(t=0),this.x=null!=(n=e[t])?n:this.x,this.y=null!=(i=e[t+1])?i:this.y,this},t.toString=function(){return "["+this.x+", "+this.y+"]"},t.toArray=function(e,t){return void 0===e&&(e=[]),void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e},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}();eX.ZERO=Object.freeze(new eX(0,0)),eX.HALF=Object.freeze(new eX(.5,.5)),eX.ONE=Object.freeze(new eX(1,1)),eX.UP=Object.freeze(new eX(0,1)),eX.DOWN=Object.freeze(new eX(0,-1)),eX.RIGHT=Object.freeze(new eX(1,0)),eX.LEFT=Object.freeze(new eX(-1,0));var eY=function(){function e(e,t,n,i){ void 0===e&&(e=0),void 0===t&&(t=0),void 0===n&&(n=0),void 0===i&&(i=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=n,this.w=i);}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.addScaled=function(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this},t.clone=function(){return new this.constructor(this.x,this.y,this.z,this.w)},t.copy=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},t.div=function(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this},t.div2=function(e,t){return this.x=e.x/t.x,this.y=e.y/t.y,this.z=e.z/t.z,this.w=e.w/t.w,this},t.divScalar=function(e){return this.x/=e,this.y/=e,this.z/=e,this.w/=e,this},t.dot=function(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w},t.equals=function(e){return this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},t.equalsApprox=function(e,t){return void 0===t&&(t=1e-6),Math.abs(this.x-e.x)0){var n=1/Math.sqrt(t);this.x=e.x*n,this.y=e.y*n,this.z=e.z*n,this.w=e.w*n;}return this},t.floor=function(e){return void 0===e&&(e=this),this.x=Math.floor(e.x),this.y=Math.floor(e.y),this.z=Math.floor(e.z),this.w=Math.floor(e.w),this},t.ceil=function(e){return void 0===e&&(e=this),this.x=Math.ceil(e.x),this.y=Math.ceil(e.y),this.z=Math.ceil(e.z),this.w=Math.ceil(e.w),this},t.round=function(e){return void 0===e&&(e=this),this.x=Math.round(e.x),this.y=Math.round(e.y),this.z=Math.round(e.z),this.w=Math.round(e.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,n,i){return this.x=e,this.y=t,this.z=n,this.w=i,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.fromArray=function(e,t){var n,i,r,s;return void 0===t&&(t=0),this.x=null!=(n=e[t])?n:this.x,this.y=null!=(i=e[t+1])?i:this.y,this.z=null!=(r=e[t+2])?r:this.z,this.w=null!=(s=e[t+3])?s:this.w,this},t.toString=function(){return "["+this.x+", "+this.y+", "+this.z+", "+this.w+"]"},t.toArray=function(e,t){return void 0===e&&(e=[]),void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e},e}();eY.ZERO=Object.freeze(new eY(0,0,0,0)),eY.HALF=Object.freeze(new eY(.5,.5,.5,.5)),eY.ONE=Object.freeze(new eY(1,1,1,1));var eq=new eX,eK=new eW,eZ=new eW,eQ=new eW,eJ=new eW,e$=function(){function e(){this.data=new Float32Array(16),this.data[0]=this.data[5]=this.data[10]=this.data[15]=1;}var t,n=e.prototype;return n.add2=function(e,t){var n=e.data,i=t.data,r=this.data;return r[0]=n[0]+i[0],r[1]=n[1]+i[1],r[2]=n[2]+i[2],r[3]=n[3]+i[3],r[4]=n[4]+i[4],r[5]=n[5]+i[5],r[6]=n[6]+i[6],r[7]=n[7]+i[7],r[8]=n[8]+i[8],r[9]=n[9]+i[9],r[10]=n[10]+i[10],r[11]=n[11]+i[11],r[12]=n[12]+i[12],r[13]=n[13]+i[13],r[14]=n[14]+i[14],r[15]=n[15]+i[15],this},n.add=function(e){return this.add2(this,e)},n.clone=function(){return new this.constructor().copy(this)},n.copy=function(e){var t=e.data,n=this.data;return n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=t[3],n[4]=t[4],n[5]=t[5],n[6]=t[6],n[7]=t[7],n[8]=t[8],n[9]=t[9],n[10]=t[10],n[11]=t[11],n[12]=t[12],n[13]=t[13],n[14]=t[14],n[15]=t[15],this},n.equals=function(e){var t=this.data,n=e.data;return t[0]===n[0]&&t[1]===n[1]&&t[2]===n[2]&&t[3]===n[3]&&t[4]===n[4]&&t[5]===n[5]&&t[6]===n[6]&&t[7]===n[7]&&t[8]===n[8]&&t[9]===n[9]&&t[10]===n[10]&&t[11]===n[11]&&t[12]===n[12]&&t[13]===n[13]&&t[14]===n[14]&&t[15]===n[15]},n.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]},n.mul2=function(e,t){var n,i,r,s,a=e.data,o=t.data,l=this.data,u=a[0],c=a[1],h=a[2],f=a[3],d=a[4],p=a[5],m=a[6],_=a[7],v=a[8],g=a[9],y=a[10],S=a[11],x=a[12],b=a[13],T=a[14],E=a[15];return n=o[0],i=o[1],r=o[2],s=o[3],l[0]=u*n+d*i+v*r+x*s,l[1]=c*n+p*i+g*r+b*s,l[2]=h*n+m*i+y*r+T*s,l[3]=f*n+_*i+S*r+E*s,n=o[4],i=o[5],r=o[6],s=o[7],l[4]=u*n+d*i+v*r+x*s,l[5]=c*n+p*i+g*r+b*s,l[6]=h*n+m*i+y*r+T*s,l[7]=f*n+_*i+S*r+E*s,n=o[8],i=o[9],r=o[10],s=o[11],l[8]=u*n+d*i+v*r+x*s,l[9]=c*n+p*i+g*r+b*s,l[10]=h*n+m*i+y*r+T*s,l[11]=f*n+_*i+S*r+E*s,n=o[12],i=o[13],r=o[14],s=o[15],l[12]=u*n+d*i+v*r+x*s,l[13]=c*n+p*i+g*r+b*s,l[14]=h*n+m*i+y*r+T*s,l[15]=f*n+_*i+S*r+E*s,this},n.mulAffine2=function(e,t){var n,i,r,s=e.data,a=t.data,o=this.data,l=s[0],u=s[1],c=s[2],h=s[4],f=s[5],d=s[6],p=s[8],m=s[9],_=s[10],v=s[12],g=s[13],y=s[14];return n=a[0],i=a[1],r=a[2],o[0]=l*n+h*i+p*r,o[1]=u*n+f*i+m*r,o[2]=c*n+d*i+_*r,o[3]=0,n=a[4],i=a[5],r=a[6],o[4]=l*n+h*i+p*r,o[5]=u*n+f*i+m*r,o[6]=c*n+d*i+_*r,o[7]=0,n=a[8],i=a[9],r=a[10],o[8]=l*n+h*i+p*r,o[9]=u*n+f*i+m*r,o[10]=c*n+d*i+_*r,o[11]=0,n=a[12],i=a[13],r=a[14],o[12]=l*n+h*i+p*r+v,o[13]=u*n+f*i+m*r+g,o[14]=c*n+d*i+_*r+y,o[15]=1,this},n.mul=function(e){return this.mul2(this,e)},n.transformPoint=function(e,t){ void 0===t&&(t=new eW);var n=this.data,i=e.x,r=e.y,s=e.z;return t.x=i*n[0]+r*n[4]+s*n[8]+n[12],t.y=i*n[1]+r*n[5]+s*n[9]+n[13],t.z=i*n[2]+r*n[6]+s*n[10]+n[14],t},n.transformVector=function(e,t){ void 0===t&&(t=new eW);var n=this.data,i=e.x,r=e.y,s=e.z;return t.x=i*n[0]+r*n[4]+s*n[8],t.y=i*n[1]+r*n[5]+s*n[9],t.z=i*n[2]+r*n[6]+s*n[10],t},n.transformVec4=function(e,t){ void 0===t&&(t=new eY);var n=this.data,i=e.x,r=e.y,s=e.z,a=e.w;return t.x=i*n[0]+r*n[4]+s*n[8]+a*n[12],t.y=i*n[1]+r*n[5]+s*n[9]+a*n[13],t.z=i*n[2]+r*n[6]+s*n[10]+a*n[14],t.w=i*n[3]+r*n[7]+s*n[11]+a*n[15],t},n.setLookAt=function(e,t,n){eQ.sub2(e,t).normalize(),eZ.copy(n).normalize(),eK.cross(eZ,eQ).normalize(),eZ.cross(eQ,eK);var i=this.data;return i[0]=eK.x,i[1]=eK.y,i[2]=eK.z,i[3]=0,i[4]=eZ.x,i[5]=eZ.y,i[6]=eZ.z,i[7]=0,i[8]=eQ.x,i[9]=eQ.y,i[10]=eQ.z,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this},n.setFrustum=function(e,t,n,i,r,s){var a=2*r,o=t-e,l=i-n,u=s-r,c=this.data;return c[0]=a/o,c[1]=0,c[2]=0,c[3]=0,c[4]=0,c[5]=a/l,c[6]=0,c[7]=0,c[8]=(t+e)/o,c[9]=(i+n)/l,c[10]=(-s-r)/u,c[11]=-1,c[12]=0,c[13]=0,c[14]=-a*s/u,c[15]=0,this},n.setPerspective=function(t,n,i,r,s){return e._getPerspectiveHalfSize(eq,t,n,i,s),this.setFrustum(-eq.x,eq.x,-eq.y,eq.y,i,r)},n.setOrtho=function(e,t,n,i,r,s){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/(i-n),a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=-2/(s-r),a[11]=0,a[12]=-(t+e)/(t-e),a[13]=-(i+n)/(i-n),a[14]=-(s+r)/(s-r),a[15]=1,this},n.setFromAxisAngle=function(e,t){t*=ek.DEG_TO_RAD;var n=e.x,i=e.y,r=e.z,s=Math.cos(t),a=Math.sin(t),o=1-s,l=o*n,u=o*i,c=this.data;return c[0]=l*n+s,c[1]=l*i+a*r,c[2]=l*r-a*i,c[3]=0,c[4]=l*i-a*r,c[5]=u*i+s,c[6]=u*r+a*n,c[7]=0,c[8]=l*r+a*i,c[9]=u*r-n*a,c[10]=o*r*r+s,c[11]=0,c[12]=0,c[13]=0,c[14]=0,c[15]=1,this},n.setTranslate=function(e,t,n){var i=this.data;return i[0]=1,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=1,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=e,i[13]=t,i[14]=n,i[15]=1,this},n.setScale=function(e,t,n){var i=this.data;return i[0]=e,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=t,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=n,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,this},n.setViewport=function(e,t,n,i){var r=this.data;return r[0]=.5*n,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=.5*i,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=.5,r[11]=0,r[12]=e+.5*n,r[13]=t+.5*i,r[14]=.5,r[15]=1,this},n.setReflection=function(e,t){var n=e.x,i=e.y,r=e.z,s=this.data;return s[0]=1-2*n*n,s[1]=-2*n*i,s[2]=-2*n*r,s[3]=0,s[4]=-2*n*i,s[5]=1-2*i*i,s[6]=-2*i*r,s[7]=0,s[8]=-2*n*r,s[9]=-2*i*r,s[10]=1-2*r*r,s[11]=0,s[12]=-2*n*t,s[13]=-2*i*t,s[14]=-2*r*t,s[15]=1,this},n.invert=function(e){ void 0===e&&(e=this);var t=e.data,n=t[0],i=t[1],r=t[2],s=t[3],a=t[4],o=t[5],l=t[6],u=t[7],c=t[8],h=t[9],f=t[10],d=t[11],p=t[12],m=t[13],_=t[14],v=t[15],g=n*o-i*a,y=n*l-r*a,S=n*u-s*a,x=i*l-r*o,b=i*u-s*o,T=r*u-s*l,E=c*m-h*p,w=c*_-f*p,A=c*v-d*p,C=h*_-f*m,P=h*v-d*m,I=f*v-d*_,L=g*I-y*P+S*C+x*A-b*w+T*E;if(0===L)this.setIdentity();else {var D=1/L,R=this.data;R[0]=(o*I-l*P+u*C)*D,R[1]=(-i*I+r*P-s*C)*D,R[2]=(m*T-_*b+v*x)*D,R[3]=(-h*T+f*b-d*x)*D,R[4]=(-a*I+l*A-u*w)*D,R[5]=(n*I-r*A+s*w)*D,R[6]=(-p*T+_*S-v*y)*D,R[7]=(c*T-f*S+d*y)*D,R[8]=(a*P-o*A+u*E)*D,R[9]=(-n*P+i*A-s*E)*D,R[10]=(p*b-m*S+v*g)*D,R[11]=(-c*b+h*S-d*g)*D,R[12]=(-a*C+o*w-l*E)*D,R[13]=(n*C-i*w+r*E)*D,R[14]=(-p*x+m*y-_*g)*D,R[15]=(c*x-h*y+f*g)*D;}return this},n.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},n.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},n.setTRS=function(e,t,n){var i=t.x,r=t.y,s=t.z,a=t.w,o=n.x,l=n.y,u=n.z,c=i+i,h=r+r,f=s+s,d=i*c,p=i*h,m=i*f,_=r*h,v=r*f,g=s*f,y=a*c,S=a*h,x=a*f,b=this.data;return b[0]=(1-(_+g))*o,b[1]=(p+x)*o,b[2]=(m-S)*o,b[3]=0,b[4]=(p-x)*l,b[5]=(1-(d+g))*l,b[6]=(v+y)*l,b[7]=0,b[8]=(m+S)*u,b[9]=(v-y)*u,b[10]=(1-(d+_))*u,b[11]=0,b[12]=e.x,b[13]=e.y,b[14]=e.z,b[15]=1,this},n.transpose=function(e){ void 0===e&&(e=this);var t,n=e.data,i=this.data;return n===i?(t=n[1],i[1]=n[4],i[4]=t,t=n[2],i[2]=n[8],i[8]=t,t=n[3],i[3]=n[12],i[12]=t,t=n[6],i[6]=n[9],i[9]=t,t=n[7],i[7]=n[13],i[13]=t,t=n[11],i[11]=n[14],i[14]=t):(i[0]=n[0],i[1]=n[4],i[2]=n[8],i[3]=n[12],i[4]=n[1],i[5]=n[5],i[6]=n[9],i[7]=n[13],i[8]=n[2],i[9]=n[6],i[10]=n[10],i[11]=n[14],i[12]=n[3],i[13]=n[7],i[14]=n[11],i[15]=n[15]),this},n.getTranslation=function(e){return void 0===e&&(e=new eW),e.set(this.data[12],this.data[13],this.data[14])},n.getX=function(e){return void 0===e&&(e=new eW),e.set(this.data[0],this.data[1],this.data[2])},n.getY=function(e){return void 0===e&&(e=new eW),e.set(this.data[4],this.data[5],this.data[6])},n.getZ=function(e){return void 0===e&&(e=new eW),e.set(this.data[8],this.data[9],this.data[10])},n.getScale=function(e){return void 0===e&&(e=new eW),this.getX(eK),this.getY(eZ),this.getZ(eQ),e.set(eK.length(),eZ.length(),eQ.length()),e},n.setFromEulerAngles=function(e,t,n){e*=ek.DEG_TO_RAD,t*=ek.DEG_TO_RAD,n*=ek.DEG_TO_RAD;var i=Math.sin(-e),r=Math.cos(-e),s=Math.sin(-t),a=Math.cos(-t),o=Math.sin(-n),l=Math.cos(-n),u=this.data;return u[0]=a*l,u[1]=-a*o,u[2]=s,u[3]=0,u[4]=r*o+l*i*s,u[5]=r*l-i*s*o,u[6]=-a*i,u[7]=0,u[8]=i*o-r*l*s,u[9]=l*i+r*s*o,u[10]=r*a,u[11]=0,u[12]=0,u[13]=0,u[14]=0,u[15]=1,this},n.getEulerAngles=function(e){ void 0===e&&(e=new eW),this.getScale(eJ);var t,n,i=eJ.x,r=eJ.y,s=eJ.z;if(0===i||0===r||0===s)return e.set(0,0,0);var a=this.data,o=Math.asin(-a[2]/i),l=.5*Math.PI;return o-l?(t=Math.atan2(a[6]/r,a[10]/s),n=Math.atan2(a[1]/i,a[0]/i)):(n=0,t=-Math.atan2(a[4]/r,a[5]/r)):(n=0,t=Math.atan2(a[4]/r,a[5]/r)),e.set(t,o,n).mulScalar(ek.RAD_TO_DEG)},n.toString=function(){return "["+this.data.join(", ")+"]"},e._getPerspectiveHalfSize=function(e,t,n,i,r){r?(e.x=i*Math.tan(t*Math.PI/360),e.y=e.x/n):(e.y=i*Math.tan(t*Math.PI/360),e.x=e.y*n);},t=[{key:"scaleSign",get:function(){return this.getX(eK),this.getY(eZ),this.getZ(eQ),eK.cross(eK,eZ),0>eK.dot(eQ)?-1:1}}],function(e,t){for(var n=0;n=.99999?(t=2*Math.atan2(r,o),n=Math.PI/2,i=0):(t=Math.atan2(2*(o*r+s*a),1-2*(r*r+s*s)),n=Math.asin(l),i=Math.atan2(2*(o*a+r*s),1-2*(s*s+a*a))),e.set(t,n,i).mulScalar(ek.RAD_TO_DEG)},t.invert=function(e){return void 0===e&&(e=this),this.conjugate(e).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.lerp=function(e,t,n){var i=(1-n)*(0>e.dot(t)?-1:1);return this.x=e.x*i+t.x*n,this.y=e.y*i+t.y*n,this.z=e.z*i+t.z*n,this.w=e.w*i+t.w*n,this.normalize()},t.mul=function(e){var t=this.x,n=this.y,i=this.z,r=this.w,s=e.x,a=e.y,o=e.z,l=e.w;return this.x=r*s+t*l+n*o-i*a,this.y=r*a+n*l+i*s-t*o,this.z=r*o+i*l+t*a-n*s,this.w=r*l-t*s-n*a-i*o,this},t.mulScalar=function(e,t){return void 0===t&&(t=this),this.x=t.x*e,this.y=t.y*e,this.z=t.z*e,this.w=t.w*e,this},t.mul2=function(e,t){var n=e.x,i=e.y,r=e.z,s=e.w,a=t.x,o=t.y,l=t.z,u=t.w;return this.x=s*a+n*u+i*l-r*o,this.y=s*o+i*u+r*a-n*l,this.z=s*l+r*u+n*o-i*a,this.w=s*u-n*a-i*o-r*l,this},t.normalize=function(e){ void 0===e&&(e=this);var t=e.length();return 0===t?(this.x=this.y=this.z=0,this.w=1):(t=1/t,this.x=e.x*t,this.y=e.y*t,this.z=e.z*t,this.w=e.w*t),this},t.set=function(e,t,n,i){return this.x=e,this.y=t,this.z=n,this.w=i,this},t.setFromAxisAngle=function(e,t){var n=Math.sin(t*=.5*ek.DEG_TO_RAD),i=Math.cos(t);return this.x=n*e.x,this.y=n*e.y,this.z=n*e.z,this.w=i,this},t.setFromEulerAngles=function(e,t,n){if(r=e,null!=eW&&"undefined"!=typeof Symbol&&eW[Symbol.hasInstance]?!!eW[Symbol.hasInstance](r):i(r,eW)){var r,s=e;e=s.x,t=s.y,n=s.z;}var a=.5*ek.DEG_TO_RAD,o=Math.sin(e*=a),l=Math.cos(e),u=Math.sin(t*=a),c=Math.cos(t),h=Math.sin(n*=a),f=Math.cos(n);return this.x=o*c*f-l*u*h,this.y=l*u*f+o*c*h,this.z=l*c*h-o*u*f,this.w=l*c*f+o*u*h,this},t.setFromMat4=function(e){var t,n=e.data,i=n[0],r=n[1],s=n[2],a=n[4],o=n[5],l=n[6],u=n[8],c=n[9],h=n[10];return 0==(t=i*i+r*r+s*s)||(i*=t=1/Math.sqrt(t),r*=t,s*=t,0==(t=a*a+o*o+l*l)||(a*=t=1/Math.sqrt(t),o*=t,l*=t,0==(t=u*u+c*c+h*h)))?this.set(0,0,0,1):(u*=t=1/Math.sqrt(t),c*=t,(h*=t)<0?i>o?this.set(1+i-o-h,r+a,u+s,l-c):this.set(r+a,1-i+o-h,l+c,u-s):i<-o?this.set(u+s,l+c,1-i-o+h,r-a):this.set(l-c,u-s,r-a,1+i+o+h),this.mulScalar(1/this.length()))},t.setFromDirections=function(e,t){var n=1+e.dot(t);return nMath.abs(e.y)?(this.x=-e.z,this.y=0,this.z=e.x):(this.x=0,this.y=-e.z,this.z=e.y),this.w=0):(this.x=e.y*t.z-e.z*t.y,this.y=e.z*t.x-e.x*t.z,this.z=e.x*t.y-e.y*t.x,this.w=n),this.normalize()},t.slerp=function(e,t,n){var i=e.x,r=e.y,s=e.z,a=e.w,o=t.x,l=t.y,u=t.z,c=t.w,h=a*c+i*o+r*l+s*u;if(h<0&&(c=-c,o=-o,l=-l,u=-u,h=-h),Math.abs(h)>=1)return this.w=a,this.x=i,this.y=r,this.z=s,this;var f=Math.acos(h),d=Math.sqrt(1-h*h);if(.001>Math.abs(d))return this.w=.5*a+.5*c,this.x=.5*i+.5*o,this.y=.5*r+.5*l,this.z=.5*s+.5*u,this;var p=Math.sin((1-n)*f)/d,m=Math.sin(n*f)/d;return this.w=a*p+c*m,this.x=i*p+o*m,this.y=r*p+l*m,this.z=s*p+u*m,this},t.transformVector=function(e,t){ void 0===t&&(t=new eW);var n=e.x,i=e.y,r=e.z,s=this.x,a=this.y,o=this.z,l=this.w,u=l*n+a*r-o*i,c=l*i+o*n-s*r,h=l*r+s*i-a*n,f=-s*n-a*i-o*r;return t.x=u*l+-(f*s)+-(c*o)- -(h*a),t.y=c*l+-(f*a)+-(h*s)- -(u*o),t.z=h*l+-(f*o)+-(u*a)- -(c*s),t},t.fromArray=function(e,t){var n,i,r,s;return void 0===t&&(t=0),this.x=null!=(n=e[t])?n:this.x,this.y=null!=(i=e[t+1])?i:this.y,this.z=null!=(r=e[t+2])?r:this.z,this.w=null!=(s=e[t+3])?s:this.w,this},t.toString=function(){return "["+this.x+", "+this.y+", "+this.z+", "+this.w+"]"},t.toArray=function(e,t){return void 0===e&&(e=[]),void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e},e}();e0.IDENTITY=Object.freeze(new e0(0,0,0,1)),e0.ZERO=Object.freeze(new e0(0,0,0,0));var e1=new eW,e2=new eW,e3=new eW,e4=new eW,e5=new eW,e8=function(){function e(e,t){this.center=new eW,this.halfExtents=new eW(.5,.5,.5),this._min=new eW,this._max=new eW,e&&this.center.copy(e),t&&this.halfExtents.copy(t);}var t=e.prototype;return t.add=function(e){var t=this.center,n=t.x,i=t.y,r=t.z,s=this.halfExtents,a=s.x,o=s.y,l=s.z,u=n-a,c=n+a,h=i-o,f=i+o,d=r-l,p=r+l,m=e.center,_=m.x,v=m.y,g=m.z,y=e.halfExtents,S=y.x,x=y.y,b=y.z,T=_-S,E=_+S,w=v-x,A=v+x,C=g-b,P=g+b;Tc&&(c=E),wf&&(f=A),Cp&&(p=P),t.x=(u+c)*.5,t.y=(h+f)*.5,t.z=(d+p)*.5,s.x=(c-u)*.5,s.y=(f-h)*.5,s.z=(p-d)*.5;},t.copy=function(e){this.center.copy(e.center),this.halfExtents.copy(e.halfExtents);},t.clone=function(){return new e(this.center,this.halfExtents)},t.intersects=function(e){var t=this.getMax(),n=this.getMin(),i=e.getMax(),r=e.getMin();return n.x<=i.x&&t.x>=r.x&&n.y<=i.y&&t.y>=r.y&&n.z<=i.z&&t.z>=r.z},t._intersectsRay=function(e,t){var n=e1.copy(this.getMin()).sub(e.origin),i=e2.copy(this.getMax()).sub(e.origin),r=e.direction;0===r.x?(n.x=n.x<0?-Number.MAX_VALUE:Number.MAX_VALUE,i.x=i.x<0?-Number.MAX_VALUE:Number.MAX_VALUE):(n.x/=r.x,i.x/=r.x),0===r.y?(n.y=n.y<0?-Number.MAX_VALUE:Number.MAX_VALUE,i.y=i.y<0?-Number.MAX_VALUE:Number.MAX_VALUE):(n.y/=r.y,i.y/=r.y),0===r.z?(n.z=n.z<0?-Number.MAX_VALUE:Number.MAX_VALUE,i.z=i.z<0?-Number.MAX_VALUE:Number.MAX_VALUE):(n.z/=r.z,i.z/=r.z);var s=e3.set(Math.min(n.x,i.x),Math.min(n.y,i.y),Math.min(n.z,i.z)),a=e4.set(Math.max(n.x,i.x),Math.max(n.y,i.y),Math.max(n.z,i.z)),o=Math.min(Math.min(a.x,a.y),a.z),l=Math.max(Math.max(s.x,s.y),s.z),u=o>=l&&l>=0;return u&&t.copy(e.direction).mulScalar(l).add(e.origin),u},t._fastIntersectsRay=function(e){var t=e.direction;return e1.sub2(e.origin,this.center),e4.set(Math.abs(e1.x),Math.abs(e1.y),Math.abs(e1.z)),e3.mul2(e1,t),(!(e4.x>this.halfExtents.x)||!(e3.x>=0))&&(!(e4.y>this.halfExtents.y)||!(e3.y>=0))&&(!(e4.z>this.halfExtents.z)||!(e3.z>=0))&&(e5.set(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z)),e2.cross(t,e1),e2.set(Math.abs(e2.x),Math.abs(e2.y),Math.abs(e2.z)),!(e2.x>this.halfExtents.y*e5.z+this.halfExtents.z*e5.y)&&!(e2.y>this.halfExtents.x*e5.z+this.halfExtents.z*e5.x)&&!(e2.z>this.halfExtents.x*e5.y+this.halfExtents.y*e5.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(),n=this.getMax();return !(e.xn.x)&&!(e.yn.y)&&!(e.zn.z)},t.setFromTransformedAabb=function(e,t,n){ void 0===n&&(n=false);var i=e.center,r=e.halfExtents,s=t.data,a=s[0],o=s[4],l=s[8],u=s[1],c=s[5],h=s[9],f=s[2],d=s[6],p=s[10];if(n){var m=a*a+o*o+l*l;if(m>0){var _=1/Math.sqrt(m);a*=_,o*=_,l*=_;}if((m=u*u+c*c+h*h)>0){var v=1/Math.sqrt(m);u*=v,c*=v,h*=v;}if((m=f*f+d*d+p*p)>0){var g=1/Math.sqrt(m);f*=g,d*=g,p*=g;}}this.center.set(s[12]+a*i.x+o*i.y+l*i.z,s[13]+u*i.x+c*i.y+h*i.z,s[14]+f*i.x+d*i.y+p*i.z),this.halfExtents.set(Math.abs(a)*r.x+Math.abs(o)*r.y+Math.abs(l)*r.z,Math.abs(u)*r.x+Math.abs(c)*r.y+Math.abs(h)*r.z,Math.abs(f)*r.x+Math.abs(d)*r.y+Math.abs(p)*r.z);},t.compute=function(t,n){e.computeMinMax(t,e1,e2,n),this.setMinMax(e1,e2);},t.intersectsBoundingSphere=function(e){return this._distanceToBoundingSphereSq(e)<=e.radius*e.radius},t._distanceToBoundingSphereSq=function(e){for(var t=this.getMin(),n=this.getMax(),i=0,r=["x","y","z"],s=0;s<3;++s){var a=0,o=e.center[r[s]],l=t[r[s]],u=n[r[s]],c=0;ou&&(a+=(c=o-u)*c),i+=a;}return i},t._expand=function(e,t){e1.add2(this.getMin(),e),e2.add2(this.getMax(),t),this.setMinMax(e1,e2);},e.computeMinMax=function(e,t,n,i){if(void 0===i&&(i=e.length/3),i>0){for(var r=e[0],s=e[1],a=e[2],o=r,l=s,u=a,c=3*i,h=3;ho&&(o=f),d>l&&(l=d),p>u&&(u=p);}t.set(r,s,a),n.set(o,l,u);}},e}(),e6=new eW,e9=new eW,e7=function(){function e(e,t){ void 0===e&&(e=new eW),void 0===t&&(t=.5),this.center=e,this.radius=t;}var t=e.prototype;return t.containsPoint=function(e){var t=e6.sub2(e,this.center).lengthSq(),n=this.radius;return t0&&i>0)return false;var s=i*i-r;if(s<0)return false;var a=Math.abs(-i-Math.sqrt(s));return t&&t.copy(e.direction).mulScalar(a).add(e.origin),true},t.intersectsBoundingSphere=function(e){e6.sub2(e.center,this.center);var t=e.radius+this.radius;return e6.lengthSq()<=t*t},e}(),te=function(){function e(e,t){ void 0===e&&(e=eW.UP),void 0===t&&(t=0),this.normal=new eW,this.normal.copy(e),this.distance=t;}var t=e.prototype;return t.clone=function(){return new this.constructor().copy(this)},t.copy=function(e){return this.normal.copy(e.normal),this.distance=e.distance,this},t.intersectsLine=function(e,t,n){var i=this.distance,r=this.normal.dot(e)+i,s=r/(r-(this.normal.dot(t)+i)),a=s>=0&&s<=1;return a&&n&&n.lerp(e,t,s),a},t.intersectsRay=function(e,t){var n=this.normal.dot(e.direction);if(0===n)return false;var i=-(this.normal.dot(e.origin)+this.distance)/n;return i>=0&&t&&t.copy(e.direction).mulScalar(i).add(e.origin),i>=0},t.normalize=function(){var e=1/this.normal.length();return this.normal.mulScalar(e),this.distance*=e,this},t.set=function(e,t,n,i){return this.normal.set(e,t,n),this.distance=i,this},t.setFromPointNormal=function(e,t){return this.normal.copy(t),this.distance=-this.normal.dot(e),this},e}(),tt=function(){function e(){this.planes=[];for(var e=0;e<6;e++)this.planes[e]=new te;}var t=e.prototype;return t.clone=function(){return new this.constructor().copy(this)},t.copy=function(e){for(var t=0;t<6;t++)this.planes[t].copy(e.planes[t]);return this},t.setFromMat4=function(e){var t=e.data,n=t[0],i=t[1],r=t[2],s=t[3],a=t[4],o=t[5],l=t[6],u=t[7],c=t[8],h=t[9],f=t[10],d=t[11],p=t[12],m=t[13],_=t[14],v=t[15],g=this.planes;g[0].set(s-n,u-a,d-c,v-p).normalize(),g[1].set(s+n,u+a,d+c,v+p).normalize(),g[2].set(s+i,u+o,d+h,v+m).normalize(),g[3].set(s-i,u-o,d-h,v-m).normalize(),g[4].set(s-r,u-l,d-f,v-_).normalize(),g[5].set(s+r,u+l,d+f,v+_).normalize();},t.containsPoint=function(e){for(var t=0;t<6;t++){var n=this.planes[t],i=n.normal,r=n.distance;if(i.dot(e)+r<=0)return false}return true},t.containsSphere=function(e){for(var t=e.center,n=e.radius,i=0,r=0;r<6;r++){var s=this.planes[r],a=s.normal,o=s.distance,l=a.dot(t)+o;if(l<=-n)return 0;l>n&&i++;}return 6===i?2:1},e}(),tn=function(){function e(e,t){this.origin=new eW,this.direction=eW.FORWARD.clone(),e&&this.origin.copy(e),t&&this.direction.copy(t);}var t=e.prototype;return t.set=function(e,t){return this.origin.copy(e),this.direction.copy(t),this},t.copy=function(e){return this.set(e.origin,e.direction)},t.clone=function(){return new this.constructor(this.origin,this.direction)},e}(),ti=new tn,tr=new eW,ts=new e7,ta=new e$,to=function(){function e(e,t){ void 0===e&&(e=new e$),this.halfExtents=new eW(.5,.5,.5),t&&this.halfExtents.copy(t),this._modelTransform=e.clone().invert(),this._worldTransform=e.clone(),this._aabb=new e8(new eW,this.halfExtents);}var t,n=e.prototype;return n.intersectsRay=function(e,t){if(this._modelTransform.transformPoint(e.origin,ti.origin),this._modelTransform.transformVector(e.direction,ti.direction),t){var n=this._aabb._intersectsRay(ti,t);return ta.copy(this._modelTransform).invert().transformPoint(t,t),n}return this._aabb._fastIntersectsRay(ti)},n.containsPoint=function(e){return this._modelTransform.transformPoint(e,tr),this._aabb.containsPoint(tr)},n.intersectsBoundingSphere=function(e){return this._modelTransform.transformPoint(e.center,ts.center),ts.radius=e.radius,!!this._aabb.intersectsBoundingSphere(ts)},t=[{key:"worldTransform",get:function(){return this._worldTransform},set:function(e){this._worldTransform.copy(e),this._modelTransform.copy(e).invert();}}],function(e,t){for(var n=0;n-1e-6&&n<1e-6)return false;var r=1/n;th.sub2(e.origin,this.v0);var s=r*th.dot(tc);if(s<0||s>1)return false;tf.cross(th,tl);var a=r*e.direction.dot(tf);if(a<0||s+a>1)return false;var o=r*tu.dot(tf);return !!(o>1e-6)&&((null!=eW&&"undefined"!=typeof Symbol&&eW[Symbol.hasInstance]?!!eW[Symbol.hasInstance](t):i(t,eW))&&t.copy(e.direction).mulScalar(o).add(e.origin),true)},t.toString=function(){return "["+this.v0.toString()+", "+this.v1.toString()+", "+this.v2.toString()+"]"},e}(),tp="linear",tm="inverse",t_="exponential";function tv(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(tg);!(t=n()).done;){var i=t.value,r=i[0];if(i[1].srgbFormat===e)return r}return e},tE=function(e){var t=tg.get(e);return !!((null==t?void 0:t.ldr)&&!(null==t?void 0:t.srgb))},tw=function(e){switch(e){case 15:case 13:case 14:return Float32Array;case 36:case 42:case 48:return Int32Array;case 37:case 43:case 49:return Uint32Array;case 34:case 40:case 46:return Int16Array;case 53:case 35:case 41:case 47:case 3:case 4:case 5:case 50:case 51:case 11:case 12:return Uint16Array;case 32:case 38:case 44:return Int8Array;default:return Uint8Array}},tA="POSITION",tC="NORMAL",tP="TANGENT",tI="BLENDWEIGHT",tL="BLENDINDICES",tD="COLOR",tR="TEXCOORD",tM="TEXCOORD0",tO="TEXCOORD1",tk="TEXCOORD2",tN="TEXCOORD3",tF="TEXCOORD4",tB="TEXCOORD5",tU="TEXCOORD6",tV="TEXCOORD7",tz="ATTR0",tG="ATTR1",tH="ATTR2",tW="ATTR3",tj="ATTR4",tX="ATTR5",tY="ATTR6",tq="ATTR7",tK="ATTR8",tZ="ATTR9",tQ="ATTR10",tJ="ATTR11",t$="ATTR12",t0="ATTR13",t1="ATTR14",t2="ATTR15",t3="default",t4="rgbm",t5="rgbe",t8="rgbp",t6="swizzleGGGR",t9="2d-array",t7="cube",ne="cube-array",nt="none",nn="cube",ni="equirect",nr="octahedral",ns="glsl",na="wgsl",no=["bool","int","float","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","mat2","mat3","mat4","sampler2D","samplerCube","","sampler2DShadow","samplerCubeShadow","sampler3D","","","","","sampler2DArray","uint","uvec2","uvec3","uvec4","","","","","","","","","","","","","isampler2D","usampler2D","isamplerCube","usamplerCube","isampler3D","usampler3D","isampler2DArray","usampler2DArray"],nl=[["bool"],["i32"],["f32"],["vec2f","vec2"],["vec3f","vec3"],["vec4f","vec4"],["vec2i","vec2"],["vec3i","vec3"],["vec4i","vec4"],["vec2"],["vec3"],["vec4"],["mat2x2f","mat2x2"],["mat3x3f","mat3x3"],["mat4x4f","mat4x4"],["texture_2d"],["texture_cube"],["array"],["texture_depth_2d"],["texture_depth_cube"],["texture_3d"],["array>"],["array>"],["array>"],["array>"],["texture_2d_array"],["u32"],["vec2u","vec2"],["vec3u","vec3"],["vec4u","vec4"],["array"],["array"],["array"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["texture_2d"],["texture_2d"],["texture_cube"],["texture_cube"],["texture_3d"],["texture_3d"],["texture_2d_array"],["texture_2d_array"]],nu=new Map;nl.forEach(function(e,t){e.forEach(function(e){return nu.set(e,t)});});var nc=new Uint8Array([4,4,6,6,6,6,4,4,4,4,4,4,6,6,6,4,4,6,4,4,4,6,6,6,6,4,5,5,5,5,4,5,4,4,5,4,4,5,4,4,5,4,4,5,4,5,4,5,4,5]),nh="webgl2",nf="webgpu",nd="null",np="ldr_srgb",nm=["view","mesh","mesh_ub"],n_="default",nv="_unused_float_uniform",ng=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Uint16Array],ny=[1,1,2,2,4,4,4,2],nS=[Uint8Array,Uint16Array,Uint32Array],nx=[1,2,4],nb={};function nT(e,t){if("function"!=typeof t&&null!==t)throw TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:true,configurable:true}}),t&&nw(e,t);}function nE(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?!!t[Symbol.hasInstance](e):i(e,t)}function nw(e,t){return (nw=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}nb[tA]=0,nb[tC]=1,nb[tI]=2,nb[tL]=3,nb[tD]=4,nb[tM]=5,nb[tO]=6,nb[tk]=7,nb[tN]=8,nb[tF]=9,nb[tB]=10,nb[tU]=11,nb[tV]=12,nb[tP]=13,nb[tz]=0,nb[tG]=1,nb[tH]=2,nb[tW]=3,nb[tj]=4,nb[tX]=5,nb[tY]=6,nb[tq]=7,nb[tK]=8,nb[tZ]=9,nb[tQ]=10,nb[tJ]=11,nb[t$]=12,nb[t0]=13,nb[t1]=14,nb[t2]=15;var nA=0,nC=function(e,t){this.slot=-1,this.scopeId=null,this.name=e,this.visibility=t;},nP=function(e){function t(){return e.apply(this,arguments)||this}return nT(t,e),t}(nC),nI=function(e){function t(t,n,i){var r;return void 0===i&&(i=false),(r=e.call(this,t,n)||this).format="",r.readOnly=i,r}return nT(t,e),t}(nC),nL=function(e){function t(t,n,i,r,s,a){var o;return void 0===i&&(i="2d"),void 0===r&&(r=0),void 0===s&&(s=true),void 0===a&&(a=null),(o=e.call(this,t,n)||this).textureDimension=i,o.sampleType=r,o.hasSampler=s,o.samplerName=null!=a?a:""+t+"_sampler",o}return nT(t,e),t}(nC),nD=function(e){function t(t,n,i,r,s){var a;return void 0===n&&(n=7),void 0===i&&(i="2d"),void 0===r&&(r=true),void 0===s&&(s=false),(a=e.call(this,t,4)||this).format=n,a.textureDimension=i,a.write=r,a.read=s,a}return nT(t,e),t}(nC),nR=function(){function e(e,t){var n=this;this.uniformBufferFormats=[],this.textureFormats=[],this.storageTextureFormats=[],this.storageBufferFormats=[],this.id=nA++;var i=0;t.forEach(function(e){e.slot=i++,nE(e,nL)&&e.hasSampler&&i++,nE(e,nP)?n.uniformBufferFormats.push(e):nE(e,nL)?n.textureFormats.push(e):nE(e,nD)?n.storageTextureFormats.push(e):nE(e,nI)&&n.storageBufferFormats.push(e);}),this.device=e;var r=e.scope;this.bufferFormatsMap=new Map,this.uniformBufferFormats.forEach(function(e,t){return n.bufferFormatsMap.set(e.name,t)}),this.textureFormatsMap=new Map,this.textureFormats.forEach(function(e,t){n.textureFormatsMap.set(e.name,t),e.scopeId=r.resolve(e.name);}),this.storageTextureFormatsMap=new Map,this.storageTextureFormats.forEach(function(e,t){n.storageTextureFormatsMap.set(e.name,t),e.scopeId=r.resolve(e.name);}),this.storageBufferFormatsMap=new Map,this.storageBufferFormats.forEach(function(e,t){n.storageBufferFormatsMap.set(e.name,t),e.scopeId=r.resolve(e.name);}),this.impl=e.createBindGroupFormatImpl(this);}var t=e.prototype;return t.destroy=function(){this.impl.destroy();},t.getTexture=function(e){var t=this.textureFormatsMap.get(e);return void 0!==t?this.textureFormats[t]:null},t.getStorageTexture=function(e){var t=this.storageTextureFormatsMap.get(e);return void 0!==t?this.storageTextureFormats[t]:null},t.loseContext=function(){},e}(),nM=function(){function e(){this._cache=new Map;}var t=e.prototype;return t.get=function(e,t){var n=this;return this._cache.has(e)||(this._cache.set(e,t()),e.on("destroy",function(){n.remove(e);}),e.on("devicelost",function(){var t,i;null==(i=n._cache.get(e))||null==(t=i.loseContext)||t.call(i,e);})),this._cache.get(e)},t.remove=function(e){var t,n;null==(n=this._cache.get(e))||null==(t=n.destroy)||t.call(n,e),this._cache.delete(e);},e}(),nO=function(){function e(){}return e.calcLevelDimension=function(e,t){return Math.max(e>>t,1)},e.calcMipLevelsCount=function(e,t,n){return void 0===n&&(n=1),1+Math.floor(Math.log2(Math.max(e,t,n)))},e.calcLevelGpuSize=function(e,t,n,i){var r,s,a,o=tg.get(i),l=null!=(s=null==(r=tg.get(i))?void 0:r.size)?s:0;if(l>0)return e*t*n*l;var u=null!=(a=o.blockSize)?a:0,c=Math.floor((e+3)/4),h=Math.floor((t+3)/4),f=Math.floor((n+3)/4);return (24===i||25===i)&&(c=Math.max(Math.floor(c/2),1)),c*h*f*u},e.calcGpuSize=function(t,n,i,r,s,a){for(var o=0;o+=e.calcLevelGpuSize(t,n,i,r),s&&(1!==t||1!==n||1!==i);)t=Math.max(t>>1,1),n=Math.max(n>>1,1),i=Math.max(i>>1,1);return o*(a?6:1)},e}(),nk=0,nN=function(){function e(e,t){ void 0===t&&(t={}),this._gpuSize=0,this.id=nk++,this._invalid=false,this._lockedLevel=-1,this._lockedMode=0,this.renderVersionDirty=0,this._storage=false,this._numLevels=0,this.device=e,this.name=null!=(n=t.name)?n:"",this._width=Math.floor(null!=(i=t.width)?i:4),this._height=Math.floor(null!=(r=t.height)?r:4),this._format=null!=(s=t.format)?s:7,this._compressed=ty(this._format),this._integerFormat=tx(this._format),this._integerFormat&&(t.minFilter=0,t.magFilter=0),this._volume=null!=(a=t.volume)&&a,this._depth=Math.floor(null!=(o=t.depth)?o:1),this._arrayLength=Math.floor(null!=(l=t.arrayLength)?l:0),this._storage=null!=(u=t.storage)&&u,this._cubemap=null!=(c=t.cubemap)&&c,this._flipY=null!=(h=t.flipY)&&h,this._premultiplyAlpha=null!=(f=t.premultiplyAlpha)&&f,this._mipmaps=null==(d=t.mipmaps)||d,this._numLevelsRequested=t.numLevels,void 0!==t.numLevels&&(this._numLevels=t.numLevels),this._updateNumLevel(),this._minFilter=null!=(p=t.minFilter)?p:5,this._magFilter=null!=(m=t.magFilter)?m:1,this._anisotropy=null!=(_=t.anisotropy)?_:1,this._addressU=null!=(v=t.addressU)?v:0,this._addressV=null!=(g=t.addressV)?g:0,this._addressW=null!=(y=t.addressW)?y:0,this._compareOnRead=null!=(S=t.compareOnRead)&&S,this._compareFunc=null!=(x=t.compareFunc)?x:1,this._type=null!=(b=t.type)?b:t3,this.projection=nt,this._cubemap?this.projection=nn:t.projection&&t.projection!==nn&&(this.projection=t.projection),this._levels=t.levels;var n,i,r,s,a,o,l,u,c,h,f,d,p,m,_,v,g,y,S,x,b,T=!!t.levels;this._levels||(this._levels=this._cubemap?[[null,null,null,null,null,null]]:[null]),this.recreateImpl(T),e.textures.push(this);}var t,n=e.prototype;return n.destroy=function(){var e=this.device;if(e){var t=e.textures.indexOf(this);-1!==t&&e.textures.splice(t,1),e.scope.removeValue(this),this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this._gpuSize),this._levels=null,this.device=null;}},n.recreateImpl=function(e){ void 0===e&&(e=true);var t,n=this.device;null==(t=this.impl)||t.destroy(n),this.impl=null,this.impl=n.createTextureImpl(this),this.dirtyAll(),e&&this.upload();},n.resize=function(e,t,n){ void 0===n&&(n=1);var i=this.device;this.adjustVramSizeTracking(i._vram,-this._gpuSize),this.impl.destroy(i),this._width=Math.floor(e),this._height=Math.floor(t),this._depth=Math.floor(n),this._updateNumLevel(),this.impl=i.createTextureImpl(this),this.dirtyAll();},n.loseContext=function(){this.impl.loseContext(),this.dirtyAll();},n.adjustVramSizeTracking=function(e,t){e.tex+=t;},n.propertyChanged=function(e){this.impl.propertyChanged(e),this.renderVersionDirty=this.device.renderVersion;},n._updateNumLevel=function(){var e=this.mipmaps?nO.calcMipLevelsCount(this.width,this.height):1,t=this._numLevelsRequested;this._numLevels=Math.min(null!=t?t:e,e),this._mipmaps=this._numLevels>1;},n.dirtyAll=function(){this._levelsUpdated=this._cubemap?[[true,true,true,true,true,true]]:[true],this._needsUpload=true,this._needsMipmapsUpload=this._mipmaps,this._mipmapsUploaded=false,this.propertyChanged(255);},n.lock=function(e){ void 0===e&&(e={}),null!=(t=e).level||(t.level=0),null!=(n=e).face||(n.face=0),null!=(i=e).mode||(i.mode=2),this._lockedMode=e.mode,this._lockedLevel=e.level;var t,n,i,r=this.cubemap?this._levels[e.face]:this._levels;if(null===r[e.level]){var s=Math.max(1,this._width>>e.level),a=Math.max(1,this._height>>e.level),o=Math.max(1,this._depth>>e.level),l=new ArrayBuffer(nO.calcLevelGpuSize(s,a,o,this._format));r[e.level]=new(tw(this._format))(l);}return r[e.level]},n.setSource=function(e,t){ void 0===t&&(t=0);var n,r,s,a=false;if(this._cubemap){if(e[0]){r=e[0].width||0,s=e[0].height||0;for(var o=0;o<6;o++){var l=e[o];if(!l||l.width!==r||l.height!==s||!this.device._isBrowserInterface(l)){a=true;break}}}else a=true;if(!a)for(var u=0;u<6;u++)this._levels[t][u]!==e[u]&&(this._levelsUpdated[t][u]=true);}else this.device._isBrowserInterface(e)||(a=true),a||((e!==this._levels[t]&&(this._levelsUpdated[t]=true),null!=(n=HTMLVideoElement)&&"undefined"!=typeof Symbol&&n[Symbol.hasInstance]?!!n[Symbol.hasInstance](e):i(e,n))?(r=e.videoWidth,s=e.videoHeight):(r=e.width,s=e.height));if(a)if(this._width=4,this._height=4,this._cubemap)for(var c=0;c<6;c++)this._levels[t][c]=null,this._levelsUpdated[t][c]=true;else this._levels[t]=null,this._levelsUpdated[t]=true;else 0===t&&(this._width=r,this._height=s),this._levels[t]=e;this._invalid===a&&a||(this._invalid=a,this.upload());},n.getSource=function(e){return void 0===e&&(e=0),this._levels[e]},n.unlock=function(){this._lockedMode,2===this._lockedMode&&this.upload(),this._lockedLevel=-1,this._lockedMode=0;},n.upload=function(){this._needsUpload=true,this._needsMipmapsUpload=this._mipmaps,null==this.impl.uploadImmediate||this.impl.uploadImmediate.call(this.impl,this.device,this);},n.read=function(e,t,n,i,r){return void 0===r&&(r={}),null==this.impl.read?void 0:this.impl.read.call(this.impl,e,t,n,i,r)},n.write=function(e,t,n,i,r){return null==this.impl.write?void 0:this.impl.write.call(this.impl,e,t,n,i,r)},t=[{key:"lockedMode",get:function(){return this._lockedMode}},{key:"minFilter",get:function(){return this._minFilter},set:function(e){this._minFilter!==e&&(tx(this._format)||(this._minFilter=e,this.propertyChanged(1)));}},{key:"magFilter",get:function(){return this._magFilter},set:function(e){this._magFilter!==e&&(tx(this._format)||(this._magFilter=e,this.propertyChanged(2)));}},{key:"addressU",get:function(){return this._addressU},set:function(e){this._addressU!==e&&(this._addressU=e,this.propertyChanged(4));}},{key:"addressV",get:function(){return this._addressV},set:function(e){this._addressV!==e&&(this._addressV=e,this.propertyChanged(8));}},{key:"addressW",get:function(){return this._addressW},set:function(e){this._volume&&e!==this._addressW&&(this._addressW=e,this.propertyChanged(16));}},{key:"compareOnRead",get:function(){return this._compareOnRead},set:function(e){this._compareOnRead!==e&&(this._compareOnRead=e,this.propertyChanged(32));}},{key:"compareFunc",get:function(){return this._compareFunc},set:function(e){this._compareFunc!==e&&(this._compareFunc=e,this.propertyChanged(64));}},{key:"anisotropy",get:function(){return this._anisotropy},set:function(e){this._anisotropy!==e&&(this._anisotropy=e,this.propertyChanged(128));}},{key:"mipmaps",get:function(){return this._mipmaps},set:function(e){this._mipmaps!==e&&(this.device.isWebGPU||tx(this._format)||(this._mipmaps=e),e&&(this._needsMipmapsUpload=true));}},{key:"numLevels",get:function(){return this._numLevels}},{key:"storage",get:function(){return this._storage}},{key:"width",get:function(){return this._width}},{key:"height",get:function(){return this._height}},{key:"depth",get:function(){return this._depth}},{key:"format",get:function(){return this._format}},{key:"cubemap",get:function(){return this._cubemap}},{key:"gpuSize",get:function(){var e=this.pot&&this._mipmaps&&!(this._compressed&&1===this._levels.length);return nO.calcGpuSize(this._width,this._height,this._depth,this._format,e,this._cubemap)}},{key:"array",get:function(){return this._arrayLength>0}},{key:"arrayLength",get:function(){return this._arrayLength}},{key:"volume",get:function(){return this._volume}},{key:"type",get:function(){return this._type},set:function(e){this._type!==e&&(this._type=e,this.device._shadersDirty=true);}},{key:"srgb",get:function(){return tS(this.format)},set:function(e){if(e!==tS(this.format))if(e){var t=tb(this.format);this._format!==t&&(this._format=t,this.recreateImpl(),this.device._shadersDirty=true);}else {var n=tT(this.format);this._format!==n&&(this._format=n,this.recreateImpl(),this.device._shadersDirty=true);}}},{key:"flipY",get:function(){return this._flipY},set:function(e){this._flipY!==e&&(this._flipY=e,this._needsUpload=true);}},{key:"premultiplyAlpha",get:function(){return this._premultiplyAlpha},set:function(e){this._premultiplyAlpha!==e&&(this._premultiplyAlpha=e,this._needsUpload=true);}},{key:"pot",get:function(){return ek.powerOfTwo(this._width)&&ek.powerOfTwo(this._height)}},{key:"encoding",get:function(){switch(this.type){case t4:return "rgbm";case t5:return "rgbe";case t8:return "rgbp"}return tE(this.format)?"srgb":"linear"}}],function(e,t){for(var n=0;n>t&n},nX=function(e,t,n){ void 0===n&&(n=1);var i=n<>>0}var n8=new nq,n6=[2,4,8,12,16],n9=new nM,n7=function(){function e(e,t,n){this.device=e,this._elements=[],this.hasUv0=false,this.hasUv1=false,this.hasColor=false,this.hasTangents=false,this.verticesByteSize=0,this.vertexCount=n,this.interleaved=void 0===n,this.instancing=false,this.size=t.reduce(function(e,t){return e+4*Math.ceil(t.components*ny[t.type]/4)},0);for(var i,r=0,s=0,a=t.length;se.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}it.DEFAULT=Object.freeze(new it);var il=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t,n){(i=e.call(this)||this).backBuffer=null,i.backBufferSize=new eX,i.backBufferAntialias=false,i.isWebGPU=false,i.isWebGL2=false,i.isHdr=false,i.maxColorAttachments=1,i.maxSamples=1,i.supportsCompute=false,i.supportsStorageTextureRead=false,i.renderTarget=null,i.shaders=[],i.textures=[],i.targets=new Set,i.renderVersion=0,i.insideRenderPass=false,i.supportsUniformBuffers=false,i.supportsClipDistances=false,i.textureRG11B10Renderable=false,i.textureFloatFilterable=false,i.blendState=new nY,i.depthState=new nZ,i.stencilEnabled=false,i.stencilFront=new it,i.stencilBack=new it,i.defaultClearOptions={color:[0,0,0,1],depth:1,stencil:0,flags:3},i.clientRect={width:0,height:0},i._shadersDirty=false,i.capsDefines=new Map,i.canvas=t,"setAttribute"in t&&t.setAttribute("data-engine","PlayCanvas "+J),i.initOptions=ir({},n),null!=(r=i.initOptions).alpha||(r.alpha=true),null!=(s=i.initOptions).depth||(s.depth=true),null!=(a=i.initOptions).stencil||(a.stencil=true),null!=(o=i.initOptions).antialias||(o.antialias=true),null!=(l=i.initOptions).powerPreference||(l.powerPreference="high-performance"),null!=(u=i.initOptions).displayFormat||(u.displayFormat="ldr"),i._maxPixelRatio=ef.browser?Math.min(1,window.devicePixelRatio):1,i.buffers=[],i._vram={tex:0,vb:0,ib:0,ub:0,sb:0},i._shaderStats={vsCompiled:0,fsCompiled:0,linked:0,materialShaders:0,compileTime:0},i.initializeContextCaches(),i._drawCallsPerFrame=0,i._shaderSwitchesPerFrame=0,i._primsPerFrame=[];for(var i,r,s,a,o,l,u,c=0;c<=6;c++)i._primsPerFrame[c]=0;return i._renderTargetCreationTime=0,i.scope=new n1("Device"),i.textureBias=i.scope.resolve("textureBias"),i.textureBias.setValue(0),i}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&ia(t,e);var n,i=t.prototype;return i.postInit=function(){var e=new n7(this,[{semantic:tA,components:2,type:6}]),t=new Float32Array([-1,-1,1,-1,-1,1,1,1]);this.quadVertexBuffer=new n3(this,e,4,{data:t});},i.initCapsDefines=function(){var e=this.capsDefines;e.clear(),this.textureFloatFilterable&&e.set("CAPS_TEXTURE_FLOAT_FILTERABLE",""),this.textureFloatRenderable&&e.set("CAPS_TEXTURE_FLOAT_RENDERABLE","");},i.destroy=function(){var e,t,n;this.fire("destroy"),null==(e=this.quadVertexBuffer)||e.destroy(),this.quadVertexBuffer=null,null==(t=this.dynamicBuffers)||t.destroy(),this.dynamicBuffers=null,null==(n=this.gpuProfiler)||n.destroy(),this.gpuProfiler=null;},i.onDestroyShader=function(e){this.fire("destroy:shader",e);var t=this.shaders.indexOf(e);-1!==t&&this.shaders.splice(t,1);},i.postDestroy=function(){this.scope=null,this.canvas=null;},i.loseContext=function(){this.contextLost=true,this.backBufferSize.set(-1,-1);for(var e,t,n=io(this.textures);!(t=n()).done;)t.value.loseContext();for(var i,r=io(this.buffers);!(i=r()).done;)i.value.loseContext();for(var s,a=io(this.targets);!(s=a()).done;)s.value.loseContext();null==(e=this.gpuProfiler)||e.loseContext();},i.restoreContext=function(){this.contextLost=false,this.initializeRenderState(),this.initializeContextCaches();for(var e,t,n,i=io(this.buffers);!(n=i()).done;)n.value.unlock();null==(t=this.gpuProfiler)||null==(e=t.restoreContext)||e.call(t);},i.toJSON=function(e){},i.initializeContextCaches=function(){this.vertexBuffers=[],this.shader=null,this.shaderValid=void 0,this.shaderAsyncCompile=false,this.renderTarget=null;},i.initializeRenderState=function(){this.blendState=new nY,this.depthState=new nZ,this.cullMode=1,this.vx=this.vy=this.vw=this.vh=0,this.sx=this.sy=this.sw=this.sh=0,this.blendColor=new eN(0,0,0,0);},i.setStencilState=function(e,t){},i.setBlendState=function(e){},i.setBlendColor=function(e,t,n,i){},i.setDepthState=function(e){},i.setCullMode=function(e){},i.setRenderTarget=function(e){this.renderTarget=e;},i.setVertexBuffer=function(e){e&&this.vertexBuffers.push(e);},i.clearVertexBuffer=function(){this.vertexBuffers.length=0;},i.getRenderTarget=function(){return this.renderTarget},i.initRenderTarget=function(e){e.initialized||(e.init(),this.targets.add(e));},i.draw=function(e,t,n,i,r){},i._isBrowserInterface=function(e){return this._isImageBrowserInterface(e)||this._isImageCanvasInterface(e)||this._isImageVideoInterface(e)},i._isImageBrowserInterface=function(e){return "undefined"!=typeof ImageBitmap&&is(e,ImageBitmap)||"undefined"!=typeof HTMLImageElement&&is(e,HTMLImageElement)},i._isImageCanvasInterface=function(e){return "undefined"!=typeof HTMLCanvasElement&&is(e,HTMLCanvasElement)},i._isImageVideoInterface=function(e){return "undefined"!=typeof HTMLVideoElement&&is(e,HTMLVideoElement)},i.resizeCanvas=function(e,t){var n=Math.min(this._maxPixelRatio,ef.browser?window.devicePixelRatio:1),i=Math.floor(e*n),r=Math.floor(t*n);(i!==this.canvas.width||r!==this.canvas.height)&&this.setResolution(i,r);},i.setResolution=function(e,n){this.canvas.width=e,this.canvas.height=n,this.fire(t.EVENT_RESIZE,e,n);},i.updateClientRect=function(){if(ef.worker)this.clientRect.width=this.canvas.width,this.clientRect.height=this.canvas.height;else {var e=this.canvas.getBoundingClientRect();this.clientRect.width=e.width,this.clientRect.height=e.height;}},i.startRenderPass=function(e){},i.endRenderPass=function(e){},i.startComputePass=function(e){},i.endComputePass=function(){},i.frameStart=function(){this.renderPassIndex=0,this.renderVersion++;},i.frameEnd=function(){},i.computeDispatch=function(e,t){},i.getRenderableHdrFormat=function(e,t,n){ void 0===e&&(e=[18,12,14]),void 0===t&&(t=true),void 0===n&&(n=1);for(var i=0;i1)continue;if(this.textureFloatRenderable&&(!t||this.textureFloatFilterable))return r}}},i.validateAttributes=function(e,t,n){},n=[{key:"width",get:function(){return this.canvas.width}},{key:"height",get:function(){return this.canvas.height}},{key:"fullscreen",get:function(){return false},set:function(e){}},{key:"maxPixelRatio",get:function(){return this._maxPixelRatio},set:function(e){this._maxPixelRatio=e;}},{key:"deviceType",get:function(){return this._deviceType}}],function(e,t){for(var n=0;n1?v:1),this._colorBuffer=e.colorBuffer,e.colorBuffer&&(this._colorBuffers=[e.colorBuffer]),this._depthBuffer=e.depthBuffer,this._face=null!=(l=e.face)?l:0,this._depthBuffer){var g=this._depthBuffer._format;16===g||69===g?(this._depth=true,this._stencil=false):17===g?(this._depth=true,this._stencil=true):(15===g&&this._depthBuffer.device.isWebGPU&&this._samples>1?this._depth=true:this._depth=false,this._stencil=false);}else this._depth=null==(u=e.depth)||u,this._stencil=null!=(c=e.stencil)&&c;e.colorBuffers&&!this._colorBuffers&&(this._colorBuffers=[].concat(e.colorBuffers),this._colorBuffer=e.colorBuffers[0]),this.autoResolve=null==(h=e.autoResolve)||h,this.name=e.name,this.name||(this.name=null==(f=this._colorBuffer)?void 0:f.name),this.name||(this.name=null==(d=this._depthBuffer)?void 0:d.name),this.name||(this.name="Untitled"),this.flipY=null!=(p=e.flipY)&&p,this._mipLevel=null!=(m=e.mipLevel)?m:0,this._mipLevel>0&&this._depth&&(this._mipLevel=0),this._mipmaps=void 0===e.mipLevel,this.validateMrt(),this.impl=_.createRenderTargetImpl(this);}var t,n=e.prototype;return n.destroy=function(){var e=this._device;e&&(e.targets.delete(this),e.renderTarget===this&&e.setRenderTarget(null),this.destroyFrameBuffers());},n.destroyFrameBuffers=function(){var e=this._device;e&&this.impl.destroy(e);},n.destroyTextureBuffers=function(){var e,t;null==(e=this._depthBuffer)||e.destroy(),this._depthBuffer=null,null==(t=this._colorBuffers)||t.forEach(function(e){e.destroy();}),this._colorBuffers=null,this._colorBuffer=null;},n.resize=function(e,t){if((this.width!==e||this.height!==t)&&!(this.mipLevel>0)){var n,i,r=this._device;this.destroyFrameBuffers(),r.renderTarget===this&&r.setRenderTarget(null),null==(n=this._depthBuffer)||n.resize(e,t),null==(i=this._colorBuffers)||i.forEach(function(n){n.resize(e,t);}),this.validateMrt(),this.impl=r.createRenderTargetImpl(this);}},n.validateMrt=function(){},n.init=function(){this.impl.init(this._device,this);},n.loseContext=function(){this.impl.loseContext();},n.resolve=function(e,t){ void 0===e&&(e=true),void 0===t&&(t=!!this._depthBuffer),this._device&&this._samples>1&&this.impl.resolve(this._device,this,e,t);},n.copy=function(e,t,n){if(!this._device)if(!e._device)return false;else this._device=e._device;return this._device.copyRenderTarget(e,this,t,n)},n.getColorBuffer=function(e){var t;return null==(t=this._colorBuffers)?void 0:t[e]},n.isColorBufferSrgb=function(e){if(void 0===e&&(e=0),this.device.backBuffer===this)return tS(this.device.backBufferFormat);var t=this.getColorBuffer(e);return !!t&&tS(t.format)},t=[{key:"initialized",get:function(){return this.impl.initialized}},{key:"device",get:function(){return this._device}},{key:"samples",get:function(){return this._samples}},{key:"depth",get:function(){return this._depth}},{key:"stencil",get:function(){return this._stencil}},{key:"colorBuffer",get:function(){return this._colorBuffer}},{key:"depthBuffer",get:function(){return this._depthBuffer}},{key:"face",get:function(){return this._face}},{key:"mipLevel",get:function(){return this._mipLevel}},{key:"mipmaps",get:function(){return this._mipmaps}},{key:"width",get:function(){var e,t,n=(null==(e=this._colorBuffer)?void 0:e.width)||(null==(t=this._depthBuffer)?void 0:t.width)||this._device.width;return this._mipLevel>0&&(n=nO.calcLevelDimension(n,this._mipLevel)),n}},{key:"height",get:function(){var e,t,n=(null==(e=this._colorBuffer)?void 0:e.height)||(null==(t=this._depthBuffer)?void 0:t.height)||this._device.height;return this._mipLevel>0&&(n=nO.calcLevelDimension(n,this._mipLevel)),n}}],function(e,t){for(var n=0;n1?"x"+o.numComponents:"")}),t&&a!==s-1||(n.push({attributes:r,arrayStride:o.stride,stepMode:i}),r=[]);}};return e&&i(e),t&&i(t),n},e}(),iA=function(){function e(e){this.device=e;}return e.prototype.getPipelineLayout=function(e){var t=[];return e.forEach(function(e){t.push(e.bindGroupLayout);}),this.device.wgpu.createPipelineLayout({bindGroupLayouts:t})},e}();function iC(e,t){return (iC=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var iP=["point-list","line-list",void 0,"line-strip","triangle-list","triangle-strip",void 0],iI=["add","subtract","reverse-subtract","min","max"],iL=["zero","one","src","one-minus-src","dst","one-minus-dst","src-alpha","src-alpha-saturated","one-minus-src-alpha","dst-alpha","one-minus-dst-alpha","constant","one-minus-constant"],iD=["never","less","equal","less-equal","greater","not-equal","greater-equal","always"],iR=["none","back","front"],iM=["keep","zero","replace","increment-clamp","increment-wrap","decrement-clamp","decrement-wrap","invert"],iO=["","uint16","uint32"],ik=function(){},iN=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this,t)||this).lookupHashes=new Uint32Array(14),n.vertexBufferLayout=new iw,n.cache=new Map,n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&iC(t,e);var n=t.prototype;return n.get=function(e,t,n,i,r,s,a,o,l,u,c,h,f){var d,p,m,_,v,g,y,S,x=e.type;i&&3!==x&&5!==x&&(i=void 0);var b=this.lookupHashes;b[0]=x,b[1]=r.id,b[2]=u,b[3]=l.key,b[4]=o.key,b[5]=null!=(_=null==t?void 0:t.renderingHash)?_:0,b[6]=null!=(v=null==n?void 0:n.renderingHash)?v:0,b[7]=s.impl.key,b[8]=null!=(g=null==(d=a[0])?void 0:d.key)?g:0,b[9]=null!=(y=null==(p=a[1])?void 0:p.key)?y:0,b[10]=null!=(S=null==(m=a[2])?void 0:m.key)?S:0,b[11]=c?h.key:0,b[12]=c?f.key:0,b[13]=null!=i?i:0;var T=n5(b),E=this.cache.get(T);if(E)for(var w=0;w0){var _=0;s.redWrite&&(_|=GPUColorWrite.RED),s.greenWrite&&(_|=GPUColorWrite.GREEN),s.blueWrite&&(_|=GPUColorWrite.BLUE),s.alphaWrite&&(_|=GPUColorWrite.ALPHA);var v=this.getBlend(s);m.forEach(function(e){p.fragment.targets.push({format:e.format,writeMask:_,blend:v});});}return f.createRenderPipeline(p)},t}(iA);function iF(e,t){return (iF=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var iB=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(){return e.apply(this,arguments)||this}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&iF(t,e);var n=t.prototype;return n.get=function(e,t){var n=this.getPipelineLayout([t.impl]);return this.create(e,n)},n.create=function(e,t){var n=this.device.wgpu,i=e.impl,r={compute:{module:i.getComputeShaderModule(),entryPoint:i.computeEntryPoint},layout:t};return n.createComputePipeline(r)},t}(iA),iU=function(){function e(){this._refCount=0;}var t,n=e.prototype;return n.incRefCount=function(){this._refCount++;},n.decRefCount=function(){this._refCount--;},t=[{key:"refCount",get:function(){return this._refCount}}],function(e,t){for(var n=0;n1?i.resolveTarget=n:i.view=n,this.setColorAttachment(0,void 0,e.backBufferViewFormat),this.updateKey();},t.setColorAttachment=function(e,t,n){this.colorAttachments[e]||(this.colorAttachments[e]=new iY),t&&(this.colorAttachments[e].multisampledBuffer=t),n&&(this.colorAttachments[e].format=n);},t.init=function(e,t){var n=this,i=e.wgpu;this.initDepthStencil(e,i,t),t._colorBuffers&&t._colorBuffers.forEach(function(e,t){n.setColorAttachment(t,void 0,e.impl.format);}),this.renderPassDescriptor.colorAttachments=[];for(var r=this.isBackbuffer?1:null!=(o=null==(a=t._colorBuffers)?void 0:a.length)?o:0,s=0;s1){var u="depth24plus-stencil8";this.depthAttachment.format=u,this.depthAttachment.hasStencil=true;var c=l.id+":"+s+":"+a+":"+r+":"+u,h=ij(e),f=h.get(c);if(!f){var d={size:[s,a,1],dimension:"2d",sampleCount:r,format:u,usage:GPUTextureUsage.RENDER_ATTACHMENT|(u!==l.impl.format?GPUTextureUsage.TEXTURE_BINDING:0)};f=t.createTexture(d),h.set(c,f);}this.depthAttachment.multisampledDepthBuffer=f,this.depthAttachment.multisampledDepthBufferKey=c,i=f.createView();}else {var p=l.impl.gpuTexture;this.depthAttachment.depthTexture=p,i=p.createView();}else {this.depthAttachment=new iq("depth24plus-stencil8");var m={size:[s,a,1],dimension:"2d",sampleCount:r,format:this.depthAttachment.format,usage:GPUTextureUsage.RENDER_ATTACHMENT};r>1?m.usage|=GPUTextureUsage.TEXTURE_BINDING:m.usage|=GPUTextureUsage.COPY_SRC;var _=t.createTexture(m);this.depthAttachment.depthTexture=_,this.depthAttachment.depthTextureInternal=true,i=_.createView();}this.renderPassDescriptor.depthStencilAttachment={view:i};}},t.initColor=function(e,t,n,i){var r={},s=n.samples,a=n.width,o=n.height,l=n.mipLevel,u=n.getColorBuffer(i),c=null;if(u&&(c=u.cubemap?u.impl.createView({dimension:"2d",baseArrayLayer:n.face,arrayLayerCount:1,mipLevelCount:1,baseMipLevel:l}):u.impl.createView({mipLevelCount:1,baseMipLevel:l})),s>1){var h={size:[a,o,1],dimension:"2d",sampleCount:s,format:this.isBackbuffer?e.backBufferViewFormat:u.impl.format,usage:GPUTextureUsage.RENDER_ATTACHMENT},f=t.createTexture(h);this.setColorAttachment(i,f,h.format),r.view=f.createView(),r.resolveTarget=c;}else r.view=c;return r},t.setupForRenderPass=function(e,t){for(var n,i,r=null!=(i=null==(n=this.renderPassDescriptor.colorAttachments)?void 0:n.length)?i:0,s=0;s0)switch(t){case 2:this.updateType=17;break;case 1:this.updateType=30;break;case 26:this.updateType=31;break;case 0:this.updateType=32;break;case 3:this.updateType=21;break;case 6:this.updateType=33;break;case 27:this.updateType=34;break;case 9:this.updateType=35;break;case 4:this.updateType=22;break;case 7:this.updateType=36;break;case 28:this.updateType=37;break;case 10:this.updateType=38;break;case 5:this.updateType=23;break;case 8:this.updateType=39;break;case 29:this.updateType=40;break;case 11:this.updateType=41;break;case 14:this.updateType=24;}this.count=n;var i=this.numComponents;n&&(i=ek.roundUp(i,4)),this.byteSize=4*i,n&&(this.byteSize*=n);}return t.prototype.calculateOffset=function(e){var t=this.byteSize<=8?this.byteSize:16;this.count&&(t=16),e=ek.roundUp(e,t),this.offset=e/4;},e=[{key:"isArrayType",get:function(){return this.count>0}}],function(e,t){for(var n=0;n]*>)\s*([\w\d_]+)\s*:\s*(.*?)\s*;|(<(?!storage,)[^>]*>)?\s*([\w\d_]+)\s*:\s*(texture_.*|storage_texture_.*|storage\w.*|external_texture|sampler(?:_comparison)?)\s*;)\s*$/gm,rt=/(?:@interpolate\([^)]*\)\s*)?([\w]+)\s*:/,rn=/(@vertex|@fragment)\s*fn\s+\w+\s*\(\s*(\w+)\s*:[\s\S]*?\{/,ri={texture_1d:{viewDimension:"1d",baseSampleType:0},texture_2d:{viewDimension:"2d",baseSampleType:0},texture_2d_array:{viewDimension:t9,baseSampleType:0},texture_3d:{viewDimension:"3d",baseSampleType:0},texture_cube:{viewDimension:t7,baseSampleType:0},texture_cube_array:{viewDimension:ne,baseSampleType:0},texture_multisampled_2d:{viewDimension:"2d",baseSampleType:0},texture_depth_2d:{viewDimension:"2d",baseSampleType:2},texture_depth_2d_array:{viewDimension:t9,baseSampleType:2},texture_depth_cube:{viewDimension:t7,baseSampleType:2},texture_depth_cube_array:{viewDimension:ne,baseSampleType:2},texture_external:{viewDimension:"2d",baseSampleType:1}},rr=function(e,t){var n=ri[e],i=n.baseSampleType;if(0===n.baseSampleType&&"texture_multisampled_2d"!==e)switch(t){case "u32":i=4;break;case "i32":i=3;break;case "f32":i=0;break;case "uff":i=1;}return {viewDimension:n.viewDimension,sampleType:i}},rs=function(e,t){var n,i;if(2===t)switch(e){case "2d":return "texture_depth_2d";case t9:return "texture_depth_2d_array";case t7:return "texture_depth_cube";case ne:return "texture_depth_cube_array"}switch(e){case "1d":n="texture_1d";break;case "2d":n="texture_2d";break;case t9:n="texture_2d_array";break;case "3d":n="texture_3d";break;case t7:n="texture_cube";break;case ne:n="texture_cube_array";}switch(t){case 0:case 1:i="f32";break;case 4:i="u32";break;case 3:i="i32";}return n+"<"+i+">"},ra={f32:"WrappedF32",i32:"WrappedI32",u32:"WrappedU32",vec2f:"WrappedVec2F",vec2i:"WrappedVec2I",vec2u:"WrappedVec2U"},ro=function(e){return (e=e.replace(/\s+/g," ").trim()).split(/[\s:]+/)},rl=/array<([^,]+),\s*([^>]+)>/,ru=function(e,t){this.ubName=null,this.arraySize=0,this.line=e;var n=ro(e);if(n.length<2){t.failed=true;return}if(this.name=n[0],this.type=n.slice(1).join(" "),this.type.includes("array<")){var i=rl.exec(this.type);this.type=i[1].trim(),this.arraySize=Number(i[2]),isNaN(this.arraySize)&&(t.failed=true);}},rc=/^\s*var\s+(\w+)\s*:\s*(texture_\w+)(?:<(\w+)>)?;\s*$/,rh=/^\s*var\s+([\w\d_]+)\s*:\s*(texture_storage_2d|texture_storage_2d_array)<([\w\d_]+),\s*(\w+)>\s*;\s*$/,rf=/^\s*var\s*\s*([\w\d_]+)\s*:\s*(.*)\s*;\s*$/,rd=/^\s*var\s+([\w\d_]+)\s*:\s*texture_external;\s*$/,rp=/^\s*var\s+([\w\d_]+)\s*:\s*(sampler|sampler_comparison)\s*;\s*$/,rm=function(){function e(e,t){this.originalLine=e,this.line=e,this.isTexture=false,this.isSampler=false,this.isStorageTexture=false,this.isStorageBuffer=false,this.isExternalTexture=false,this.type="",this.matchedElements=[];var n,i,r,s,a=this.line.match(rc);if(a){this.name=a[1],this.type=a[2],this.textureFormat=a[3],this.isTexture=true,(o=this.matchedElements).push.apply(o,[].concat(a));var o,l=rr(this.type,this.textureFormat);this.textureDimension=l.viewDimension,this.sampleType=l.sampleType;}var u=this.line.match(rh);u&&(this.isStorageTexture=true,this.name=u[1],this.textureType=u[2],this.format=u[3],this.access=u[4],(n=this.matchedElements).push.apply(n,[].concat(u)));var c=this.line.match(rf);c&&(this.isStorageBuffer=true,this.accessMode=c[1]||"none",this.name=c[2],this.type=c[3],(i=this.matchedElements).push.apply(i,[].concat(c)));var h=this.line.match(rd);h&&(this.name=h[1],this.isExternalTexture=true,(r=this.matchedElements).push.apply(r,[].concat(c)));var f=this.line.match(rp);f&&(this.name=f[1],this.samplerType=f[2],this.isSampler=true,(s=this.matchedElements).push.apply(s,[].concat(f))),0===this.matchedElements.length&&(t.failed=true);}return e.prototype.equals=function(e){return this.name===e.name&&this.type===e.type&&this.isTexture===e.isTexture&&this.isSampler===e.isSampler&&this.isStorageTexture===e.isStorageTexture&&this.isStorageBuffer===e.isStorageBuffer&&this.isExternalTexture===e.isExternalTexture&&this.textureFormat===e.textureFormat&&this.textureDimension===e.textureDimension&&this.sampleType===e.sampleType&&this.textureType===e.textureType&&this.format===e.format&&this.access===e.access&&this.accessMode===e.accessMode&&this.samplerType===e.samplerType&&true},e}(),r_=function(){function e(){}return e.run=function(t,n,i){var r=new Map,s=e.extract(n.vshader),a=e.extract(n.fshader),o=new Map,l=e.processAttributes(s.attributes,n.attributes,o,n.processingOptions,i),u=e.processVaryings(s.varyings,r,true),c=e.processVaryings(a.varyings,r,false),h=Array.from(new Set(s.uniforms.concat(a.uniforms))).map(function(e){return new ru(e,i)}),f=e.processUniforms(t,h,n.processingOptions,i);s.src=e.renameUniformAccess(s.src,h),a.src=e.renameUniformAccess(a.src,h);var d=e.mergeResources(s.resources,a.resources,i),p=e.processResources(t,d,n.processingOptions,i),m=e.generateFragmentOutputStruct(a.src,t.maxColorAttachments);s.src=e.copyInputs(s.src,i),a.src=e.copyInputs(a.src,i);var _=l+"\n"+u+"\n"+f.code+"\n"+p.code+"\n",v=s.src.replace("@@@",_),g=c+"\n"+m+"\n"+f.code+"\n"+p.code+"\n";return {vshader:v,fshader:a.src.replace("@@@",g),attributes:o,meshUniformBufferFormat:f.meshUniformBufferFormat,meshBindGroupFormat:p.meshBindGroupFormat}},e.extract=function(t){for(var n,i=[],r=[],s=[],a=[],o="@@@\n";null!==(n=i9.exec(t));){var l=n[1];i7.lastIndex=n.index;var u=i7.exec(t);"attribute"===l?i.push(u[2]):"varying"===l?r.push(u[2]):"uniform"===l&&s.push(u[2]),t=e.cutOut(t,n.index,i7.lastIndex,o),i9.lastIndex=n.index+o.length,o="";}for(;null!==(n=re.exec(t));)a.push(n[0]),t=e.cutOut(t,n.index,re.lastIndex,o),re.lastIndex=n.index+o.length,o="";return {src:t,attributes:i,varyings:r,uniforms:s,resources:a}},e.processUniforms=function(t,n,i,r){var s=[];n.forEach(function(e){if(i.hasUniform(e.name))e.ubName="ub_view";else {e.ubName="ub_mesh_ub";var t=nu.get(e.type),n=new iQ(e.name,t,e.arraySize);s.push(n);}}),0===s.length&&s.push(new iQ(nv,2));var a=new iJ(t,s),o="";return i.uniformFormats.forEach(function(t,n){t&&(o+=e.getUniformShaderDeclaration(t,n,0));}),a&&(o+=e.getUniformShaderDeclaration(a,2,0)),{code:o,meshUniformBufferFormat:a}},e.renameUniformAccess=function(e,t){return t.forEach(function(t){var n="uniform."+t.name,i=t.ubName+"."+t.name,r=RegExp("\\b"+n+"\\b","g");e=e.replace(r,i);}),e},e.mergeResources=function(e,t,n){var i=e.map(function(e){return new rm(e,n)});return t.map(function(e){return new rm(e,n)}).forEach(function(e){var t=i.find(function(t){return t.name===e.name});t?t.equals(e)||(n.failed=true):i.push(e);}),i},e.processResources=function(t,n,i,r){for(var s=[],a=0;a0?(ra.hasOwnProperty(t)&&(t=ra[t]),s+=" "+e.shortName+": array<"+t+", "+e.count+">,\n"):s+=" "+e.shortName+": "+t+",\n";}),s+="};\n"+("@group("+t+") @binding("+n+") var ub_"+i+" : "+r)+";\n\n"},e.getTextureShaderDeclaration=function(e,t,n){var i="",r=n;return e.textureFormats.forEach(function(e){var n=rs(e.textureDimension,e.sampleType);if(i+="@group("+t+") @binding("+r+") var "+e.name+": "+n+";\n",r++,e.hasSampler){var s=2===e.sampleType?"sampler_comparison":"sampler";i+="@group("+t+") @binding("+r+") var "+e.samplerName+": "+s+";\n",r++;}}),e.storageBufferFormats.forEach(function(e){var n=e.readOnly?"read":"read_write";i+="@group("+t+") @binding("+r+") var "+e.name+" : "+e.format+";\n",r++;}),i},e.processVaryings=function(e,t,n){var i="",r="",s="";e.forEach(function(e,a){var o=e.match(rt);if(o){var l=o[1];n?t.set(l,a):a=t.get(l),i+=" @location("+a+") "+e+",\n",n||(r+=" var "+e+";\n",s+=" "+l+" = input."+l+";\n");}}),n?i+=" @builtin(position) position : vec4f,\n":i+=" @builtin(position) position : vec4f,\n @builtin(front_facing) frontFacing : bool,\n @builtin(sample_index) sampleIndex : u32\n";var a=n?"":"\n var pcPosition: vec4f;\n var pcFrontFacing: bool;\n var pcSampleIndex: u32;\n "+r+"\n \n // function to copy inputs (varyings) to private global variables\n fn _pcCopyInputs(input: FragmentInput) {\n "+s+"\n pcPosition = input.position;\n pcFrontFacing = input.frontFacing;\n pcSampleIndex = input.sampleIndex;\n }\n ";return "\n struct "+(n?"VertexOutput":"FragmentInput")+" {\n "+i+"\n };\n "+a+"\n "},e.generateFragmentOutputStruct=function(e,t){for(var n="struct FragmentOutput {\n",i=0;i0?i:"")+" : vec4f,\n";return -1!==e.search(/\.fragDepth\s*=/)&&(n+=" @builtin(frag_depth) fragDepth : f32\n"),""+n+"};\n"},e.floatAttributeToInt=function(e,t){return ({f32:t?"i32":"u32",vec2f:t?"vec2i":"vec2u",vec3f:t?"vec3i":"vec3u",vec4f:t?"vec4i":"vec4u"})[({f32:"f32","vec2":"vec2f","vec3":"vec3f","vec4":"vec4f"})[e]||e]||null},e.processAttributes=function(t,n,i,r,s){ void 0===n&&(n={});var a="",o="",l="";return t.forEach(function(t){var s=ro(t),u=s[0],c=s[1],h=c;if(n.hasOwnProperty(u)){var f=n[u],d=nb[f];i.set(d,u);var p=r.getVertexElement(f);if(p){var m=p.dataType;6===m||7===m||p.normalize||p.asInt||(c=e.floatAttributeToInt(c,0===m||2===m||4===m));}a+=" @location("+d+") "+u+": "+c+",\n",o+=" var "+t+";\n",l+=" "+u+" = "+h+"(input."+u+");\n";}}),"\n struct VertexInput {\n "+a+"\n @builtin(vertex_index) vertexIndex : u32, // built-in vertex index\n @builtin(instance_index) instanceIndex : u32 // built-in instance index\n };\n\n "+o+"\n var pcVertexIndex: u32;\n var pcInstanceIndex: u32;\n\n fn _pcCopyInputs(input: VertexInput) {\n "+l+"\n pcVertexIndex = input.vertexIndex;\n pcInstanceIndex = input.instanceIndex;\n }\n "},e.copyInputs=function(e,t){var n=e.match(rn);if(!n||!n[2])return e;var i=n[2],r=n.index+n[0].length-1;return e.slice(0,r+1)+"\n _pcCopyInputs("+i+");"+e.slice(r+1)},e.cutOut=function(e,t,n,i){return e.substring(0,t)+i+e.substring(n)},e}(),rv=function(){function e(e){this._vertexCode=null,this._fragmentCode=null,this._computeCode=null,this.vertexEntryPoint="main",this.fragmentEntryPoint="main",this.computeEntryPoint="main",this.shader=e;var t,n,i,r=e.definition;r.shaderLanguage===na?(r.cshader?(this._computeCode=null!=(t=r.cshader)?t:null,this.computeUniformBufferFormats=r.computeUniformBufferFormats,this.computeBindGroupFormat=r.computeBindGroupFormat):(this.vertexEntryPoint="vertexMain",this.fragmentEntryPoint="fragmentMain",r.processingOptions?this.processWGSL():(this._vertexCode=null!=(n=r.vshader)?n:null,this._fragmentCode=null!=(i=r.fshader)?i:null,e.meshUniformBufferFormat=r.meshUniformBufferFormat,e.meshBindGroupFormat=r.meshBindGroupFormat)),e.ready=true):r.processingOptions&&this.processGLSL();}var t,n=e.prototype;return n.destroy=function(e){this._vertexCode=null,this._fragmentCode=null;},n.createShaderModule=function(e,t){return this.shader.device.wgpu.createShaderModule({code:e})},n.getVertexShaderModule=function(){return this.createShaderModule(this._vertexCode,"Vertex")},n.getFragmentShaderModule=function(){return this.createShaderModule(this._fragmentCode,"Fragment")},n.getComputeShaderModule=function(){return this.createShaderModule(this._computeCode,"Compute")},n.processGLSL=function(){var e=this.shader,t=i6.run(e.device,e.definition,e);this._vertexCode=this.transpile(t.vshader,"vertex",e.definition.vshader),this._fragmentCode=this.transpile(t.fshader,"fragment",e.definition.fshader),this._vertexCode&&this._fragmentCode?e.ready=true:e.failed=true,e.meshUniformBufferFormat=t.meshUniformBufferFormat,e.meshBindGroupFormat=t.meshBindGroupFormat,e.attributes=t.attributes;},n.processWGSL=function(){var e=this.shader,t=r_.run(e.device,e.definition,e);this._vertexCode=t.vshader,this._fragmentCode=t.fshader,e.meshUniformBufferFormat=t.meshUniformBufferFormat,e.meshBindGroupFormat=t.meshBindGroupFormat,e.attributes=t.attributes;},n.transpile=function(e,t,n){var i=this.shader.device;if(!i.glslang||!i.twgsl)return null;try{var r=i.glslang.compileGLSL(e,t);return i.twgsl.convertSpirV2WGSL(r)}catch(e){}},n.loseContext=function(){},n.restoreContext=function(e,t){},t=[{key:"vertexCode",get:function(){return this._vertexCode}},{key:"fragmentCode",get:function(){return this._fragmentCode}}],function(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var rI=/[ \t]*#(ifn?def|if|endif|else|elif|define|undef|extension|include)/g,rL=/define[ \t]+([^\n]+)\r?(?:\n|$)/g,rD=/extension[ \t]+([\w-]+)[ \t]*:[ \t]*(enable|require)/g,rR=/undef[ \t]+([^\n]+)\r?(?:\n|$)/g,rM=/(ifdef|ifndef|if)[ \t]*([^\r\n]+)\r?\n/g,rO=/(endif|else|elif)(?:[ \t]+([^\r\n]*))?\r?\n?/g,rk=/\{?[\w-]+\}?/,rN=/(!|\s)?defined\(([\w-]+)\)/,rF=/([a-z_]\w*)\s*(==|!=|<|<=|>|>=)\s*([\w"']+)/i,rB=/[+\-]/g,rU=/include[ \t]+"([\w-]+)(?:\s*,\s*([\w-]+))?"/g,rV=/\{i\}/g,rz=/(pcFragColor[1-8])\b/g,rG=function(){function e(){}return e.run=function(t,n,i){ void 0===n&&(n=new Map),void 0===i&&(i={}),e.sourceName=i.sourceName,t=(t=this.stripComments(t)).split(/\r?\n/).map(function(e){return e.trimEnd()}).join("\n");var r=new Map,s=new Map;if(null===(t=this._preprocess(t,r,s,n,i.stripDefines)))return null;var a=new Map;return r.forEach(function(e,t){Number.isInteger(parseFloat(e))&&!e.includes(".")&&a.set(t,e);}),t=this.stripComments(t),t=this.stripUnusedColorAttachments(t,i),t=this.RemoveEmptyLines(t),t=this.processArraySize(t,a),t=this.injectDefines(t,s)},e.stripUnusedColorAttachments=function(e,t){if(t.stripUnusedColorAttachments){var n=new Map,i=e.match(rz);if(null==i||i.forEach(function(e){var t,i=parseInt(e.charAt(e.length-1),10);n.set(i,(null!=(t=n.get(i))?t:0)+1);}),Array.from(n.values()).some(function(e){return 1===e})){for(var r=e.split("\n"),s=[],a=0;a0&&1===n.get(l))continue}s.push(r[a]);}e=s.join("\n");}}return e},e.stripComments=function(e){return e.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm,"$1")},e.processArraySize=function(e,t){return null!==e&&t.forEach(function(t,n){e=e.replace(RegExp("\\["+n+"\\]","g"),"["+t+"]");}),e},e.injectDefines=function(e,t){if(null!==e&&t.size>0){var n=e.split("\n");t.forEach(function(e,t){for(var i=RegExp(t,"g"),r=0;r0&&(o=true),o)?null:t},e._keep=function(e){for(var t=0;t":f=u>c;break;case ">=":f=u>=c;break;default:n=true;}return {result:f,error:n}}return {result:t.has(e),error:n}},e.evaluate=function(t,n){for(var i,r=null===rB.exec(t),s=t.split("||"),a=rP(s);!(i=a()).done;){for(var o,l=i.value.split("&&"),u=true,c=rP(l);!(o=c()).done;){var h=o.value,f=e.evaluateAtomicExpression(h.trim(),n),d=f.result,p=f.error;if(!d||p){u=false;break}}if(u)return {result:true,error:!r}}return {result:false,error:!r}},e}(),rH="\n#ifndef outType_0\n#define outType_0 vec4\n#endif\nlayout(location = 0) out highp outType_0 pcFragColor0;\n#if COLOR_ATTACHMENT_1\nlayout(location = 1) out highp outType_1 pcFragColor1;\n#endif\n#if COLOR_ATTACHMENT_2\nlayout(location = 2) out highp outType_2 pcFragColor2;\n#endif\n#if COLOR_ATTACHMENT_3\nlayout(location = 3) out highp outType_3 pcFragColor3;\n#endif\n#if COLOR_ATTACHMENT_4\nlayout(location = 4) out highp outType_4 pcFragColor4;\n#endif\n#if COLOR_ATTACHMENT_5\nlayout(location = 5) out highp outType_5 pcFragColor5;\n#endif\n#if COLOR_ATTACHMENT_6\nlayout(location = 6) out highp outType_6 pcFragColor6;\n#endif\n#if COLOR_ATTACHMENT_7\nlayout(location = 7) out highp outType_7 pcFragColor7;\n#endif\n#define gl_FragColor pcFragColor0\n#define varying in\n#define texture2D texture\n#define texture2DBias texture\n#define textureCube texture\n#define texture2DProj textureProj\n#define texture2DLod textureLod\n#define texture2DProjLod textureProjLod\n#define textureCubeLod textureLod\n#define texture2DGrad textureGrad\n#define texture2DProjGrad textureProjGrad\n#define textureCubeGrad textureGrad\n#define utexture2D texture\n#define itexture2D texture\n#define texture2DLodEXT texture2DLodEXT_is_no_longer_supported_use_texture2DLod_instead\n#define texture2DProjLodEXT texture2DProjLodEXT_is_no_longer_supported_use_texture2DProjLod\n#define textureCubeLodEXT textureCubeLodEXT_is_no_longer_supported_use_textureCubeLod_instead\n#define texture2DGradEXT texture2DGradEXT_is_no_longer_supported_use_texture2DGrad_instead\n#define texture2DProjGradEXT texture2DProjGradEXT_is_no_longer_supported_use_texture2DProjGrad_instead\n#define textureCubeGradEXT textureCubeGradEXT_is_no_longer_supported_use_textureCubeGrad_instead\n#define textureShadow(res, uv) textureGrad(res, uv, vec2(1, 1), vec2(1, 1))\n#define SHADOWMAP_PASS(name) name\n#define SHADOWMAP_ACCEPT(name) sampler2DShadow name\n#define TEXTURE_PASS(name) name\n#define TEXTURE_ACCEPT(name) sampler2D name\n#define TEXTURE_ACCEPT_HIGHP(name) highp sampler2D name\n#define GL2\n",rW="\n#define attribute in\n#define varying out\n#define texture2D texture\n#define utexture2D texture\n#define itexture2D texture\n#define GL2\n#define VERTEXSHADER\n#define TEXTURE_PASS(name) name\n#define TEXTURE_ACCEPT(name) sampler2D name\n#define TEXTURE_ACCEPT_HIGHP(name) highp sampler2D name\n",rj="\n#extension GL_EXT_samplerless_texture_functions : require\n#ifndef outType_0\n#define outType_0 vec4\n#endif\n#ifndef outType_1\n#define outType_1 vec4\n#endif\n#ifndef outType_2\n#define outType_2 vec4\n#endif\n#ifndef outType_3\n#define outType_3 vec4\n#endif\n#ifndef outType_4\n#define outType_4 vec4\n#endif\n#ifndef outType_5\n#define outType_5 vec4\n#endif\n#ifndef outType_6\n#define outType_6 vec4\n#endif\n#ifndef outType_7\n#define outType_7 vec4\n#endif\nlayout(location = 0) out highp outType_0 pcFragColor0;\nlayout(location = 1) out highp outType_1 pcFragColor1;\nlayout(location = 2) out highp outType_2 pcFragColor2;\nlayout(location = 3) out highp outType_3 pcFragColor3;\nlayout(location = 4) out highp outType_4 pcFragColor4;\nlayout(location = 5) out highp outType_5 pcFragColor5;\nlayout(location = 6) out highp outType_6 pcFragColor6;\nlayout(location = 7) out highp outType_7 pcFragColor7;\n#define gl_FragColor pcFragColor0\n#define texture2D(res, uv) texture(sampler2D(res, res ## _sampler), uv)\n#define texture2DBias(res, uv, bias) texture(sampler2D(res, res ## _sampler), uv, bias)\n#define texture2DLod(res, uv, lod) textureLod(sampler2D(res, res ## _sampler), uv, lod)\n#define textureCube(res, uv) texture(samplerCube(res, res ## _sampler), uv)\n#define textureCubeLod(res, uv, lod) textureLod(samplerCube(res, res ## _sampler), uv, lod)\n#define textureShadow(res, uv) textureLod(sampler2DShadow(res, res ## _sampler), uv, 0.0)\n#define itexture2D(res, uv) texture(isampler2D(res, res ## _sampler), uv)\n#define utexture2D(res, uv) texture(usampler2D(res, res ## _sampler), uv)\n#define texture2DLodEXT texture2DLodEXT_is_no_longer_supported_use_texture2DLod_instead\n#define texture2DProjLodEXT texture2DProjLodEXT_is_no_longer_supported_use_texture2DProjLod\n#define textureCubeLodEXT textureCubeLodEXT_is_no_longer_supported_use_textureCubeLod_instead\n#define texture2DGradEXT texture2DGradEXT_is_no_longer_supported_use_texture2DGrad_instead\n#define texture2DProjGradEXT texture2DProjGradEXT_is_no_longer_supported_use_texture2DProjGrad_instead\n#define textureCubeGradEXT textureCubeGradEXT_is_no_longer_supported_use_textureCubeGrad_instead\n#define SHADOWMAP_PASS(name) name, name ## _sampler\n#define SHADOWMAP_ACCEPT(name) texture2D name, sampler name ## _sampler\n#define TEXTURE_PASS(name) name, name ## _sampler\n#define TEXTURE_ACCEPT(name) texture2D name, sampler name ## _sampler\n#define TEXTURE_ACCEPT_HIGHP TEXTURE_ACCEPT\n#define GL2\n#define WEBGPU\n",rX="\n#extension GL_EXT_samplerless_texture_functions : require\n#define texture2D(res, uv) texture(sampler2D(res, res ## _sampler), uv)\n#define itexture2D(res, uv) texture(isampler2D(res, res ## _sampler), uv)\n#define utexture2D(res, uv) texture(usampler2D(res, res ## _sampler), uv)\n#define TEXTURE_PASS(name) name, name ## _sampler\n#define TEXTURE_ACCEPT(name) texture2D name, sampler name ## _sampler\n#define TEXTURE_ACCEPT_HIGHP TEXTURE_ACCEPT\n#define GL2\n#define WEBGPU\n#define VERTEXSHADER\n#define gl_VertexID gl_VertexIndex\n#define gl_InstanceID gl_InstanceIndex\n",rY="\n#define VERTEXSHADER\n",rq="\nvec2 getGrabScreenPos(vec4 clipPos) {\n vec2 uv = (clipPos.xy / clipPos.w) * 0.5 + 0.5;\n #ifdef WEBGPU\n uv.y = 1.0 - uv.y;\n #endif\n return uv;\n}\nvec2 getImageEffectUV(vec2 uv) {\n #ifdef WEBGPU\n uv.y = 1.0 - uv.y;\n #endif\n return uv;\n}\n",rK="\nfn getGrabScreenPos(clipPos: vec4) -> vec2 {\n var uv: vec2 = (clipPos.xy / clipPos.w) * 0.5 + vec2(0.5);\n uv.y = 1.0 - uv.y;\n return uv;\n}\nfn getImageEffectUV(uv: vec2) -> vec2 {\n var modifiedUV: vec2 = uv;\n modifiedUV.y = 1.0 - modifiedUV.y;\n return modifiedUV;\n}\nstruct WrappedF32 { @size(16) element: f32 }\nstruct WrappedI32 { @size(16) element: i32 }\nstruct WrappedU32 { @size(16) element: u32 }\nstruct WrappedVec2F { @size(16) element: vec2f }\nstruct WrappedVec2I { @size(16) element: vec2i }\nstruct WrappedVec2U { @size(16) element: vec2u }\n",rZ={vertex_position:tA,vertex_normal:tC,vertex_tangent:tP,vertex_texCoord0:tM,vertex_texCoord1:tO,vertex_texCoord2:tk,vertex_texCoord3:tN,vertex_texCoord4:tF,vertex_texCoord5:tB,vertex_texCoord6:tU,vertex_texCoord7:tV,vertex_color:tD,vertex_boneIndices:tL,vertex_boneWeights:tI},rQ=function(){function e(){}return e.createDefinition=function(t,n){var i,r,s,a,o=function(e,n,i,r){var s=t.isWebGPU?e:n,a="";if(!i){var o=null!=(u=r.fragmentOutputTypes)?u:"vec4";Array.isArray(o)||(o=[o]);for(var l=0;l=0&&(!(i>0)||"/"!==e[i-1]);){var r=false;if(i>0){var s=e.lastIndexOf("\n",i);s=-1!==s?s+1:0,e.substring(s,i).includes("#")&&(r=true);}if(!r){var a=e.indexOf(";",i),o=e.lastIndexOf(" ",a),l=e.substring(o+1,a);if(t[l]);else {var u=rZ[l];void 0!==u?t[l]=u:(t[l]="ATTR"+n,n++);}}i=e.indexOf("attribute",i+1);}return t},e}(),rJ=0,r$=function(){function e(e,t){if(this.attributes=new Map,this.id=rJ++,this.device=e,this.definition=t,this.name=t.name||"Untitled",this.init(),t.cshader);else {var n=t.shaderLanguage===na;t.vshader=rG.run(t.vshader,t.vincludes,{sourceName:"vertex shader for "+this.label,stripDefines:n}),t.shaderLanguage===ns&&(null!=t.attributes||(t.attributes=rQ.collectAttributes(t.vshader)));var i=e.isWebGL2&&("osx"===ef.name||"ios"===ef.name);if(t.fshader=rG.run(t.fshader,t.fincludes,{stripUnusedColorAttachments:i,stripDefines:n,sourceName:"fragment shader for "+this.label}),!t.vshader||!t.fshader){this.failed=true;return}}this.impl=e.createShaderImpl(this);}var t,n=e.prototype;return n.init=function(){this.ready=false,this.failed=false;},n.destroy=function(){this.device.onDestroyShader(this),this.impl.destroy(this);},n.loseContext=function(){this.init(),this.impl.loseContext();},n.restoreContext=function(){this.impl.restoreContext(this.device,this);},t=[{key:"label",get:function(){return "Shader Id "+this.id+" ("+(this.definition.shaderLanguage===na?"WGSL":"GLSL")+") "+this.name}}],function(e,t){for(var n=0;n=0;s--){var a=this.usedBuffers[s],o=a.stagingBuffer,l=a.gpuBuffer,u=a.offset,c=a.size,h=o.buffer;h.unmap(),r.copyBufferToBuffer(h,u,l.buffer,u,c),i.push(l);}var f=r.finish();n.addCommandBuffer(f,true);for(var d=0;d0&&(this._frameTime=t[0]),eO.get(Q))for(var i=0;i0&&r[r.length-1])&&(6===u[0]||2===u[0])){s=0;continue}if(3===u[0]&&(!r||u[1]>r[0]&&u[1]1&&t.autoResolve){var n=t.impl.depthAttachment,i=t.depthBuffer.impl.gpuTexture;n&&i&&this.resolver.resolveDepth(this.commandEncoder,n.multisampledDepthBuffer,i);}for(var r=0;r0&&(this.dynamicBuffers.submit(),this.wgpu.queue.submit(this.commandBuffers),this.commandBuffers.length=0,this.dynamicBuffers.onCommandBuffersSubmitted());},n.clear=function(e){e.flags&&this.clearRenderer.clear(this,this.renderTarget,e,this.defaultClearOptions);},n.setViewport=function(e,t,n,i){this.passEncoder&&(this.renderTarget.flipY||(t=this.renderTarget.height-t-i),this.vx=e,this.vy=t,this.vw=n,this.vh=i,this.passEncoder.setViewport(e,t,n,i,0,1));},n.setScissor=function(e,t,n,i){this.passEncoder&&(this.renderTarget.flipY||(t=this.renderTarget.height-t-i),this.sx=e,this.sy=t,this.sw=n,this.sh=i,this.passEncoder.setScissorRect(e,t,n,i));},n.clearStorageBuffer=function(e,t,n){ void 0===t&&(t=0),void 0===n&&(n=e.byteSize),this.getCommandEncoder().clearBuffer(e.buffer,t,n);},n.readStorageBuffer=function(e,t,n,i,r){ void 0===t&&(t=0),void 0===n&&(n=e.byteSize-t),void 0===i&&(i=null),void 0===r&&(r=false);var s=this.createBufferImpl(9);s.allocate(this,n);var a=s.buffer;return this.getCommandEncoder().copyBufferToBuffer(e.buffer,t,a,0,n),this.readBuffer(s,n,i,r)},n.readBuffer=function(e,t,n,i){var r=this;void 0===n&&(n=null),void 0===i&&(i=false);var s=e.buffer;return new Promise(function(a,o){var l=function(){null==s||s.mapAsync(GPUMapMode.READ).then(function(){null!=n||(n=new Uint8Array(t));var i=s.getMappedRange(0,t),o=n.constructor;n.set(new o(i)),s.unmap(),e.destroy(r),a(n);});};i?(r.submit(),l()):setTimeout(function(){l();});})},n.writeStorageBuffer=function(e,t,n,i,r){ void 0===t&&(t=0),void 0===i&&(i=0),this.wgpu.queue.writeBuffer(e.buffer,t,n,i,r);},n.copyRenderTarget=function(e,t,n,i){var r={width:e?e.width:t.width,height:e?e.height:t.height,depthOrArrayLayers:1},s=this.getCommandEncoder();if(n){var a={texture:e?e.colorBuffer.impl.gpuTexture:this.backBuffer.impl.assignedColorTexture,mipLevel:0},o={texture:t?t.colorBuffer.impl.gpuTexture:this.backBuffer.impl.assignedColorTexture,mipLevel:0};s.copyTextureToTexture(a,o,r);}if(i){var l=(e||this.renderTarget).impl.depthAttachment.depthTexture;if(e.samples>1){var u=t.colorBuffer.impl.gpuTexture;this.resolver.resolveDepth(s,l,u);}else {var c=t?t.depthBuffer.impl.gpuTexture:this.renderTarget.impl.depthAttachment.depthTexture;s.copyTextureToTexture({texture:l,mipLevel:0},{texture:c,mipLevel:0},r);}}return true},t}(il),sp=function(){function e(){this.bufferId=null;}var t,n=e.prototype;return n.destroy=function(e){this.bufferId&&(e.gl.deleteBuffer(this.bufferId),this.bufferId=null);},n.loseContext=function(){this.bufferId=null;},n.unlock=function(e,t,n,i){var r,s=e.gl;if(this.bufferId)s.bindBuffer(n,this.bufferId),s.bufferSubData(n,0,i);else {switch(t){case 0:r=s.STATIC_DRAW;break;case 1:r=s.DYNAMIC_DRAW;break;case 2:r=s.STREAM_DRAW;break;case 3:r=s.DYNAMIC_COPY;}this.bufferId=s.createBuffer(),s.bindBuffer(n,this.bufferId),s.bufferData(n,i,r);}},t=[{key:"initialized",get:function(){return !!this.bufferId}}],function(e,t){for(var n=0;n ":" ")+(l+1)+": "+r[l]+"\n";n.source=e;}return [i,n]},e}();function sw(e,t){var n=e.width,i=e.height;if(n>t||i>t){var r=t/Math.max(n,i),s=Math.floor(n*r),a=Math.floor(i*r),o=document.createElement("canvas");return o.width=s,o.height=a,o.getContext("2d").drawImage(e,0,0,n,i,0,0,s,a),o}return e}var sA=function(){function e(e){this._glTexture=null,this.dirtyParameterFlags=0,this.texture=e;}var t=e.prototype;return t.destroy=function(e){if(this._glTexture){for(var t=0;te.maxCubeMapSize||u.height>e.maxCubeMapSize)&&(u=sw(u,e.maxCubeMapSize),0===s&&(t._width=u.width,t._height=u.height)),e.setUnpackFlipY(false),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),this._glCreated?r.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+l,s,0,0,this._glFormat,this._glPixelType,u):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+l,s,this._glInternalFormat,this._glFormat,this._glPixelType,u);}}else for(l=0,i=1/Math.pow(2,s);l<6;l++)if(t._levelsUpdated[0][l]){var c=n[l];t._compressed?this._glCreated&&c?r.compressedTexSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+l,s,0,0,Math.max(t._width*i,1),Math.max(t._height*i,1),this._glInternalFormat,c):r.compressedTexImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+l,s,this._glInternalFormat,Math.max(t._width*i,1),Math.max(t._height*i,1),0,c):(e.setUnpackFlipY(false),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),this._glCreated&&c?r.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+l,s,0,0,Math.max(t._width*i,1),Math.max(t._height*i,1),this._glFormat,this._glPixelType,c):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+l,s,this._glInternalFormat,Math.max(t._width*i,1),Math.max(t._height*i,1),0,this._glFormat,this._glPixelType,c));}}else if(t._volume)t._compressed?r.compressedTexImage3D(r.TEXTURE_3D,s,this._glInternalFormat,Math.max(t._width*i,1),Math.max(t._height*i,1),Math.max(t._depth*i,1),0,n):(e.setUnpackFlipY(false),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),r.texImage3D(r.TEXTURE_3D,s,this._glInternalFormat,Math.max(t._width*i,1),Math.max(t._height*i,1),Math.max(t._depth*i,1),0,this._glFormat,this._glPixelType,n));else if(t.array&&(void 0===n?"undefined":(o=n)&&"undefined"!=typeof Symbol&&o.constructor===Symbol?"symbol":typeof o)=="object"){if(t._arrayLength===n.length)if(t._compressed)for(var h=0;he.maxTextureSize||n.height>e.maxTextureSize)&&(n=sw(n,e.maxTextureSize),0===s&&(t._width=n.width,t._height=n.height));var d=n.width||n.videoWidth,p=n.height||n.videoHeight;e.setUnpackFlipY(t._flipY),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),this._glCreated&&t._width===d&&t._height===p&&!e._isImageVideoInterface(n)?r.texSubImage2D(r.TEXTURE_2D,s,0,0,this._glFormat,this._glPixelType,n):(r.texImage2D(r.TEXTURE_2D,s,this._glInternalFormat,this._glFormat,this._glPixelType,n),0===s&&(t._width=d,t._height=p));}else i=1/Math.pow(2,s),t._compressed?this._glCreated&&n?r.compressedTexSubImage2D(r.TEXTURE_2D,s,0,0,Math.max(Math.floor(t._width*i),1),Math.max(Math.floor(t._height*i),1),this._glInternalFormat,n):r.compressedTexImage2D(r.TEXTURE_2D,s,this._glInternalFormat,Math.max(Math.floor(t._width*i),1),Math.max(Math.floor(t._height*i),1),0,n):(e.setUnpackFlipY(false),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),this._glCreated&&n?r.texSubImage2D(r.TEXTURE_2D,s,0,0,Math.max(t._width*i,1),Math.max(t._height*i,1),this._glFormat,this._glPixelType,n):r.texImage2D(r.TEXTURE_2D,s,this._glInternalFormat,Math.max(t._width*i,1),Math.max(t._height*i,1),0,this._glFormat,this._glPixelType,n));0===s?t._mipmapsUploaded=false:t._mipmapsUploaded=true;}s++;}if(t._needsUpload)if(t._cubemap)for(var m=0;m<6;m++)t._levelsUpdated[0][m]=false;else t._levelsUpdated[0]=false;!t._compressed&&!t._integerFormat&&t._mipmaps&&t._needsMipmapsUpload&&1===t._levels.length&&(r.generateMipmap(this._glTarget),t._mipmapsUploaded=true),t._gpuSize&&t.adjustVramSizeTracking(e._vram,-t._gpuSize),t._gpuSize=t.gpuSize,t.adjustVramSizeTracking(e._vram,t._gpuSize),this._glCreated=true;}},t.read=function(e,t,n,i,r){var s=this.texture;return s.device.readTextureAsync(s,e,t,n,i,r)},t.write=function(e,t,n,i,r){var s=this.texture,a=s.device;return a.setTexture(s,0),a.writeTextureAsync(s,e,t,n,i,r)},e}(),sC=function(){function e(e,t){this.msaaFB=e,this.resolveFB=t;}return e.prototype.destroy=function(e){this.msaaFB&&(e.deleteRenderbuffer(this.msaaFB),this.msaaFB=null),this.resolveFB&&(e.deleteRenderbuffer(this.resolveFB),this.resolveFB=null);},e}(),sP=function(){function e(){this._glFrameBuffer=null,this._glDepthBuffer=null,this._glResolveFrameBuffer=null,this.colorMrtFramebuffers=null,this._glMsaaColorBuffers=[],this._glMsaaDepthBuffer=null,this._isInitialized=false;}var t,n=e.prototype;return n.destroy=function(e){var t,n=e.gl;this._isInitialized=false,this._glFrameBuffer&&(this._glFrameBuffer!==this.suppliedColorFramebuffer&&n.deleteFramebuffer(this._glFrameBuffer),this._glFrameBuffer=null),this._glDepthBuffer&&(n.deleteRenderbuffer(this._glDepthBuffer),this._glDepthBuffer=null),this._glResolveFrameBuffer&&(this._glResolveFrameBuffer!==this.suppliedColorFramebuffer&&n.deleteFramebuffer(this._glResolveFrameBuffer),this._glResolveFrameBuffer=null),this._glMsaaColorBuffers.forEach(function(e){n.deleteRenderbuffer(e);}),this._glMsaaColorBuffers.length=0,null==(t=this.colorMrtFramebuffers)||t.forEach(function(e){e.destroy(n);}),this.colorMrtFramebuffers=null,this._glMsaaDepthBuffer&&(this._glMsaaDepthBuffer=null,this.msaaDepthBufferKey&&ij(e).release(this.msaaDepthBufferKey)),this.suppliedColorFramebuffer=void 0;},n.init=function(e,t){var n=e.gl;this._isInitialized=true;var i=[];if(void 0!==this.suppliedColorFramebuffer)this._glFrameBuffer=this.suppliedColorFramebuffer;else {this._glFrameBuffer=n.createFramebuffer(),e.setFramebuffer(this._glFrameBuffer);for(var r,s,a=null!=(s=null==(r=t._colorBuffers)?void 0:r.length)?s:0,o=n.COLOR_ATTACHMENT0,l=0;l1)){this._glDepthBuffer||(this._glDepthBuffer=n.createRenderbuffer());var f=t._stencil?n.DEPTH24_STENCIL8:n.DEPTH_COMPONENT32F;n.bindRenderbuffer(n.RENDERBUFFER,this._glDepthBuffer),n.renderbufferStorage(n.RENDERBUFFER,f,t.width,t.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,h,n.RENDERBUFFER,this._glDepthBuffer),n.bindRenderbuffer(n.RENDERBUFFER,null);}}}if(t._samples>1){this._glResolveFrameBuffer=this._glFrameBuffer,this._glFrameBuffer=n.createFramebuffer(),e.setFramebuffer(this._glFrameBuffer);var d=null!=(S=null==(y=t._colorBuffers)?void 0:y.length)?S:0;if(void 0!==this.suppliedColorFramebuffer){var p=n.createRenderbuffer();this._glMsaaColorBuffers.push(p);var m=7===e.backBufferFormat?n.RGBA8:n.RGB8;n.bindRenderbuffer(n.RENDERBUFFER,p),n.renderbufferStorageMultisample(n.RENDERBUFFER,t._samples,m,t.width,t.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.RENDERBUFFER,p);}else for(var _=0;_1&&(this._createMsaaMrtFramebuffers(e,t,d),e.setFramebuffer(this._glFrameBuffer),n.drawBuffers(i));}},n._createMsaaMrtFramebuffers=function(e,t,n){var i=e.gl;this.colorMrtFramebuffers=[];for(var r=0;r0){this.frameQueries=[];var a=new sL;a.queries=s,a.renderVersion=r,this.previousFrameQueries.push(a);}if(this.previousFrameQueries.length>0){var o=this.previousFrameQueries[0],l=o.queries,u=l[l.length-1],c=i.getQueryParameter(u,i.QUERY_RESULT_AVAILABLE),h=i.getParameter(n.GPU_DISJOINT_EXT);if(c&&!h){this.previousFrameQueries.shift();var f=this.timings;f.length=0;for(var d=0;de.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function sF(e,t){var n,i,r,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(o){return function(l){var u=[o,l];if(n)throw TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(s=0)),s;)try{if(n=1,i&&(r=2&u[0]?i.return:u[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,u[1])).done)return r;switch(i=0,r&&(u=[2&u[0],r.value]),u[0]){case 0:case 1:r=u;break;case 4:return s.label++,{value:u[1],done:!1};case 5:s.label++,i=u[1],u=[0];continue;case 7:u=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===u[0]||2===u[0])){s=0;continue}if(3===u[0]&&(!r||u[1]>r[0]&&u[1]=120||115===p)||"android"===ef.name&&p>=132)&&(n.antialias=false);}}i.backBufferAntialias=null!=(r=n.antialias)&&r,n.antialias=false;var m=null!=(s=n.gl)?s:t.getContext("webgl2",n);if(!m)throw Error("WebGL not supported");i.gl=m,i.isWebGL2=true,i._deviceType=nh,i.updateBackbufferFormat(null);var _="chrome"===ef.browserName,v="safari"===ef.browserName,g=ef.browser&&-1!==navigator.appVersion.indexOf("Mac");return i._tempEnableSafariTextureUnitWorkaround=v,i._tempMacChromeBlitFramebufferWorkaround=g&&_&&!n.alpha,t.addEventListener("webglcontextlost",i._contextLostHandler,false),t.addEventListener("webglcontextrestored",i._contextRestoredHandler,false),i.initializeExtensions(),i.initializeCapabilities(),i.initializeRenderState(),i.initializeContextCaches(),i.createBackbuffer(null),i.supportsImageBitmap=!v&&"undefined"!=typeof ImageBitmap,i._samplerTypes=new Set([m.SAMPLER_2D,m.SAMPLER_CUBE,m.UNSIGNED_INT_SAMPLER_2D,m.INT_SAMPLER_2D,m.SAMPLER_2D_SHADOW,m.SAMPLER_CUBE_SHADOW,m.SAMPLER_3D,m.INT_SAMPLER_3D,m.UNSIGNED_INT_SAMPLER_3D,m.SAMPLER_2D_ARRAY,m.INT_SAMPLER_2D_ARRAY,m.UNSIGNED_INT_SAMPLER_2D_ARRAY]),i.glAddress=[m.REPEAT,m.CLAMP_TO_EDGE,m.MIRRORED_REPEAT],i.glBlendEquation=[m.FUNC_ADD,m.FUNC_SUBTRACT,m.FUNC_REVERSE_SUBTRACT,m.MIN,m.MAX],i.glBlendFunctionColor=[m.ZERO,m.ONE,m.SRC_COLOR,m.ONE_MINUS_SRC_COLOR,m.DST_COLOR,m.ONE_MINUS_DST_COLOR,m.SRC_ALPHA,m.SRC_ALPHA_SATURATE,m.ONE_MINUS_SRC_ALPHA,m.DST_ALPHA,m.ONE_MINUS_DST_ALPHA,m.CONSTANT_COLOR,m.ONE_MINUS_CONSTANT_COLOR],i.glBlendFunctionAlpha=[m.ZERO,m.ONE,m.SRC_COLOR,m.ONE_MINUS_SRC_COLOR,m.DST_COLOR,m.ONE_MINUS_DST_COLOR,m.SRC_ALPHA,m.SRC_ALPHA_SATURATE,m.ONE_MINUS_SRC_ALPHA,m.DST_ALPHA,m.ONE_MINUS_DST_ALPHA,m.CONSTANT_ALPHA,m.ONE_MINUS_CONSTANT_ALPHA],i.glComparison=[m.NEVER,m.LESS,m.EQUAL,m.LEQUAL,m.GREATER,m.NOTEQUAL,m.GEQUAL,m.ALWAYS],i.glStencilOp=[m.KEEP,m.ZERO,m.REPLACE,m.INCR,m.INCR_WRAP,m.DECR,m.DECR_WRAP,m.INVERT],i.glClearFlag=[0,m.COLOR_BUFFER_BIT,m.DEPTH_BUFFER_BIT,m.COLOR_BUFFER_BIT|m.DEPTH_BUFFER_BIT,m.STENCIL_BUFFER_BIT,m.STENCIL_BUFFER_BIT|m.COLOR_BUFFER_BIT,m.STENCIL_BUFFER_BIT|m.DEPTH_BUFFER_BIT,m.STENCIL_BUFFER_BIT|m.COLOR_BUFFER_BIT|m.DEPTH_BUFFER_BIT],i.glCull=[0,m.BACK,m.FRONT,m.FRONT_AND_BACK],i.glFilter=[m.NEAREST,m.LINEAR,m.NEAREST_MIPMAP_NEAREST,m.NEAREST_MIPMAP_LINEAR,m.LINEAR_MIPMAP_NEAREST,m.LINEAR_MIPMAP_LINEAR],i.glPrimitive=[m.POINTS,m.LINES,m.LINE_LOOP,m.LINE_STRIP,m.TRIANGLES,m.TRIANGLE_STRIP,m.TRIANGLE_FAN],i.glType=[m.BYTE,m.UNSIGNED_BYTE,m.SHORT,m.UNSIGNED_SHORT,m.INT,m.UNSIGNED_INT,m.FLOAT,m.HALF_FLOAT],i.pcUniformType={},i.pcUniformType[m.BOOL]=0,i.pcUniformType[m.INT]=1,i.pcUniformType[m.FLOAT]=2,i.pcUniformType[m.FLOAT_VEC2]=3,i.pcUniformType[m.FLOAT_VEC3]=4,i.pcUniformType[m.FLOAT_VEC4]=5,i.pcUniformType[m.INT_VEC2]=6,i.pcUniformType[m.INT_VEC3]=7,i.pcUniformType[m.INT_VEC4]=8,i.pcUniformType[m.BOOL_VEC2]=9,i.pcUniformType[m.BOOL_VEC3]=10,i.pcUniformType[m.BOOL_VEC4]=11,i.pcUniformType[m.FLOAT_MAT2]=12,i.pcUniformType[m.FLOAT_MAT3]=13,i.pcUniformType[m.FLOAT_MAT4]=14,i.pcUniformType[m.SAMPLER_2D]=15,i.pcUniformType[m.SAMPLER_CUBE]=16,i.pcUniformType[m.UNSIGNED_INT]=26,i.pcUniformType[m.UNSIGNED_INT_VEC2]=27,i.pcUniformType[m.UNSIGNED_INT_VEC3]=28,i.pcUniformType[m.UNSIGNED_INT_VEC4]=29,i.pcUniformType[m.SAMPLER_2D_SHADOW]=18,i.pcUniformType[m.SAMPLER_CUBE_SHADOW]=19,i.pcUniformType[m.SAMPLER_2D_ARRAY]=25,i.pcUniformType[m.SAMPLER_3D]=20,i.pcUniformType[m.INT_SAMPLER_2D]=42,i.pcUniformType[m.UNSIGNED_INT_SAMPLER_2D]=43,i.pcUniformType[m.INT_SAMPLER_CUBE]=44,i.pcUniformType[m.UNSIGNED_INT_SAMPLER_2D]=45,i.pcUniformType[m.INT_SAMPLER_3D]=46,i.pcUniformType[m.UNSIGNED_INT_SAMPLER_3D]=47,i.pcUniformType[m.INT_SAMPLER_2D_ARRAY]=48,i.pcUniformType[m.UNSIGNED_INT_SAMPLER_2D_ARRAY]=49,i.targetToSlot={},i.targetToSlot[m.TEXTURE_2D]=0,i.targetToSlot[m.TEXTURE_CUBE_MAP]=1,i.targetToSlot[m.TEXTURE_3D]=2,i.commitFunction=[],i.commitFunction[0]=function(e,t){e.value!==t&&(m.uniform1i(e.locationId,t),e.value=t);},i.commitFunction[1]=i.commitFunction[0],i.commitFunction[2]=function(e,t){e.value!==t&&(m.uniform1f(e.locationId,t),e.value=t);},i.commitFunction[3]=function(e,t){c=e.value,a=t[0],o=t[1],(c[0]!==a||c[1]!==o)&&(m.uniform2fv(e.locationId,t),c[0]=a,c[1]=o);},i.commitFunction[4]=function(e,t){c=e.value,a=t[0],o=t[1],l=t[2],(c[0]!==a||c[1]!==o||c[2]!==l)&&(m.uniform3fv(e.locationId,t),c[0]=a,c[1]=o,c[2]=l);},i.commitFunction[5]=function(e,t){c=e.value,a=t[0],o=t[1],l=t[2],u=t[3],(c[0]!==a||c[1]!==o||c[2]!==l||c[3]!==u)&&(m.uniform4fv(e.locationId,t),c[0]=a,c[1]=o,c[2]=l,c[3]=u);},i.commitFunction[6]=function(e,t){c=e.value,a=t[0],o=t[1],(c[0]!==a||c[1]!==o)&&(m.uniform2iv(e.locationId,t),c[0]=a,c[1]=o);},i.commitFunction[9]=i.commitFunction[6],i.commitFunction[7]=function(e,t){c=e.value,a=t[0],o=t[1],l=t[2],(c[0]!==a||c[1]!==o||c[2]!==l)&&(m.uniform3iv(e.locationId,t),c[0]=a,c[1]=o,c[2]=l);},i.commitFunction[10]=i.commitFunction[7],i.commitFunction[8]=function(e,t){c=e.value,a=t[0],o=t[1],l=t[2],u=t[3],(c[0]!==a||c[1]!==o||c[2]!==l||c[3]!==u)&&(m.uniform4iv(e.locationId,t),c[0]=a,c[1]=o,c[2]=l,c[3]=u);},i.commitFunction[11]=i.commitFunction[8],i.commitFunction[12]=function(e,t){m.uniformMatrix2fv(e.locationId,false,t);},i.commitFunction[13]=function(e,t){m.uniformMatrix3fv(e.locationId,false,t);},i.commitFunction[14]=function(e,t){m.uniformMatrix4fv(e.locationId,false,t);},i.commitFunction[17]=function(e,t){m.uniform1fv(e.locationId,t);},i.commitFunction[21]=function(e,t){m.uniform2fv(e.locationId,t);},i.commitFunction[22]=function(e,t){m.uniform3fv(e.locationId,t);},i.commitFunction[23]=function(e,t){m.uniform4fv(e.locationId,t);},i.commitFunction[26]=function(e,t){e.value!==t&&(m.uniform1ui(e.locationId,t),e.value=t);},i.commitFunction[27]=function(e,t){c=e.value,a=t[0],o=t[1],(c[0]!==a||c[1]!==o)&&(m.uniform2uiv(e.locationId,t),c[0]=a,c[1]=o);},i.commitFunction[28]=function(e,t){c=e.value,a=t[0],o=t[1],l=t[2],(c[0]!==a||c[1]!==o||c[2]!==l)&&(m.uniform3uiv(e.locationId,t),c[0]=a,c[1]=o,c[2]=l);},i.commitFunction[29]=function(e,t){c=e.value,a=t[0],o=t[1],l=t[2],u=t[3],(c[0]!==a||c[1]!==o||c[2]!==l||c[3]!==u)&&(m.uniform4uiv(e.locationId,t),c[0]=a,c[1]=o,c[2]=l,c[3]=u);},i.commitFunction[30]=function(e,t){m.uniform1iv(e.locationId,t);},i.commitFunction[31]=function(e,t){m.uniform1uiv(e.locationId,t);},i.commitFunction[32]=i.commitFunction[30],i.commitFunction[33]=function(e,t){m.uniform2iv(e.locationId,t);},i.commitFunction[34]=function(e,t){m.uniform2uiv(e.locationId,t);},i.commitFunction[35]=i.commitFunction[33],i.commitFunction[36]=function(e,t){m.uniform3iv(e.locationId,t);},i.commitFunction[37]=function(e,t){m.uniform3uiv(e.locationId,t);},i.commitFunction[38]=i.commitFunction[36],i.commitFunction[39]=function(e,t){m.uniform4iv(e.locationId,t);},i.commitFunction[40]=function(e,t){m.uniform4uiv(e.locationId,t);},i.commitFunction[41]=i.commitFunction[39],i.commitFunction[24]=function(e,t){m.uniformMatrix4fv(e.locationId,false,t);},i.constantTexSource=i.scope.resolve("source"),i.postInit(),i}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&sk(t,e);var n,r=t.prototype;return r.postInit=function(){e.prototype.postInit.call(this),this.gpuProfiler=new sD(this);},r.destroy=function(){e.prototype.destroy.call(this);var t=this.gl;this.feedback&&t.deleteTransformFeedback(this.feedback),this.clearVertexArrayObjectCache(),this.canvas.removeEventListener("webglcontextlost",this._contextLostHandler,false),this.canvas.removeEventListener("webglcontextrestored",this._contextRestoredHandler,false),this._contextLostHandler=null,this._contextRestoredHandler=null,this.gl=null,e.prototype.postDestroy.call(this);},r.createBackbuffer=function(e){this.supportsStencil=this.initOptions.stencil,this.backBuffer=new ic({name:"WebglFramebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.backBuffer.impl.suppliedColorFramebuffer=e;},r.updateBackbufferFormat=function(e){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,e);var n=this.gl.getParameter(this.gl.ALPHA_BITS);this.backBufferFormat=n?7:6;},r.updateBackbuffer=function(){var e=this.canvas.width!==this.backBufferSize.x||this.canvas.height!==this.backBufferSize.y;(this._defaultFramebufferChanged||e)&&(this._defaultFramebufferChanged&&this.updateBackbufferFormat(this._defaultFramebuffer),this._defaultFramebufferChanged=false,this.backBufferSize.set(this.canvas.width,this.canvas.height),this.backBuffer.destroy(),this.createBackbuffer(this._defaultFramebuffer));},r.createVertexBufferImpl=function(e,t){return new s_},r.createIndexBufferImpl=function(e){return new sg(e)},r.createShaderImpl=function(e){return new sE(e)},r.createTextureImpl=function(e){return new sA(e)},r.createRenderTargetImpl=function(e){return new sP},r.getPrecision=function(){var e=this.gl,t="highp";if(e.getShaderPrecisionFormat){var n=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT),i=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT),r=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT),s=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT);if(n&&i&&r&&s){var a=n.precision>0&&r.precision>0,o=i.precision>0&&s.precision>0;a||(t=o?"mediump":"lowp");}}return t},r.getExtension=function(){for(var e=0;e0&&e.fullSizeClearRect&&r.invalidateFramebuffer(r.DRAW_FRAMEBUFFER,sB),n&&(null==(i=e.colorOps)?void 0:i.resolve)&&e.samples>1&&t.autoResolve&&t.resolve(true,false),t.depthBuffer&&e.depthStencilOps.resolveDepth&&e.samples>1&&t.autoResolve&&t.resolve(false,true);for(var o=0;o1&&e.autoResolve&&e.resolve();var t=e._colorBuffer;t&&t.impl._glTexture&&t.mipmaps&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(t),this.gl.generateMipmap(t.impl._glTarget));}},r.setUnpackFlipY=function(e){if(this.unpackFlipY!==e){this.unpackFlipY=e;var t=this.gl;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,e);}},r.setUnpackPremultiplyAlpha=function(e){if(this.unpackPremultiplyAlpha!==e){this.unpackPremultiplyAlpha=e;var t=this.gl;t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e);}},r.activeTexture=function(e){this.textureUnit!==e&&(this.gl.activeTexture(this.gl.TEXTURE0+e),this.textureUnit=e);},r.bindTexture=function(e){var t=e.impl,n=t._glTarget,i=t._glTexture,r=this.textureUnit,s=this.targetToSlot[n];this.textureUnits[r][s]!==i&&(this.gl.bindTexture(n,i),this.textureUnits[r][s]=i);},r.bindTextureOnUnit=function(e,t){var n=e.impl,i=n._glTarget,r=n._glTexture,s=this.targetToSlot[i];this.textureUnits[t][s]!==r&&(this.activeTexture(t),this.gl.bindTexture(i,r),this.textureUnits[t][s]=r);},r.setTextureParameters=function(e){var t=this.gl,n=e.impl.dirtyParameterFlags,i=e.impl._glTarget;if(1&n){var r=e._minFilter;(!e._mipmaps||e._compressed&&1===e._levels.length)&&(2===r||3===r?r=0:(4===r||5===r)&&(r=1)),t.texParameteri(i,t.TEXTURE_MIN_FILTER,this.glFilter[r]);}if(2&n&&t.texParameteri(i,t.TEXTURE_MAG_FILTER,this.glFilter[e._magFilter]),4&n&&t.texParameteri(i,t.TEXTURE_WRAP_S,this.glAddress[e._addressU]),8&n&&t.texParameteri(i,t.TEXTURE_WRAP_T,this.glAddress[e._addressV]),16&n&&t.texParameteri(i,t.TEXTURE_WRAP_R,this.glAddress[e._addressW]),32&n&&t.texParameteri(i,t.TEXTURE_COMPARE_MODE,e._compareOnRead?t.COMPARE_REF_TO_TEXTURE:t.NONE),64&n&&t.texParameteri(i,t.TEXTURE_COMPARE_FUNC,this.glComparison[e._compareFunc]),128&n){var s=this.extTextureFilterAnisotropic;s&&t.texParameterf(i,s.TEXTURE_MAX_ANISOTROPY_EXT,ek.clamp(Math.round(e._anisotropy),1,this.maxAnisotropy));}},r.setTexture=function(e,t){var n=e.impl;n._glTexture||n.initialize(this,e),n.dirtyParameterFlags>0||e._needsUpload||e._needsMipmapsUpload?(this.activeTexture(t),this.bindTexture(e),n.dirtyParameterFlags&&(this.setTextureParameters(e),n.dirtyParameterFlags=0),(e._needsUpload||e._needsMipmapsUpload)&&(n.upload(this,e),e._needsUpload=false,e._needsMipmapsUpload=false)):this.bindTextureOnUnit(e,t);},r.createVertexArray=function(e){var t,n,i=e.length>1;if(i){t="";for(var r=0;r0?o.drawElementsInstanced(P,I,L,D,n):o.drawElements(P,I,L,D);}else {var R=e.base;n>0?o.drawArraysInstanced(P,R,I,n):o.drawArrays(P,R,I);}this.transformFeedbackBuffer&&(o.endTransformFeedback(),o.bindBufferBase(o.TRANSFORM_FEEDBACK_BUFFER,0,null)),this._drawCallsPerFrame++;}s&&this.clearVertexBuffer();},r.clear=function(e){var t=this.defaultClearOptions,n=null!=(r=(e=e||t).flags)?r:t.flags;if(0!==n){var i=this.gl;if(1&n){var r,s,a=null!=(s=e.color)?s:t.color,o=a[0],l=a[1],u=a[2],c=a[3],h=this.clearColor;(o!==h.r||l!==h.g||u!==h.b||c!==h.a)&&(this.gl.clearColor(o,l,u,c),this.clearColor.set(o,l,u,c)),this.setBlendState(nY.NOBLEND);}if(2&n){var f,d=null!=(f=e.depth)?f:t.depth;d!==this.clearDepth&&(this.gl.clearDepth(d),this.clearDepth=d),this.setDepthState(nZ.WRITEDEPTH);}if(4&n){var p,m=null!=(p=e.stencil)?p:t.stencil;m!==this.clearStencil&&(this.gl.clearStencil(m),this.clearStencil=m),i.stencilMask(255),this.stencilWriteMaskFront=255,this.stencilWriteMaskBack=255;}i.clear(this.glClearFlag[n]);}},r.submit=function(){this.gl.flush();},r.readPixels=function(e,t,n,i,r){var s=this.gl;s.readPixels(e,t,n,i,s.RGBA,s.UNSIGNED_BYTE,r);},r.clientWaitAsync=function(e,t){var n=this.gl,i=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);return this.submit(),new Promise(function(r,s){!function a(){var o=n.clientWaitSync(i,e,0);o===n.TIMEOUT_EXPIRED?setTimeout(a,t):(n.deleteSync(i),o===n.WAIT_FAILED?s(Error("webgl clientWaitSync sync failed")):r());}();})},r.readPixelsAsync=function(e,t,n,i,r){var s=this;return sO(function(){var a,o,l,u,c,h,f,d;return sF(this,function(p){switch(p.label){case 0:return o=s.gl,c=null!=(u=null==(l=null==(a=s.renderTarget.colorBuffer)?void 0:a.impl)?void 0:l._glFormat)?u:o.RGBA,f=null!=(h=null==l?void 0:l._glPixelType)?h:o.UNSIGNED_BYTE,d=o.createBuffer(),o.bindBuffer(o.PIXEL_PACK_BUFFER,d),o.bufferData(o.PIXEL_PACK_BUFFER,r.byteLength,o.STREAM_READ),o.readPixels(e,t,n,i,c,f,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),[4,s.clientWaitAsync(0,16)];case 1:return p.sent(),o.bindBuffer(o.PIXEL_PACK_BUFFER,d),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,r),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteBuffer(d),[2,r]}})})()},r.readTextureAsync=function(e,t,n,i,r,s){var a,o,l,u=this,c=null!=(a=s.face)?a:0,h=null!=(o=s.renderTarget)?o:new ic({colorBuffer:e,depth:false,face:c}),f=new ArrayBuffer(nO.calcLevelGpuSize(i,r,1,e._format)),d=null!=(l=s.data)?l:new(tw(e._format))(f);return this.setRenderTarget(h),this.initRenderTarget(h),new Promise(function(e,a){u.readPixelsAsync(t,n,i,r,d).then(function(t){s.renderTarget||h.destroy(),e(t);}).catch(a);})},r.writeTextureAsync=function(e,t,n,i,r,s){var a=this;return sO(function(){var o,l,u,c,h,f,d;return sF(this,function(p){switch(p.label){case 0:return o=a.gl,c=null!=(u=null==(l=e.impl)?void 0:l._glFormat)?u:o.RGBA,f=null!=(h=null==l?void 0:l._glPixelType)?h:o.UNSIGNED_BYTE,d=o.createBuffer(),o.bindBuffer(o.PIXEL_UNPACK_BUFFER,d),o.bufferData(o.PIXEL_UNPACK_BUFFER,s,o.STREAM_DRAW),o.bindTexture(o.TEXTURE_2D,l._glTexture),o.texSubImage2D(o.TEXTURE_2D,0,t,n,i,r,c,f,0),o.bindBuffer(o.PIXEL_UNPACK_BUFFER,null),e._needsUpload=false,e._mipmapsUploaded=false,[4,a.clientWaitAsync(0,16)];case 1:return p.sent(),[2]}})})()},r.setAlphaToCoverage=function(e){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));},r.setTransformFeedbackBuffer=function(e){if(this.transformFeedbackBuffer!==e){this.transformFeedbackBuffer=e;var t=this.gl;e?(this.feedback||(this.feedback=t.createTransformFeedback()),t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,this.feedback)):t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,null);}},r.setRaster=function(e){this.raster!==e&&(this.raster=e,e?this.gl.disable(this.gl.RASTERIZER_DISCARD):this.gl.enable(this.gl.RASTERIZER_DISCARD));},r.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;}},r.setStencilFunc=function(e,t,n){(this.stencilFuncFront!==e||this.stencilRefFront!==t||this.stencilMaskFront!==n||this.stencilFuncBack!==e||this.stencilRefBack!==t||this.stencilMaskBack!==n)&&(this.gl.stencilFunc(this.glComparison[e],t,n),this.stencilFuncFront=this.stencilFuncBack=e,this.stencilRefFront=this.stencilRefBack=t,this.stencilMaskFront=this.stencilMaskBack=n);},r.setStencilFuncFront=function(e,t,n){if(this.stencilFuncFront!==e||this.stencilRefFront!==t||this.stencilMaskFront!==n){var i=this.gl;i.stencilFuncSeparate(i.FRONT,this.glComparison[e],t,n),this.stencilFuncFront=e,this.stencilRefFront=t,this.stencilMaskFront=n;}},r.setStencilFuncBack=function(e,t,n){if(this.stencilFuncBack!==e||this.stencilRefBack!==t||this.stencilMaskBack!==n){var i=this.gl;i.stencilFuncSeparate(i.BACK,this.glComparison[e],t,n),this.stencilFuncBack=e,this.stencilRefBack=t,this.stencilMaskBack=n;}},r.setStencilOperation=function(e,t,n,i){(this.stencilFailFront!==e||this.stencilZfailFront!==t||this.stencilZpassFront!==n||this.stencilFailBack!==e||this.stencilZfailBack!==t||this.stencilZpassBack!==n)&&(this.gl.stencilOp(this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[n]),this.stencilFailFront=this.stencilFailBack=e,this.stencilZfailFront=this.stencilZfailBack=t,this.stencilZpassFront=this.stencilZpassBack=n),(this.stencilWriteMaskFront!==i||this.stencilWriteMaskBack!==i)&&(this.gl.stencilMask(i),this.stencilWriteMaskFront=i,this.stencilWriteMaskBack=i);},r.setStencilOperationFront=function(e,t,n,i){(this.stencilFailFront!==e||this.stencilZfailFront!==t||this.stencilZpassFront!==n)&&(this.gl.stencilOpSeparate(this.gl.FRONT,this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[n]),this.stencilFailFront=e,this.stencilZfailFront=t,this.stencilZpassFront=n),this.stencilWriteMaskFront!==i&&(this.gl.stencilMaskSeparate(this.gl.FRONT,i),this.stencilWriteMaskFront=i);},r.setStencilOperationBack=function(e,t,n,i){(this.stencilFailBack!==e||this.stencilZfailBack!==t||this.stencilZpassBack!==n)&&(this.gl.stencilOpSeparate(this.gl.BACK,this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[n]),this.stencilFailBack=e,this.stencilZfailBack=t,this.stencilZpassBack=n),this.stencilWriteMaskBack!==i&&(this.gl.stencilMaskSeparate(this.gl.BACK,i),this.stencilWriteMaskBack=i);},r.setBlendState=function(e){var t=this.blendState;if(!t.equals(e)){var n=this.gl,i=e.blend,r=e.colorOp,s=e.alphaOp,a=e.colorSrcFactor,o=e.colorDstFactor,l=e.alphaSrcFactor,u=e.alphaDstFactor;if(t.blend!==i&&(i?n.enable(n.BLEND):n.disable(n.BLEND)),t.colorOp!==r||t.alphaOp!==s){var c=this.glBlendEquation;n.blendEquationSeparate(c[r],c[s]);}(t.colorSrcFactor!==a||t.colorDstFactor!==o||t.alphaSrcFactor!==l||t.alphaDstFactor!==u)&&n.blendFuncSeparate(this.glBlendFunctionColor[a],this.glBlendFunctionColor[o],this.glBlendFunctionAlpha[l],this.glBlendFunctionAlpha[u]),t.allWrite!==e.allWrite&&this.gl.colorMask(e.redWrite,e.greenWrite,e.blueWrite,e.alphaWrite),t.copy(e);}},r.setBlendColor=function(e,t,n,i){var r=this.blendColor;(e!==r.r||t!==r.g||n!==r.b||i!==r.a)&&(this.gl.blendColor(e,t,n,i),r.set(e,t,n,i));},r.setStencilState=function(e,t){e||t?(this.setStencilTest(true),e===t?(this.setStencilFunc(e.func,e.ref,e.readMask),this.setStencilOperation(e.fail,e.zfail,e.zpass,e.writeMask)):(null!=e||(e=it.DEFAULT),this.setStencilFuncFront(e.func,e.ref,e.readMask),this.setStencilOperationFront(e.fail,e.zfail,e.zpass,e.writeMask),null!=t||(t=it.DEFAULT),this.setStencilFuncBack(t.func,t.ref,t.readMask),this.setStencilOperationBack(t.fail,t.zfail,t.zpass,t.writeMask))):this.setStencilTest(false);},r.setDepthState=function(e){var t=this.depthState;if(!t.equals(e)){var n=this.gl,i=e.write;t.write!==i&&n.depthMask(i);var r=e.func,s=e.test;!s&&i&&(s=true,r=7),t.func!==r&&n.depthFunc(this.glComparison[r]),t.test!==s&&(s?n.enable(n.DEPTH_TEST):n.disable(n.DEPTH_TEST));var a=e.depthBias,o=e.depthBiasSlope;a||o?(this.depthBiasEnabled||(this.depthBiasEnabled=true,this.gl.enable(this.gl.POLYGON_OFFSET_FILL)),n.polygonOffset(o,a)):this.depthBiasEnabled&&(this.depthBiasEnabled=false,this.gl.disable(this.gl.POLYGON_OFFSET_FILL)),t.copy(e);}},r.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;}},r.setShader=function(e,t){ void 0===t&&(t=false),e!==this.shader&&(this.shader=e,this.shaderAsyncCompile=t,this.shaderValid=void 0);},r.activateShader=function(){var e=this.shader,t=e.impl;void 0===this.shaderValid&&(e.failed?this.shaderValid=false:!e.ready&&(this.shaderAsyncCompile?t.isLinked(this)?t.finalize(this,e)||(e.failed=true,this.shaderValid=false):this.shaderValid=false:t.finalize(this,e)||(e.failed=true,this.shaderValid=false))),void 0===this.shaderValid&&(this.gl.useProgram(t.glProgram),this.shaderValid=true);},r.clearVertexArrayObjectCache=function(){var e=this.gl;this._vaoMap.forEach(function(t,n,i){e.deleteVertexArray(t);}),this._vaoMap.clear();},n=[{key:"extDisjointTimerQuery",get:function(){return this._extDisjointTimerQuery||(this._extDisjointTimerQuery=this.getExtension("EXT_disjoint_timer_query_webgl2","EXT_disjoint_timer_query")),this._extDisjointTimerQuery}},{key:"defaultFramebuffer",get:function(){return this._defaultFramebuffer},set:function(e){this._defaultFramebuffer!==e&&(this._defaultFramebuffer=e,this._defaultFramebufferChanged=true);}},{key:"fullscreen",get:function(){return !!document.fullscreenElement},set:function(e){e?this.gl.canvas.requestFullscreen():document.exitFullscreen();}}],function(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(this.parameters);!(e=t()).done;){var n=e.value[1];n.scopeId.setValue(n.value);}},t.setupDispatch=function(e,t,n){this.countX=e,this.countY=t,this.countZ=n;},e}(),sZ=0,sQ=function(){function e(e,t,n,i,r,s){ void 0===i&&(i=0),this.device=e,this.format=t,this.numIndices=n,this.usage=i,this.id=sZ++,this.impl=e.createIndexBufferImpl(this,s);var a=nx[t];this.bytesPerIndex=a,this.numBytes=this.numIndices*a,r?this.setData(r):this.storage=new ArrayBuffer(this.numBytes),this.adjustVramSizeTracking(e._vram,this.numBytes),this.device.buffers.push(this);}var t=e.prototype;return t.destroy=function(){var e=this.device,t=e.buffers.indexOf(this);-1!==t&&e.buffers.splice(t,1),this.device.indexBuffer===this&&(this.device.indexBuffer=null),this.impl.initialized&&(this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this.storage.byteLength));},t.adjustVramSizeTracking=function(e,t){e.ib+=t;},t.loseContext=function(){this.impl.loseContext();},t.getFormat=function(){return this.format},t.getNumIndices=function(){return this.numIndices},t.lock=function(){return this.storage},t.unlock=function(){this.impl.unlock(this);},t.setData=function(e){return e.byteLength===this.numBytes&&(this.storage=e,this.unlock(),true)},t._lockTypedArray=function(){var e=this.lock();return 2===this.format?new Uint32Array(e):1===this.format?new Uint16Array(e):new Uint8Array(e)},t.writeData=function(e,t){var n=this._lockTypedArray();if(e.length>t)if(ArrayBuffer.isView(e))e=e.subarray(0,t),n.set(e);else for(var i=0;ithis.vertexBuffer.numVertices&&(n=this.vertexBuffer.numVertices);var r=i.numComponents;if(this.vertexBuffer.getFormat().interleaved)for(var s=0,a=0;an*r){var o=n*r;if(ArrayBuffer.isView(t))t=t.subarray(0,o),i.array.set(t);else for(var l=0;l0?this.wheelDelta=1:n.deltaY<0&&(this.wheelDelta=-1)),ag()?(this.dx=n.movementX||n.webkitMovementX||n.mozMovementX||0,this.dy=n.movementY||n.webkitMovementY||n.mozMovementY||0):(this.dx=this.x-t._lastX,this.dy=this.y-t._lastY),("mousedown"===n.type||"mouseup"===n.type)&&(this.button=n.button),this.buttons=t._buttons.slice(0),this.element=n.target,this.ctrlKey=null!=(a=n.ctrlKey)&&a,this.altKey=null!=(o=n.altKey)&&o,this.shiftKey=null!=(l=n.shiftKey)&&l,this.metaKey=null!=(u=n.metaKey)&&u,this.event=n;};function aS(e,t){return (aS=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var ax=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this)||this)._lastX=0,n._lastY=0,n._buttons=[false,false,false],n._lastbuttons=[false,false,false],n._target=null,n._attached=false,n._upHandler=n._handleUp.bind(n),n._downHandler=n._handleDown.bind(n),n._moveHandler=n._handleMove.bind(n),n._wheelHandler=n._handleWheel.bind(n),n._contextMenuHandler=function(e){e.preventDefault();},n.attach(t),n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&aS(t,e);var n=t.prototype;return n.attach=function(e){if(this._target=e,!this._attached){this._attached=true;var t=!!ef.passiveEvents&&{passive:false};window.addEventListener("mouseup",this._upHandler,t),window.addEventListener("mousedown",this._downHandler,t),window.addEventListener("mousemove",this._moveHandler,t),window.addEventListener("wheel",this._wheelHandler,t);}},n.detach=function(){if(this._attached){this._attached=false,this._target=null;var e=!!ef.passiveEvents&&{passive:false};window.removeEventListener("mouseup",this._upHandler,e),window.removeEventListener("mousedown",this._downHandler,e),window.removeEventListener("mousemove",this._moveHandler,e),window.removeEventListener("wheel",this._wheelHandler,e);}},n.disableContextMenu=function(){this._target&&this._target.addEventListener("contextmenu",this._contextMenuHandler);},n.enableContextMenu=function(){this._target&&this._target.removeEventListener("contextmenu",this._contextMenuHandler);},n.enablePointerLock=function(e,t){if(!document.body.requestPointerLock){t&&t();return}var n=function(){e(),document.removeEventListener("pointerlockchange",n);},i=function(){t(),document.removeEventListener("pointerlockerror",i);};e&&document.addEventListener("pointerlockchange",n,false),t&&document.addEventListener("pointerlockerror",i,false),document.body.requestPointerLock();},n.disablePointerLock=function(e){if(document.exitPointerLock){var t=function(){e(),document.removeEventListener("pointerlockchange",t);};e&&document.addEventListener("pointerlockchange",t,false),document.exitPointerLock();}},n.update=function(){this._lastbuttons[0]=this._buttons[0],this._lastbuttons[1]=this._buttons[1],this._lastbuttons[2]=this._buttons[2];},n.isPressed=function(e){return this._buttons[e]},n.wasPressed=function(e){return this._buttons[e]&&!this._lastbuttons[e]},n.wasReleased=function(e){return !this._buttons[e]&&this._lastbuttons[e]},n._handleUp=function(e){this._buttons[e.button]=false;var t=new ay(this,e);t.event&&this.fire("mouseup",t);},n._handleDown=function(e){this._buttons[e.button]=true;var t=new ay(this,e);t.event&&this.fire("mousedown",t);},n._handleMove=function(e){var t=new ay(this,e);t.event&&(this.fire("mousemove",t),this._lastX=t.x,this._lastY=t.y);},n._handleWheel=function(e){var t=new ay(this,e);t.event&&this.fire("mousewheel",t);},n._getTargetCoords=function(e){var t=this._target.getBoundingClientRect(),n=Math.floor(t.left),i=Math.floor(t.top);return e.clientX=n+this._target.clientWidth||e.clientY=i+this._target.clientHeight?null:{x:e.clientX-n,y:e.clientY-i}},t.isPointerLocked=function(){return ag()},t}(ex);ax.EVENT_MOUSEMOVE="mousemove",ax.EVENT_MOUSEDOWN="mousedown",ax.EVENT_MOUSEUP="mouseup",ax.EVENT_MOUSEWHEEL="mousewheel";var ab=function(){function e(e,t){ void 0===t&&(t={}),this._element=null,this._actions={},this._axes={},this._axesValues={},this._keyboard=t.keyboard||null,this._mouse=t.mouse||null,this._gamepads=t.gamepads||null,e&&this.attach(e);}var t=e.prototype;return t.attach=function(e){this._element=e,this._keyboard&&this._keyboard.attach(e),this._mouse&&this._mouse.attach(e);},t.detach=function(){this._keyboard&&this._keyboard.detach(),this._mouse&&this._mouse.detach(),this._element=null;},t.disableContextMenu=function(){this._mouse||this._enableMouse(),this._mouse.disableContextMenu();},t.enableContextMenu=function(){this._mouse||this._enableMouse(),this._mouse.enableContextMenu();},t.update=function(e){for(var t in this._keyboard&&this._keyboard.update(),this._mouse&&this._mouse.update(),this._gamepads&&this._gamepads.update(),this._axesValues={},this._axes)this._axesValues[t]=[];},t.appendAction=function(e,t){this._actions[e]=this._actions[e]||[],this._actions[e].push(t);},t.registerKeys=function(e,t){if(this._keyboard||this._enableKeyboard(),this._actions[e])throw Error("Action: "+e+" already registered");if(void 0===t)throw Error("Invalid button");t.length||(t=[t]),this.appendAction(e,{type:au,keys:t});},t.registerMouse=function(e,t){if(this._mouse||this._enableMouse(),void 0===t)throw Error("Invalid button");this.appendAction(e,{type:al,button:t});},t.registerPadButton=function(e,t,n){if(void 0===n)throw Error("Invalid button");this.appendAction(e,{type:ac,button:n,pad:t});},t.registerAxis=function(e){var t=e.name;this._axes[t]||(this._axes[t]=[]);var n=this._axes[t].push(t);(e=e||{}).pad=e.pad||0;var i=function(i,r,s,a){switch(r){case "mousex":i._mouse.on("mousemove",function(e){i._axesValues[t][n]=e.dx/10;});break;case "mousey":i._mouse.on("mousemove",function(e){i._axesValues[t][n]=e.dy/10;});break;case "key":i._axes[t].push(function(){return i._keyboard.isPressed(a)?s:0});break;case "padrx":i._axes[t].push(function(){return i._gamepads.getAxis(e.pad,2)});break;case "padry":i._axes[t].push(function(){return i._gamepads.getAxis(e.pad,3)});break;case "padlx":i._axes[t].push(function(){return i._gamepads.getAxis(e.pad,0)});break;case "padly":i._axes[t].push(function(){return i._gamepads.getAxis(e.pad,1)});break;default:throw Error("Unknown axis")}};i(this,e.positive,1,e.positiveKey),(e.negativeKey||e.negative!==e.positive)&&i(this,e.negative,-1,e.negativeKey);},t.isPressed=function(e){if(!this._actions[e])return false;for(var t=this._actions[e].length,n=0;nMath.abs(t)&&(t=r);}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 ax,!this._element)throw Error("Controller must be attached to an Element");this._mouse.attach(this._element);},t._enableKeyboard=function(){if(this._keyboard=new av,!this._element)throw Error("Controller must be attached to an Element");this._keyboard.attach(this._element);},e}();function aT(e,t,n,i,r,s,a){try{var o=e[s](a),l=o.value;}catch(e){n(e);return}o.done?t(l):Promise.resolve(l).then(i,r);}function aE(e){return function(){var t=this,n=arguments;return new Promise(function(i,r){var s=e.apply(t,n);function a(e){aT(s,i,r,a,o,"next",e);}function o(e){aT(s,i,r,a,o,"throw",e);}a(void 0);})}}function aw(e,t,n){return t&&function(e,t){for(var n=0;n0&&r[r.length-1])&&(6===u[0]||2===u[0])){s=0;continue}if(3===u[0]&&(!r||u[1]>r[0]&&u[1]0):(this.value=e.value,this.pressed=e.pressed,this.touched=null!=(n=e.touched)?n:e.value>0),t&&("number"==typeof t?(this.wasPressed=1!==t&&this.pressed,this.wasReleased=1===t&&!this.pressed,this.wasTouched=0===t&&this.touched):(this.wasPressed=!t.pressed&&this.pressed,this.wasReleased=t.pressed&&!this.pressed,this.wasTouched=!(null!=(i=t.touched)?i:t.value>0)&&this.touched));}return e.prototype.update=function(e){var t,n=e.value,i=e.pressed,r=null!=(t=e.touched)?t:n>0;this.wasPressed=!this.pressed&&i,this.wasReleased=this.pressed&&!i,this.wasTouched=!this.touched&&r,this.value=n,this.pressed=i,this.touched=r;},e}(),aB=Object.freeze(new aF(0)),aU=function(){function e(e,t){this._compiledMapping={buttons:[],axes:[]},this.id=e.id,this.index=e.index,this._buttons=e.buttons.map(function(e){return new aF(e)}),this._axes=[].concat(e.axes),this._previousAxes=[].concat(e.axes),this.mapping=t.mapping,this.map=t,this.hand=e.hand||"none",this.pad=e,this._compileMapping();}var t=e.prototype;return t._compileMapping=function(){var e=this,t=this._compiledMapping,n=t.axes,i=t.buttons;n.length=0,i.length=0,this.map.axes&&this.map.axes.forEach(function(t,i){n[aD[t]]=function(){return e.pad.axes[i]||0};});for(var r=0,s=n.length;raN?t:0},aw(e,[{key:"connected",get:function(){return this.pad.connected}},{key:"axes",get:function(){return this._compiledMapping.axes.map(function(e){return e()})}},{key:"buttons",get:function(){return this._compiledMapping.buttons.map(function(e){return e()})}}]),e}(),aV=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(){var t;return (t=e.call(this)||this).gamepadsSupported=ef.gamepads,t.current=[],t._previous=[],t._ongamepadconnectedHandler=t._ongamepadconnected.bind(t),t._ongamepaddisconnectedHandler=t._ongamepaddisconnected.bind(t),window.addEventListener("gamepadconnected",t._ongamepadconnectedHandler,false),window.addEventListener("gamepaddisconnected",t._ongamepaddisconnectedHandler,false),t.poll(),t}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&aA(t,e);var n=t.prototype;return n._ongamepadconnected=function(e){for(var t=new aU(e.gamepad,this.getMap(e.gamepad)),n=this.current,i=n.findIndex(function(e){return e.index===t.index});-1!==i;)n.splice(i,1),i=n.findIndex(function(e){return e.index===t.index});n.push(t),this.fire("gamepadconnected",t);},n._ongamepaddisconnected=function(e){var t=this.current,n=t.findIndex(function(t){return t.index===e.gamepad.index});-1!==n&&(this.fire("gamepaddisconnected",t[n]),t.splice(n,1));},n.update=function(){this.poll();},n.poll=function(e){ void 0===e&&(e=[]),e.length>0&&(e.length=0);for(var t=aI(),n=0,i=t.length;n=0?e.ResponseType.ARRAY_BUFFER:".json"===i?e.ResponseType.JSON:".xml"===i?e.ResponseType.DOCUMENT:e.ResponseType.TEXT},t._isBinaryContentType=function(t){return [e.ContentType.BASIS,e.ContentType.BIN,e.ContentType.DDS,e.ContentType.GLB,e.ContentType.MP3,e.ContentType.MP4,e.ContentType.OGG,e.ContentType.OPUS,e.ContentType.WAV].indexOf(t)>=0},t._isBinaryResponseType=function(t){return t===e.ResponseType.ARRAY_BUFFER||t===e.ResponseType.BLOB||t===e.ResponseType.JSON},t._onReadyStateChange=function(e,t,n,i){if(4===i.readyState)switch(i.status){case 0:i.responseURL&&i.responseURL.startsWith("file:///")?this._onSuccess(e,t,n,i):this._onError(e,t,n,i);break;case 200:case 201:case 206:case 304:this._onSuccess(e,t,n,i);break;default:this._onError(e,t,n,i);}},t._onSuccess=function(t,n,i,r){var s,a,o=r.getResponseHeader("Content-Type");o&&(a=o.split(";")[0].trim());try{s=this._isBinaryContentType(a)||this._isBinaryResponseType(r.responseType)?r.response:a===e.ContentType.JSON||n.split("?")[0].endsWith(".json")?JSON.parse(r.responseText):r.responseType===e.ResponseType.DOCUMENT||a===e.ContentType.XML?r.responseXML:r.responseText,i.callback(null,s);}catch(e){i.callback(e);}},t._onError=function(t,n,i,r){var s=this;i.retrying||(i.retry&&i.retriesi)return 0;var o=0;return s===tp?o=1-r*(a-n)/(i-n):s===tm?o=n/(n+r*(a-n)):s===t_&&(o=Math.pow(a/n,-r)),ek.clamp(o,0,1)};Object.assign(aJ.prototype,{setPosition:function(e){if(this.position.copy(e),this.source){var t=a0(this.manager.listener.getPosition(),this.position,this.minDistance,this.maxDistance,this.rollOffFactor,this.distanceModel),n=this.getVolume();this.source.volume=n*t;}},getMaxDistance:function(){return this.maxDistance},setMaxDistance:function(e){this.maxDistance=e;},getMinDistance:function(){return this.minDistance},setMinDistance:function(e){this.minDistance=e;},getRollOffFactor:function(){return this.rollOffFactor},setRollOffFactor:function(e){this.rollOffFactor=e;},getDistanceModel:function(){return this.distanceModel},setDistanceModel:function(e){this.distanceModel=e;}});}var a1=function(){function e(e){this.position=new eW,this.orientation=new e$,this._manager=e;}var t,n=e.prototype;return n.getPosition=function(){return this.position},n.setPosition=function(e){this.position.copy(e);var t=this.listener;t&&("positionX"in t?(t.positionX.value=e.x,t.positionY.value=e.y,t.positionZ.value=e.z):t.setPosition&&t.setPosition(e.x,e.y,e.z));},n.setOrientation=function(e){this.orientation.copy(e);var t=this.listener;if(t){var n=e.data;"forwardX"in t?(t.forwardX.value=-n[8],t.forwardY.value=-n[9],t.forwardZ.value=-n[10],t.upX.value=n[4],t.upY.value=n[5],t.upZ.value=n[6]):t.setOrientation&&t.setOrientation(-n[8],-n[9],-n[10],n[4],n[5],n[6]);}},n.getOrientation=function(){return this.orientation},t=[{key:"listener",get:function(){var e=this._manager.context;return e?e.listener:null}}],function(e,t){for(var n=0;n0)return void this._suspendEndEvent--;this.fire("end"),this._onEndCallback&&this._onEndCallback(this),this.stop();},i._onManagerVolumeChange=function(){this.volume=this._volume;},i._onManagerSuspend=function(){0!==this._state||this._suspended||(this._suspended=true,this.pause());},i._onManagerResume=function(){this._suspended&&(this._suspended=false,this.resume());},i._initializeNodes=function(){this.gain=this._manager.context.createGain(),this._inputNode=this.gain,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination);},i.play=function(){return 2!==this._state&&this.stop(),this._state=0,this._playWhenLoaded=false,!this._waitingContextSuspension&&(this._manager.suspended?(this._manager.once("resume",this._playAudioImmediate,this),this._waitingContextSuspension=true,false):(this._playAudioImmediate(),true))},i._playAudioImmediate=function(){if(this._waitingContextSuspension=false,0===this._state){this.source||this._createSource();var e=this._startOffset%this.duration||0;e=(this._startTime+e)%this._sound.duration||0,this._startOffset=null,this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentTime=0,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._manager.on("volumechange",this._onManagerVolumeChange,this),this._manager.on("suspend",this._onManagerSuspend,this),this._manager.on("resume",this._onManagerResume,this),this._manager.on("destroy",this._onManagerDestroy,this),this._suspendInstanceEvents||this._onPlay();}},i.pause=function(){return this._playWhenLoaded=false,0===this._state&&(this._state=1,!!this._waitingContextSuspension||(this._updateCurrentTime(),this._suspendEndEvent++,this.source.stop(0),this.source=null,this._startOffset=null,this._suspendInstanceEvents||this._onPause(),true))},i.resume=function(){if(1!==this._state)return false;var e=this.currentTime;return this._state=0,!!this._waitingContextSuspension||(this.source||this._createSource(),null!==this._startOffset&&(e=this._startOffset%this.duration||0,e=(this._startTime+e)%this._sound.duration||0,this._startOffset=null),this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._playWhenLoaded=false,this._suspendInstanceEvents||this._onResume(),true)},i.stop=function(){if(this._playWhenLoaded=false,2===this._state)return false;var e=0===this._state;return this._state=2,!!this._waitingContextSuspension||(this._manager.off("volumechange",this._onManagerVolumeChange,this),this._manager.off("suspend",this._onManagerSuspend,this),this._manager.off("resume",this._onManagerResume,this),this._manager.off("destroy",this._onManagerDestroy,this),this._startedAt=0,this._currentTime=0,this._currentOffset=0,this._startOffset=null,this._suspendEndEvent++,e&&this.source&&this.source.stop(0),this.source=null,this._suspendInstanceEvents||this._onStop(),true)},i.setExternalNodes=function(e,t){if(e){t||(t=e);var n=this._manager.context.destination;this._firstNode!==e&&(this._firstNode?this._connectorNode.disconnect(this._firstNode):this._connectorNode.disconnect(n),this._firstNode=e,this._connectorNode.connect(e)),this._lastNode!==t&&(this._lastNode&&this._lastNode.disconnect(n),this._lastNode=t,this._lastNode.connect(n));}},i.clearExternalNodes=function(){var e=this._manager.context.destination;this._firstNode&&(this._connectorNode.disconnect(this._firstNode),this._firstNode=null),this._lastNode&&(this._lastNode.disconnect(e),this._lastNode=null),this._connectorNode.connect(e);},i.getExternalNodes=function(){return [this._firstNode,this._lastNode]},i._createSource=function(){if(!this._sound)return null;var e=this._manager.context;return this._sound.buffer&&(this.source=e.createBufferSource(),this.source.buffer=this._sound.buffer,this.source.connect(this._inputNode),this.source.onended=this._endedHandler,this.source.loopStart=this._startTime%this.source.buffer.duration||0,this._duration&&(this.source.loopEnd=Math.max(this.source.loopStart,(this._startTime+this._duration)%this.source.buffer.duration||0))),this.source},i._updateCurrentTime=function(){this._currentTime=((this._manager.context.currentTime-this._startedAt)*this._pitch+this._currentOffset)%this.duration||0;},i._onManagerDestroy=function(){this.source&&0===this._state&&(this.source.stop(0),this.source=null);},n=[{key:"currentTime",get:function(){return null!==this._startOffset?this._startOffset:1===this._state?this._currentTime:2!==this._state&&this.source?(this._updateCurrentTime(),this._currentTime):0},set:function(e){if(!(e<0))if(0===this._state){var t=this._suspendInstanceEvents;this._suspendInstanceEvents=true,this.stop(),this._startOffset=e,this.play(),this._suspendInstanceEvents=t;}else this._startOffset=e,this._currentTime=e;}},{key:"duration",get:function(){if(!this._sound)return 0;if(this._duration)return this._duration%this._sound.duration||0;return this._sound.duration},set:function(e){this._duration=Math.max(0,Number(e)||0);var t=0===this._state;this.stop(),t&&this.play();}},{key:"isPaused",get:function(){return 1===this._state}},{key:"isPlaying",get:function(){return 0===this._state}},{key:"isStopped",get:function(){return 2===this._state}},{key:"isSuspended",get:function(){return this._suspended}},{key:"loop",get:function(){return this._loop},set:function(e){this._loop=!!e,this.source&&(this.source.loop=this._loop);}},{key:"pitch",get:function(){return this._pitch},set:function(e){this._currentOffset=this.currentTime,this._startedAt=this._manager.context.currentTime,this._pitch=Math.max(Number(e)||0,.01),this.source&&(this.source.playbackRate.value=this._pitch);}},{key:"sound",get:function(){return this._sound},set:function(e){this._sound=e,2!==this._state?this.stop():this._createSource();}},{key:"startTime",get:function(){return this._startTime},set:function(e){this._startTime=Math.max(0,Number(e)||0);var t=0===this._state;this.stop(),t&&this.play();}},{key:"volume",get:function(){return this._volume},set:function(e){e=ek.clamp(e,0,1),this._volume=e,this.gain&&(this.gain.gain.value=e*this._manager.volume);}}],function(e,t){for(var n=0;n((this._startTime+this._duration)%this.source.duration||0)&&(this.loop?this.source.currentTime=this._startTime%this.source.duration||0:(this.source.removeEventListener("timeupdate",this._timeUpdateHandler),this.source.pause(),this._onEnded()));},_onManagerDestroy:function(){this.source&&this.source.pause();}}),Object.defineProperty(a9.prototype,"volume",{get:function(){return this._volume},set:function(e){e=ek.clamp(e,0,1),this._volume=e,this.source&&(this.source.volume=e*this._manager.volume);}}),Object.defineProperty(a9.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(a9.prototype,"sound",{get:function(){return this._sound},set:function(e){this.stop(),this._sound=e;}}),Object.defineProperty(a9.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=(this._startTime+(e%this.duration||0))%this._sound.duration||0,this._startOffset=null);}}));var oe=function(e){var t;if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function n(t,n,i){var r;return void 0===i&&(i={}),(r=e.call(this,t,n,i)||this)._position=new eW,r._velocity=new eW,i.position&&(r.position=i.position),r.maxDistance=void 0!==i.maxDistance?Number(i.maxDistance):1e4,r.refDistance=void 0!==i.refDistance?Number(i.refDistance):1,r.rollOffFactor=void 0!==i.rollOffFactor?Number(i.rollOffFactor):1,r.distanceModel=void 0!==i.distanceModel?i.distanceModel:tp,r}return n.prototype=Object.create(e&&e.prototype,{constructor:{value:n,writable:true,configurable:true}}),e&&a7(n,e),n.prototype._initializeNodes=function(){this.gain=this._manager.context.createGain(),this.panner=this._manager.context.createPanner(),this.panner.connect(this.gain),this._inputNode=this.panner,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination);},t=[{key:"position",get:function(){return this._position},set:function(e){this._position.copy(e);var t=this.panner;"positionX"in t?(t.positionX.value=e.x,t.positionY.value=e.y,t.positionZ.value=e.z):t.setPosition&&t.setPosition(e.x,e.y,e.z);}},{key:"velocity",get:function(){return this._velocity},set:function(e){this._velocity.copy(e);}},{key:"maxDistance",get:function(){return this.panner.maxDistance},set:function(e){this.panner.maxDistance=e;}},{key:"refDistance",get:function(){return this.panner.refDistance},set:function(e){this.panner.refDistance=e;}},{key:"rollOffFactor",get:function(){return this.panner.rolloffFactor},set:function(e){this.panner.rolloffFactor=e;}},{key:"distanceModel",get:function(){return this.panner.distanceModel},set:function(e){this.panner.distanceModel=e;}}],function(e,t){for(var n=0;ni)return 0;var o=0;return s===tp?o=1-r*(a-n)/(i-n):s===tm?o=n/(n+r*(a-n)):s===t_&&(o=Math.pow(a/n,-r)),ek.clamp(o,0,1)};Object.defineProperty(oe.prototype,"position",{get:function(){return this._position},set:function(e){if(this._position.copy(e),this.source){var t=on(this._manager.listener.getPosition(),this._position,this.refDistance,this.maxDistance,this.rollOffFactor,this.distanceModel),n=this.volume;this.source.volume=n*t*this._manager.volume;}}}),Object.defineProperty(oe.prototype,"maxDistance",{get:function(){return this._maxDistance},set:function(e){this._maxDistance=e;}}),Object.defineProperty(oe.prototype,"refDistance",{get:function(){return this._refDistance},set:function(e){this._refDistance=e;}}),Object.defineProperty(oe.prototype,"rollOffFactor",{get:function(){return this._rollOffFactor},set:function(e){this._rollOffFactor=e;}}),Object.defineProperty(oe.prototype,"distanceModel",{get:function(){return this._distanceModel},set:function(e){this._distanceModel=e;}});}var oi=((h={})[0]="SUBTRACTIVE",h[1]="ADDITIVE",h[2]="NORMAL",h[3]="NONE",h[4]="PREMULTIPLIED",h[5]="MULTIPLICATIVE",h[6]="ADDITIVEALPHA",h[7]="MULTIPLICATIVE2X",h[8]="SCREEN",h[9]="MIN",h[10]="MAX",h),or="none",os="linear",oa=((f={})[0]="NONE",f[2]="SCHLICK",f),oo=((d={})[0]="DIRECTIONAL",d[1]="OMNI",d[2]="SPOT",d),ol=((p={})[0]="PUNCTUAL",p[1]="RECT",p[2]="DISK",p[3]="SPHERE",p),ou=((m={})[0]="LINEAR",m[1]="INVERSESQUARED",m),oc=new Map([[5,{name:"PCF1_32F",kind:"PCF1",format:16,pcf:true}],[0,{name:"PCF3_32F",kind:"PCF3",format:16,pcf:true}],[4,{name:"PCF5_32F",kind:"PCF5",format:16,pcf:true}],[7,{name:"PCF1_16F",kind:"PCF1",format:69,pcf:true}],[8,{name:"PCF3_16F",kind:"PCF3",format:69,pcf:true}],[9,{name:"PCF5_16F",kind:"PCF5",format:69,pcf:true}],[2,{name:"VSM_16F",kind:"VSM",format:12,vsm:true}],[3,{name:"VSM_32F",kind:"VSM",format:14,vsm:true}],[6,{name:"PCSS_32F",kind:"PCSS",format:15,pcss:true}]]),oh=((_={})[0]="NONE",_[1]="BOX",_),of=((v={})[0]="NONE",v[1]="SRGB",v),od=["LINEAR","FILMIC","HEJL","ACES","ACES2","NEUTRAL","NONE"],op=((g={})[0]="NONE",g[1]="AO",g[2]="GLOSSDEPENDENT",g),om="none",o_="envAtlas",ov="envAtlasHQ",og="cubeMap",oy="sphereMap",oS=((y={})[om]="NONE",y[o_]="ENVATLAS",y[ov]="ENVATLASHQ",y[og]="CUBEMAP",y[oy]="SPHEREMAP",y),ox="ambientSH",ob="envAtlas",oT="constant",oE=((S={})[ox]="AMBIENTSH",S[ob]="ENVALATLAS",S[oT]="CONSTANT",S),ow=((x={})[0]="SIMPLE",x[1]="SLICED",x[2]="TILED",x),oA="infinite",oC="dome",oP="none",oI="bayer8",oL="bluenoise",oD="ignnoise",oR=((b={})[oP]="NONE",b[oI]="BAYER8",b[oL]="BLUENOISE",b[oD]="IGNNOISE",b),oM="prerender",oO="postrender",ok="prerender:layer",oN="postrender:layer",oF="precull",oB="postcull",oU=function(){function e(e,t,n){this.uniformFormats=[],this.bindGroupFormats=[],this.uniformFormats[0]=e,this.bindGroupFormats[0]=t,this.vertexFormat=n;}var t=e.prototype;return t.hasUniform=function(e){for(var t=0;tt[0]?1:-1})))},e}(),oH=new nM,oW=function(){function e(e,t,n){ void 0===n&&(n={}),this.defines=new Map,this.name=e,this.index=t,Object.assign(this,n),this.buildShaderDefines();}return e.prototype.buildShaderDefines=function(){var e;this.isShadow?e="SHADOW":this.isForward?e="FORWARD":3===this.index&&(e="PICK"),this.defines.set(""+e+"_PASS",""),this.defines.set(""+this.name.toUpperCase()+"_PASS","");},e}(),oj=function(){function e(){var e=this;this.passesNamed=new Map,this.passesIndexed=[],this.nextIndex=0;var t=function(t,n,i){e.allocate(t,i);};t("forward",0,{isForward:true}),t("prepass"),t("shadow"),t("pick");}var t=e.prototype;return t.allocate=function(e,t){var n=this.passesNamed.get(e);return void 0===n&&(n=new oW(e,this.nextIndex,t),this.passesNamed.set(n.name,n),this.passesIndexed[n.index]=n,this.nextIndex++),n},t.getByIndex=function(e){return this.passesIndexed[e]},t.getByName=function(e){return this.passesNamed.get(e)},e.get=function(t){return oH.get(t,function(){return new e})},e}();function oX(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o$=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(){var t;return t=e.apply(this,arguments)||this,t._keyDirty=false,t._key="",t}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&oK(t,e);var n,i=t.prototype;return i.set=function(t,n){return this.has(t)&&this.get(t)===n||this.markDirty(),e.prototype.set.call(this,t,n)},i.add=function(e){for(var t,n=oJ(Object.entries(e));!(t=n()).done;){var i=t.value,r=i[0],s=i[1];this.set(r,s);}return this},i.delete=function(t){var n=this.has(t),i=e.prototype.delete.call(this,t);return n&&i&&this.markDirty(),i},i.clear=function(){this.size>0&&this.markDirty(),e.prototype.clear.call(this);},i.markDirty=function(){this._dirty=true,this._keyDirty=true;},i.isDirty=function(){return this._dirty},i.resetDirty=function(){this._dirty=false;},i.copy=function(e){this.clear();for(var t,n=oJ(e);!(t=n()).done;){var i=t.value,r=i[0],s=i[1];this.set(r,s);}return this},n=[{key:"key",get:function(){return this._keyDirty&&(this._keyDirty=false,this._key=Array.from(this.entries()).sort(function(e,t){var n=e[0],i=t[0];return ni)}).map(function(e){return e[0]+"="+n4(e[1])}).join(",")),this._key}}],function(e,t){for(var n=0;n0}},{key:"key",get:function(){return "GLSL:"+this.glsl.key+"|WGSL:"+this.wgsl.key+"|API:"+this.version}}],function(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(s);!(o=l()).done;){var u=o.value,c=u[0],h=u[1];i.set(c,h);}}return i},e}();function o4(){return (o4=Object.assign||function(e){for(var t=1;t1&&(a.colorOps.store=true),a.render(),s.destroy();}var lo=function(){function e(e,t,n){this._aabb=new e8,this.meshInstance=null,this.origMeshInstances=e,this.dynamic=t,this.batchGroupId=n;}var t,n=e.prototype;return n.destroy=function(e,t){this.meshInstance&&(this.removeFromLayers(e,t),this.meshInstance.destroy(),this.meshInstance=null);},n.addToLayers=function(e,t){for(var n=0;n=0;n--)this.matrices[n].mulAffine2(lu,this.bones[n].getWorldTransform()),this.matrices[n].mulAffine2(this.matrices[n],this.skin.inverseBindPose[n]);}},n.updateMatrices=function(e,t){this._updateBeforeCull&&this._updateMatrices(e,t);},n.updateMatrixPalette=function(e,t){this._updateMatrices(e,t);for(var n=this.matrixPalette,i=this.bones.length,r=0;r0){var x=v.array[v.index+S];if(h[x]=true,t=m.array[m.index],n=m.array[m.index+1],i=m.array[m.index+2],r=c[x],(s=u[x]).x>t&&(s.x=t),s.y>n&&(s.y=n),s.z>i&&(s.z=i),r.xb&&(s.x=b),s.y>T&&(s.y=T),s.z>E&&(s.z=E),r.x0&&this.indexBuffer[0]&&(this._geometryData.indexCount=this.indexBuffer[0].numIndices,this._geometryData.maxIndices=this.indexBuffer[0].numIndices));},i.clear=function(e,t,n,i){ void 0===n&&(n=0),void 0===i&&(i=0),this._initGeometryData(),this._geometryData.initDefaults(),this._geometryData.recreate=true,this._geometryData.maxVertices=n,this._geometryData.maxIndices=i,this._geometryData.verticesUsage=+!e,this._geometryData.indicesUsage=+!t;},i.setVertexStream=function(e,t,n,i,r,s,a){ void 0===r&&(r=6),void 0===s&&(s=false),void 0===a&&(a=false),this._initGeometryData();var o=i||t.length/n;this._geometryData._changeVertexCount(o,e),this._geometryData.vertexStreamsUpdated=true,this._geometryData.vertexStreamDictionary[e]=new l_(t,n,r,s,a);},i.getVertexStream=function(e,t){var n=0,i=false;if(this._geometryData){var r=this._geometryData.vertexStreamDictionary[e];r&&(i=true,n=this._geometryData.vertexCount,ArrayBuffer.isView(t)?t.set(r.data):(t.length=0,t.push(r.data)));}return !i&&this.vertexBuffer&&(n=new ao(this.vertexBuffer).readData(e,t)),n},i.setPositions=function(e,t,n){ void 0===t&&(t=lm.DEFAULT_COMPONENTS_POSITION),this.setVertexStream(tA,e,t,n,6,false);},i.setNormals=function(e,t,n){ void 0===t&&(t=lm.DEFAULT_COMPONENTS_NORMAL),this.setVertexStream(tC,e,t,n,6,false);},i.setUvs=function(e,t,n,i){ void 0===n&&(n=lm.DEFAULT_COMPONENTS_UV),this.setVertexStream(tR+e,t,n,i,6,false);},i.setColors=function(e,t,n){ void 0===t&&(t=lm.DEFAULT_COMPONENTS_COLORS),this.setVertexStream(tD,e,t,n,6,false);},i.setColors32=function(e,t){this.setVertexStream(tD,e,lm.DEFAULT_COMPONENTS_COLORS,t,1,true);},i.setIndices=function(e,t){this._initGeometryData(),this._geometryData.indexStreamUpdated=true,this._geometryData.indices=e,this._geometryData.indexCount=t||e.length;},i.getPositions=function(e){return this.getVertexStream(tA,e)},i.getNormals=function(e){return this.getVertexStream(tC,e)},i.getUvs=function(e,t){return this.getVertexStream(tR+e,t)},i.getColors=function(e){return this.getVertexStream(tD,e)},i.getIndices=function(e){var t=0;if(this._geometryData&&this._geometryData.indices){var n=this._geometryData.indices;if(t=this._geometryData.indexCount,ArrayBuffer.isView(e))e.set(n);else {e.length=0;for(var i=0,r=n.length;i0&&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=true),this._geometryData){if(t){var n=this._geometryData.vertexStreamDictionary[tA];n&&3===n.componentCount&&(this._aabb.compute(n.data,this._geometryData.vertexCount),this._aabbVer++);}var i=this._geometryData.recreate;this._geometryData.vertexCount>this._geometryData.maxVertices&&(i=true,this._geometryData.maxVertices=this._geometryData.vertexCount),i&&this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);var r=this._geometryData.recreate;this._geometryData.indexCount>this._geometryData.maxIndices&&(r=true,this._geometryData.maxIndices=this._geometryData.indexCount),r&&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=true):this._geometryData.vertexStreamsUpdated&&(this.primitive[0].count=this._geometryData.vertexCount,this.primitive[0].indexed=false),this._geometryData.vertexCount=0,this._geometryData.indexCount=0,this._geometryData.vertexStreamsUpdated=false,this._geometryData.indexStreamUpdated=false,this._geometryData.recreate=false,this.updateRenderStates();}},i._buildVertexFormat=function(e){var t=[];for(var n in this._geometryData.vertexStreamDictionary){var i=this._geometryData.vertexStreamDictionary[n];t.push({semantic:n,components:i.componentCount,type:i.dataType,normalize:i.dataTypeNormalize,asInt:i.asInt});}return new n7(this.device,t,e)},i._updateVertexBuffer=function(){if(!this.vertexBuffer){var e=this._geometryData.maxVertices,t=this._buildVertexFormat(e);this.vertexBuffer=new n3(this.device,t,e,{usage:this._geometryData.verticesUsage,storage:this._storageVertex});}var n=new ao(this.vertexBuffer),i=this._geometryData.vertexCount;for(var r in this._geometryData.vertexStreamDictionary){var s=this._geometryData.vertexStreamDictionary[r];n.writeData(r,s.data,i),delete this._geometryData.vertexStreamDictionary[r];}n.end();},i._updateIndexBuffer=function(){if(this.indexBuffer.length<=0||!this.indexBuffer[0]){var e=this._geometryData.maxVertices,t=this._storageIndex?{storage:true}:void 0;this.indexBuffer[0]=new sQ(this.device,e>65535||0===e?2:1,this._geometryData.maxIndices,this._geometryData.indicesUsage,void 0,t);}var n=this._geometryData.indices;n&&(this.indexBuffer[0].writeData(n,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:false});},i.updateRenderStates=function(){this.primitive[2]&&this.prepareRenderState(2),this.primitive[1]&&this.prepareRenderState(1);},i.generateWireframe=function(){this._destroyIndexBuffer(1);var e,t=this.vertexBuffer.numVertices,n=[];if(this.indexBuffer.length>0&&this.indexBuffer[0]){for(var i=[[0,1],[1,2],[2,0]],r=this.primitive[0].base,s=this.primitive[0].count,a=this.indexBuffer[0],o=new nS[a.format](a.storage),l=new Set,u=r;uf?f*t+h:h*t+f;l.has(d)||(l.add(d),n.push(h,f));}e=a.format;}else {for(var p=0;p65535?2:1;}var m=new sQ(this.vertexBuffer.device,e,n.length);new nS[m.format](m.storage).set(n),m.unlock(),this.primitive[1]={type:1,base:0,count:n.length,indexed:true},this.indexBuffer[1]=m;},t.fromGeometry=function(e,n,i){ void 0===i&&(i={});var r=new t(e,i),s=n.positions,a=n.normals,o=n.tangents,l=n.colors,u=n.uvs,c=n.uvs1,h=n.blendIndices,f=n.blendWeights,d=n.indices;return s&&r.setPositions(s),a&&r.setNormals(a),o&&r.setVertexStream(tP,o,4),l&&r.setColors32(l),u&&r.setUvs(0,u),c&&r.setUvs(1,c),h&&r.setVertexStream(tL,h,4,h.length/4,1),f&&r.setVertexStream(tI,f,4),d&&r.setIndices(d),r.update(),r},n=[{key:"morph",get:function(){return this._morph},set:function(e){e!==this._morph&&(this._morph&&this._morph.decRefCount(),this._morph=e,e&&e.incRefCount());}},{key:"aabb",get:function(){return this._aabb},set:function(e){this._aabb=e,this._aabbVer++;}}],function(e,t){for(var n=0;n0))},n.updateKey=function(){var e=this.material;this._sortKeyForward=this._drawBucket<<25|(e.alphaToCoverage||e.alphaTest?0x1000000:0)|0xffffff&e.id;},n.setInstancing=function(e,t){ void 0===t&&(t=false),e?(this.instancingData=new lP(e.numVertices),this.instancingData.vertexBuffer=e,e.format.instancing=true,this.cull=t):(this.instancingData=null,this.cull=true),this._updateShaderDefs(e?32|this._shaderDefs:-33&this._shaderDefs);},n.ensureMaterial=function(e){this.material||(this.material=ly(e));},n.clearParameters=function(){this.parameters={};},n.getParameters=function(){return this.parameters},n.getParameter=function(e){return this.parameters[e]},n.setParameter=function(e,t,n){ void 0===n&&(n=0xffffffff);var i=this.parameters[e];i?(i.data=t,i.passFlags=n):this.parameters[e]={scopeId:null,data:t,passFlags:n};},n.setRealtimeLightmap=function(e,t){var n=this.getParameter(e);n!==t&&(n&&lx.decRef(n.data),t?(lx.incRef(t),this.setParameter(e,t)):this.deleteParameter(e));},n.deleteParameter=function(e){this.parameters[e]&&delete this.parameters[e];},n.setParameters=function(e,t){var n=this.parameters;for(var i in n){var r=n[i];r.passFlags&t&&(r.scopeId||(r.scopeId=e.scope.resolve(i)),r.scopeId.setValue(r.data));}},n.setLightmapped=function(t){t?this.mask=(2|this.mask)&-6:(this.setRealtimeLightmap(e.lightmapParamNames[0],null),this.setRealtimeLightmap(e.lightmapParamNames[1],null),this._shaderDefs&=-4289,this.mask=(1|this.mask)&-7);},n.setCustomAabb=function(e){e?this._customAabb?this._customAabb.copy(e):this._customAabb=e.clone():(this._customAabb=null,this._aabbVer=-1),this._setupSkinUpdate();},n._setupSkinUpdate=function(){this._skinInstance&&(this._skinInstance._updateBeforeCull=!this._customAabb);},e._prepareRenderStyleForArray=function(e,t){if(e){for(var n=0;n>16},set:function(e){var t=65535&this._shaderDefs;this._updateShaderDefs(t|e<<16);}},{key:"instancingCount",get:function(){return this.instancingData?this.instancingData.count:0},set:function(e){this.instancingData&&(this.instancingData.count=e);}}],function(e,t){for(var n=0;nthis._dirtyGroups.indexOf(e)&&this._dirtyGroups.push(e);},t.getGroupByName=function(e){var t=this._batchGroups;for(var n in t)if(t.hasOwnProperty(n)&&t[n].name===e)return t[n];return null},t.getBatches=function(e){for(var t=[],n=this._batchList.length,i=0;ii._obj[e].indexOf(n)&&(i._obj[e].push(n),this.markGroupDirty(t));},t.remove=function(e,t,n){var i=this._batchGroups[t];if(i){var r=i._obj[e].indexOf(n);r>=0&&(i._obj[e].splice(r,1),this.markGroupDirty(t));}},t._extractRender=function(e,t,n,i){return e.render&&(t=i[e.render.batchGroupId]=t.concat(e.render.meshInstances),e.render.removeFromLayers()),t},t._extractModel=function(e,t,n,i){return e.model&&e.model.model&&(t=i[e.model.batchGroupId]=t.concat(e.model.meshInstances),e.model.removeModelFromLayers()),t},t._extractElement=function(e,t,n){if(e.element){var i=false;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),i=true):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())),i=true),i&&(n._ui=true);}},t._collectAndRemoveMeshInstances=function(e,t){for(var n=0;ne.indexOf(this._batchList[o].batchGroupId)){a.push(this._batchList[o]);continue}this.destroyBatch(this._batchList[o]);}if(this._batchList=a,this._collectAndRemoveMeshInstances(s,e),e===this._dirtyGroups)this._dirtyGroups.length=0;else {for(var l=[],u=0;ue.indexOf(this._dirtyGroups[u])&&l.push(this._dirtyGroups[u]);this._dirtyGroups=l;}for(var c in s)if(s.hasOwnProperty(c)&&(t=s[c],i=this._batchGroups[c])){n=this.prepare(t,i.dynamic,i.maxAabbSize,i._ui||i._sprite);for(var h=0;h0;){c[h]=[f[0]],s=[];var p=f[0].material,m=f[0].layer,_=f[0]._shaderDefs,v=f[0].parameters,g=f[0].stencilFront,y=f[0].mesh.vertexBuffer.getNumVertices(),S=f[0].drawOrder;o.copy(f[0].aabb);var x=lN(f[0]),b=f[0].mesh.vertexBuffer.format.batchingHash,T=f[0].mesh.primitive[0].indexed;u=null;for(var E=1;E=1024){s=s.concat(f.slice(E));break}if(p!==w.material||m!==w.layer||b!==w.mesh.vertexBuffer.format.batchingHash||T!==w.mesh.primitive[0].indexed||_!==w._shaderDefs||y+w.mesh.vertexBuffer.getNumVertices()>0xffffffff||(l.copy(o),l.add(w.aabb),l.halfExtents.x>a||l.halfExtents.y>a||l.halfExtents.z>a||g&&(!(r=w.stencilFront)||g.func!==r.func||g.zpass!==r.zpass)||x!==lN(w)||!function(e,t){for(var n in e)if(e.hasOwnProperty(n)&&!lk(e[n],t[n]))return false;for(var i in t)if(t.hasOwnProperty(i)&&!lk(t[i],e[i]))return false;return true}(v,w.parameters)||i&&u&&u.intersects(w.aabb)&&w.drawOrder!==S)){d(w);continue}o.add(w.aabb),y+=w.mesh.vertexBuffer.getNumVertices(),c[h].push(w);}h++,f=s;}return c},t.collectBatchedMeshData=function(e,t){for(var n=null,i=0,r=0,s=null,a=0;a=3){if(a===tA)for(var T=f.data,E=T[0],w=T[1],A=T[2],C=T[4],P=T[5],I=T[6],L=T[8],D=T[9],R=T[10],M=T[12],O=T[13],k=T[14],N=void 0,F=void 0,B=void 0,U=0;U0&&o.setIndices(y),o.update(4,false),t&&(p=p.clone()).update();var ei=new lL(o,p,this.rootNode);ei.castShadow=r.origMeshInstances[0].castShadow,ei.parameters=r.origMeshInstances[0].parameters,ei.layer=r.origMeshInstances[0].layer,ei._shaderDefs=r.origMeshInstances[0]._shaderDefs,ei.batching=true,ei.cull=r.origMeshInstances[0].cull;var er=this._batchGroups[n];if(er&&er._ui&&(ei.cull=false),t){for(var es=[],ea=0;ea0&&this.generate(this._dirtyGroups);for(var e=0;e1&&(l=15,o=false);var u=null!=(i=null==(e=r.renderTarget)?void 0:e.depthBuffer)?i:null==(t=r.renderTarget)?void 0:t.colorBuffer;this.shouldReallocate(this.depthRenderTarget,u)&&(this.releaseRenderTarget(this.depthRenderTarget),this.depthRenderTarget=this.allocateRenderTarget(this.depthRenderTarget,r.renderTarget,s,l,o));var c=o?this.depthRenderTarget.depthBuffer:this.depthRenderTarget.colorBuffer;s.scope.resolve(lG).setValue(c);},n.execute=function(){var e=this.device;if(e.isWebGL2&&e.renderTarget.samples>1){var t=e.renderTarget.impl._glFrameBuffer,n=this.depthRenderTarget;e.renderTarget=n,e.updateBegin(),this.depthRenderTarget.impl.internalResolve(e,t,n.impl._glFrameBuffer,this.depthRenderTarget,e.gl.DEPTH_BUFFER_BIT);}else e.copyRenderTarget(e.renderTarget,this.depthRenderTarget,false,true);},t}(s0),lW=function(){var e;function t(){this._gammaCorrection=1,this._toneMapping=0,this._srgbRenderTarget=false,this._ssaoEnabled=false,this._fog=or,this._sceneDepthMapLinear=false,this._defines=new Map,this._definesDirty=true;}return t.prototype.markDirty=function(){this._hash=void 0,this._definesDirty=true;},e=[{key:"hash",get:function(){if(void 0===this._hash){var e=this.gammaCorrection+"_"+this.toneMapping+"_"+this.srgbRenderTarget+"_"+this.fog+"_"+this.ssaoEnabled+"_"+this.sceneDepthMapLinear;this._hash=n4(e);}return this._hash}},{key:"defines",get:function(){var e=this._defines;return this._definesDirty&&(this._definesDirty=false,e.clear(),this._sceneDepthMapLinear&&e.set("SCENE_DEPTHMAP_LINEAR",true),e.set("FOG",this._fog.toUpperCase()),e.set("TONEMAP",od[this._toneMapping]),e.set("GAMMA",of[this.shaderOutputGamma])),e}},{key:"fog",get:function(){return this._fog},set:function(e){this._fog!==e&&(this._fog=e,this.markDirty());}},{key:"ssaoEnabled",get:function(){return this._ssaoEnabled},set:function(e){this._ssaoEnabled!==e&&(this._ssaoEnabled=e,this.markDirty());}},{key:"gammaCorrection",get:function(){return this._gammaCorrection},set:function(e){this._gammaCorrectionAssigned=true,this._gammaCorrection!==e&&(this._gammaCorrection=e,this.markDirty());}},{key:"toneMapping",get:function(){return this._toneMapping},set:function(e){this._toneMapping!==e&&(this._toneMapping=e,this.markDirty());}},{key:"srgbRenderTarget",get:function(){return this._srgbRenderTarget},set:function(e){this._srgbRenderTarget!==e&&(this._srgbRenderTarget=e,this.markDirty());}},{key:"sceneDepthMapLinear",get:function(){return this._sceneDepthMapLinear},set:function(e){this._sceneDepthMapLinear!==e&&(this._sceneDepthMapLinear=e,this.markDirty());}},{key:"shaderOutputGamma",get:function(){return +(1===this._gammaCorrection&&!this._srgbRenderTarget)}}],function(e,t){for(var n=0;n=0?e.insertChild(this,t):e.addChild(this));},i.setLocalEulerAngles=function(e,t,n){this.localRotation.setFromEulerAngles(e,t,n),this._dirtyLocal||this._dirtifyLocal();},i.setLocalPosition=function(e,t,n){lQ(e,eW)?this.localPosition.copy(e):this.localPosition.set(e,t,n),this._dirtyLocal||this._dirtifyLocal();},i.setLocalRotation=function(e,t,n,i){lQ(e,e0)?this.localRotation.copy(e):this.localRotation.set(e,t,n,i),this._dirtyLocal||this._dirtifyLocal();},i.setLocalScale=function(e,t,n){lQ(e,eW)?this.localScale.copy(e):this.localScale.set(e,t,n),this._dirtyLocal||this._dirtifyLocal();},i._dirtifyLocal=function(){!this._dirtyLocal&&(this._dirtyLocal=true,this._dirtyWorld||this._dirtifyWorld());},i._unfreezeParentToRoot=function(){for(var e=this._parent;e;)e._frozen=false,e=e._parent;},i._dirtifyWorld=function(){this._dirtyWorld||this._unfreezeParentToRoot(),this._dirtifyWorldInternal();},i._dirtifyWorldInternal=function(){if(!this._dirtyWorld){this._frozen=false,this._dirtyWorld=true;for(var e=0;e1?0:1),this.lightsBuffer.updateUniforms(),this._clusterWorldTextureId.setValue(this.clusterTexture),this._clusterMaxCellsId.setValue(this.maxCellLightCount);var e=this.boundsDelta;this._clusterCellsCountByBoundsSizeData[0]=this._cells.x/e.x,this._clusterCellsCountByBoundsSizeData[1]=this._cells.y/e.y,this._clusterCellsCountByBoundsSizeData[2]=this._cells.z/e.z,this._clusterCellsCountByBoundsSizeId.setValue(this._clusterCellsCountByBoundsSizeData),this._clusterBoundsMinData[0]=this.boundsMin.x,this._clusterBoundsMinData[1]=this.boundsMin.y,this._clusterBoundsMinData[2]=this.boundsMin.z,this._clusterBoundsDeltaData[0]=e.x,this._clusterBoundsDeltaData[1]=e.y,this._clusterBoundsDeltaData[2]=e.z,this._clusterTextureSizeId.setValue(this._clusterTextureSizeData),this._clusterBoundsMinId.setValue(this._clusterBoundsMinData),this._clusterBoundsDeltaId.setValue(this._clusterBoundsDeltaData),this._clusterCellsDotId.setValue(this._clusterCellsDotData),this._clusterCellsMaxId.setValue(this._clusterCellsMaxData);},n.evalLightCellMinMax=function(e,t,n){t.copy(e.min),t.sub(this.boundsMin),t.div(this.boundsDelta),t.mul2(t,this.cells),t.floor(),n.copy(e.max),n.sub(this.boundsMin),n.div(this.boundsDelta),n.mul2(n,this.cells),n.ceil(),t.max(eW.ZERO),n.min(this._cellsLimit);},n.collectLights=function(e){var t=this.lightsBuffer.maxLights,n=this._usedLights,i=1;e.forEach(function(e){var r,s=!!(3&e.mask),a=2===e.type&&0===e._outerConeAngle;e.enabled&&0!==e.type&&e.visibleThisFrame&&e.intensity>0&&s&&!a&&i1){t.copy(e[1].min),n.copy(e[1].max);for(var i=2;i1)for(var l=1/o,u=0;u1)for(var d=0;d0){for(var i=this.slots,r=0;re.length)&&(t=e.length);for(var n=0,i=Array(t);n0)for(var e,t,n,i=function(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return (n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return uB(e,void 0);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return uB(e,void 0)}}(e))){n&&(e=n);var i=0;return function(){return i>=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(Object.entries(this._oldChunks));!(n=i()).done;){var r=n.value,s=r[0],a=r[1];this.shaderChunks.glsl.set(s,a),delete this._oldChunks[s];}(this._definesDirty||(null==(t=this._shaderChunks)?void 0:t.isDirty()))&&(this._definesDirty=false,null==(e=this._shaderChunks)||e.resetDirty(),this.clearVariants()),this.dirty=true;},n.clearParameters=function(){this.parameters={};},n.getParameters=function(){return this.parameters},n.clearVariants=function(){this.variants.clear();for(var e=this.meshInstances,t=e.length,n=0;n_&&(_=g);}var y=u.right,S=u.up,x=u.forward,b=.25*e._shadowResolution/_,T=Math.ceil(uK.dot(S)*b)/b,E=Math.ceil(uK.dot(y)*b)/b,w=S.mulScalar(T),A=y.mulScalar(E),C=uK.dot(x),P=x.mulScalar(C);uK.add2(w,A).add(P),u.setPosition(uK),u.translateLocal(0,0,1e6),l.nearClip=.01,l.farClip=2e6,l.orthoHeight=_,this.renderer.updateCameraFrustum(l),this.shadowRenderer.cullShadowCasters(t,e,o.visibleCasters,l,i);for(var I=true,L=o.visibleCasters,D=0;Dr&&(r=a);}return uJ.min=i,uJ.max=r,uJ}(uZ,uq.getMin(),uq.getMax());u.translateLocal(0,0,M.max+.1),l.farClip=M.max-M.min+.2,o.projectionCompensation=_;}},t.generateSplitDistances=function(e,t,n){e._shadowCascadeDistances.fill(n);for(var i=1;i1&&(this.renderer.scene.clusteredLightingEnabled&&0!==e._type||this.applyVsmBlur(e,t));},t.getVsmBlurShader=function(e,t){var n=this.blurVsmShader,i=n[e][t];if(!i){this.blurVsmWeights[t]=function(e){for(var t,n=(e-1)/6,i=(e-1)*.5,r=Array(e),s=0,a=0;a0;},i.filter=function(e,t){for(var n=0;n1?this.quadRendererCube:this.quadRenderer2D;a>1&&this.initInvViewProjMatrices(),this.blitTextureId.setValue(s.cookie);for(var l=0;l1){var u=ce.z/3,c=n[l];ce.x+=u*c.x,ce.y+=u*c.y,ce.z=u,ce.w=u,this.invViewProjId.setValue(ct[l].data);}ce.mulScalar(t),o.render(ce);}}i.length=0;},t.create=function(e,n){var i=new t(e.device,n);return i.init(e),i.colorOps.clear=false,i.depthStencilOps.clearDepth=false,i},n=[{key:"quadRenderer2D",get:function(){if(!this._quadRenderer2D){var e=o6.createShader(this.device,{uniqueName:"cookieRenderer2d",attributes:{vertex_position:tA},vertexChunk:"cookieBlitVS",fragmentChunk:"cookieBlit2DPS"});this._quadRenderer2D=new ln(e);}return this._quadRenderer2D}},{key:"quadRendererCube",get:function(){if(!this._quadRendererCube){var e=o6.createShader(this.device,{uniqueName:"cookieRendererCube",attributes:{vertex_position:tA},vertexChunk:"cookieBlitVS",fragmentChunk:"cookieBlitCubePS"});this._quadRendererCube=new ln(e);}return this._quadRendererCube}}],function(e,t){for(var n=0;n0,i&&this.shadowRenderer.setupRenderPass(this,n,false);},n.execute=function(){for(var e=this.shadowRendererLocal.shadowLights,t=e.length,n=0;ne.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var cu=0,cc=new e$,ch=new e$,cf=new e$,cd=new ej,cp=new e7,cm=new e$().setScale(1,-1,1),c_=new Set,cv=new Set,cg=new nG,cy=new e$().set([1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1]),cS=[new eX(.5,.333333),new eX(.25,.666667),new eX(.75,.111111),new eX(.125,.444444),new eX(.625,.777778),new eX(.375,.222222),new eX(.875,.555556),new eX(.0625,.888889),new eX(.5625,.037037),new eX(.3125,.37037),new eX(.8125,.703704),new eX(.1875,.148148),new eX(.6875,.481481),new eX(.4375,.814815),new eX(.9375,.259259),new eX(.03125,.592593)],cx=new e$,cb=new e$,cT=new e$,cE=new e$,cw=new e$,cA=new e$,cC=new Set,cP=[],cI=[],cL=function(){function e(e){this.clustersDebugRendered=false,this.processingMeshInstances=new Set,this.lights=[],this.localLights=[],this.cameraDirShadowLights=new Map,this.dirLightShadows=new Map,this.blueNoise=new uA(123),this.device=e,this.scene=null,this.worldClustersAllocator=new u9(e),this.lightTextureAtlas=new uF(e),this.shadowMapCache=new uG,this.shadowRenderer=new u8(this,this.lightTextureAtlas),this._shadowRendererLocal=new uj(this,this.shadowRenderer),this._shadowRendererDirectional=new u$(this,this.shadowRenderer),this._renderPassUpdateClustered=new ca(this.device,this,this.shadowRenderer,this._shadowRendererLocal,this.lightTextureAtlas),this.viewUniformFormat=null,this.viewBindGroupFormat=null,this._skinTime=0,this._morphTime=0,this._cullTime=0,this._shadowMapTime=0,this._lightClustersTime=0,this._layerCompositionUpdateTime=0,this._shadowDrawCalls=0,this._skinDrawCalls=0,this._instancedDrawCalls=0,this._shadowMapUpdates=0,this._numDrawCallsCulled=0,this._camerasRendered=0,this._lightClusters=0;var t=e.scope;this.boneTextureId=t.resolve("texture_poseMap"),this.modelMatrixId=t.resolve("matrix_model"),this.normalMatrixId=t.resolve("matrix_normal"),this.viewInvId=t.resolve("matrix_viewInverse"),this.viewPos=new Float32Array(3),this.viewPosId=t.resolve("view_position"),this.projId=t.resolve("matrix_projection"),this.projSkyboxId=t.resolve("matrix_projectionSkybox"),this.viewId=t.resolve("matrix_view"),this.viewId3=t.resolve("matrix_view3"),this.viewProjId=t.resolve("matrix_viewProjection"),this.flipYId=t.resolve("projectionFlipY"),this.tbnBasis=t.resolve("tbnBasis"),this.nearClipId=t.resolve("camera_near"),this.farClipId=t.resolve("camera_far"),this.cameraParams=new Float32Array(4),this.cameraParamsId=t.resolve("camera_params"),this.viewIndexId=t.resolve("view_index"),this.viewIndexId.setValue(0),this.blueNoiseJitterVersion=0,this.blueNoiseJitterVec=new eY,this.blueNoiseJitterData=new Float32Array(4),this.blueNoiseJitterId=t.resolve("blueNoiseJitter"),this.blueNoiseTextureId=t.resolve("blueNoiseTex32"),this.alphaTestId=t.resolve("alpha_ref"),this.opacityMapId=t.resolve("texture_opacityMap"),this.exposureId=t.resolve("exposure"),this.twoSidedLightingNegScaleFactorId=t.resolve("twoSidedLightingNegScaleFactor"),this.twoSidedLightingNegScaleFactorId.setValue(0),this.morphPositionTex=t.resolve("morphPositionTex"),this.morphNormalTex=t.resolve("morphNormalTex"),this.morphTexParams=t.resolve("morph_tex_params"),this.lightCube=new uP,this.constantLightCube=t.resolve("lightCube[0]");}var t=e.prototype;return t.destroy=function(){this.shadowRenderer=null,this._shadowRendererLocal=null,this._shadowRendererDirectional=null,this.shadowMapCache.destroy(),this.shadowMapCache=null,this._renderPassUpdateClustered.destroy(),this._renderPassUpdateClustered=null,this.lightTextureAtlas.destroy(),this.lightTextureAtlas=null;},t.setupViewport=function(e,t){var n=this.device,i=t?t.width:n.width,r=t?t.height:n.height,s=e.rect,a=Math.floor(s.x*i),o=Math.floor(s.y*r),l=Math.floor(s.z*i),u=Math.floor(s.w*r);if(n.setViewport(a,o,l,u),e._scissorRectClear){var c=e.scissorRect;a=Math.floor(c.x*i),o=Math.floor(c.y*r),l=Math.floor(c.z*i),u=Math.floor(c.w*r);}n.setScissor(a,o,l,u);},t.setCameraUniforms=function(e,t){var n=null==t?void 0:t.flipY,i=null;if(e.xr&&e.xr.session){var r,s,a=(null==(s=e._node)||null==(r=s.parent)?void 0:r.getWorldTransform())||null;i=e.xr.views.list;for(var o=0;o0){var p=t?t.width:this.device.width,m=t?t.height:this.device.height,_=cS[this.device.renderVersion%cS.length];f=h*(2*_.x-1)/p,d=h*(2*_.y-1)/m,(u=cw.copy(u)).data[8]=f,u.data[9]=d,(c=cA.copy(c)).data[8]=f,c.data[9]=d,this.blueNoiseJitterVersion!==this.device.renderVersion&&(this.blueNoiseJitterVersion=this.device.renderVersion,this.blueNoise.vec4(this.blueNoiseJitterVec));}var v=h>0?this.blueNoiseJitterVec:eY.ZERO;if(this.blueNoiseJitterData[0]=v.x,this.blueNoiseJitterData[1]=v.y,this.blueNoiseJitterData[2]=v.z,this.blueNoiseJitterData[3]=v.w,this.blueNoiseJitterId.setValue(this.blueNoiseJitterData),this.projId.setValue(u.data),this.projSkyboxId.setValue(c.data),e.calculateTransform)e.calculateTransform(ch,0);else {var g=e._node.getPosition(),y=e._node.getRotation();ch.setTRS(g,y,eW.ONE);}this.viewInvId.setValue(ch.data),cf.copy(ch).invert(),this.viewId.setValue(cf.data),cd.setFromMat4(cf),this.viewId3.setValue(cd.data),cc.mul2(u,cf),this.viewProjId.setValue(cc.data),e._storeShaderMatrices(cc,f,d,this.device.renderVersion),this.flipYId.setValue(n?-1:1),this.dispatchViewPos(e._node.getPosition()),e.frustum.setFromMat4(cc);}this.tbnBasis.setValue(n?-1:1);var S=e._nearClip,x=e._farClip;return this.nearClipId.setValue(S),this.farClipId.setValue(x),this.cameraParams[0]=1/x,this.cameraParams[1]=x,this.cameraParams[2]=S,this.cameraParams[3]=+(1===e.projection),this.cameraParamsId.setValue(this.cameraParams),this.exposureId.setValue(this.scene.physicalUnits?e.getExposure():this.scene.exposure),i},t.clear=function(e,t,n,i){var r=(null!=t?!!t:!!e._clearColorBuffer)|2*(null!=n?!!n:!!e._clearDepthBuffer)|4*(null!=i?!!i:!!e._clearStencilBuffer);r&&this.device.clear({color:[e._clearColor.r,e._clearColor.g,e._clearColor.b,e._clearColor.a],depth:e._clearDepth,stencil:e._clearStencil,flags:r});},t.setCamera=function(e,t,n,i){this.setCameraUniforms(e,t),this.clearView(e,t,n,false);},t.clearView=function(e,t,n,i){var r=this.device;if(r.setRenderTarget(t),r.updateBegin(),i&&(r.setColorWrite(true,true,true,true),r.setDepthWrite(true)),this.setupViewport(e,t),n){var s=e._clearOptions;r.clear(s||{color:[e._clearColor.r,e._clearColor.g,e._clearColor.b,e._clearColor.a],depth:e._clearDepth,flags:!!e._clearColorBuffer|2*!!e._clearDepthBuffer|4*!!e._clearStencilBuffer,stencil:e._clearStencil});}},t.setupCullMode=function(e,t,n){var i=n.material,r=0;if(e){var s=1;(2===i.cull||1===i.cull)&&(s=t*n.flipFacesFactor*n.node.worldScaleSign),r=s<0?2===i.cull?1:2:i.cull;}this.device.setCullMode(r),0===r&&0===i.cull&&this.twoSidedLightingNegScaleFactorId.setValue(n.node.worldScaleSign);},t.updateCameraFrustum=function(e){if(e.xr&&e.xr.views.list.length){var t=e.xr.views.list[0];cc.mul2(t.projMat,t.viewOffMat),e.frustum.setFromMat4(cc);return}var n=e.projectionMatrix;if(e.calculateProjection&&e.calculateProjection(n,0),e.calculateTransform)e.calculateTransform(ch,0);else {var i=e._node.getPosition(),r=e._node.getRotation();ch.setTRS(i,r,eW.ONE),this.viewInvId.setValue(ch.data);}cf.copy(ch).invert(),cc.mul2(n,cf),e.frustum.setFromMat4(cc);},t.setBaseConstants=function(e,t){e.setCullMode(t.cull),t.opacityMap&&this.opacityMapId.setValue(t.opacityMap),(t.opacityMap||t.alphaTest>0)&&this.alphaTestId.setValue(t.alphaTest);},t.updateCpuSkinMatrices=function(e){cu++;var t=e.length;if(0!==t)for(var n=0;n0}}],function(e,t){for(var n=0;n0){var a=this._shaderVersion;cH.forEach(function(e){a>=0&&e._shaderVersion!==a&&(e.getShaderVariant!==uz.prototype.getShaderVariant&&e.clearVariants(),e._shaderVersion=a);}),cH.clear();}},n.removeMeshInstances=function(e,t){for(var n=this.meshInstances,i=this.meshInstancesSet,r=0;r=0&&n.splice(a,1);}}t||this.removeShadowCasters(e);},n.addShadowCasters=function(e){for(var t=this.shadowCasters,n=this.shadowCastersSet,i=0;i=0&&t.splice(s,1);}}},n.clearMeshInstances=function(e){ void 0===e&&(e=false),this.meshInstances.length=0,this.meshInstancesSet.clear(),e||(this.shadowCasters.length=0,this.shadowCastersSet.clear());},n.markLightsDirty=function(){this._lightHashDirty=true,this._lightIdHashDirty=true,this._splitLightsDirty=true;},n.hasLight=function(e){return this._lightsSet.has(e)},n.addLight=function(e){var t=e.light;this._lightsSet.has(t)||(this._lightsSet.add(t),this._lights.push(t),this.markLightsDirty()),0!==t.type&&this._clusteredLightsSet.add(t);},n.removeLight=function(e){var t=e.light;this._lightsSet.has(t)&&(this._lightsSet.delete(t),this._lights.splice(this._lights.indexOf(t),1),this.markLightsDirty()),0!==t.type&&this._clusteredLightsSet.delete(t);},n.clearLights=function(){var e=this;this._lightsSet.forEach(function(t){return t.removeLayer(e)}),this._lightsSet.clear(),this._clusteredLightsSet.clear(),this._lights.length=0,this.markLightsDirty();},n.evaluateLightHash=function(e,t,n){for(var i=0,r=this._lights,s=0;s0&&(cG.sort(),i=n5(cG),cG.length=0),i},n.getLightHash=function(e){return this._lightHashDirty&&(this._lightHashDirty=false,this._lightHash=this.evaluateLightHash(!e,true,false)),this._lightHash},n.getLightIdHash=function(){return this._lightIdHashDirty&&(this._lightIdHashDirty=false,this._lightIdHash=this.evaluateLightHash(true,false,true)),this._lightIdHash},n.addCamera=function(e){this.camerasSet.has(e.camera)||(this.camerasSet.add(e.camera),this.cameras.push(e),this._dirtyComposition=true);},n.removeCamera=function(e){if(this.camerasSet.has(e.camera)){this.camerasSet.delete(e.camera);var t=this.cameras.indexOf(e);this.cameras.splice(t,1),this._dirtyComposition=true;}},n.clearCameras=function(){this.cameras.length=0,this.camerasSet.clear(),this._dirtyComposition=true;},n._calculateSortDistances=function(e,t,n){for(var i=e.length,r=t.x,s=t.y,a=t.z,o=n.x,l=n.y,u=n.z,c=0;c0}},{key:"clusteredLightsSet",get:function(){return this._clusteredLightsSet}},{key:"splitLights",get:function(){if(this._splitLightsDirty){this._splitLightsDirty=false;for(var e=this._splitLights,t=0;tthis.cameras.indexOf(s)&&this.cameras.push(s);}}this.cameras.length>1&&cq(this.cameras);var a=[],o=0;this.destroyRenderActions();for(var l=0;l0){this.addDummyRenderAction(o,u),o++;continue}for(var c=true,h=o,f=null,d=false,p=0;p0&&u.layers.indexOf(m.id)>=0){a.push(m),!d&&m.id===u.disablePostEffectsLayer&&(d=true,f&&(f.triggerPostprocess=true));var _=this.subLayerList[p];f=this.addRenderAction(o,m,_,u,c,d),o++,c=false;}}h=0;u--)if(l[u].camera===i&&l[u].renderTarget===a){o=true;break}s&&i.postEffectsEnabled&&(a=null);var c=this.getNextRenderAction(e);c.triggerPostprocess=false,c.layer=t,c.transparent=n,c.camera=i,c.renderTarget=a,c.firstCameraUse=r,c.lastCameraUse=false;var h=r||!o,f=t.clearColorBuffer||t.clearDepthBuffer||t.clearStencilBuffer;return (h||f)&&c.setupClears(h?i:void 0,t),c},n.propagateRenderTarget=function(e,t){for(var n=e;n>=0;n--){var i=this._renderActions[n],r=i.layer;if(i.renderTarget&&1!==r.id)break;if(1!==r.id){if(i.useCameraPasses)break;var s=null==i?void 0:i.camera.camera;if(s&&(!t.camera.rect.equals(s.rect)||!t.camera.scissorRect.equals(s.scissorRect)))break;i.renderTarget=t.renderTarget;}}},n._logRenderActions=function(){},n._isLayerAdded=function(e){return this.layerIdMap.get(e.id)===e},n._isSublayerAdded=function(e,t){return void 0!==(t?this.layerTransparentIndexMap:this.layerOpaqueIndexMap).get(e)},n.push=function(e){this._isLayerAdded(e)||(this.layerList.push(e),this.layerList.push(e),this._opaqueOrder[e.id]=this.subLayerList.push(false)-1,this._transparentOrder[e.id]=this.subLayerList.push(true)-1,this.subLayerEnabled.push(true),this.subLayerEnabled.push(true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e));},n.insert=function(e,t){if(!this._isLayerAdded(e)){this.layerList.splice(t,0,e,e),this.subLayerList.splice(t,0,false,true);var n=this.layerList.length;this._updateOpaqueOrder(t,n-1),this._updateTransparentOrder(t,n-1),this.subLayerEnabled.splice(t,0,true,true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e);}},n.remove=function(e){var t=this.layerList.indexOf(e);for(delete this._opaqueOrder[t],delete this._transparentOrder[t];t>=0;)this.layerList.splice(t,1),this.subLayerList.splice(t,1),this.subLayerEnabled.splice(t,1),t=this.layerList.indexOf(e),this._dirty=true,this.fire("remove",e);var n=this.layerList.length;this._updateOpaqueOrder(0,n-1),this._updateTransparentOrder(0,n-1),this._updateLayerMaps();},n.pushOpaque=function(e){this._isSublayerAdded(e,false)||(this.layerList.push(e),this._opaqueOrder[e.id]=this.subLayerList.push(false)-1,this.subLayerEnabled.push(true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e));},n.insertOpaque=function(e,t){if(!this._isSublayerAdded(e,false)){this.layerList.splice(t,0,e),this.subLayerList.splice(t,0,false);var n=this.subLayerList.length;this._updateOpaqueOrder(t,n-1),this.subLayerEnabled.splice(t,0,true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e);}},n.removeOpaque=function(e){for(var t=0,n=this.layerList.length;tthis.layerList.indexOf(e)&&this.fire("remove",e);break}this._updateLayerMaps();},n.pushTransparent=function(e){this._isSublayerAdded(e,true)||(this.layerList.push(e),this._transparentOrder[e.id]=this.subLayerList.push(true)-1,this.subLayerEnabled.push(true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e));},n.insertTransparent=function(e,t){if(!this._isSublayerAdded(e,true)){this.layerList.splice(t,0,e),this.subLayerList.splice(t,0,true);var n=this.subLayerList.length;this._updateTransparentOrder(t,n-1),this.subLayerEnabled.splice(t,0,true),this._updateLayerMaps(),this._dirty=true,this.fire("add",e);}},n.removeTransparent=function(e){for(var t=0,n=this.layerList.length;tthis.layerList.indexOf(e)&&this.fire("remove",e);break}this._updateLayerMaps();},n.getOpaqueIndex=function(e){var t;return null!=(t=this.layerOpaqueIndexMap.get(e))?t:-1},n.getTransparentIndex=function(e){var t;return null!=(t=this.layerTransparentIndexMap.get(e))?t:-1},n.isEnabled=function(e,t){if(e.enabled){var n=t?this.getTransparentIndex(e):this.getOpaqueIndex(e);if(n>=0)return this.subLayerEnabled[n]}return false},n._updateLayerMaps=function(){this.layerIdMap.clear(),this.layerNameMap.clear(),this.layerOpaqueIndexMap.clear(),this.layerTransparentIndexMap.clear();for(var e=0;e45?(e.radius=t*this._outerConeAngleSin,cJ.mulScalar(-t*i)):(e.radius=t/(2*i),cJ.mulScalar(-e.radius)),e.center.add2(r.getPosition(),cJ);}else 1===this._type&&(e.center=this._node.getPosition(),e.radius=this.attenuationEnd);},t.getBoundingBox=function(e){if(2===this._type){var t=this.attenuationEnd,n=this._outerConeAngle,i=this._node,r=Math.abs(Math.sin(n*ek.DEG_TO_RAD)*t);e.center.set(0,-(.5*t),0),e.halfExtents.set(r,.5*t,r),e.setFromTransformedAabb(e,i.getWorldTransform(),true);}else 1===this._type&&(e.center.copy(this._node.getPosition()),e.halfExtents.set(this.attenuationEnd,this.attenuationEnd,this.attenuationEnd));},t._updateShadowBias=function(){if(1!==this._type||this.clusteredLighting){var e=-1e3*this.shadowBias;this.shadowDepthState.depthBias=e,this.shadowDepthState.depthBiasSlope=e;}else this.shadowDepthState.depthBias=0,this.shadowDepthState.depthBiasSlope=0;},t._updateLinearColor=function(){var t=this._intensity;this._usePhysicalUnits&&(t=this._luminance/e.getLightUnitConversion(this._type,this._outerConeAngle*ek.DEG_TO_RAD,this._innerConeAngle*ek.DEG_TO_RAD));var n=this._color,i=this._colorLinear;t>=1?c0.linear(n).mulScalar(t):c0.copy(n).mulScalar(t).linear(),i[0]=c0.r,i[1]=c0.g,i[2]=c0.b,this.updateClusterData(true);},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._updateLinearColor();},t.layersDirty=function(){var e=this;this.layers.forEach(function(t){t.hasLight(e)&&t.markLightsDirty();});},t.updateKey=function(){var e=this._type<<29|this._shadowType<<25|this._falloffMode<<23|(0!==this._normalOffsetBias)<<22|!!this._cookie<<21|!!this._cookieFalloff<<20|c1[this._cookieChannel.charAt(0)]<<18|!!this._cookieTransform<<12|this._shape<<10|(this.numCascades>0)<<9|(this._cascadeBlend>0)<<8|!!this.affectSpecularity<<7|this.mask<<6|!!this._castShadows<<3;3===this._cookieChannel.length&&(e|=c1[this._cookieChannel.charAt(1)]<<16,e|=c1[this._cookieChannel.charAt(2)]<<14),e!==this.key&&this.layersDirty(),this.key=e;},t.updateClusteredFlags=function(){var e,t=!!(1&this.mask),n=!!(2&this.mask);this.clusteredFlags=(2===this.type)<<30|(3&this._shape)<<28|(1&this._falloffMode)<<27|(null!=(e=c4[this._cookieChannel])?e:0)<<23|!!t<<22|!!n<<21;},t.getClusteredFlags=function(e,t){return this.clusteredFlags|(e?Math.floor(255*this.shadowIntensity):0)&255|((t?Math.floor(255*this.cookieIntensity):0)&255)<<8},t.updateClusterData=function(e,t){var n=this.clusteredData16,i=eG.float2Half;e&&(n[0]=i(ek.clamp(this._colorLinear[0]/100,0,65504)),n[1]=i(ek.clamp(this._colorLinear[1]/100,0,65504)),n[2]=i(ek.clamp(this._colorLinear[2]/100,0,65504))),t&&(n[4]=i(this._innerConeAngleCos),n[5]=i(this._outerConeAngleCos));},e.getLightUnitConversion=function(e,t,n){switch(void 0===t&&(t=Math.PI/4),void 0===n&&(n=0),e){case 2:var i=Math.cos(n);return 2*Math.PI*(1-i+(i-Math.cos(t))/2);case 1:return 4*Math.PI;case 0:return 1}},cQ(e,[{key:"shadowSamples",get:function(){return this._softShadowParams[0]},set:function(e){this._softShadowParams[0]=e;}},{key:"shadowBlockerSamples",get:function(){return this._softShadowParams[1]},set:function(e){this._softShadowParams[1]=e;}},{key:"shadowBias",get:function(){return this._shadowBias},set:function(e){this._shadowBias!==e&&(this._shadowBias=e,this._updateShadowBias());}},{key:"numCascades",get:function(){return this.cascades.length},set:function(e){this.cascades&&this.numCascades===e||(this.cascades=c3[e-1],this._shadowMatrixPalette=new Float32Array(64),this._shadowCascadeDistances=new Float32Array(4),this._destroyShadowMap(),this.updateKey());}},{key:"cascadeBlend",get:function(){return this._cascadeBlend},set:function(e){this._cascadeBlend!==e&&(this._cascadeBlend=e,this.updateKey());}},{key:"shadowMap",get:function(){return this._shadowMap},set:function(e){this._shadowMap!==e&&(this._destroyShadowMap(),this._shadowMap=e);}},{key:"mask",get:function(){return this._mask},set:function(e){this._mask!==e&&(this._mask=e,this.updateKey(),this.updateClusteredFlags());}},{key:"numShadowFaces",get:function(){var e=this._type;return 0===e?this.numCascades:1===e?6:1}},{key:"type",get:function(){return this._type},set:function(e){if(this._type!==e){this._type=e,this._destroyShadowMap(),this._updateShadowBias(),this.updateKey(),this.updateClusteredFlags();var t=this._shadowType;this._shadowType=null,this.shadowUpdateOverrides=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(),this.updateClusteredFlags();var t=this._shadowType;this._shadowType=null,this.shadowType=t;}}},{key:"usePhysicalUnits",get:function(){return this._usePhysicalUnits},set:function(e){this._usePhysicalUnits!==e&&(this._usePhysicalUnits=e,this._updateLinearColor());}},{key:"shadowType",get:function(){return this._shadowType},set:function(e){if(this._shadowType!==e){var t,n,i=oc.get(e);i||(e=0);var r=this.device;6!==e||r.textureFloatRenderable||r.textureHalfFloatRenderable||(e=0),1===this._type&&5!==e&&0!==e&&7!==e&&8!==e&&6!==e&&(e=0),3!==e||r.textureFloatRenderable&&r.textureFloatFilterable||(e=2),2!==e||r.textureHalfFloatRenderable||(e=0),i=oc.get(e),this._isVsm=null!=(t=null==i?void 0:i.vsm)&&t,this._isPcf=null!=(n=null==i?void 0:i.pcf)&&n,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:"shadowIntensity",get:function(){return this._shadowIntensity},set:function(e){this._shadowIntensity!==e&&(this._shadowIntensity=e,this.updateKey());}},{key:"bakeShadows",get:function(){return this._castShadows&&4===this._mask}},{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){if(this._normalOffsetBias!==e){var t=!this._normalOffsetBias&&e||this._normalOffsetBias&&!e;this._normalOffsetBias=e,t&&this.updateKey();}}},{key:"falloffMode",get:function(){return this._falloffMode},set:function(e){this._falloffMode!==e&&(this._falloffMode=e,this.updateKey(),this.updateClusteredFlags());}},{key:"innerConeAngle",get:function(){return this._innerConeAngle},set:function(e){this._innerConeAngle!==e&&(this._innerConeAngle=e,this._innerConeAngleCos=Math.cos(e*Math.PI/180),this.updateClusterData(false,true),this._usePhysicalUnits&&this._updateLinearColor());}},{key:"outerConeAngle",get:function(){return this._outerConeAngle},set:function(e){this._outerConeAngle!==e&&(this._outerConeAngle=e,this._updateOuterAngle(e),this._usePhysicalUnits&&this._updateLinearColor());}},{key:"penumbraSize",get:function(){return this._penumbraSize},set:function(e){this._penumbraSize=e,this._softShadowParams[2]=e;}},{key:"penumbraFalloff",get:function(){return this._softShadowParams[3]},set:function(e){this._softShadowParams[3]=e;}},{key:"intensity",get:function(){return this._intensity},set:function(e){this._intensity!==e&&(this._intensity=e,this._updateLinearColor());}},{key:"affectSpecularity",get:function(){return this._affectSpecularity},set:function(e){0===this._type&&(this._affectSpecularity=e,this.updateKey());}},{key:"luminance",get:function(){return this._luminance},set:function(e){this._luminance!==e&&(this._luminance=e,this._updateLinearColor());}},{key:"cookieMatrix",get:function(){return this._cookieMatrix||(this._cookieMatrix=new e$),this._cookieMatrix}},{key:"atlasViewport",get:function(){return this._atlasViewport||(this._atlasViewport=new eY(0,0,1,1)),this._atlasViewport}},{key:"cookie",get:function(){return this._cookie},set:function(e){this._cookie!==e&&(this._cookie=e,this.updateKey());}},{key:"cookieFalloff",get:function(){return this._cookieFalloff},set:function(e){this._cookieFalloff!==e&&(this._cookieFalloff=e,this.updateKey());}},{key:"cookieChannel",get:function(){return this._cookieChannel},set:function(e){if(this._cookieChannel!==e){if(e.length<3)for(var t=e.charAt(e.length-1),n=3-e.length,i=0;i0||!this.zeroTextures)&&(this.rtPositions&&this._updateTextureRenderTarget(this.rtPositions,e,true),this.rtNormals&&this._updateTextureRenderTarget(this.rtNormals,e,false),this.zeroTextures=0===e);},t.setAabbUniforms=function(e){ void 0===e&&(e=true),this.aabbSizeId.setValue(e?this._aabbSize:this._aabbNrmSize),this.aabbMinId.setValue(e?this._aabbMin:this._aabbNrmMin);},t.prepareRendering=function(e){this.setAabbUniforms();},t.update=function(){this._dirty=false;for(var e=this.morph._targets,t=this._shaderMorphWeights,n=this._shaderMorphIndex,i=0,r=0;r1e-5&&(t[i]=this.getWeight(r),n[i]=r,i++);this._updateTextureMorph(i);},e}(),he=function(){function e(){this.graph=null,this.meshInstances=[],this.skinInstances=[],this.morphInstances=[],this.cameras=[],this.lights=[],this._shadersVersion=0,this._immutable=false;}var t=e.prototype;return t.getGraph=function(){return this.graph},t.setGraph=function(e){this.graph=e;},t.getCameras=function(){return this.cameras},t.setCameras=function(e){this.cameras=e;},t.getLights=function(){return this.lights},t.setLights=function(e){this.lights=e;},t.getMaterials=function(){for(var e=[],t=0;tl)){this.morphTextureWidth=u,this.morphTextureHeight=c;var h=false,f=eG.float2Half;12===this._textureFormat&&(h=true);for(var d=[],p=[],m=u*c*4,_=0;_0&&(this.targetsTexturePositions=this._createTexture("MorphPositionsTexture",this._textureFormat,n.length,[d]),this.targetsTexturePositions.upload()),p.length>0&&(this.targetsTextureNormals=this._createTexture("MorphNormalsTexture",this._textureFormat,n.length,[p]),this.targetsTextureNormals.upload());var w=[{semantic:t2,components:1,type:5,asInt:true}];return this.vertexBufferIds=new n3(this.device,new n7(this.device,w,s.length),s.length,{data:new Uint32Array(s)}),true}},i._updateMorphFlags=function(){this._morphPositions=false,this._morphNormals=false;for(var e=0;e=D)&&this.calcSpawnPosition(n,i,r,s,P);var N=R>0&&R0&&(1===S.emitterShape?(hl.copy(hu).mulScalar(2).sub(eW.ONE).normalize(),hf.add(hl.mulScalar(S.initialVelocity))):hf.add(eW.FORWARD.mulScalar(S.initialVelocity))),hh.x+=(hd.x-hh.x)*hu.x,hh.y+=(hd.y-hh.y)*hu.y,hh.z+=(hd.z-hh.z)*hu.z,d+=(p-d)*hu.y,O=(O+1e4*I%1*(m-O))*hr,k=1e3*I%1*(v-_),S.meshInstance.node&&(S.localSpace?(hf.x/=T.x,hf.y/=T.y,hf.z/=T.z):hs.transformPoint(hf,hf)),S.localSpace?(ha.transformPoint(hh,hh),hf.add(hh).add(hm)):(hf.add(hh.mul(T)),hf.add(hm.mul(T))),hg.copy(hf),h_.copy(hc).add(hf.mulScalar(a)),hv.copy(h_),n[4*P]=hv.x,n[4*P+1]=hv.y,n[4*P+2]=hv.z,n[4*P+3]+=d*a,S.wrap&&S.wrapBounds&&(S.localSpace||hv.sub(s),hv.x=hx(hv.x,S.wrapBounds.x)-.5*S.wrapBounds.x,hv.y=hx(hv.y,S.wrapBounds.y)-.5*S.wrapBounds.y,hv.z=hx(hv.z,S.wrapBounds.z)-.5*S.wrapBounds.z,S.localSpace||hv.add(s)),S.sort>0&&(1===S.sort?(hy.copy(hv).sub(E),S.particleDistance[P]=-(hy.x*hy.x+hy.y*hy.y+hy.z*hy.z)):2===S.sort?S.particleDistance[P]=R:3===S.sort&&(S.particleDistance[P]=-R))),o?R<0&&(n[4*P+3+2*S.numParticlesPot*4]=-1):(R>=D&&(R-=Math.max(D,(S.numParticles-1)*L),n[4*P+3+2*S.numParticlesPot*4]=S.loop?1:-1),R<0&&S.loop&&(n[4*P+3+2*S.numParticlesPot*4]=1)),n[4*P+3+2*S.numParticlesPot*4]<0&&(N=false),n[4*P+3+4*S.numParticlesPot]=R;for(var F=0;F0&&S.camera){for(var H=S.useMesh?6:4,W=S.particleDistance,j=0;j0&&n.set("SOFT",""),e.stretch>0&&n.set("STRETCH",""),e.customFace&&n.set("CUSTOM_FACE",""),e.pack8&&n.set("PACK8",""),e.localSpace&&n.set("LOCAL_SPACE",""),e.animTexLoop&&n.set("ANIMTEX_LOOP",""),e.wrap&&n.set("WRAP",""),e.alignToMotion&&n.set("ALIGN_TO_MOTION",""),n.set("NORMAL",hI[e.normal]),t.particle_vertexData=tA,e.mesh&&e.meshUv&&(t.particle_uv=tM),n},n.createFragmentDefines=function(e){var t=new Map(e.defines);return e.soft>0&&t.set("SOFT",""),e.halflambert&&t.set("HALF_LAMBERT",""),t.set("NORMAL",hI[e.normal]),t.set("BLEND",oi[e.blend]),t},n.createShaderDefinition=function(e,t){var n=e.isWebGPU?na:ns,i=o1.get(e,n),r={},s=this.createVertexDefines(t,r),a=this.createFragmentDefines(t),o="PARTICLE_"+(t.useCpu?"CPU":"GPU")+"\n";s.set(o,""),a.set(o,"");var l=new Map(i);return rQ.createDefinition(e,{name:"ParticleShader",shaderLanguage:n,attributes:r,vertexCode:i.get("particle_shaderVS"),fragmentCode:i.get("particle_shaderPS"),fragmentDefines:a,fragmentIncludes:l,vertexIncludes:l,vertexDefines:s})},t}(oG));function hD(e,t){return (hD=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var hR=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this)||this).emitter=null,n.emitter=t,n}return t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&hD(t,e),t.prototype.getShaderVariant=function(e){var t,n,i=e.device,r=e.scene,s=e.cameraShaderParams,a=e.objDefs,o=this.emitter,l={defines:o6.getCoreDefines(this,e),pass:0,useCpu:this.emitter.useCpu,normal:o.lighting?null!==o.normalMap?2:1:0,halflambert:this.emitter.halfLambert,stretch:this.emitter.stretch,alignToMotion:this.emitter.alignToMotion,soft:this.emitter.depthSoftening,mesh:this.emitter.useMesh,meshUv:4&a,gamma:null!=(t=null==s?void 0:s.shaderOutputGamma)?t:0,toneMap:null!=(n=null==s?void 0:s.toneMapping)?n:0,fog:r&&!this.emitter.noFog?r.fog.type:"none",wrap:this.emitter.wrap&&this.emitter.wrapBounds,localSpace:this.emitter.localSpace,screenSpace:!o.inTools&&this.emitter.screenSpace,blend:this.emitter.blendType,animTex:this.emitter._isAnimated(),animTexLoop:this.emitter.animLoop,pack8:this.emitter.pack8,customFace:0!==this.emitter.orientation},u=new oU(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),c=oz(i);return c.register("particle",hL),c.getProgram("particle",l,u,this.userId)},t}(uz),hM=[[-1,-1],[1,-1],[1,1],[-1,1]];function hO(e,t,n,i,r,s,a){ void 0===r&&(r=14);var o=0;a&&(7===r||20===r)&&(o=1);var l=new nN(e,{width:t,height:n,format:r,cubemap:false,mipmaps:false,minFilter:o,magFilter:o,addressU:1,addressV:1,name:"ParticleSystemTexture"}),u=l.lock();if(7===r||20===r){for(var c=new Uint8Array(i.length),h=0;he.maxTextureSize&&(this.numParticles=e.maxTextureSize),hX("rate",1),hX("rate2",this.rate),hX("lifetime",50),hX("emitterExtents",new eW(0,0,0)),hX("emitterExtentsInner",new eW(0,0,0)),hX("emitterRadius",0),hX("emitterRadiusInner",0),hX("emitterShape",0),hX("initialVelocity",1),hX("wrap",false),hX("localSpace",false),hX("screenSpace",false),hX("wrapBounds",null),hX("colorMap",this.defaultParamTexture),hX("normalMap",null),hX("loop",true),hX("preWarm",false),hX("sort",0),hX("mode",0),hX("scene",null),hX("lighting",false),hX("halfLambert",false),hX("intensity",1),hX("stretch",0),hX("alignToMotion",false),hX("depthSoftening",0),hX("mesh",null),hX("particleNormal",new eW(0,1,0)),hX("orientation",0),hX("depthWrite",false),hX("noFog",false),hX("blendType",2),hX("node",null),hX("startAngle",0),hX("startAngle2",this.startAngle),hX("animTilesX",1),hX("animTilesY",1),hX("animStartFrame",0),hX("animNumFrames",1),hX("animNumAnimations",1),hX("animIndex",0),hX("randomizeAnimIndex",false),hX("animSpeed",1),hX("animLoop",true),this._gpuUpdater=new hC(this,e),this._cpuUpdater=new hT(this),this.emitterPosUniform=new Float32Array(3),this.wrapBoundsUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),hX("colorGraph",hU),hX("colorGraph2",this.colorGraph),hX("scaleGraph",hF),hX("scaleGraph2",this.scaleGraph),hX("alphaGraph",hF),hX("alphaGraph2",this.alphaGraph),hX("localVelocityGraph",hB),hX("localVelocityGraph2",this.localVelocityGraph),hX("velocityGraph",hB),hX("velocityGraph2",this.velocityGraph),hX("rotationSpeedGraph",hN),hX("rotationSpeedGraph2",this.rotationSpeedGraph),hX("radialSpeedGraph",hN),hX("radialSpeedGraph2",this.radialSpeedGraph),this.animTilesParams=new Float32Array(2),this.animParams=new Float32Array(4),this.animIndexParams=new Float32Array(2),this.vbToSort=null,this.vbOld=null,this.particleDistance=null,this.camera=null,this.swapTex=false,this.useMesh=true,this.useCpu=!e.supportsGpuParticles,this.pack8=true,this.localBounds=new e8,this.worldBoundsNoTrail=new e8,this.worldBoundsTrail=[new e8,new e8],this.worldBounds=new e8,this.worldBoundsSize=new eW,this.prevWorldBoundsSize=new eW,this.prevWorldBoundsCenter=new eW,this.prevEmitterExtents=this.emitterExtents,this.prevEmitterRadius=this.emitterRadius,this.worldBoundsMul=new eW,this.worldBoundsAdd=new eW,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=false,this._layer=null,this.rebuild();}var t,n=e.prototype;return n.onChangeCamera=function(){this.resetMaterial();},n.calculateBoundsMad=function(){this.worldBoundsMul.x=1/this.worldBoundsSize.x,this.worldBoundsMul.y=1/this.worldBoundsSize.y,this.worldBoundsMul.z=1/this.worldBoundsSize.z,this.worldBoundsAdd.copy(this.worldBounds.center).mul(this.worldBoundsMul).mulScalar(-1),this.worldBoundsAdd.x+=.5,this.worldBoundsAdd.y+=.5,this.worldBoundsAdd.z+=.5;},n.calculateWorldBounds=function(){if(this.node){if(this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),!this.useCpu){(0===this.emitterShape?this.emitterExtents.equals(this.prevEmitterExtents):this.emitterRadius===this.prevEmitterRadius)||this.calculateLocalBounds();}var t=this.node.getWorldTransform();this.localSpace?this.worldBoundsNoTrail.copy(this.localBounds):this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,t),this.worldBoundsTrail[0].add(this.worldBoundsNoTrail),this.worldBoundsTrail[1].add(this.worldBoundsNoTrail);var n=this.simTimeTotal;n>=this.timeToSwitchBounds&&(this.worldBoundsTrail[0].copy(this.worldBoundsTrail[1]),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.timeToSwitchBounds=n+this.lifetime),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.localSpace?(this.meshInstance.aabb.setFromTransformedAabb(this.worldBounds,t),this.meshInstance.mesh.aabb.setFromTransformedAabb(this.worldBounds,t)):(this.meshInstance.aabb.copy(this.worldBounds),this.meshInstance.mesh.aabb.copy(this.worldBounds)),this.meshInstance._aabbVer=1-this.meshInstance._aabbVer,this.pack8&&this.calculateBoundsMad();}},n.resetWorldBounds=function(){this.node&&(this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,this.localSpace?e$.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);},n.calculateLocalBounds=function(){for(var e,t,n,i=Number.MAX_VALUE,r=Number.MAX_VALUE,s=Number.MAX_VALUE,a=-Number.MAX_VALUE,o=-Number.MAX_VALUE,l=-Number.MAX_VALUE,u=0,c=0,h=this.lifetime/this.precision,f=[this.qVelocity,this.qVelocity2],d=[this.qLocalVelocity,this.qLocalVelocity2],p=[0,0],m=[0,0],_=[0,0],v=[0,0],g=[0,0],y=0;y0||e.maxVertexTextures<=1||e.fragmentUniformsCount<64||e.forceCpuParticles,this._destroyResources(),this.pack8=(this.pack8||!e.textureFloatRenderable)&&!this.useCpu,hV=this.useCpu||this.pack8?4:2,this.useMesh=!!this.mesh,this.numParticlesPot=ek.nextPowerOfTwo(this.numParticles),this.rebuildGraphs(),this.calculateLocalBounds(),this.resetWorldBounds(),this.node&&(this.worldBounds.setFromTransformedAabb(this.localBounds,this.localSpace?e$.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=Array(this.numParticles);for(var t=0;t=1&&(this.animTilesX>1||this.animTilesY>1)&&(this.colorMap&&this.colorMap!==this.defaultParamTexture||this.normalMap)},n.rebuildGraphs=function(){var e=this.precision,t=this.graphicsDevice;this.qLocalVelocity=this.localVelocityGraph.quantize(e),this.qVelocity=this.velocityGraph.quantize(e),this.qColor=this.colorGraph.quantizeClamped(e,0,1),this.qRotSpeed=this.rotationSpeedGraph.quantize(e),this.qScale=this.scaleGraph.quantize(e),this.qAlpha=this.alphaGraph.quantize(e),this.qRadialSpeed=this.radialSpeedGraph.quantize(e),this.qLocalVelocity2=this.localVelocityGraph2.quantize(e),this.qVelocity2=this.velocityGraph2.quantize(e),this.qColor2=this.colorGraph2.quantizeClamped(e,0,1),this.qRotSpeed2=this.rotationSpeedGraph2.quantize(e),this.qScale2=this.scaleGraph2.quantize(e),this.qAlpha2=this.alphaGraph2.quantize(e),this.qRadialSpeed2=this.radialSpeedGraph2.quantize(e);for(var n=0;n0&&e.setParameter("softening",1/(this.depthSoftening*this.depthSoftening*100)),this.stretch>0&&(e.cull=0),this._compParticleFaceParams();},n._compParticleFaceParams=function(){if(0===this.orientation)e=new Float32Array([1,0,0]),t=new Float32Array([0,0,1]);else {var e,t,n=1===this.orientation?this.particleNormal.normalize():(null===this.node?e$.IDENTITY:this.node.getWorldTransform()).transformVector(this.particleNormal).normalize(),i=new eW(1,0,0);1===Math.abs(i.dot(n))&&i.set(0,0,1);var r=new eW().cross(n,i).normalize();i.cross(r,n).normalize(),e=new Float32Array([i.x,i.y,i.z]),t=new Float32Array([r.x,r.y,r.z]);}this.material.setParameter("faceTangent",e),this.material.setParameter("faceBinorm",t);},n.getVertexInfo=function(){var e=[];return this.useCpu?e.push({semantic:tz,components:4,type:6},{semantic:tG,components:4,type:6},{semantic:tH,components:4,type:6},{semantic:tW,components:1,type:6},{semantic:tj,components:this.useMesh?4:2,type:6}):(e.push({semantic:tz,components:4,type:6}),this.useMesh&&e.push({semantic:tG,components:2,type:6})),e},n._allocate=function(e){var t=e*this.numParticleVerts,n=e*this.numParticleIndices;if(void 0===this.vertexBuffer||this.vertexBuffer.getNumVertices()!==t){var i,r,s,a=this.getVertexInfo(),o=new n7(this.graphicsDevice,a);this.vertexBuffer=new n3(this.graphicsDevice,o,t,{usage:1}),this.indexBuffer=new sQ(this.graphicsDevice,2,n);var l=new Float32Array(this.vertexBuffer.lock());if(this.useMesh){r=(i=new Float32Array(this.mesh.vertexBuffer.lock())).length/this.mesh.vertexBuffer.numVertices;for(var u=0;uthis.endTime&&(this.onFinished&&this.onFinished(),this.meshInstance.visible=false),this.meshInstance&&(this.meshInstance.drawOrder=this.drawOrder);},n._destroyResources=function(){var e,t,n,i,r,s,a,o,l,u,c,h;null==(e=this.particleTexIN)||e.destroy(),this.particleTexIN=null,null==(t=this.particleTexOUT)||t.destroy(),this.particleTexOUT=null,this.particleTexStart&&this.particleTexStart.destroy&&(this.particleTexStart.destroy(),this.particleTexStart=null),null==(n=this.rtParticleTexIN)||n.destroy(),this.rtParticleTexIN=null,null==(i=this.rtParticleTexOUT)||i.destroy(),this.rtParticleTexOUT=null,null==(r=this.internalTex0)||r.destroy(),this.internalTex0=null,null==(s=this.internalTex1)||s.destroy(),this.internalTex1=null,null==(a=this.internalTex2)||a.destroy(),this.internalTex2=null,null==(o=this.internalTex3)||o.destroy(),this.internalTex3=null,null==(l=this.colorParam)||l.destroy(),this.colorParam=null,null==(u=this.vertexBuffer)||u.destroy(),this.vertexBuffer=void 0,null==(c=this.indexBuffer)||c.destroy(),this.indexBuffer=void 0,null==(h=this.material)||h.destroy(),this.material=null;},n.destroy=function(){this.camera=null,this._destroyResources();},t=[{key:"defaultParamTexture",get:function(){var e=this;return hQ.get(this.graphicsDevice,function(){for(var t=new Float32Array(1024),n=0;n<16;n++)for(var i=0;i<16;i++){var r=i+1-8.5,s=n+1-8.5,a=hk(1-hk(Math.sqrt(r*r+s*s)/16)-.5),o=16*n+i;t[4*o]=1,t[4*o+1]=1,t[4*o+2]=1,t[4*o+3]=a;}var l=hO(e.graphicsDevice,16,16,t,20,1,true);return l.minFilter=1,l.magFilter=1,l})}}],function(e,t){for(var n=0;nN.dot(O)?-1:1;}return _},h7=function(){function e(){}var t=e.prototype;return t.calculateNormals=function(){this.normals=h6(this.positions,this.indices);},t.calculateTangents=function(){this.tangents=h9(this.positions,this.normals,this.uvs,this.indices);},e}();function fe(e,t){return (fe=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var ft=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){ void 0===t&&(t={});var n,i,r,s,a,o=e.call(this)||this,l=null!=(n=t.halfExtents)?n:new eW(.5,.5,.5),u=null!=(i=t.widthSegments)?i:1,c=null!=(r=t.lengthSegments)?r:1,h=null!=(s=t.heightSegments)?s:1,f=null!=(a=t.yOffset)?a:0,d=-l.y+f,p=l.y+f,m=[new eW(-l.x,d,l.z),new eW(l.x,d,l.z),new eW(l.x,p,l.z),new eW(-l.x,p,l.z),new eW(l.x,d,-l.z),new eW(-l.x,d,-l.z),new eW(-l.x,p,-l.z),new eW(l.x,p,-l.z)],_=[[0,1,3],[4,5,7],[3,2,6],[1,0,4],[1,4,2],[5,0,6]],v=[[0,0,1],[0,0,-1],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0]],g=[],y=[],S=[],x=[],b=0,T=function(e,t,n){for(var i=new eW,r=new eW,s=new eW,a=new eW,o=0;o<=t;o++)for(var l=0;l<=n;l++){i.lerp(m[_[e][0]],m[_[e][1]],o/t),r.lerp(m[_[e][0]],m[_[e][2]],l/n),s.sub2(r,m[_[e][0]]),a.add2(i,s);var u=o/t,c=l/n;g.push(a.x,a.y,a.z),y.push(v[e][0],v[e][1],v[e][2]),S.push(u,1-c),c=(.875*c+.0625)/3,u=(.875*u+.0625)/3+e%3/3,c+=Math.floor(e/3)/3,o0&&this.material.transparent===t&&(this.mesh.setPositions(this.positions),this.mesh.setColors(this.colors),this.mesh.update(1,false),this.meshInstance||(this.meshInstance=new lL(this.mesh,this.material,fu)),e.push(this.meshInstance));},t.clear=function(){this.positions.length=0,this.colors.length=0;},e}(),fh=function(){function e(e){this.device=e,this.map=new Map;}var t=e.prototype;return t.getBatch=function(e,t){var n=this.map.get(e);return n||(n=new fc(this.device,e,t),this.map.set(e,n)),n},t.onPreRender=function(e,t){this.map.forEach(function(n){n.onPreRender(e,t);});},t.clear=function(){this.map.forEach(function(e){return e.clear()});},e}(),ff=[],fd=new eW,fp=function(){function e(e){this.shaderDescs=new Map,this.device=e,this.quadMesh=null,this.textureShader=null,this.depthTextureShader=null,this.cubeLocalPos=null,this.cubeWorldPos=null,this.batchesMap=new Map,this.allBatches=new Set,this.updatedLayers=new Set,this._materialDepth=null,this._materialNoDepth=null,this.layerMeshInstances=new Map;}var t,n=e.prototype;return n.createMaterial=function(e){var t=new h3({uniqueName:"ImmediateLine",vertexGLSL:o1.get(this.device,ns).get("immediateLineVS"),fragmentGLSL:o1.get(this.device,ns).get("immediateLinePS"),vertexWGSL:o1.get(this.device,na).get("immediateLineVS"),fragmentWGSL:o1.get(this.device,na).get("immediateLinePS"),attributes:{vertex_position:tA,vertex_color:tD}});return t.blendType=2,t.depthTest=e,t.update(),t},n.getBatch=function(e,t){var n=this.batchesMap.get(e);n||(n=new fh(this.device),this.batchesMap.set(e,n)),this.allBatches.add(n);var i=t?this.materialDepth:this.materialNoDepth;return n.getBatch(i,e)},n.getShaderDesc=function(e,t,n){return this.shaderDescs.has(e)||this.shaderDescs.set(e,{uniqueName:"DebugShader:"+e,vertexGLSL:"\n attribute vec2 vertex_position;\n uniform mat4 matrix_model;\n varying vec2 uv0;\n void main(void) {\n gl_Position = matrix_model * vec4(vertex_position, 0, 1);\n uv0 = vertex_position.xy + 0.5;\n }\n ",vertexWGSL:"\n attribute vertex_position: vec2f;\n uniform matrix_model: mat4x4f;\n varying uv0: vec2f;\n @vertex fn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n output.position = uniform.matrix_model * vec4f(input.vertex_position, 0.0, 1.0);\n output.uv0 = input.vertex_position.xy + vec2f(0.5);\n return output;\n }\n ",fragmentGLSL:t,fragmentWGSL:n,attributes:{vertex_position:tA}}),this.shaderDescs.get(e)},n.getTextureShaderDesc=function(e){var t=h8.decodeFunc(e);return this.getShaderDesc("textureShader-"+e,'\n #include "gammaPS"\n varying vec2 uv0;\n uniform sampler2D colorMap;\n void main (void) {\n vec3 linearColor = '+t+"(texture2D(colorMap, uv0));\n gl_FragColor = vec4(gammaCorrectOutput(linearColor), 1);\n }\n ",'\n #include "gammaPS"\n varying uv0: vec2f;\n var colorMap: texture_2d;\n var colorMapSampler: sampler;\n @fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n let sampledTex = textureSample(colorMap, colorMapSampler, input.uv0);\n let linearColor: vec3f = '+t+"(sampledTex);\n output.color = vec4f(gammaCorrectOutput(linearColor), 1.0);\n return output;\n }\n ")},n.getUnfilterableTextureShaderDesc=function(){return this.getShaderDesc("textureShaderUnfilterable","\n varying vec2 uv0;\n uniform highp sampler2D colorMap;\n void main (void) {\n ivec2 uv = ivec2(uv0 * textureSize(colorMap, 0));\n gl_FragColor = vec4(texelFetch(colorMap, uv, 0).xyz, 1);\n }\n ","\n varying uv0: vec2f;\n var colorMap: texture_2d;\n @fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n let uv : vec2 = vec2(input.uv0 * vec2f(textureDimensions(colorMap, 0)));\n let fetchedColor : vec4f = textureLoad(colorMap, uv, 0);\n output.color = vec4f(fetchedColor.xyz, 1.0);\n return output;\n }\n ")},n.getDepthTextureShaderDesc=function(){return this.getShaderDesc("depthTextureShader",'\n #include "screenDepthPS"\n #include "gammaPS"\n varying vec2 uv0;\n void main() {\n float depth = getLinearScreenDepth(getImageEffectUV(uv0)) * camera_params.x;\n gl_FragColor = vec4(gammaCorrectOutput(vec3(depth)), 1.0);\n }\n ','\n #include "screenDepthPS"\n #include "gammaPS"\n varying uv0: vec2f;\n @fragment fn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n let depth: f32 = getLinearScreenDepth(getImageEffectUV(input.uv0)) * uniform.camera_params.x;\n output.color = vec4f(gammaCorrectOutput(vec3f(depth)), 1.0);\n return output;\n }\n ')},n.getQuadMesh=function(){return this.quadMesh||(this.quadMesh=new lv(this.device),this.quadMesh.setPositions([-0.5,-0.5,0,.5,-0.5,0,-0.5,.5,0,.5,.5,0]),this.quadMesh.update(5)),this.quadMesh},n.drawMesh=function(e,t,n,i,r){i||(i=new lL(n,e,this.getGraphNode(t)));var s=this.layerMeshInstances.get(r);s||(s=[],this.layerMeshInstances.set(r,s)),s.push(i);},n.drawWireAlignedBox=function(e,t,n,i,r,s){if(s){var a=function(e,t,n){fd.set(e,t,n),s.transformPoint(fd,fd),ff.push(fd.x,fd.y,fd.z);};a(e.x,e.y,e.z),a(e.x,t.y,e.z),a(e.x,t.y,e.z),a(t.x,t.y,e.z),a(t.x,t.y,e.z),a(t.x,e.y,e.z),a(t.x,e.y,e.z),a(e.x,e.y,e.z),a(e.x,e.y,t.z),a(e.x,t.y,t.z),a(e.x,t.y,t.z),a(t.x,t.y,t.z),a(t.x,t.y,t.z),a(t.x,e.y,t.z),a(t.x,e.y,t.z),a(e.x,e.y,t.z),a(e.x,e.y,e.z),a(e.x,e.y,t.z),a(e.x,t.y,e.z),a(e.x,t.y,t.z),a(t.x,t.y,e.z),a(t.x,t.y,t.z),a(t.x,e.y,e.z),a(t.x,e.y,t.z);}else ff.push(e.x,e.y,e.z,e.x,t.y,e.z,e.x,t.y,e.z,t.x,t.y,e.z,t.x,t.y,e.z,t.x,e.y,e.z,t.x,e.y,e.z,e.x,e.y,e.z,e.x,e.y,t.z,e.x,t.y,t.z,e.x,t.y,t.z,t.x,t.y,t.z,t.x,t.y,t.z,t.x,e.y,t.z,t.x,e.y,t.z,e.x,e.y,t.z,e.x,e.y,e.z,e.x,e.y,t.z,e.x,t.y,e.z,e.x,t.y,t.z,t.x,t.y,e.z,t.x,t.y,t.z,t.x,e.y,e.z,t.x,e.y,t.z);this.getBatch(r,i).addLinesArrays(ff,n),ff.length=0;},n.drawWireSphere=function(e,t,n,i,r,s){for(var a=2*Math.PI/i,o=0,l=0;l>>16)>>>0;return 23283064365386963e-26*(t=((0xff00ff&(t=((0xf0f0f0f&(t=((0x33333333&(t=((0x55555555&t)<<1|(0xaaaaaaaa&t)>>>1)>>>0))<<2|(0xcccccccc&t)>>>2)>>>0))<<4|(0xf0f0f0f0&t)>>>4)>>>0))<<8|(0xff00ff00&t)>>>8)>>>0)}},f_=function(e){switch(e){case nn:return "Cubemap";case nr:return "Octahedral";default:return "Equirect"}},fv=function(e,t,n){if(e<=0)t[n+0]=0,t[n+1]=0,t[n+2]=0,t[n+3]=0;else if(e>=1)t[n+0]=255,t[n+1]=0,t[n+2]=0,t[n+3]=0;else {var i=e%1,r=255*e%1,s=65025*e%1,a=0xfd02ff*e%1;i-=r/255,r-=s/255,s-=a/255,t[n+0]=Math.min(255,Math.floor(256*i)),t[n+1]=Math.min(255,Math.floor(256*r)),t[n+2]=Math.min(255,Math.floor(256*s)),t[n+3]=Math.min(255,Math.floor(256*a));}},fg=function(e){for(var t=e.length,n=Math.min(t,512),i=Math.ceil(t/n),r=new Uint8Array(n*i*4),s=0,a=0;a0){var d=.5*Math.log2(i/(fb(Math.min(1,f),s)/4+.001));u.push(o.x,o.y,o.z,d);}}for(;u.length<4*e;)u.push(0,0,0,0);return u},fP=function(e,t,n){var i=fg(n);return new nN(e,{name:t,width:i.width,height:i.height,mipmaps:false,minFilter:0,magFilter:0,levels:[i.data]})},fI=function(){function e(e){ void 0===e&&(e=true),this.map=new Map,this.destroyContent=e;}var t=e.prototype;return t.destroy=function(){this.destroyContent&&this.map.forEach(function(e,t){e.destroy();});},t.get=function(e,t){if(!this.map.has(e)){var n=t();return this.map.set(e,n),n}return this.map.get(e)},e}(),fL=new fI(false),fD=new nM,fR=function(e,t,n){return fD.get(e,function(){return new fI}).get(t,function(){return fP(e,t,fL.get(t,n))})};function fM(e,t,n){ void 0===n&&(n={});var i,r,s,a,o,l=null!=(s=n.seamPixels)?s:0,u=(null!=(a=null==(i=n.rect)?void 0:i.z)?a:t.width)-2*l,c=(null!=(o=null==(r=n.rect)?void 0:r.w)?o:t.height)-2*l;if(u<1||c<1)return false;var h=n.hasOwnProperty("specularPower")?n.specularPower:1,f=n.hasOwnProperty("face")?n.face:null,d=n.hasOwnProperty("distribution")?n.distribution:1===h?"none":"phong",p={none:"reproject",lambert:"prefilterSamplesUnweighted",phong:"prefilterSamplesUnweighted",ggx:"prefilterSamples"}[d]||"reproject",m=p.startsWith("prefilterSamples"),_=h8.decodeFunc(e.encoding),v=h8.encodeFunc(t.encoding),g="sample"+f_(e.projection),y="getDirection"+f_(t.projection),S=n.hasOwnProperty("numSamples")?n.numSamples:1024,x="ReprojectShader:"+p+"_"+_+"_"+v+"_"+g+"_"+y+"_"+S,b=e.device,T=oz(b).getCachedShader(x);if(!T){var E=new Map;m&&E.set("USE_SAMPLES_TEX",""),e.cubemap&&E.set("CUBEMAP_SOURCE",""),E.set("{PROCESS_FUNC}",p),E.set("{DECODE_FUNC}",_),E.set("{ENCODE_FUNC}",v),E.set("{SOURCE_FUNC}",g),E.set("{TARGET_FUNC}",y),E.set("{NUM_SAMPLES}",S),E.set("{NUM_SAMPLES_SQRT}",Math.round(Math.sqrt(S)).toFixed(1));var w=b.isWebGPU,A=o1.get(b,w?na:ns),C=new Map;C.set("decodePS",A.get("decodePS")),C.set("encodePS",A.get("encodePS")),T=o6.createShader(b,{uniqueName:x,attributes:{vertex_position:tA},vertexChunk:"reprojectVS",fragmentChunk:"reprojectPS",fragmentIncludes:C,fragmentDefines:E});}b.setBlendState(nY.NOBLEND),b.scope.resolve(e.cubemap?"sourceCube":"sourceTex").setValue(e);var P=b.scope.resolve("params"),I=b.scope.resolve("uvMod");l>0?I.setValue([(u+2*l)/u,(c+2*l)/c,-l/u,-l/c]):I.setValue([1,1,0,0]);var L=[0,t.width*t.height*(t.cubemap?6:1),e.width*e.height*(e.cubemap?6:1)];if(m){var D=e.width*e.height*(e.cubemap?6:1),R="ggx"===d?fR(b,"ggx-samples-"+S+"-"+h+"-"+D,function(){return fC(S,h,D)}):"lambert"===d?fR(b,"lambert-samples-"+S+"-"+D,function(){return fE(S,D)}):fR(b,"phong-samples-"+S+"-"+h,function(){return fT(S,h)});b.scope.resolve("samplesTex").setValue(R),b.scope.resolve("samplesTexInverseSize").setValue([1/R.width,1/R.height]);}for(var M=0;M<(t.cubemap?6:1);M++)if(null===f||M===f){var O=new ic({colorBuffer:t,face:M,depth:false,flipY:b.isWebGPU});L[0]=M,P.setValue(L),la(b,O,T,null==n?void 0:n.rect),O.destroy();}return true}var fO=function(e,t){return void 0===t&&(t=0),1+Math.floor(Math.log2(Math.max(e,t)))},fk=function(){function e(){}return e.generateSkyboxCubemap=function(e,t){var n,i,r=(n=e.device,i=t||(e.cubemap?e.width:e.width/4),new nN(n,{name:"lighting-"+i,cubemap:true,width:i,height:i,format:7,type:t8,addressU:1,addressV:1,mipmaps:false}));return fM(e,r,{numSamples:1024}),r},e.generateLightingSource=function(e,t){var n,i=e.device,r=(n=i).textureHalfFloatRenderable?12:n.textureFloatRenderable?14:7,s=(null==t?void 0:t.target)||new nN(i,{name:"lighting-source",cubemap:true,width:(null==t?void 0:t.size)||128,height:(null==t?void 0:t.size)||128,format:r,type:7===r?t8:t3,addressU:1,addressV:1,mipmaps:true});return fM(e,s,{numSamples:e.mipmaps?1:1024}),s},e.generateAtlas=function(e,t){for(var n=e.device,i=(null==t?void 0:t.target)||new nN(n,{name:"envAtlas",width:(null==t?void 0:t.size)||512,height:(null==t?void 0:t.size)||512,format:7,type:t8,projection:ni,addressU:1,addressV:1,mipmaps:false}),r=i.width/512,s=new eY(0,0,512*r,256*r),a=fO(256)-fO(4),o=0;o>2*l),rect:s,seamPixels:r}),s.y+=s.w,s.z=Math.max(1,Math.floor(.5*s.z)),s.w=Math.max(1,Math.floor(.5*s.w));return s.set(128*r,384*r,64*r,32*r),fM(e,i,{numSamples:(null==t?void 0:t.numAmbientSamples)||2048,distribution:"lambert",rect:s,seamPixels:r}),i},e.generatePrefilteredAtlas=function(e,t){for(var n=e[0].device,i=e[0].format,r=e[0].type,s=(null==t?void 0:t.target)||new nN(n,{name:"envPrefilteredAtlas",width:(null==t?void 0:t.size)||512,height:(null==t?void 0:t.size)||512,format:i,type:r,projection:ni,addressU:1,addressV:1,mipmaps:false}),a=s.width/512,o=new eY(0,0,512*a,256*a),l=fO(512),u=0;ue.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(this._meshes);!(e=t()).done;){var n=e.value;n&&n.destroy();}this._meshes.length=0;},n=[{key:"frameKeys",get:function(){return this._frameKeys},set:function(e){this._frameKeys=e,this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=true:this._createMeshes()),this.fire("set:frameKeys",e);}},{key:"atlas",get:function(){return this._atlas},set:function(e){e!==this._atlas&&(this._atlas&&(this._atlas.off("set:frames",this._onSetFrames,this),this._atlas.off("set:frame",this._onFrameChanged,this),this._atlas.off("remove:frame",this._onFrameRemoved,this)),this._atlas=e,this._atlas&&this._frameKeys&&(this._atlas.on("set:frames",this._onSetFrames,this),this._atlas.on("set:frame",this._onFrameChanged,this),this._atlas.on("remove:frame",this._onFrameRemoved,this),this._updatingProperties?this._meshesDirty=true:this._createMeshes()),this.fire("set:atlas",e));}},{key:"pixelsPerUnit",get:function(){return this._pixelsPerUnit},set:function(e){this._pixelsPerUnit!==e&&(this._pixelsPerUnit=e,this.fire("set:pixelsPerUnit",e),this._atlas&&this._frameKeys&&0===this.renderMode&&(this._updatingProperties?this._meshesDirty=true:this._createMeshes()));}},{key:"renderMode",get:function(){return this._renderMode},set:function(e){if(this._renderMode!==e){var t=this._renderMode;this._renderMode=e,this.fire("set:renderMode",e),(0===t||0===e)&&this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=true:this._createMeshes());}}},{key:"meshes",get:function(){return this._meshes}}],function(e,t){for(var n=0;nn){this._time=this.looping?0:n;for(var i=0;i=0?1:-1,u=0;u=0;m+=l){var _=f[m],v=f[m+1];if(_.time<=this._time&&v.time>=this._time){var g=(this._time-_.time)/(v.time-_.time);d._pos.lerp(_.position,v.position,g),d._quat.slerp(_.rotation,v.rotation,g),d._scale.lerp(_.scale,v.scale,g),d._written=true,this._currKeyIndices[h]=m,p=true;break}}(1===f.length||!p&&0===this._time&&this.looping)&&(d._pos.copy(f[0].position),d._quat.copy(f[0].rotation),d._scale.copy(f[0].scale),d._written=true);}}}}},n.blend=function(e,t,n){for(var i=this._interpolatedKeys.length,r=0;r0,e.blendType=t.blendType,e.screenSpace=i&&(256&i)!=0,e.skin=i&&(2&i)!=0,e.useInstancing=i&&(32&i)!=0,e.useMorphPosition=i&&(1024&i)!=0,e.useMorphNormal=i&&(2048&i)!=0,e.useMorphTextureBasedInt=i&&(8192&i)!=0,e.hasTangents=i&&(512&i)!=0,e.nineSlicedMode=t.nineSlicedMode||0,t.useLighting&&n.clusteredLightingEnabled?(e.clusteredLightingEnabled=true,e.clusteredLightingCookiesEnabled=n.lighting.cookiesEnabled,e.clusteredLightingShadowsEnabled=n.lighting.shadowsEnabled,e.clusteredLightingShadowType=n.lighting.shadowType,e.clusteredLightingAreaLightsEnabled=n.lighting.areaLightsEnabled):(e.clusteredLightingEnabled=false,e.clusteredLightingCookiesEnabled=false,e.clusteredLightingShadowsEnabled=false,e.clusteredLightingAreaLightsEnabled=false);},e.updateMaterialOptions=function(e,t){e.separateAmbient=false,e.pixelSnap=t.pixelSnap,e.ambientSH=t.ambientSH,e.twoSidedLighting=t.twoSidedLighting,e.occludeDirect=t.occludeDirect,e.occludeSpecular=t.occludeSpecular,e.occludeSpecularFloat=1!==t.occludeSpecularIntensity,e.useMsdf=false,e.msdfTextAttribute=false,e.alphaToCoverage=t.alphaToCoverage,e.opacityFadesSpecular=t.opacityFadesSpecular,e.opacityDither=t.opacityDither,e.cubeMapProjection=0,e.useSpecular=t.hasSpecular,e.useSpecularityFactor=t.hasSpecularityFactor,e.enableGGXSpecular=t.ggxSpecular,e.fresnelModel=t.fresnelModel,e.useRefraction=t.hasRefraction,e.useClearCoat=t.hasClearCoat,e.useSheen=t.hasSheen,e.useIridescence=t.hasIrridescence,e.useMetalness=t.hasMetalness,e.useDynamicRefraction=t.dynamicRefraction,e.dispersion=t.dispersion>0,e.vertexColors=false,e.lightMapEnabled=t.hasLighting,e.dirLightMapEnabled=t.dirLightMap,e.useHeights=t.hasHeights,e.useNormals=t.hasNormals,e.useClearCoatNormals=t.hasClearCoatNormals,e.useAo=t.hasAo,e.diffuseMapEnabled=t.hasDiffuseMap;},e.updateEnvOptions=function(e,t,n,i){e.fog=t.useFog?i.fog:or,e.gamma=i.shaderOutputGamma,e.toneMap=t.useTonemap?i.toneMapping:6,t.useSkybox&&n.envAtlas&&n.skybox?(e.reflectionSource=ov,e.reflectionEncoding=n.envAtlas.encoding,e.reflectionCubemapEncoding=n.skybox.encoding):t.useSkybox&&n.envAtlas?(e.reflectionSource=o_,e.reflectionEncoding=n.envAtlas.encoding):t.useSkybox&&n.skybox?(e.reflectionSource=og,e.reflectionEncoding=n.skybox.encoding):(e.reflectionSource=om,e.reflectionEncoding=null),t.ambientSH?(e.ambientSource=ox,e.ambientEncoding=null):e.reflectionSource!==om&&n.envAtlas?(e.ambientSource=ob,e.ambientEncoding=n.envAtlas.encoding):(e.ambientSource=oT,e.ambientEncoding=null);var r=e.reflectionSource!==om;e.skyboxIntensity=r,e.useCubeMapRotation=r&&n._skyboxRotationShaderInclude;},e.updateLightingOptions=function(t,n,i,r,s){if(t.lightMapWithoutAmbient=false,n.useLighting){var a=[],o=r?r>>16:1;t.lightMaskDynamic=!!(1&o),t.lightMapWithoutAmbient=false,s&&(e.collectLights(0,s[0],a,o),i.clusteredLightingEnabled||(e.collectLights(1,s[1],a,o),e.collectLights(2,s[2],a,o))),t.lights=a;}else t.lights=[];(0!==t.lights.length||i.clusteredLightingEnabled)&&(1&r)==0||(t.noShadow=true);},e.collectLights=function(e,t,n,i){for(var r=0;re.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(Object.entries(t.userAttributes));!(s=a()).done;){var o=s.value,l=o[0],u=o[1];this.attributes[u]=l;}var c=o1.get(e,this.shaderLanguage);this.chunks=new Map(c),r&&(this.shaderLanguage===ns?r.glsl:r.wgsl).forEach(function(e,t){for(var n in f5)f5.hasOwnProperty(n)&&e.indexOf(n)>=0&&(i.attributes[n]=f5[n]);i.chunks.set(t,e);}),this.shaderPassInfo=oj.get(this.device).getByIndex(t.pass),this.shadowPass=this.shaderPassInfo.isShadow,this.lighting=t.lights.length>0||t.dirLightMapEnabled||t.clusteredLightingEnabled,this.reflections=t.reflectionSource!==om,this.needsNormal=this.lighting||this.reflections||t.useSpecular||t.ambientSH||t.useHeights||t.enableGGXSpecular||t.clusteredLightingEnabled&&!this.shadowPass||t.useClearCoatNormals,this.needsNormal=this.needsNormal&&!this.shadowPass,this.needsSceneColor=t.useDynamicRefraction,this.needsScreenSize=t.useDynamicRefraction,this.needsTransforms=t.useDynamicRefraction,this.vshader=null,this.fshader=null;}var t=e.prototype;return t.fDefineSet=function(e,t,n){ void 0===n&&(n=""),e&&this.fDefines.set(t,n);},t.generateVertexShader=function(e,t,n){var i=this,r=this.options,s=this.vDefines,a=this.attributes,o=new Map;if(o.set("vPositionW","vec3"),(1===r.nineSlicedMode||2===r.nineSlicedMode)&&s.set("NINESLICED",true),this.options.linearDepth&&(s.set("LINEAR_DEPTH",true),o.set("vLinearDepth","float")),this.needsNormal&&s.set("NORMALS",true),this.options.useInstancing){var l=o1.get(this.device,this.shaderLanguage);this.chunks.get("transformInstancingVS")===l.get("transformInstancingVS")&&(a.instance_line1=t$,a.instance_line2=t0,a.instance_line3=t1,a.instance_line4=t2);}this.needsNormal&&(a.vertex_normal=tC,o.set("vNormalW","vec3"),r.hasTangents&&(r.useHeights||r.useNormals||r.useClearCoatNormals||r.enableGGXSpecular)?(s.set("TANGENTS",true),a.vertex_tangent=tP,o.set("vTangentW","vec3"),o.set("vBinormalW","vec3")):r.enableGGXSpecular&&(s.set("GGX_SPECULAR",true),o.set("vObjectSpaceUpW","vec3")));for(var u=0;u<2;u++)e[u]&&(s.set("UV"+u,true),a["vertex_texCoord"+u]="TEXCOORD"+u),t[u]&&(s.set("UV"+u+"_UNMODIFIED",true),o.set("vUv"+u,"vec2"));var c=0,h=new Set;n.forEach(function(e){var t=e.id,n=e.uv,i=e.name,r=t+100*n;!h.has(r)&&(h.add(r),o.set("vUV"+n+"_"+t,"vec2"),s.set("{TRANSFORM_NAME_"+c+"}","texture_"+i+"MapTransform"),s.set("{TRANSFORM_UV_"+c+"}",n),s.set("{TRANSFORM_ID_"+c+"}",t),c++);}),s.set("UV_TRANSFORMS_COUNT",c),r.vertexColors&&(a.vertex_color=tD,s.set("VERTEX_COLOR",true),o.set("vVertexColor","vec4")),r.useMsdf&&r.msdfTextAttribute&&(a.vertex_outlineParameters=tK,a.vertex_shadowParameters=tZ,s.set("MSDF",true)),(r.useMorphPosition||r.useMorphNormal)&&(s.set("MORPHING",true),r.useMorphTextureBasedInt&&s.set("MORPHING_INT",true),r.useMorphPosition&&s.set("MORPHING_POSITION",true),r.useMorphNormal&&s.set("MORPHING_NORMAL",true),a.morph_vertex_id=t2),r.skin&&(a.vertex_boneIndices=tL,r.batch?s.set("BATCH",true):(a.vertex_boneWeights=tI,s.set("SKIN",true))),r.useInstancing&&s.set("INSTANCING",true),r.screenSpace&&s.set("SCREENSPACE",true),r.pixelSnap&&s.set("PIXELSNAP",true),o.forEach(function(e,t){i.varyingsCode+="#define VARYING_"+t.toUpperCase()+"\n",i.varyingsCode+=i.shaderLanguage===na?"varying "+t+": "+f8.get(e)+";\n":"varying "+e+" "+t+";\n";}),this.includes.set("varyingsVS",this.varyingsCode),this.includes.set("varyingsPS",this.varyingsCode),this.vshader='\n #include "litMainVS"\n ';},t._setupLightingDefines=function(e,t){var n=this.fDefines,i=this.options;if(this.fDefines.set("LIGHT_COUNT",i.lights.length),e&&n.set("AREA_LIGHTS",true),t&&this.lighting&&(n.set("LIT_CLUSTERED_LIGHTS",true),i.clusteredLightingCookiesEnabled&&n.set("CLUSTER_COOKIES",true),i.clusteredLightingAreaLightsEnabled&&n.set("CLUSTER_AREALIGHTS",true),i.lightMaskDynamic&&n.set("CLUSTER_MESH_DYNAMIC_LIGHTS",true),i.clusteredLightingShadowsEnabled&&!i.noShadow)){var r=oc.get(i.clusteredLightingShadowType);n.set("CLUSTER_SHADOWS",true),n.set("SHADOW_KIND_"+r.kind,true),n.set("CLUSTER_SHADOW_TYPE_"+r.kind,true);}for(var s=0;s0&&n.set("LIGHT"+s+"_SHADOW_CASCADE_BLEND",true),a.numCascades>1&&n.set("LIGHT"+s+"_SHADOW_CASCADES",true)),(h.pcf||h.pcss||this.device.isWebGPU)&&n.set("LIGHT"+s+"_SHADOW_SAMPLE_SOURCE_ZBUFFER",true),1===o&&n.set("LIGHT"+s+"_SHADOW_SAMPLE_POINT",true)),c&&(n.set("SHADOW_KIND_"+h.kind,true),0===o&&n.set("SHADOW_DIRECTIONAL",true));}}},t.prepareForwardPass=function(e){var t=this.options,n=t.clusteredLightingEnabled&&t.clusteredLightingAreaLightsEnabled||t.lights.some(function(e){return e._shape&&0!==e._shape}),i=!t.lightMapEnabled||t.lightMapWithoutAmbient,r=this.needsNormal&&(t.useNormals||t.useClearCoatNormals||t.enableGGXSpecular&&!t.useHeights);t.useSpecular&&(this.fDefineSet(true,"LIT_SPECULAR"),this.fDefineSet(this.reflections,"LIT_REFLECTIONS"),this.fDefineSet(t.useClearCoat,"LIT_CLEARCOAT"),this.fDefineSet(t.fresnelModel>0,"LIT_SPECULAR_FRESNEL"),this.fDefineSet(t.useSheen,"LIT_SHEEN"),this.fDefineSet(t.useIridescence,"LIT_IRIDESCENCE")),this.fDefineSet(this.lighting&&t.useSpecular||this.reflections,"LIT_SPECULAR_OR_REFLECTION"),this.fDefineSet(this.needsSceneColor,"LIT_SCENE_COLOR"),this.fDefineSet(this.needsScreenSize,"LIT_SCREEN_SIZE"),this.fDefineSet(this.needsTransforms,"LIT_TRANSFORMS"),this.fDefineSet(this.needsNormal,"LIT_NEEDS_NORMAL"),this.fDefineSet(this.lighting,"LIT_LIGHTING"),this.fDefineSet(t.useMetalness,"LIT_METALNESS"),this.fDefineSet(t.enableGGXSpecular,"LIT_GGX_SPECULAR"),this.fDefineSet(t.useSpecularityFactor,"LIT_SPECULARITY_FACTOR"),this.fDefineSet(t.useCubeMapRotation,"CUBEMAP_ROTATION"),this.fDefineSet(t.occludeSpecularFloat,"LIT_OCCLUDE_SPECULAR_FLOAT"),this.fDefineSet(t.separateAmbient,"LIT_SEPARATE_AMBIENT"),this.fDefineSet(t.twoSidedLighting,"LIT_TWO_SIDED_LIGHTING"),this.fDefineSet(t.lightMapEnabled,"LIT_LIGHTMAP"),this.fDefineSet(t.dirLightMapEnabled,"LIT_DIR_LIGHTMAP"),this.fDefineSet(t.skyboxIntensity>0,"LIT_SKYBOX_INTENSITY"),this.fDefineSet(t.clusteredLightingShadowsEnabled,"LIT_CLUSTERED_SHADOWS"),this.fDefineSet(t.clusteredLightingAreaLightsEnabled,"LIT_CLUSTERED_AREA_LIGHTS"),this.fDefineSet(r,"LIT_TBN"),this.fDefineSet(i,"LIT_ADD_AMBIENT"),this.fDefineSet(t.hasTangents,"LIT_TANGENTS"),this.fDefineSet(t.useNormals,"LIT_USE_NORMALS"),this.fDefineSet(t.useClearCoatNormals,"LIT_USE_CLEARCOAT_NORMALS"),this.fDefineSet(t.useRefraction,"LIT_REFRACTION"),this.fDefineSet(t.useDynamicRefraction,"LIT_DYNAMIC_REFRACTION"),this.fDefineSet(t.dispersion,"LIT_DISPERSION"),this.fDefineSet(t.useHeights,"LIT_HEIGHTS"),this.fDefineSet(t.opacityFadesSpecular,"LIT_OPACITY_FADES_SPECULAR"),this.fDefineSet(t.alphaToCoverage,"LIT_ALPHA_TO_COVERAGE"),this.fDefineSet(t.alphaTest,"LIT_ALPHA_TEST"),this.fDefineSet(t.useMsdf,"LIT_MSDF"),this.fDefineSet(t.ssao,"LIT_SSAO"),this.fDefineSet(t.useAo,"LIT_AO"),this.fDefineSet(t.occludeDirect,"LIT_OCCLUDE_DIRECT"),this.fDefineSet(t.msdfTextAttribute,"LIT_MSDF_TEXT_ATTRIBUTE"),this.fDefineSet(t.diffuseMapEnabled,"LIT_DIFFUSE_MAP"),this.fDefineSet(t.shadowCatcher,"LIT_SHADOW_CATCHER"),this.fDefineSet(true,"LIT_FRESNEL_MODEL",oa[t.fresnelModel]),this.fDefineSet(true,"LIT_NONE_SLICE_MODE",ow[t.nineSlicedMode]),this.fDefineSet(true,"LIT_BLEND_TYPE",oi[t.blendType]),this.fDefineSet(true,"LIT_CUBEMAP_PROJECTION",oh[t.cubeMapProjection]),this.fDefineSet(true,"LIT_OCCLUDE_SPECULAR",op[t.occludeSpecular]),this.fDefineSet(true,"LIT_REFLECTION_SOURCE",oS[t.reflectionSource]),this.fDefineSet(true,"LIT_AMBIENT_SOURCE",oE[t.ambientSource]),this.fDefineSet(true,"{lightingUv}",null!=e?e:""),this.fDefineSet(true,"{reflectionDecode}",h8.decodeFunc(t.reflectionEncoding)),this.fDefineSet(true,"{reflectionCubemapDecode}",h8.decodeFunc(t.reflectionCubemapEncoding)),this.fDefineSet(true,"{ambientDecode}",h8.decodeFunc(t.ambientEncoding)),this._setupLightingDefines(n,t.clusteredLightingEnabled);},t.prepareShadowPass=function(){var e=this.options,t=this.shaderPassInfo.lightType,n=this.shaderPassInfo.shadowType,i=oc.get(n),r=0===t||!i.vsm&&2===t;this.fDefineSet(r,"PERSPECTIVE_DEPTH"),this.fDefineSet(true,"LIGHT_TYPE",""+oo[t]),this.fDefineSet(true,"SHADOW_TYPE",""+i.name),this.fDefineSet(e.alphaTest,"LIT_ALPHA_TEST");},t.generateFragmentShader=function(e,t,n){var i=this.options;this.includes.set("frontendDeclPS",null!=e?e:""),this.includes.set("frontendCodePS",null!=t?t:""),3===i.pass||1===i.pass||(this.shadowPass?this.prepareShadowPass():this.prepareForwardPass(n)),this.fshader='\n #include "litMainPS"\n ';},e}(),f9={generateKey:function(e){return "lit"+Object.keys(e).sort().map(function(t){if("shaderChunks"===t){var n,i;return null!=(i=null==(n=e.shaderChunks)?void 0:n.key)?i:""}return "lights"===t?f9.generateLightsKey(e):t+e[t]}).join("\n")},generateLightsKey:function(e){return "lights:"+e.lights.map(function(t){return e.clusteredLightingEnabled&&0!==t._type?"":""+t.key+","}).join("")}};function f7(e,t){return (f7=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var de=[0,1,2,3,4,5,6,7],dt=new(function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(){return e.apply(this,arguments)||this}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&f7(t,e);var n=t.prototype;return n.generateKey=function(e){var t,n,i=oG.definesHash(e.defines),r=n4(null!=(t=e.shaderChunkGLSL)?t:""),s=n4(null!=(n=e.shaderChunkWGSL)?n:""),a=f9.generateKey(e.litOptions);return "lit_"+i+"_"+de.map(function(t,n){return e.usedUvs[n]?"1":"0"}).join("")+"_"+r+"_"+s+"_"+a},n.createShaderDefinition=function(e,t){var n=!!t.shaderChunkWGSL,i=new f6(e,t.litOptions,n),r={name:"LitShader",shaderLanguage:i.shaderLanguage,tag:i.shaderPassInfo.isForward?1:void 0},s=t.usedUvs||[true];i.generateVertexShader(s,s,[]),i.generateFragmentShader("",i.shaderLanguage===na?t.shaderChunkWGSL:t.shaderChunkGLSL,"vUv0");var a=o3.merge(i.chunks,i.includes),o=i.vDefines;t.defines.forEach(function(e,t){return o.set(t,e)});var l=i.fDefines;return t.defines.forEach(function(e,t){return l.set(t,e)}),r.attributes=i.attributes,r.vertexCode=i.vshader,r.vertexIncludes=a,r.vertexDefines=o,r.fragmentCode=i.fshader,r.fragmentIncludes=a,r.fragmentDefines=l,rQ.createDefinition(e,r)},t}(oG));function dn(e,t){return (dn=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var di=new function(){this.litOptions=new f2;},dr=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(){var t;return t=e.apply(this,arguments)||this,t.usedUvs=[true],t.shaderChunkGLSL=null,t.shaderChunkWGSL=null,t.useLighting=true,t.useFog=true,t.useTonemap=true,t.useSkybox=true,t.ambientSH=null,t.pixelSnap=false,t.nineSlicedMode=null,t.twoSidedLighting=false,t.occludeDirect=false,t.occludeSpecular=1,t.occludeSpecularIntensity=1,t.opacityFadesSpecular=true,t.opacityDither=oP,t.opacityShadowDither=oP,t.shadowCatcher=false,t.ggxSpecular=false,t.fresnelModel=2,t.dynamicRefraction=false,t.hasAo=false,t.hasSpecular=false,t.hasSpecularityFactor=false,t.hasLighting=false,t.hasHeights=false,t.hasNormals=false,t.hasSheen=false,t.hasRefraction=false,t.hasIrridescence=false,t.hasMetalness=false,t.hasClearCoat=false,t.hasClearCoatNormals=false,t}return t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&dn(t,e),t.prototype.getShaderVariant=function(e){di.usedUvs=this.usedUvs.slice(),di.shaderChunkGLSL=this.shaderChunkGLSL,di.shaderChunkWGSL=this.shaderChunkWGSL,di.defines=o6.getCoreDefines(this,e),f3.update(di.litOptions,this,e.scene,e.cameraShaderParams,e.objDefs,e.pass,e.sortedLights);var t=new oU(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),n=oz(e.device);return n.register("lit",dt),n.getProgram("lit",di,t,this.userId)},t}(uz),ds=function(){var e;function t(){this.defines=new Map,this.forceUv1=false,this.specularTint=false,this.metalnessTint=false,this.glossTint=false,this.emissiveEncoding="linear",this.lightMapEncoding="linear",this.packedNormal=false,this.normalDetailPackedNormal=false,this.clearCoatPackedNormal=false,this.glossInvert=false,this.sheenGlossInvert=false,this.clearCoatGlossInvert=false,this.useAO=false,this.litOptions=new f2;}return e=[{key:"pass",get:function(){return this.litOptions.pass}}],function(e,t){for(var n=0;n0){if(n[e]t.length){for(var i=t,r=i.charAt(i.length-1),s=n[e]-i.length,a=0;a0,e.litOptions.blendType=n.blendType,e.litOptions.screenSpace=i&&(256&i)!=0,e.litOptions.skin=i&&(2&i)!=0,e.litOptions.batch=i&&(16384&i)!=0,e.litOptions.useInstancing=i&&(32&i)!=0,e.litOptions.useMorphPosition=i&&(1024&i)!=0,e.litOptions.useMorphNormal=i&&(2048&i)!=0,e.litOptions.useMorphTextureBasedInt=i&&(8192&i)!=0,e.litOptions.nineSlicedMode=n.nineSlicedMode||0,t.clusteredLightingEnabled&&n.useLighting?(e.litOptions.clusteredLightingEnabled=true,e.litOptions.clusteredLightingCookiesEnabled=t.lighting.cookiesEnabled,e.litOptions.clusteredLightingShadowsEnabled=t.lighting.shadowsEnabled,e.litOptions.clusteredLightingShadowType=t.lighting.shadowType,e.litOptions.clusteredLightingAreaLightsEnabled=t.lighting.areaLightsEnabled):(e.litOptions.clusteredLightingEnabled=false,e.litOptions.clusteredLightingCookiesEnabled=false,e.litOptions.clusteredLightingShadowsEnabled=false,e.litOptions.clusteredLightingAreaLightsEnabled=false);},t._updateUVOptions=function(e,t,n,i,r){var s=false,a=false,o=false;n&&(s=(4&n)!=0,a=(8&n)!=0,o=(16&n)!=0),e.litOptions.vertexColors=false,this._mapXForms=[];var l={};for(var u in dl)this._updateTexOptions(e,t,u,s,a,o,i,l);this._mapXForms=null,e.litOptions.ssao=null==r?void 0:r.ssaoEnabled,e.useAO=e.litOptions.ssao,e.litOptions.lightMapEnabled=e.lightMap,e.litOptions.dirLightMapEnabled=e.dirLightMap,e.litOptions.useHeights=e.heightMap,e.litOptions.useNormals=e.normalMap,e.litOptions.useClearCoatNormals=e.clearCoatNormalMap,e.litOptions.useAo=e.aoMap||e.aoVertexColor||e.litOptions.ssao,e.litOptions.diffuseMapEnabled=e.diffuseMap;},t._updateTexOptions=function(e,t,n,i,r,s,a,o){var l="opacity"===n;if(!a||l){var u=""+n+"Map",c=""+n+"VertexColor",h=""+n+"VertexColorChannel",f=""+u+"Channel",d=""+u+"Transform",p=""+u+"Uv",m=""+u+"Identifier";if("light"!==n&&(e[u]=false,e[m]=void 0,e[f]="",e[d]=0,e[p]=0),e[c]=false,e[h]="",l&&3===t.blendType&&0===t.alphaTest&&!t.alphaToCoverage&&t.opacityDither===oP)return;if("height"!==n&&t[c]&&s&&(e[c]=t[c],e[h]=t[h],e.litOptions.vertexColors=true),t[u]){var _=true;if(0!==t[p]||i||(_=false),1!==t[p]||r||(_=false),_){var v=t[u].id,g=o[v];void 0===g&&(o[v]=n,g=n),e[u]=!!t[u],e[m]=g,e[d]=this._getMapTransformID(t.getUniform(d),t[p]),e[f]=t[f],e[p]=t[p];}}}},t._updateMinOptions=function(e,t,n){var i=1===n;e.litOptions.opacityShadowDither=i?t.opacityDither:t.opacityShadowDither,e.litOptions.linearDepth=i,e.litOptions.lights=[];},t._updateMaterialOptions=function(e,t,n){var i,r,s,a,o,l,u,c,h=!!(t.useMetalness||t.specularMap||t.sphereMap||t.cubeMap||0!==(r=t.specular).r||0!==r.g||0!==r.b||t.specularityFactor>0&&t.useMetalness||t.enableGGXSpecular||t.clearCoat>0),f=!t.useMetalness||t.useMetalnessSpecularColor,d=h&&(t.specularTint||!t.specularMap&&!t.specularVertexColor)&&(1!==(i=t.specular).r||1!==i.g||1!==i.b),p=h&&t.useMetalnessSpecularColor&&(t.specularityFactorTint||t.specularityFactor<1&&!t.specularityFactorMap),m=function(e){return !!e&&(10===e.format||e.type===t6)},_=function(e,t){return 1e-4>Math.abs(e-t)};e.specularTint=d,e.specularityFactorTint=p,e.metalnessTint=t.useMetalness&&t.metalness<1,e.glossTint=true,e.diffuseEncoding=null==(s=t.diffuseMap)?void 0:s.encoding,e.diffuseDetailEncoding=null==(a=t.diffuseDetailMap)?void 0:a.encoding,e.emissiveEncoding=null==(o=t.emissiveMap)?void 0:o.encoding,e.lightMapEncoding=null==(l=t.lightMap)?void 0:l.encoding,e.packedNormal=m(t.normalMap),e.refractionTint=_(t.refraction,1),e.refractionIndexTint=_(t.refractionIndex,1/1.5),e.thicknessTint=t.useDynamicRefraction&&1!==t.thickness,e.specularEncoding=null==(u=t.specularMap)?void 0:u.encoding,e.sheenEncoding=null==(c=t.sheenMap)?void 0:c.encoding,e.aoMapUv=t.aoUvSet,e.aoDetail=!!t.aoDetailMap,e.diffuseDetail=!!t.diffuseDetailMap,e.normalDetail=!!t.normalMap,e.normalDetailPackedNormal=m(t.normalDetailMap),e.diffuseDetailMode=t.diffuseDetailMode,e.aoDetailMode=t.aoDetailMode,e.clearCoatTint=_(t.clearCoat,1),e.clearCoatGloss=!!t.clearCoatGloss,e.clearCoatGlossTint=1!==t.clearCoatGloss,e.clearCoatPackedNormal=m(t.clearCoatNormalMap),e.iorTint=_(t.refractionIndex,1/1.5),n.forcePassThroughSpecular&&(e.specularEncoding="linear",e.sheenEncoding="linear"),e.iridescenceTint=1!==t.iridescence,e.glossInvert=t.glossInvert,e.sheenGlossInvert=t.sheenGlossInvert,e.clearCoatGlossInvert=t.clearCoatGlossInvert,e.useSpecularColor=f,e.litOptions.separateAmbient=false,e.litOptions.pixelSnap=t.pixelSnap,e.litOptions.ambientSH=!!t.ambientSH,e.litOptions.twoSidedLighting=t.twoSidedLighting,e.litOptions.occludeSpecular=t.occludeSpecular,e.litOptions.occludeSpecularFloat=1!==t.occludeSpecularIntensity,e.litOptions.useMsdf=!!t.msdfMap,e.litOptions.msdfTextAttribute=!!t.msdfTextAttribute,e.litOptions.alphaToCoverage=t.alphaToCoverage,e.litOptions.opacityFadesSpecular=t.opacityFadesSpecular,e.litOptions.opacityDither=t.opacityDither,e.litOptions.cubeMapProjection=t.cubeMapProjection,e.litOptions.occludeDirect=t.occludeDirect,e.litOptions.useSpecular=h,e.litOptions.useSpecularityFactor=(p||!!t.specularityFactorMap)&&t.useMetalnessSpecularColor,e.litOptions.enableGGXSpecular=t.enableGGXSpecular,e.litOptions.fresnelModel=t.fresnelModel,e.litOptions.useRefraction=(t.refraction||!!t.refractionMap)&&(t.useDynamicRefraction||e.litOptions.reflectionSource!==om),e.litOptions.useClearCoat=!!t.clearCoat,e.litOptions.useSheen=t.useSheen,e.litOptions.useIridescence=t.useIridescence&&0!==t.iridescence,e.litOptions.useMetalness=t.useMetalness,e.litOptions.useDynamicRefraction=t.useDynamicRefraction,e.litOptions.dispersion=t.dispersion>0,e.litOptions.shadowCatcher=t.shadowCatcher;},t._updateEnvOptions=function(e,t,n,i){e.litOptions.fog=t.useFog?i.fog:or,e.litOptions.gamma=i.shaderOutputGamma,e.litOptions.toneMap=t.useTonemap?i.toneMapping:6;var r=false;if(t.envAtlas&&t.cubeMap?(e.litOptions.reflectionSource=ov,e.litOptions.reflectionEncoding=t.envAtlas.encoding,e.litOptions.reflectionCubemapEncoding=t.cubeMap.encoding):t.envAtlas?(e.litOptions.reflectionSource=o_,e.litOptions.reflectionEncoding=t.envAtlas.encoding):t.cubeMap?(e.litOptions.reflectionSource=og,e.litOptions.reflectionEncoding=t.cubeMap.encoding):t.sphereMap?(e.litOptions.reflectionSource=oy,e.litOptions.reflectionEncoding=t.sphereMap.encoding):t.useSkybox&&n.envAtlas&&n.skybox?(e.litOptions.reflectionSource=ov,e.litOptions.reflectionEncoding=n.envAtlas.encoding,e.litOptions.reflectionCubemapEncoding=n.skybox.encoding,r=true):t.useSkybox&&n.envAtlas?(e.litOptions.reflectionSource=o_,e.litOptions.reflectionEncoding=n.envAtlas.encoding,r=true):t.useSkybox&&n.skybox?(e.litOptions.reflectionSource=og,e.litOptions.reflectionEncoding=n.skybox.encoding,r=true):(e.litOptions.reflectionSource=om,e.litOptions.reflectionEncoding=null),t.ambientSH)e.litOptions.ambientSource=ox,e.litOptions.ambientEncoding=null;else {var s=t.envAtlas||(t.useSkybox&&n.envAtlas?n.envAtlas:null);s&&!t.sphereMap?(e.litOptions.ambientSource=ob,e.litOptions.ambientEncoding=s.encoding):(e.litOptions.ambientSource=oT,e.litOptions.ambientEncoding=null);}e.litOptions.skyboxIntensity=r,e.litOptions.useCubeMapRotation=r&&n._skyboxRotationShaderInclude;},t._updateLightOptions=function(e,t,n,i,r){if(e.lightMap=false,e.lightMapChannel="",e.lightMapUv=0,e.lightMapTransform=0,e.litOptions.lightMapWithoutAmbient=false,e.dirLightMap=false,i&&(e.litOptions.noShadow=(1&i)!=0,(64&i)!=0&&(e.lightMapEncoding=7===t.lightmapPixelFormat?"rgbm":"linear",e.lightMap=true,e.lightMapChannel="rgb",e.lightMapUv=1,e.lightMapTransform=0,e.litOptions.lightMapWithoutAmbient=!n.lightMap,(128&i)!=0&&(e.dirLightMap=true),(4096&i)!=0&&(e.litOptions.lightMapWithoutAmbient=false))),n.useLighting){var s=[],a=i?i>>16:1;e.litOptions.lightMaskDynamic=!!(1&a),r&&(f3.collectLights(0,r[0],s,a),t.clusteredLightingEnabled||(f3.collectLights(1,r[1],s,a),f3.collectLights(2,r[2],s,a))),e.litOptions.lights=s;}else e.litOptions.lights=[];0!==e.litOptions.lights.length||t.clusteredLightingEnabled||(e.litOptions.noShadow=true);},t._getMapTransformID=function(e,t){if(!e)return 0;var n=this._mapXForms[t];n||(n=[],this._mapXForms[t]=n);for(var i=0;i0&&(this._setParameter("material_clearCoat",this.clearCoat),this._setParameter("material_clearCoatGloss",this.clearCoatGloss),this._setParameter("material_clearCoatBumpiness",this.clearCoatBumpiness)),this._setParameter("material_gloss",this.gloss),this._setParameter("material_emissive",r("emissive")),this._setParameter("material_emissiveIntensity",this.emissiveIntensity),this.refraction>0&&this._setParameter("material_refraction",this.refraction),this.dispersion>0&&this._setParameter("material_dispersion",this.dispersion),this.useDynamicRefraction&&(this._setParameter("material_thickness",this.thickness),this._setParameter("material_attenuation",r("attenuation")),this._setParameter("material_invAttenuationDistance",0===this.attenuationDistance?0:1/this.attenuationDistance)),this.useIridescence&&(this._setParameter("material_iridescence",this.iridescence),this._setParameter("material_iridescenceRefractionIndex",this.iridescenceRefractionIndex),this._setParameter("material_iridescenceThicknessMin",this.iridescenceThicknessMin),this._setParameter("material_iridescenceThicknessMax",this.iridescenceThicknessMax)),this._setParameter("material_opacity",this.opacity),false===this.opacityFadesSpecular&&this._setParameter("material_alphaFade",this.alphaFade),this.occludeSpecular&&this._setParameter("material_occludeSpecularIntensity",this.occludeSpecularIntensity),1===this.cubeMapProjection&&this._setParameter(r("cubeMapProjectionBox")),dl)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",r("heightMapFactor")),this.envAtlas&&this.cubeMap?(this._setParameter("texture_envAtlas",this.envAtlas),this._setParameter("texture_cubeMap",this.cubeMap)):this.envAtlas?this._setParameter("texture_envAtlas",this.envAtlas):this.cubeMap?this._setParameter("texture_cubeMap",this.cubeMap):this.sphereMap&&this._setParameter("texture_sphereMap",this.sphereMap),this._setParameter("material_reflectivity",this.reflectivity),this._processParameters("_activeParams"),e.prototype.updateUniforms.call(this,t,n);},n.updateEnvUniforms=function(e,t){!(this.envAtlas||this.cubeMap||this.sphereMap)&&this.useSkybox&&(t.envAtlas&&t.skybox?(this._setParameter("texture_envAtlas",t.envAtlas),this._setParameter("texture_cubeMap",t.skybox)):t.envAtlas?this._setParameter("texture_envAtlas",t.envAtlas):t.skybox&&this._setParameter("texture_cubeMap",t.skybox)),this._processParameters("_activeLightingParams");},n.getShaderVariant=function(e){var t=e.device,n=e.scene,i=e.pass,r=e.objDefs,s=e.sortedLights,a=e.cameraShaderParams;this.updateEnvUniforms(t,n);var o=oj.get(t).getByIndex(i),l=3===i||1===i||o.isShadow,u=l?dc.optionsContextMin:dc.optionsContext;u.defines=o6.getCoreDefines(this,e),l?this.shaderOptBuilder.updateMinRef(u,n,this,r,i,s):this.shaderOptBuilder.updateRef(u,n,a,this,r,i,s),this.useFog||u.defines.set("FOG","NONE"),u.defines.set("TONEMAP",od[u.litOptions.toneMap]),this.onUpdateShader&&(u=this.onUpdateShader(u));var c=new oU(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),h=oz(t);h.register("standard",dc);var f=h.getProgram("standard",u,c,this.userId);return this._dirtyShader=false,f},n.destroy=function(){for(var t in this._assetReferences)this._assetReferences[t]._unbind();this._assetReferences=null,e.prototype.destroy.call(this);},t}(uz);dA.TEXTURE_PARAMETERS=d_,dA.CUBEMAP_PARAMETERS=dg;var dC=function(e,t){dT[e]=t;},dP=function(e,t,n,i){Object.defineProperty(dA.prototype,e,{get:i||function(){return this["_"+e]},set:n}),db[e]={value:t};},dI=function(e){var t="_"+e.name,n=e.dirtyShaderFunc||function(){return true};dP(e.name,function(){return e.defaultValue},function(e){var i=this[t];i!==e&&(this._dirtyShader=this._dirtyShader||n(i,e),this[t]=e);},e.getterFunc);},dL=function(e){var t="_"+e.name,n=e.dirtyShaderFunc||function(){return true};dP(e.name,function(){return e.defaultValue.clone()},function(e){var i=this[t];i.equals(e)||(this._dirtyShader=this._dirtyShader||n(i,e),this[t]=i.copy(e));},e.getterFunc);},dD=function(e){return e.defaultValue&&e.defaultValue.clone?dL(e):dI(e)};function dR(e,t,n,i){ void 0===t&&(t="rgb"),void 0===n&&(n=true),void 0===i&&(i=0),dl[e]=t.length||-1,dD({name:""+e+"Map",defaultValue:null,dirtyShaderFunc:function(e,t){return !!e!=!!t||e&&(e.type!==t.type||e.format!==t.format)}}),dD({name:""+e+"MapTiling",defaultValue:new eX(1,1)}),dD({name:""+e+"MapOffset",defaultValue:new eX(0,0)}),dD({name:""+e+"MapRotation",defaultValue:0}),dD({name:""+e+"MapUv",defaultValue:i}),t&&(dD({name:""+e+"MapChannel",defaultValue:t}),n&&(dD({name:""+e+"VertexColor",defaultValue:false}),dD({name:""+e+"VertexColorChannel",defaultValue:t})));var r=""+e+"MapTiling",s=""+e+"MapOffset",a=""+e+"MapRotation",o=""+e+"MapTransform";dC(o,function(e,t,n){var i=e[r],l=e[s],u=e[a];if(1===i.x&&1===i.y&&0===l.x&&0===l.y&&0===u)return null;var c=e._allocUniform(o,function(){return [{name:"texture_"+o+"0",value:new Float32Array(3)},{name:"texture_"+o+"1",value:new Float32Array(3)}]}),h=Math.cos(u*ek.DEG_TO_RAD),f=Math.sin(u*ek.DEG_TO_RAD),d=c[0].value;d[0]=h*i.x,d[1]=-f*i.y,d[2]=l.x;var p=c[1].value;return p[0]=f*i.x,p[1]=h*i.y,p[2]=1-i.y-l.y,c});}function dM(e,t){dD({name:e,defaultValue:t,getterFunc:function(){return this._dirtyShader=true,this["_"+e]}}),dC(e,function(t,n,i){var r=t._allocUniform(e,function(){return new Float32Array(3)}),s=t[e];return dw.linear(s),r[0]=dw.r,r[1]=dw.g,r[2]=dw.b,r});}function dO(e,t,n){dD({name:e,defaultValue:t,dirtyShaderFunc:function(e,t){return (0===e||1===e)!=(0===t||1===t)}}),dC(e,n);}function dk(e,t){dD({name:e,defaultValue:null,dirtyShaderFunc:function(e,t){return !!e==!!t}}),dC(e,t);}function dN(e,t){dD({name:e,defaultValue:t});}function dF(e,t){return (dF=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}dM("ambient",new eN(1,1,1)),dM("diffuse",new eN(1,1,1)),dM("specular",new eN(0,0,0)),dM("emissive",new eN(0,0,0)),dM("sheen",new eN(1,1,1)),dM("attenuation",new eN(1,1,1)),dO("emissiveIntensity",1),dO("specularityFactor",1),dO("sheenGloss",0),dO("gloss",.25),dO("aoIntensity",1),dO("heightMapFactor",1,function(e,t,n){return .025*e.heightMapFactor}),dO("opacity",1),dO("alphaFade",1),dO("alphaTest",0),dO("bumpiness",1),dO("normalDetailMapBumpiness",1),dO("reflectivity",1),dO("occludeSpecularIntensity",1),dO("refraction",0),dO("refractionIndex",1/1.5),dO("dispersion",0),dO("thickness",0),dO("attenuationDistance",0),dO("metalness",1),dO("anisotropyIntensity",0),dO("anisotropyRotation",0),dO("clearCoat",0),dO("clearCoatGloss",1),dO("clearCoatBumpiness",1),dO("aoUvSet",0,null),dO("iridescence",0),dO("iridescenceRefractionIndex",1/1.5),dO("iridescenceThicknessMin",0),dO("iridescenceThicknessMax",0),dk("ambientSH"),dk("cubeMapProjectionBox",function(e,t,n){var i=e._allocUniform("cubeMapProjectionBox",function(){return [{name:"envBoxMin",value:new Float32Array(3)},{name:"envBoxMax",value:new Float32Array(3)}]}),r=e.cubeMapProjectionBox.getMin(),s=i[0].value;s[0]=r.x,s[1]=r.y,s[2]=r.z;var a=e.cubeMapProjectionBox.getMax(),o=i[1].value;return o[0]=a.x,o[1]=a.y,o[2]=a.z,i}),dN("specularTint",false),dN("specularityFactorTint",false),dN("useMetalness",false),dN("useMetalnessSpecularColor",false),dN("useSheen",false),dN("enableGGXSpecular",false),dN("occludeDirect",false),dN("opacityFadesSpecular",true),dN("occludeSpecular",1),dN("fresnelModel",2),dN("useDynamicRefraction",false),dN("cubeMapProjection",0),dN("useFog",true),dN("useLighting",true),dN("useTonemap",true),dN("useSkybox",true),dN("forceUv1",false),dN("pixelSnap",false),dN("twoSidedLighting",false),dN("nineSlicedMode",void 0),dN("msdfTextAttribute",false),dN("useIridescence",false),dN("glossInvert",false),dN("sheenGlossInvert",false),dN("clearCoatGlossInvert",false),dN("opacityDither",oP),dN("opacityShadowDither",oP),dN("shadowCatcher",false),dR("diffuse"),dR("specular"),dR("emissive"),dR("thickness","g"),dR("specularityFactor","g"),dR("normal",""),dR("metalness","g"),dR("gloss","g"),dR("opacity","a"),dR("refraction","g"),dR("height","g",false),dR("ao","g"),dR("light","rgb",true,1),dR("msdf",""),dR("diffuseDetail","rgb",false),dR("normalDetail",""),dR("aoDetail","g",false),dR("clearCoat","g"),dR("clearCoatGloss","g"),dR("clearCoatNormal",""),dR("sheen","rgb"),dR("sheenGloss","g"),dR("iridescence","g"),dR("iridescenceThickness","g"),dR("anisotropy",""),dN("diffuseDetailMode","mul"),dN("aoDetailMode","mul"),dk("cubeMap"),dk("sphereMap"),dk("envAtlas"),s=[null,null,null,null,null,null],dP("prefilteredCubemaps",function(){return s.slice()},function(e){var t=this._prefilteredCubemaps;e=e||[];for(var n=false,i=true,r=0;r<6;++r){var s=e[r]||null;t[r]!==s&&(t[r]=s,n=true),i=i&&!!t[r];}n&&(i?this.envAtlas=fk.generatePrefilteredAtlas(t,{target:this.envAtlas}):this.envAtlas&&(this.envAtlas.destroy(),this.envAtlas=null),this._dirtyShader=true);},function(){return this._prefilteredCubemaps});var dB=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t,n,i,r,s,a){var o,l=e.call(this)||this,u=new eW,c=new eW,h=new eW,f=new eW,d=new eW,p=new eW,m=[],_=[],v=[],g=[],y=[];if(i>0)for(var S=0;S<=r;S++)for(var x=0;x<=s;x++){var b=x/s*2*Math.PI-Math.PI,T=Math.sin(b),E=Math.cos(b);d.set(T*t,-i/2,E*t),f.set(T*n,i/2,E*n),u.lerp(d,f,S/r),c.sub2(f,d).normalize(),p.set(E,0,-T),h.cross(p,c).normalize(),m.push(u.x,u.y,u.z),_.push(h.x,h.y,h.z);var w=x/s,A=S/r;v.push(w,1-A);var C=A;if(A=w,w=.875*(w=C)+.0625,A=.875*A+.0625,w/=3,g.push(w,1-A),S0)for(var ec=0;ec1&&y.push(o,o+ec,o+ec-1);}if(o+=s,n>0)for(var ev=0;ev1&&y.push(o,o+ev-1,o+ev);}}return l.positions=m,l.normals=_,l.uvs=v,l.uvs1=g,l.indices=y,l}return t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&dF(t,e),t}(h7);function dU(e,t){return (dU=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var dV=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){ void 0===t&&(t={});var n,i,r,s,a,o=null!=(i=t.radius)?i:.3,l=null!=(r=t.height)?r:1,u=null!=(s=t.heightSegments)?s:1,c=null!=(a=t.sides)?a:20;return n=e.call(this,o,o,l-2*o,u,c,true)||this,t.calculateTangents&&(n.tangents=h9(n.positions,n.normals,n.uvs,n.indices)),n}return t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&dU(t,e),t}(dB);function dz(e,t){return (dz=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var dG=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){ void 0===t&&(t={});var n,i,r,s,a,o,l=null!=(i=t.baseRadius)?i:.5,u=null!=(r=t.peakRadius)?r:0,c=null!=(s=t.height)?s:1,h=null!=(a=t.heightSegments)?a:5,f=null!=(o=t.capSegments)?o:18;return n=e.call(this,l,u,c,h,f,false)||this,t.calculateTangents&&(n.tangents=h9(n.positions,n.normals,n.uvs,n.indices)),n}return t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&dz(t,e),t}(dB);function dH(e,t){return (dH=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var dW=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){ void 0===t&&(t={});var n,i,r,s,a,o=null!=(i=t.radius)?i:.5,l=null!=(r=t.height)?r:1,u=null!=(s=t.heightSegments)?s:5,c=null!=(a=t.capSegments)?a:20;return n=e.call(this,o,o,l,u,c,false)||this,t.calculateTangents&&(n.tangents=h9(n.positions,n.normals,n.uvs,n.indices)),n}return t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&dH(t,e),t}(dB);function dj(e,t){return (dj=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var dX=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){ void 0===t&&(t={});for(var n,i,r,s=e.call(this)||this,a=null!=(n=t.halfExtents)?n:new eX(.5,.5),o=null!=(i=t.widthSegments)?i:5,l=null!=(r=t.lengthSegments)?r:5,u=[],c=[],h=[],f=[],d=0,p=0;p<=o;p++)for(var m=0;m<=l;m++){var _=-a.x+2*a.x*p/o,v=-(-a.y+2*a.y*m/l),g=p/o,y=m/l;u.push(_,0,v),c.push(0,1,0),h.push(g,1-y),p0)return 1/(1+Math.exp(-e));var t=Math.exp(e);return t/(1+t)};this.read=function(e){t&&(t.x=s[e],t.y=a[e],t.z=o[e]),n&&n.set(l[e],u[e],c[e],h[e]),i&&i.set(Math.exp(f[e]),Math.exp(d[e]),Math.exp(p[e])),r&&r.set(.5+.28209479177387814*m[e],.5+.28209479177387814*_[e],.5+.28209479177387814*v[e],y(g[e]));};},d2=function(e,t,n){dQ.set(n.x,n.y,n.z,n.w).normalize(),e.setTRS(t,dQ,eW.ONE);},d3=function(){function e(e,t){ void 0===t&&(t=[]),this.elements=e,this.numSplats=this.getElement("vertex").count,this.comments=t;}var t,n=e.prototype;return n.getProp=function(e,t){var n,i;return void 0===t&&(t="vertex"),null==(i=this.getElement(t))||null==(n=i.properties.find(function(t){return t.name===e}))?void 0:n.storage},n.getElement=function(e){return this.elements.find(function(t){return t.name===e})},n.addProp=function(e,t){this.getElement("vertex").properties.push({type:"float",name:e,storage:t,byteSize:4});},n.createIter=function(e,t,n,i){return new d1(this,e,t,n,i)},n.calcAabb=function(e,t){for(var n,i,r,s,a,o,l=true,u=this.getProp("x"),c=this.getProp("y"),h=this.getProp("z"),f=this.getProp("scale_0"),d=this.getProp("scale_1"),p=this.getProp("scale_2"),m=0;mn&&(n=e[i]);return {min:t,max:n}},t=this.getProp("x"),n=this.getProp("y"),i=this.getProp("z"),r=e(t),s=r.min,a=r.max,o=e(n),l=o.min,u=o.max,c=e(i),h=c.min,f=c.max,d=s===a?0:1024/(a-s),p=l===u?0:1024/(u-l),m=h===f?0:1024/(f-h),_=new Map,v=0;v0&&(i.sh1to3Texture=i.createTexture("splatSH_1to3",49,s),i.shBands>1&&(i.sh4to7Texture=i.createTexture("splatSH_4to7",49,s),i.shBands>2?(i.sh8to11Texture=i.createTexture("splatSH_8to11",49,s),i.sh12to15Texture=i.createTexture("splatSH_12to15",49,s)):i.sh8to11Texture=i.createTexture("splatSH_8to11",37,s)),i.updateSHData(n)),i}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&d8(t,e);var n=t.prototype;return n.destroy=function(){var t,n,i,r,s,a,o;null==(t=this.colorTexture)||t.destroy(),null==(n=this.transformATexture)||n.destroy(),null==(i=this.transformBTexture)||i.destroy(),null==(r=this.sh1to3Texture)||r.destroy(),null==(s=this.sh4to7Texture)||s.destroy(),null==(a=this.sh8to11Texture)||a.destroy(),null==(o=this.sh12to15Texture)||o.destroy(),e.prototype.destroy.call(this);},n.configureMaterial=function(e){e.setParameter("splatColor",this.colorTexture),e.setParameter("transformA",this.transformATexture),e.setParameter("transformB",this.transformBTexture),e.setDefine("SH_BANDS",this.shBands),this.sh1to3Texture&&e.setParameter("splatSH_1to3",this.sh1to3Texture),this.sh4to7Texture&&e.setParameter("splatSH_4to7",this.sh4to7Texture),this.sh8to11Texture&&e.setParameter("splatSH_8to11",this.sh8to11Texture),this.sh12to15Texture&&e.setParameter("splatSH_12to15",this.sh12to15Texture);},n.evalTextureSize=function(e){var t=Math.ceil(Math.sqrt(e)),n=Math.ceil(e/t);return new eX(t,n)},n.updateColorData=function(e){var t=this.colorTexture;if(t){for(var n=eG.float2Half,i=t.lock(),r=e.getProp("f_dc_0"),s=e.getProp("f_dc_1"),a=e.getProp("f_dc_2"),o=e.getProp("opacity"),l=0;l1&&(l[4*_+0]=m[9]<<21|m[10]<<11|m[11],l[4*_+1]=m[12]<<21|m[13]<<11|m[14],l[4*_+2]=m[15]<<21|m[16]<<11|m[17],l[4*_+3]=m[18]<<21|m[19]<<11|m[20],this.shBands>2?(u[4*_+0]=m[21]<<21|m[22]<<11|m[23],u[4*_+1]=m[24]<<21|m[25]<<11|m[26],u[4*_+2]=m[27]<<21|m[28]<<11|m[29],u[4*_+3]=m[30]<<21|m[31]<<11|m[32],c[4*_+0]=m[33]<<21|m[34]<<11|m[35],c[4*_+1]=m[36]<<21|m[37]<<11|m[38],c[4*_+2]=m[39]<<21|m[40]<<11|m[41],c[4*_+3]=m[42]<<21|m[43]<<11|m[44]):u[_]=m[21]<<21|m[22]<<11|m[23]);}}this.sh1to3Texture.unlock(),null==(r=this.sh4to7Texture)||r.unlock(),null==(s=this.sh8to11Texture)||s.unlock(),null==(a=this.sh12to15Texture)||a.unlock();},t}(d5);function d7(e,t){return (d7=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function pe(){var e,t,n,i,r,s,a,o,l="undefined"!=typeof self&&self||require("node:worker_threads").parentPort,u=false,c={x:0,y:0,z:0},h={x:0,y:0,z:0},f={x:0,y:0,z:0},d={x:0,y:0,z:0},p=Array(32).fill(0),m=Array(32).fill(0),_=Array(32).fill(0),v=function(e,t,n){for(;e<=t;){var i=t+e>>1,r=n(i);if(r>0)e=i+1;else {if(!(r<0))return i;t=i-1;}}return ~e},g=function(){if(e&&t&&0!==t.length&&r&&s){var g,y,S=r.x,x=r.y,b=r.z,T=s.x,E=s.y,w=s.z;if(!(!u&&.001>Math.abs(S-c.x)&&.001>Math.abs(x-c.y)&&.001>Math.abs(b-c.z)&&.001>Math.abs(T-h.x)&&.001>Math.abs(E-h.y)&&.001>Math.abs(w-h.z))){u=false,c.x=S,c.y=x,c.z=b,h.x=T,h.y=E,h.z=w;for(var A,C=0;C<8;++C){var P=(1&C?f.x:d.x)*T+(2&C?f.y:d.y)*E+(4&C?f.z:d.z)*w;0===C?g=y=P:(g=Math.min(g,P),y=Math.max(y,P));}var I=t.length/3,L=Math.pow(2,Math.max(10,Math.min(20,Math.round(Math.log2(I/4)))))+1;(null==a?void 0:a.length)!==I&&(a=new Uint32Array(I)),o&&o.length===L?o.fill(0):o=new Uint32Array(L);var D=y-g;if(D<1e-6)for(var R=0;R>>0;for(var j=0;j<32;++j)m[j]=0===j?0:m[j-1]+_[j-1];for(var X=D/32,Y=0,q=0;q>>0,Q=m[Z]+_[Z]*(K-Z)>>>0;a[q]=Q,o[Q]++;}}for(var J=1;J=0?(A=v(0,I-1,function(e){return -en(e)}),Math.min(I,Math.abs(A))):I;if(i)for(var er=0;erd.x&&(d.x=_),v>d.y&&(d.y=v),y>d.z&&(d.z=y);}}else {var S,x,b,T,E,w,A,C=t.length/3,P=Math.ceil(C/256);n=new Float32Array(4*P),f.x=f.y=f.z=1/0,d.x=d.y=d.z=-1/0;for(var I=0;IE&&(E=M),Ow&&(w=O),kA&&(A=k),Md.x&&(d.x=M),Od.y&&(d.y=O),kd.z&&(d.z=k));}n[4*I+0]=(x+E)*.5,n[4*I+1]=(b+w)*.5,n[4*I+2]=(T+A)*.5,n[4*I+3]=.5*Math.sqrt(Math.pow(E-x,2)+Math.pow(w-b,2)+Math.pow(A-T,2));}}o.hasOwnProperty("mapping")&&(i=o.mapping?new Uint32Array(o.mapping):null,u=true),o.cameraPosition&&(r=o.cameraPosition),o.cameraDirection&&(s=o.cameraDirection),g();});}var pt=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(){var t=e.call(this)||this,n="("+pe.toString()+")()",i="node"===ef.environment;return i?t.worker=new Worker(n,{eval:true}):t.worker=new Worker(URL.createObjectURL(new Blob([n],{type:"application/javascript"}))),t.worker[i?"on":"addEventListener"]("message",function(e){var n,i=null!=(n=e.data)?n:e,r=i.order,s=t.orderTexture._levels[0].buffer;t.worker.postMessage({order:s},[s]),t.orderTexture._levels[0]=new Uint32Array(r),t.orderTexture.upload(),t.fire("updated",i.count);}),t}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&d7(t,e);var n=t.prototype;return n.destroy=function(){this.worker.terminate(),this.worker=null;},n.init=function(e,t,n){this.orderTexture=e,this.centers=t.slice();var i=this.orderTexture.lock({mode:1}).slice();this.orderTexture.unlock();for(var r=0;r0){var e=this.cameras[0];this.sort(e._node),this.cameras.length=0;}},t=[{key:"material",get:function(){return this._material},set:function(e){this._material!==e&&(this._material=e,this._material.setParameter("splatOrder",this.orderTexture),this.meshInstance&&(this.meshInstance.material=e));}}],function(e,t){for(var n=0;n0&&r[r.length-1])&&(6===u[0]||2===u[0])){s=0;continue}if(3===u[0]&&(!r||u[1]>r[0]&&u[1]>>8&255,b=g>>>8&65280|y>>>16&255,T=c*(65535-S)+d*S,E=h*(65535-x)+p*x,w=f*(65535-b)+m*b,A=T<0?-T:T,C=E<0?-E:E,P=w<0?-w:w;e[3*_]=(T<0?-1:1)*(Math.exp(A)-1),e[3*_+1]=(E<0?-1:1)*(Math.exp(C)-1),e[3*_+2]=(w<0?-1:1)*(Math.exp(P)-1);}},n.calcFocalPoint=function(e,t){e.set(0,0,0);},n.decompress=function(){var e=this;return pl(function(){var t,n,i,r,s,a,o,l,u,c,h,f,d,p,m,_,v,g,y,S,x,b,T,E,w,A,C,P,I,L,D,R,M,O,k;return pu(this,function(N){switch(N.label){case 0:return t=["x","y","z","f_dc_0","f_dc_1","f_dc_2","opacity","scale_0","scale_1","scale_2","rot_0","rot_1","rot_2","rot_3"],n=e.shBands,i=e.means_l,r=e.means_u,s=e.quats,a=e.scales,o=e.sh0,l=e.sh_labels,u=e.sh_centroids,c=i._levels,h=0,[4,pc(i)];case 1:return c[h]=N.sent(),f=r._levels,d=0,[4,pc(r)];case 2:return f[d]=N.sent(),p=s._levels,m=0,[4,pc(s)];case 3:return p[m]=N.sent(),_=a._levels,v=0,[4,pc(a)];case 4:return _[v]=N.sent(),g=o._levels,y=0,[4,pc(o)];case 5:if(g[y]=N.sent(),!(n>0))return [3,8];return x=l._levels,b=0,[4,pc(l)];case 6:return x[b]=N.sent(),T=u._levels,E=0,[4,pc(u)];case 7:for(A=0,T[E]=N.sent(),w=[];A<45;++A)w.push("f_rest_"+A);(S=t).splice.apply(S,[].concat([t.indexOf("f_dc_0")+1,0],w)),N.label=8;case 8:for(C={},t.forEach(function(t){C[t]=new Float32Array(e.numSplats);}),P=new eW,I=new e0,L=new eW,D=new eY,R=n>0?new Float32Array(45):null,M=e.createIter(P,I,L,D,R),O=0;O=1?40:-Math.log(1/D.w-1),R)for(k=0;k<45;++k)C["f_rest_"+k][O]=R[k];return [2,new d3([{name:"vertex",count:e.numSplats,properties:t.map(function(e){return {name:e,type:"float",byteSize:4,storage:C[e]}})}])]}})})()},n.reorderGpuMemory=function(){var e=this,t=this.orderTexture,n=this.numSplats,i=t.device,r=t.height,s=t.width,a=i.scope,o=o6.createShader(i,{uniqueName:"GsplatSogsReorderShader",attributes:{vertex_position:tA},vertexChunk:"fullscreenQuadVS",fragmentGLSL:"\n uniform usampler2D orderTexture;\n uniform sampler2D sourceTexture;\n uniform highp uint numSplats;\n void main(void) {\n uint w = uint(textureSize(sourceTexture, 0).x);\n uint idx = uint(gl_FragCoord.x) + uint(gl_FragCoord.y) * w;\n if (idx >= numSplats) discard;\n uint sidx = texelFetch(orderTexture, ivec2(gl_FragCoord.xy), 0).x;\n uvec2 suv = uvec2(sidx % w, sidx / w);\n gl_FragColor = texelFetch(sourceTexture, ivec2(suv), 0);\n }\n",fragmentWGSL:"\n var orderTexture: texture_2d;\n var sourceTexture: texture_2d;\n uniform numSplats: u32;\n @fragment\n fn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n let w: u32 = textureDimensions(sourceTexture, 0).x;\n let idx: u32 = u32(pcPosition.x) + u32(pcPosition.y) * w;\n if (idx >= uniform.numSplats) {\n discard;\n return output;\n }\n let sidx: u32 = textureLoad(orderTexture, vec2(input.position.xy), 0).x;\n let suv: vec2 = vec2(sidx % w, sidx / w);\n output.color = textureLoad(sourceTexture, vec2(suv), 0);\n return output;\n }\n"}),l=new nN(i,{width:s,height:r,format:7,mipmaps:false});i.setBlendState(nY.NOBLEND),i.setCullMode(0),i.setDepthState(nZ.NODEPTH),["means_l","means_u","quats","scales","sh0","sh_labels"].forEach(function(r){var s=e[r];if(s){var u=new ic({colorBuffer:s,depth:false,mipLevel:0});l._levels[0]=s._levels[0],l.upload(),ph(a,{orderTexture:t,sourceTexture:l,numSplats:n}),la(i,u,o),u.destroy();}}),l.destroy();},n.calcMortonOrder=function(){for(var e=this.means_l,t=this.means_u,n=e._levels[0],i=t._levels[0],r=new BigUint64Array(this.numSplats),s=0;s>>6,o=i[4*s+1]<<2|n[4*s+1]>>>6,l=i[4*s+2]<<2|n[4*s+2]>>>6;r[s]=BigInt(function(e,t,n){var i=function(e){return e&=1023,e=((e=((e=((e=(e^e<<16)&0xff0000ff)^e<<8)&0x300f00f)^e<<4)&0x30c30c3)^e<<2)&0x9249249};return (i(n)<<2)+(i(t)<<1)+i(e)}(a,o,l))<0||h.beforePasses.length>0||(u._skipEnd=true,h._skipStart=true);}for(var f=null,d=null,p=0;p=0&&e<=1?0:1}),pI(["fr","pt"],function(e){return e>=0&&e<2?0:1}),pI(["da"],function(e){return 1===e||!Number.isInteger(e)&&e>=0&&e<=1?0:1}),pI(["de","en","it","el","es","tr","fi","sv","nb","no","ur"],function(e){return +(1!==e)}),pI(["ru","uk"],function(e){if(Number.isInteger(e)){var t=e%10,n=e%100;if(1===t&&11!==n)return 0;if(t>=2&&t<=4&&(n<12||n>14))return 1;if(0===t||t>=5&&t<=9||n>=11&&n<=14)return 2}return 3}),pI(["pl"],function(e){if(Number.isInteger(e)){if(1===e)return 0;var t=e%10,n=e%100;if(t>=2&&t<=4&&(n<12||n>14))return 1;if(t>=0&&t<=1||t>=5&&t<=9||n>=12&&n<=14)return 2}return 3}),pI(["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 pR=pP[pL(pA)],pM=RegExp("^\\s*(?:(?:[a-z]+[a-z0-9\\-+.]*:)?//|data:|blob:)","i"),pO=function(){function e(e,t,n,i,r,s){ void 0===e&&(e=""),void 0===t&&(t=""),void 0===n&&(n=null),void 0===i&&(i=null),void 0===r&&(r=null),void 0===s&&(s=null),this.url=e,this.filename=t,this.hash=n,this.size=i,this.opt=r,this.contents=s;}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}();function pk(e,t){return (pk=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var pN=-1,pF={pvr:"extCompressedTexturePVRTC",dxt:"extCompressedTextureS3TC",etc2:"extCompressedTextureETC",etc1:"extCompressedTextureETC1",basis:"canvas"},pB=["pvr","dxt","etc2","etc1","basis"],pU=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t,n,i,r,s){var a;return void 0===r&&(r={}),void 0===s&&(s={}),(a=e.call(this)||this)._file=null,a._i18n={},a._preload=false,a._resources=[],a.id=pN--,a.loaded=false,a.loading=false,a.options={},a.registry=null,a.tags=new eI(a),a.urlObject=null,a._name=t||"",a.type=n,a._data=r||{},a.options=s||{},i&&(a.file=i),a}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&pk(t,e);var n,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&&!pM.test(t)&&(t=this.registry.prefix+t),"script"!==this.type&&e.hash){var n=-1!==t.indexOf("?")?"&":"?";t+=n+"t="+e.hash;}return t},i.getAbsoluteUrl=function(e){if(e.startsWith("blob:")||e.startsWith("data:"))return e;var t=en.getDirectory(this.file.url);return en.join(t,e)},i.getLocalizedAssetId=function(e){return e=pD(e,this._i18n),this._i18n[e]||null},i.addLocalizedAssetId=function(e,t){this._i18n[e]=t,this.fire("add:localized",e,t);},i.removeLocalizedAssetId=function(e){var t=this._i18n[e];t&&(delete this._i18n[e],this.fire("remove:localized",e,t));},i.ready=function(e,t){t=t||this,this.loaded?e.call(t,this):this.once("load",function(n){e.call(t,n);});},i.reload=function(){this.loaded&&(this.loaded=false,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.urlObject&&(URL.revokeObjectURL(this.urlObject),this.urlObject=null),this.resources=[],this.loaded=false,this.file&&this.registry._loader.clearCache(this.getFileUrl(),this.type);for(var t=0;t0,maxRetries:i},t);},n=[{key:"name",get:function(){return this._name},set:function(e){if(this._name!==e){var t=this._name;this._name=e,this.fire("name",this,this._name,t);}}},{key:"file",get:function(){return this._file},set:function(e){if(e&&e.variants&&-1!==["texture","textureatlas","bundle"].indexOf(this.type)){var t=(null==(r=this.registry)||null==(i=r._loader)?void 0:i._app)||A,n=null==t?void 0:t.graphicsDevice;if(n)for(var i,r,s,a=0,o=pB.length;ae.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}pU.EVENT_LOAD="load",pU.EVENT_UNLOAD="unload",pU.EVENT_REMOVE="remove",pU.EVENT_ERROR="error",pU.EVENT_CHANGE="change",pU.EVENT_PROGRESS="progress",pU.EVENT_ADDLOCALIZED="add:localized",pU.EVENT_REMOVELOCALIZED="remove:localized";var pG=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,n=e.tags._list,i=pz(n);!(t=i()).done;){var r=t.value;this.add(r,e);}},t.removeItem=function(e){for(var t,n=e.tags._list,i=pz(n);!(t=i()).done;){var r=t.value;this.remove(r,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 n=this._index[e].list.indexOf(t);-1!==n&&(this._index[e].list.splice(n,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,n,r,s,a,o,l,u=this,c={},h=[],f=function(e,t){return u._index[e].list.length-u._index[t].list.length},d=0;de.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(n);!(i=r()).done;){var s=i.value;if(!t||s.type===t)return s}return null},n.findAll=function(e,t){var n=this._nameToAsset.get(e);if(!n)return [];var i=Array.from(n);return t?i.filter(function(e){return e.type===t}):i},t}(ex);function pX(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}pj.EVENT_LOAD="load",pj.EVENT_ADD="add",pj.EVENT_REMOVE="remove",pj.EVENT_ERROR="error";var pq=function(){function e(e){this._idToBundle=new Map,this._assetToBundles=new Map,this._urlsToBundles=new Map,this._fileRequests=new Map,this._assets=e,this._assets.bundles=this,this._assets.on("add",this._onAssetAdd,this),this._assets.on("remove",this._onAssetRemove,this);}var t=e.prototype;return t._onAssetAdd=function(e){if("bundle"===e.type){this._idToBundle.set(e.id,e),this._assets.on("load:start:"+e.id,this._onBundleLoadStart,this),this._assets.on("load:"+e.id,this._onBundleLoad,this),this._assets.on("error:"+e.id,this._onBundleError,this);for(var t=e.data.assets,n=0;nthis.bytesRead+this.headerSize){this.headerRead=true;var e=new DataView(this.data.buffer,this.bytesRead,this.headerSize);null!=this.decoder||(this.decoder=new TextDecoder("windows-1252"));var t=this.decoder.decode(e);if(this.fileName=t.substring(0,100).replace(/\0/g,""),this.fileSize=parseInt(t.substring(124,136),8),this.fileType=t.substring(156,157),this.ustarFormat=t.substring(257,263),-1!==this.ustarFormat.indexOf("ustar")){var n=t.substring(345,500).replace(/\0/g,"");n.length>0&&(this.fileName=n.trim()+this.fileName.trim());}this.bytesRead+=512;}if(this.headerRead){if(this.bytesReceivede.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(s.scripts);!(l=u()).done;){var c=l.value;s.initializeAttributes(c);}}}for(var h=0;h1&&t.sort(mi),t},n._cloneRecursively=function(n){var i=new this.constructor(void 0,this._app);for(var r in e.prototype._cloneInternal.call(this,i),this.c)this.c[r].system.cloneComponent(this,i);for(var s=0;s 0.5) {\n if (dAtten > 0.00001) {\n dirLm.xyz = dirLm.xyz * 2.0 - vec3(1.0);\n dAtten = saturate(dAtten);\n gl_FragColor.rgb = normalize(dLightDirNormW.xyz*dAtten + dirLm.xyz*dirLm.w) * 0.5 + vec3(0.5);\n gl_FragColor.a = dirLm.w + dAtten;\n gl_FragColor.a = max(gl_FragColor.a, 1.0 / 255.0);\n } else {\n gl_FragColor = dirLm;\n }\n } else {\n gl_FragColor.rgb = dirLm.xyz;\n gl_FragColor.a = max(dirLm.w, dAtten > 0.00001 ? (1.0/255.0) : 0.0);\n }\n",bakeLmEndPS:"\n#ifdef LIT_LIGHTMAP_BAKING_ADD_AMBIENT\n dDiffuseLight = ((dDiffuseLight - 0.5) * max(ambientBakeOcclusionContrast + 1.0, 0.0)) + 0.5;\n dDiffuseLight += vec3(ambientBakeOcclusionBrightness);\n dDiffuseLight = saturate(dDiffuseLight);\n dDiffuseLight *= dAmbientLight;\n#endif\n#ifdef LIGHTMAP_RGBM\n gl_FragColor.rgb = dDiffuseLight;\n gl_FragColor.rgb = pow(gl_FragColor.rgb, vec3(0.5));\n gl_FragColor.rgb /= 8.0;\n gl_FragColor.a = clamp( max( max( gl_FragColor.r, gl_FragColor.g ), max( gl_FragColor.b, 1.0 / 255.0 ) ), 0.0,1.0 );\n gl_FragColor.a = ceil(gl_FragColor.a * 255.0) / 255.0;\n gl_FragColor.rgb /= gl_FragColor.a;\n#else\n gl_FragColor = vec4(dDiffuseLight, 1.0);\n#endif\n",basePS:"\nuniform vec3 view_position;\nuniform vec3 light_globalAmbient;\nfloat square(float x) {\n return x*x;\n}\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\nvec3 saturate(vec3 x) {\n return clamp(x, vec3(0.0), vec3(1.0));\n}\n",baseNineSlicedPS:"\n#define NINESLICED\nvarying vec2 vMask;\nvarying vec2 vTiledUv;\nuniform mediump vec4 innerOffset;\nuniform mediump vec2 outerScale;\nuniform mediump vec4 atlasRect;\nvec2 nineSlicedUv;\n",baseNineSlicedTiledPS:"\n#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",bayerPS:"\nfloat bayer2(vec2 p) {\n return mod(2.0 * p.y + p.x + 1.0, 4.0);\n}\nfloat bayer4(vec2 p) {\n vec2 p1 = mod(p, 2.0);\n vec2 p2 = floor(0.5 * mod(p, 4.0));\n return 4.0 * bayer2(p1) + bayer2(p2);\n}\nfloat bayer8(vec2 p) {\n vec2 p1 = mod(p, 2.0);\n vec2 p2 = floor(0.5 * mod(p, 4.0));\n vec2 p4 = floor(0.25 * mod(p, 8.0));\n return 4.0 * (4.0 * bayer2(p1) + bayer2(p2)) + bayer2(p4);\n}\n",blurVSMPS:"\nvarying vec2 vUv0;\nuniform sampler2D source;\nuniform vec2 pixelOffset;\n#ifdef GAUSS\n uniform float weight[{SAMPLES}];\n#endif\nvoid main(void) {\n vec3 moments = vec3(0.0);\n vec2 uv = vUv0 - pixelOffset * (float({SAMPLES}) * 0.5);\n for (int i = 0; i < {SAMPLES}; i++) {\n vec4 c = texture2D(source, uv + pixelOffset * float(i));\n #ifdef GAUSS\n moments += c.xyz * weight[i];\n #else\n moments += c.xyz;\n #endif\n }\n #ifndef GAUSS\n moments *= 1.0 / float({SAMPLES});\n #endif\n gl_FragColor = vec4(moments.x, moments.y, moments.z, 1.0);\n}\n",clearCoatPS:"\n#ifdef STD_CLEARCOAT_CONSTANT\nuniform float material_clearCoat;\n#endif\nvoid getClearCoat() {\n ccSpecularity = 1.0;\n #ifdef STD_CLEARCOAT_CONSTANT\n ccSpecularity *= material_clearCoat;\n #endif\n #ifdef STD_CLEARCOAT_TEXTURE\n ccSpecularity *= texture2DBias({STD_CLEARCOAT_TEXTURE_NAME}, {STD_CLEARCOAT_TEXTURE_UV}, textureBias).{STD_CLEARCOAT_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_CLEARCOAT_VERTEX\n ccSpecularity *= saturate(vVertexColor.{STD_CLEARCOAT_VERTEX_CHANNEL});\n #endif\n}\n",clearCoatGlossPS:"\n#ifdef STD_CLEARCOATGLOSS_CONSTANT\nuniform float material_clearCoatGloss;\n#endif\nvoid getClearCoatGlossiness() {\n ccGlossiness = 1.0;\n #ifdef STD_CLEARCOATGLOSS_CONSTANT\n ccGlossiness *= material_clearCoatGloss;\n #endif\n #ifdef STD_CLEARCOATGLOSS_TEXTURE\n ccGlossiness *= texture2DBias({STD_CLEARCOATGLOSS_TEXTURE_NAME}, {STD_CLEARCOATGLOSS_TEXTURE_UV}, textureBias).{STD_CLEARCOATGLOSS_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_CLEARCOATGLOSS_VERTEX\n ccGlossiness *= saturate(vVertexColor.{STD_CLEARCOATGLOSS_VERTEX_CHANNEL});\n #endif\n #ifdef STD_CLEARCOATGLOSS_INVERT\n ccGlossiness = 1.0 - ccGlossiness;\n #endif\n ccGlossiness += 0.0000001;\n}\n",clearCoatNormalPS:"\n#ifdef STD_CLEARCOATNORMAL_TEXTURE\nuniform float material_clearCoatBumpiness;\n#endif\nvoid getClearCoatNormal() {\n#ifdef STD_CLEARCOATNORMAL_TEXTURE\n vec3 normalMap = {STD_CLEARCOATNORMAL_TEXTURE_DECODE}(texture2DBias({STD_CLEARCOATNORMAL_TEXTURE_NAME}, {STD_CLEARCOATNORMAL_TEXTURE_UV}, textureBias));\n normalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, material_clearCoatBumpiness);\n ccNormalW = normalize(dTBN * normalMap);\n#else\n ccNormalW = dVertexNormalW;\n#endif\n}\n",clusteredLightCookiesPS:"\nvec3 _getCookieClustered(TEXTURE_ACCEPT(tex), vec2 uv, float intensity, vec4 cookieChannel) {\n vec4 pixel = mix(vec4(1.0), texture2DLod(tex, uv, 0.0), intensity);\n bool isRgb = dot(cookieChannel.rgb, vec3(1.0)) == 3.0;\n return isRgb ? pixel.rgb : vec3(dot(pixel, cookieChannel));\n}\nvec3 getCookie2DClustered(TEXTURE_ACCEPT(tex), mat4 transform, vec3 worldPosition, float intensity, vec4 cookieChannel) {\n vec4 projPos = transform * vec4(worldPosition, 1.0);\n return _getCookieClustered(TEXTURE_PASS(tex), projPos.xy / projPos.w, intensity, cookieChannel);\n}\nvec3 getCookieCubeClustered(TEXTURE_ACCEPT(tex), vec3 dir, float intensity, vec4 cookieChannel, float shadowTextureResolution, float shadowEdgePixels, vec3 omniAtlasViewport) {\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);\n return _getCookieClustered(TEXTURE_PASS(tex), uv, intensity, cookieChannel);\n}\n",clusteredLightShadowsPS:"\nvec3 _getShadowCoordPerspZbuffer(mat4 shadowMatrix, vec4 shadowParams, vec3 wPos) {\n vec4 projPos = shadowMatrix * vec4(wPos, 1.0);\n projPos.xyz /= projPos.w;\n return projPos.xyz;\n}\nvec3 getShadowCoordPerspZbufferNormalOffset(mat4 shadowMatrix, vec4 shadowParams, vec3 normal) {\n vec3 wPos = vPositionW + normal * shadowParams.y;\n return _getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, wPos);\n}\nvec3 normalOffsetPointShadow(vec4 shadowParams, vec3 lightPos, vec3 lightDir, vec3 lightDirNorm, vec3 normal) {\n float distScale = length(lightDir);\n vec3 wPos = vPositionW + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;\n vec3 dir = wPos - lightPos;\n return dir;\n}\n#if defined(CLUSTER_SHADOW_TYPE_PCF1)\nfloat getShadowOmniClusteredPCF1(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {\n float shadowTextureResolution = shadowParams.x;\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;\n return textureShadow(shadowMap, vec3(uv, shadowZ));\n}\n#endif\n#if defined(CLUSTER_SHADOW_TYPE_PCF3)\nfloat getShadowOmniClusteredPCF3(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {\n float shadowTextureResolution = shadowParams.x;\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;\n vec3 shadowCoord = vec3(uv, shadowZ);\n return getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);\n}\n#endif\n#if defined(CLUSTER_SHADOW_TYPE_PCF5)\nfloat getShadowOmniClusteredPCF5(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {\n float shadowTextureResolution = shadowParams.x;\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;\n vec3 shadowCoord = vec3(uv, shadowZ);\n return getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);\n}\n#endif\n#if defined(CLUSTER_SHADOW_TYPE_PCF1)\nfloat getShadowSpotClusteredPCF1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return textureShadow(shadowMap, shadowCoord);\n}\n#endif\n#if defined(CLUSTER_SHADOW_TYPE_PCF3)\nfloat getShadowSpotClusteredPCF3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return getShadowSpotPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);\n}\n#endif\n#if defined(CLUSTER_SHADOW_TYPE_PCF5)\nfloat getShadowSpotClusteredPCF5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);\n}\n#endif\n",clusteredLightUtilsPS:"\nvec2 getCubemapFaceCoordinates(const vec3 dir, out float faceIndex, out vec2 tileOffset)\n{\n vec3 vAbs = abs(dir);\n float ma;\n vec2 uv;\n if (vAbs.z >= vAbs.x && vAbs.z >= vAbs.y) {\n faceIndex = dir.z < 0.0 ? 5.0 : 4.0;\n ma = 0.5 / vAbs.z;\n uv = vec2(dir.z < 0.0 ? -dir.x : dir.x, -dir.y);\n tileOffset.x = 2.0;\n tileOffset.y = dir.z < 0.0 ? 1.0 : 0.0;\n } else if(vAbs.y >= vAbs.x) {\n faceIndex = dir.y < 0.0 ? 3.0 : 2.0;\n ma = 0.5 / vAbs.y;\n uv = vec2(dir.x, dir.y < 0.0 ? -dir.z : dir.z);\n tileOffset.x = 1.0;\n tileOffset.y = dir.y < 0.0 ? 1.0 : 0.0;\n } else {\n faceIndex = dir.x < 0.0 ? 1.0 : 0.0;\n ma = 0.5 / vAbs.x;\n uv = vec2(dir.x < 0.0 ? dir.z : -dir.z, -dir.y);\n tileOffset.x = 0.0;\n tileOffset.y = dir.x < 0.0 ? 1.0 : 0.0;\n }\n return uv * ma + 0.5;\n}\nvec2 getCubemapAtlasCoordinates(const vec3 omniAtlasViewport, float shadowEdgePixels, float shadowTextureResolution, const vec3 dir) {\n float faceIndex;\n vec2 tileOffset;\n vec2 uv = getCubemapFaceCoordinates(dir, faceIndex, tileOffset);\n float atlasFaceSize = omniAtlasViewport.z;\n float tileSize = shadowTextureResolution * atlasFaceSize;\n float offset = shadowEdgePixels / tileSize;\n uv = uv * vec2(1.0 - offset * 2.0) + vec2(offset * 1.0);\n uv *= atlasFaceSize;\n uv += tileOffset * atlasFaceSize;\n uv += omniAtlasViewport.xy;\n return uv;\n}\n",clusteredLightPS:'\n#include "lightBufferDefinesPS"\n#include "clusteredLightUtilsPS"\n#ifdef CLUSTER_COOKIES\n #include "clusteredLightCookiesPS"\n#endif\n#ifdef CLUSTER_SHADOWS\n #include "clusteredLightShadowsPS"\n#endif\nuniform highp sampler2D clusterWorldTexture;\nuniform highp sampler2D lightsTexture;\n#ifdef CLUSTER_SHADOWS\n uniform sampler2DShadow shadowAtlasTexture;\n#endif\n#ifdef CLUSTER_COOKIES\n uniform sampler2D cookieAtlasTexture;\n#endif\nuniform int clusterMaxCells;\nuniform float clusterSkip;\nuniform vec3 clusterCellsCountByBoundsSize;\nuniform vec3 clusterTextureSize;\nuniform vec3 clusterBoundsMin;\nuniform vec3 clusterBoundsDelta;\nuniform vec3 clusterCellsDot;\nuniform vec3 clusterCellsMax;\nuniform vec2 shadowAtlasParams;\nstruct ClusterLightData {\n uint flags;\n vec3 halfWidth;\n bool isSpot;\n vec3 halfHeight;\n int lightIndex;\n vec3 position;\n uint shape;\n vec3 direction;\n bool falloffModeLinear;\n vec3 color;\n float shadowIntensity;\n vec3 omniAtlasViewport;\n float range;\n vec4 cookieChannelMask;\n float biasesData;\n float shadowBias;\n float shadowNormalBias;\n float anglesData;\n float innerConeAngleCos;\n float outerConeAngleCos;\n float cookieIntensity;\n bool isDynamic;\n bool isLightmapped;\n};\nmat4 lightProjectionMatrix;\nvec4 sampleLightTextureF(const ClusterLightData clusterLightData, int index) {\n return texelFetch(lightsTexture, ivec2(index, clusterLightData.lightIndex), 0);\n}\nvoid decodeClusterLightCore(inout ClusterLightData clusterLightData, float lightIndex) {\n clusterLightData.lightIndex = int(lightIndex);\n vec4 halfData = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_COLOR_ANGLES_BIAS});\n clusterLightData.anglesData = halfData.z;\n clusterLightData.biasesData = halfData.w;\n vec2 colorRG = unpackHalf2x16(floatBitsToUint(halfData.x));\n vec2 colorB_ = unpackHalf2x16(floatBitsToUint(halfData.y));\n clusterLightData.color = vec3(colorRG, colorB_.x) * {LIGHT_COLOR_DIVIDER};\n vec4 lightPosRange = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_POSITION_RANGE});\n clusterLightData.position = lightPosRange.xyz;\n clusterLightData.range = lightPosRange.w;\n vec4 lightDir_Flags = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_DIRECTION_FLAGS});\n clusterLightData.direction = lightDir_Flags.xyz;\n clusterLightData.flags = floatBitsToUint(lightDir_Flags.w);\n clusterLightData.isSpot = (clusterLightData.flags & (1u << 30u)) != 0u;\n clusterLightData.shape = (clusterLightData.flags >> 28u) & 0x3u;\n clusterLightData.falloffModeLinear = (clusterLightData.flags & (1u << 27u)) == 0u;\n clusterLightData.shadowIntensity = float((clusterLightData.flags >> 0u) & 0xFFu) / 255.0;\n clusterLightData.cookieIntensity = float((clusterLightData.flags >> 8u) & 0xFFu) / 255.0;\n clusterLightData.isDynamic = (clusterLightData.flags & (1u << 22u)) != 0u;\n clusterLightData.isLightmapped = (clusterLightData.flags & (1u << 21u)) != 0u;\n}\nvoid decodeClusterLightSpot(inout ClusterLightData clusterLightData) {\n vec2 angles = unpackHalf2x16(floatBitsToUint(clusterLightData.anglesData));\n clusterLightData.innerConeAngleCos = angles.x;\n clusterLightData.outerConeAngleCos = angles.y;\n}\nvoid decodeClusterLightOmniAtlasViewport(inout ClusterLightData clusterLightData) {\n clusterLightData.omniAtlasViewport = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_PROJ_MAT_0}).xyz;\n}\nvoid decodeClusterLightAreaData(inout ClusterLightData clusterLightData) {\n clusterLightData.halfWidth = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_AREA_DATA_WIDTH}).xyz;\n clusterLightData.halfHeight = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_AREA_DATA_HEIGHT}).xyz;\n}\nvoid decodeClusterLightProjectionMatrixData(inout ClusterLightData clusterLightData) {\n \n vec4 m0 = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_PROJ_MAT_0});\n vec4 m1 = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_PROJ_MAT_1});\n vec4 m2 = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_PROJ_MAT_2});\n vec4 m3 = sampleLightTextureF(clusterLightData, {CLUSTER_TEXTURE_PROJ_MAT_3});\n lightProjectionMatrix = mat4(m0, m1, m2, m3);\n}\nvoid decodeClusterLightShadowData(inout ClusterLightData clusterLightData) {\n \n vec2 biases = unpackHalf2x16(floatBitsToUint(clusterLightData.biasesData));\n clusterLightData.shadowBias = biases.x;\n clusterLightData.shadowNormalBias = biases.y;\n}\nvoid decodeClusterLightCookieData(inout ClusterLightData clusterLightData) {\n uint cookieFlags = (clusterLightData.flags >> 23u) & 0x0Fu;\n clusterLightData.cookieChannelMask = vec4(uvec4(cookieFlags) & uvec4(1u, 2u, 4u, 8u));\n clusterLightData.cookieChannelMask = step(1.0, clusterLightData.cookieChannelMask);\n}\nvoid evaluateLight(\n ClusterLightData light, \n vec3 worldNormal, \n vec3 viewDir, \n vec3 reflectionDir,\n#if defined(LIT_CLEARCOAT)\n vec3 clearcoatReflectionDir,\n#endif\n float gloss, \n vec3 specularity, \n vec3 geometricNormal, \n mat3 tbn, \n#if defined(LIT_IRIDESCENCE)\n vec3 iridescenceFresnel,\n#endif\n vec3 clearcoat_worldNormal,\n float clearcoat_gloss,\n float sheen_gloss,\n float iridescence_intensity\n) {\n vec3 cookieAttenuation = vec3(1.0);\n float diffuseAttenuation = 1.0;\n float falloffAttenuation = 1.0;\n vec3 lightDirW = evalOmniLight(light.position);\n vec3 lightDirNormW = normalize(lightDirW);\n #ifdef CLUSTER_AREALIGHTS\n if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {\n decodeClusterLightAreaData(light);\n if (light.shape == {LIGHTSHAPE_RECT}) {\n calcRectLightValues(light.position, light.halfWidth, light.halfHeight);\n } else if (light.shape == {LIGHTSHAPE_DISK}) {\n calcDiskLightValues(light.position, light.halfWidth, light.halfHeight);\n } else {\n calcSphereLightValues(light.position, light.halfWidth, light.halfHeight);\n }\n falloffAttenuation = getFalloffWindow(light.range, lightDirW);\n } else\n #endif\n {\n if (light.falloffModeLinear)\n falloffAttenuation = getFalloffLinear(light.range, lightDirW);\n else\n falloffAttenuation = getFalloffInvSquared(light.range, lightDirW);\n }\n if (falloffAttenuation > 0.00001) {\n #ifdef CLUSTER_AREALIGHTS\n if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {\n if (light.shape == {LIGHTSHAPE_RECT}) {\n diffuseAttenuation = getRectLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;\n } else if (light.shape == {LIGHTSHAPE_DISK}) {\n diffuseAttenuation = getDiskLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;\n } else {\n diffuseAttenuation = getSphereLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;\n }\n } else\n #endif\n {\n falloffAttenuation *= getLightDiffuse(worldNormal, viewDir, lightDirNormW); \n }\n if (light.isSpot) {\n decodeClusterLightSpot(light);\n falloffAttenuation *= getSpotEffect(light.direction, light.innerConeAngleCos, light.outerConeAngleCos, lightDirNormW);\n }\n #if defined(CLUSTER_COOKIES) || defined(CLUSTER_SHADOWS)\n if (falloffAttenuation > 0.00001) {\n if (light.shadowIntensity > 0.0 || light.cookieIntensity > 0.0) {\n if (light.isSpot) {\n decodeClusterLightProjectionMatrixData(light);\n } else {\n decodeClusterLightOmniAtlasViewport(light);\n }\n float shadowTextureResolution = shadowAtlasParams.x;\n float shadowEdgePixels = shadowAtlasParams.y;\n #ifdef CLUSTER_COOKIES\n if (light.cookieIntensity > 0.0) {\n decodeClusterLightCookieData(light);\n if (light.isSpot) {\n cookieAttenuation = getCookie2DClustered(TEXTURE_PASS(cookieAtlasTexture), lightProjectionMatrix, vPositionW, light.cookieIntensity, light.cookieChannelMask);\n } else {\n cookieAttenuation = getCookieCubeClustered(TEXTURE_PASS(cookieAtlasTexture), lightDirW, light.cookieIntensity, light.cookieChannelMask, shadowTextureResolution, shadowEdgePixels, light.omniAtlasViewport);\n }\n }\n #endif\n #ifdef CLUSTER_SHADOWS\n if (light.shadowIntensity > 0.0) {\n decodeClusterLightShadowData(light);\n vec4 shadowParams = vec4(shadowTextureResolution, light.shadowNormalBias, light.shadowBias, 1.0 / light.range);\n if (light.isSpot) {\n vec3 shadowCoord = getShadowCoordPerspZbufferNormalOffset(lightProjectionMatrix, shadowParams, geometricNormal);\n \n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n float shadow = getShadowSpotClusteredPCF1(SHADOWMAP_PASS(shadowAtlasTexture), shadowCoord, shadowParams);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF3)\n float shadow = getShadowSpotClusteredPCF3(SHADOWMAP_PASS(shadowAtlasTexture), shadowCoord, shadowParams);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF5)\n float shadow = getShadowSpotClusteredPCF5(SHADOWMAP_PASS(shadowAtlasTexture), shadowCoord, shadowParams);\n #elif defined(CLUSTER_SHADOW_TYPE_PCSS)\n float shadow = getShadowSpotClusteredPCSS(SHADOWMAP_PASS(shadowAtlasTexture), shadowCoord, shadowParams);\n #endif\n falloffAttenuation *= mix(1.0, shadow, light.shadowIntensity);\n } else {\n vec3 dir = normalOffsetPointShadow(shadowParams, light.position, lightDirW, lightDirNormW, geometricNormal);\n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n float shadow = getShadowOmniClusteredPCF1(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF3)\n float shadow = getShadowOmniClusteredPCF3(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF5)\n float shadow = getShadowOmniClusteredPCF5(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);\n #endif\n falloffAttenuation *= mix(1.0, shadow, light.shadowIntensity);\n }\n }\n #endif\n }\n }\n #endif\n #ifdef CLUSTER_AREALIGHTS\n if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {\n {\n vec3 areaDiffuse = (diffuseAttenuation * falloffAttenuation) * light.color * cookieAttenuation;\n #if defined(LIT_SPECULAR)\n areaDiffuse = mix(areaDiffuse, vec3(0), dLTCSpecFres);\n #endif\n dDiffuseLight += areaDiffuse;\n }\n #ifdef LIT_SPECULAR\n float areaLightSpecular;\n if (light.shape == {LIGHTSHAPE_RECT}) {\n areaLightSpecular = getRectLightSpecular(worldNormal, viewDir);\n } else if (light.shape == {LIGHTSHAPE_DISK}) {\n areaLightSpecular = getDiskLightSpecular(worldNormal, viewDir);\n } else {\n areaLightSpecular = getSphereLightSpecular(worldNormal, viewDir);\n }\n dSpecularLight += dLTCSpecFres * areaLightSpecular * falloffAttenuation * light.color * cookieAttenuation;\n #ifdef LIT_CLEARCOAT\n float areaLightSpecularCC;\n if (light.shape == {LIGHTSHAPE_RECT}) {\n areaLightSpecularCC = getRectLightSpecular(clearcoat_worldNormal, viewDir);\n } else if (light.shape == {LIGHTSHAPE_DISK}) {\n areaLightSpecularCC = getDiskLightSpecular(clearcoat_worldNormal, viewDir);\n } else {\n areaLightSpecularCC = getSphereLightSpecular(clearcoat_worldNormal, viewDir);\n }\n ccSpecularLight += ccLTCSpecFres * areaLightSpecularCC * falloffAttenuation * light.color * cookieAttenuation;\n #endif\n #endif\n } else\n #endif\n {\n {\n vec3 punctualDiffuse = falloffAttenuation * light.color * cookieAttenuation;\n #if defined(CLUSTER_AREALIGHTS)\n #if defined(LIT_SPECULAR)\n punctualDiffuse = mix(punctualDiffuse, vec3(0), specularity);\n #endif\n #endif\n dDiffuseLight += punctualDiffuse;\n }\n \n #ifdef LIT_SPECULAR\n vec3 halfDir = normalize(-lightDirNormW + viewDir);\n \n #ifdef LIT_SPECULAR_FRESNEL\n dSpecularLight += \n getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, lightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * \n getFresnel(\n dot(viewDir, halfDir), \n gloss, \n specularity\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n iridescence_intensity\n #endif\n );\n #else\n dSpecularLight += getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, lightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * specularity;\n #endif\n #ifdef LIT_CLEARCOAT\n #ifdef LIT_SPECULAR_FRESNEL\n ccSpecularLight += getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, lightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * getFresnelCC(dot(viewDir, halfDir));\n #else\n ccSpecularLight += getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, lightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation; \n #endif\n #endif\n #ifdef LIT_SHEEN\n sSpecularLight += getLightSpecularSheen(halfDir, worldNormal, viewDir, lightDirNormW, sheen_gloss) * falloffAttenuation * light.color * cookieAttenuation;\n #endif\n #endif\n }\n }\n dAtten = falloffAttenuation;\n dLightDirNormW = lightDirNormW;\n}\nvoid evaluateClusterLight(\n float lightIndex, \n vec3 worldNormal, \n vec3 viewDir, \n vec3 reflectionDir, \n#if defined(LIT_CLEARCOAT)\n vec3 clearcoatReflectionDir,\n#endif\n float gloss, \n vec3 specularity, \n vec3 geometricNormal, \n mat3 tbn, \n#if defined(LIT_IRIDESCENCE)\n vec3 iridescenceFresnel,\n#endif\n vec3 clearcoat_worldNormal,\n float clearcoat_gloss,\n float sheen_gloss,\n float iridescence_intensity\n) {\n ClusterLightData clusterLightData;\n decodeClusterLightCore(clusterLightData, lightIndex);\n #ifdef CLUSTER_MESH_DYNAMIC_LIGHTS\n bool acceptLightMask = clusterLightData.isDynamic;\n #else\n bool acceptLightMask = clusterLightData.isLightmapped;\n #endif\n if (acceptLightMask)\n evaluateLight(\n clusterLightData, \n worldNormal, \n viewDir, \n reflectionDir, \n#if defined(LIT_CLEARCOAT)\n clearcoatReflectionDir, \n#endif\n gloss, \n specularity, \n geometricNormal, \n tbn, \n#if defined(LIT_IRIDESCENCE)\n iridescenceFresnel,\n#endif\n clearcoat_worldNormal,\n clearcoat_gloss,\n sheen_gloss,\n iridescence_intensity\n );\n}\nvoid addClusteredLights(\n vec3 worldNormal, \n vec3 viewDir, \n vec3 reflectionDir, \n#if defined(LIT_CLEARCOAT)\n vec3 clearcoatReflectionDir,\n#endif\n float gloss, \n vec3 specularity, \n vec3 geometricNormal, \n mat3 tbn, \n#if defined(LIT_IRIDESCENCE)\n vec3 iridescenceFresnel,\n#endif\n vec3 clearcoat_worldNormal,\n float clearcoat_gloss,\n float sheen_gloss,\n float iridescence_intensity\n) {\n if (clusterSkip > 0.5)\n return;\n vec3 cellCoords = floor((vPositionW - clusterBoundsMin) * clusterCellsCountByBoundsSize);\n if (!(any(lessThan(cellCoords, vec3(0.0))) || any(greaterThanEqual(cellCoords, clusterCellsMax)))) {\n float cellIndex = dot(clusterCellsDot, cellCoords);\n float clusterV = floor(cellIndex * clusterTextureSize.y);\n float clusterU = cellIndex - (clusterV * clusterTextureSize.x);\n for (int lightCellIndex = 0; lightCellIndex < clusterMaxCells; lightCellIndex++) {\n float lightIndex = texelFetch(clusterWorldTexture, ivec2(int(clusterU) + lightCellIndex, clusterV), 0).x;\n if (lightIndex <= 0.0)\n break;\n evaluateClusterLight(\n lightIndex * 255.0, \n worldNormal, \n viewDir, \n reflectionDir,\n#if defined(LIT_CLEARCOAT)\n clearcoatReflectionDir,\n#endif\n gloss, \n specularity, \n geometricNormal, \n tbn, \n#if defined(LIT_IRIDESCENCE)\n iridescenceFresnel,\n#endif\n clearcoat_worldNormal,\n clearcoat_gloss,\n sheen_gloss,\n iridescence_intensity\n ); \n }\n }\n}\n',combinePS:"\nvec3 combineColor(vec3 albedo, vec3 sheenSpecularity, float clearcoatSpecularity) {\n vec3 ret = vec3(0);\n#ifdef LIT_OLD_AMBIENT\n ret += (dDiffuseLight - light_globalAmbient) * albedo + material_ambient * light_globalAmbient;\n#else\n ret += albedo * dDiffuseLight;\n#endif\n#ifdef LIT_SPECULAR\n ret += dSpecularLight;\n#endif\n#ifdef LIT_REFLECTIONS\n ret += dReflection.rgb * dReflection.a;\n#endif\n#ifdef LIT_SHEEN\n float sheenScaling = 1.0 - max(max(sheenSpecularity.r, sheenSpecularity.g), sheenSpecularity.b) * 0.157;\n ret = ret * sheenScaling + (sSpecularLight + sReflection.rgb) * sheenSpecularity;\n#endif\n#ifdef LIT_CLEARCOAT\n float clearCoatScaling = 1.0 - ccFresnel * clearcoatSpecularity;\n ret = ret * clearCoatScaling + (ccSpecularLight + ccReflection) * clearcoatSpecularity;\n#endif\n return ret;\n}\n",cookieBlit2DPS:"\n varying vec2 uv0;\n uniform sampler2D blitTexture;\n void main(void) {\n gl_FragColor = texture2D(blitTexture, uv0);\n }\n",cookieBlitCubePS:"\n varying vec2 uv0;\n uniform samplerCube blitTexture;\n uniform mat4 invViewProj;\n void main(void) {\n vec4 projPos = vec4(uv0 * 2.0 - 1.0, 0.5, 1.0);\n vec4 worldPos = invViewProj * projPos;\n gl_FragColor = textureCube(blitTexture, worldPos.xyz);\n }\n",cookieBlitVS:"\n attribute vec2 vertex_position;\n varying vec2 uv0;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.5, 1.0);\n uv0 = vertex_position.xy * 0.5 + 0.5;\n #ifndef WEBGPU\n uv0.y = 1.0 - uv0.y;\n #endif\n }\n",cookiePS:"\nvec4 getCookie2D(sampler2D tex, mat4 transform, float intensity) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n return mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);\n}\nvec4 getCookie2DClip(sampler2D tex, mat4 transform, float intensity) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n if (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0);\n return mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);\n}\nvec4 getCookie2DXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n projPos.xy += cookieOffset;\n vec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);\n return mix(vec4(1.0), texture2D(tex, uv), intensity);\n}\nvec4 getCookie2DClipXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n projPos.xy += cookieOffset;\n if (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0);\n vec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);\n return mix(vec4(1.0), texture2D(tex, uv), intensity);\n}\nvec4 getCookieCube(samplerCube tex, mat4 transform, float intensity) {\n return mix(vec4(1.0), textureCube(tex, dLightDirNormW * mat3(transform)), intensity);\n}\n",cubeMapProjectPS:"\n#if LIT_CUBEMAP_PROJECTION == BOX\n uniform vec3 envBoxMin;\n uniform vec3 envBoxMax;\n#endif\nvec3 cubeMapProject(vec3 nrdir) {\n #if LIT_CUBEMAP_PROJECTION == NONE\n return cubeMapRotate(nrdir);\n #endif\n #if LIT_CUBEMAP_PROJECTION == BOX\n nrdir = cubeMapRotate(nrdir);\n vec3 rbmax = (envBoxMax - vPositionW) / nrdir;\n vec3 rbmin = (envBoxMin - vPositionW) / nrdir;\n vec3 rbminmax = mix(rbmin, rbmax, vec3(greaterThan(nrdir, vec3(0.0))));\n float fa = min(min(rbminmax.x, rbminmax.y), rbminmax.z);\n vec3 posonbox = vPositionW + nrdir * fa;\n vec3 envBoxPos = (envBoxMin + envBoxMax) * 0.5;\n return normalize(posonbox - envBoxPos);\n #endif\n}\n",cubeMapRotatePS:"\n#ifdef CUBEMAP_ROTATION\nuniform mat3 cubeMapRotationMatrix;\n#endif\nvec3 cubeMapRotate(vec3 refDir) {\n#ifdef CUBEMAP_ROTATION\n return refDir * cubeMapRotationMatrix;\n#else\n return refDir;\n#endif\n}\n",debugOutputPS:"\n#ifdef DEBUG_ALBEDO_PASS\ngl_FragColor = vec4(gammaCorrectOutput(dAlbedo), 1.0);\n#endif\n#ifdef DEBUG_UV0_PASS\ngl_FragColor = vec4(litArgs_albedo , 1.0);\n#endif\n#ifdef DEBUG_WORLD_NORMAL_PASS\ngl_FragColor = vec4(litArgs_worldNormal * 0.5 + 0.5, 1.0);\n#endif\n#ifdef DEBUG_OPACITY_PASS\ngl_FragColor = vec4(vec3(litArgs_opacity) , 1.0);\n#endif\n#ifdef DEBUG_SPECULARITY_PASS\ngl_FragColor = vec4(litArgs_specularity, 1.0);\n#endif\n#ifdef DEBUG_GLOSS_PASS\ngl_FragColor = vec4(vec3(litArgs_gloss) , 1.0);\n#endif\n#ifdef DEBUG_METALNESS_PASS\ngl_FragColor = vec4(vec3(litArgs_metalness) , 1.0);\n#endif\n#ifdef DEBUG_AO_PASS\ngl_FragColor = vec4(vec3(litArgs_ao) , 1.0);\n#endif\n#ifdef DEBUG_EMISSION_PASS\ngl_FragColor = vec4(gammaCorrectOutput(litArgs_emission), 1.0);\n#endif\n",debugProcessFrontendPS:"\n#ifdef DEBUG_LIGHTING_PASS\nlitArgs_albedo = vec3(0.5);\n#endif\n#ifdef DEBUG_UV0_PASS\n#ifdef VARYING_VUV0\nlitArgs_albedo = vec3(vUv0, 0);\n#else\nlitArgs_albedo = vec3(0);\n#endif\n#endif\n",detailModesPS:"\n#ifndef _DETAILMODES_INCLUDED_\n#define _DETAILMODES_INCLUDED_\nvec3 detailMode_mul(vec3 c1, vec3 c2) {\n return c1 * c2;\n}\nvec3 detailMode_add(vec3 c1, vec3 c2) {\n return c1 + c2;\n}\nvec3 detailMode_screen(vec3 c1, vec3 c2) {\n return 1.0 - (1.0 - c1)*(1.0 - c2);\n}\nvec3 detailMode_overlay(vec3 c1, vec3 c2) {\n return mix(1.0 - 2.0 * (1.0 - c1)*(1.0 - c2), 2.0 * c1 * c2, step(c1, vec3(0.5)));\n}\nvec3 detailMode_min(vec3 c1, vec3 c2) {\n return min(c1, c2);\n}\nvec3 detailMode_max(vec3 c1, vec3 c2) {\n return max(c1, c2);\n}\n#endif\n",diffusePS:'\nuniform vec3 material_diffuse;\n#ifdef STD_DIFFUSEDETAIL_TEXTURE\n #include "detailModesPS"\n#endif\nvoid getAlbedo() {\n dAlbedo = material_diffuse.rgb;\n #ifdef STD_DIFFUSE_TEXTURE\n vec3 albedoTexture = {STD_DIFFUSE_TEXTURE_DECODE}(texture2DBias({STD_DIFFUSE_TEXTURE_NAME}, {STD_DIFFUSE_TEXTURE_UV}, textureBias)).{STD_DIFFUSE_TEXTURE_CHANNEL};\n #ifdef STD_DIFFUSEDETAIL_TEXTURE\n vec3 albedoDetail = {STD_DIFFUSEDETAIL_TEXTURE_DECODE}(texture2DBias({STD_DIFFUSEDETAIL_TEXTURE_NAME}, {STD_DIFFUSEDETAIL_TEXTURE_UV}, textureBias)).{STD_DIFFUSEDETAIL_TEXTURE_CHANNEL};\n albedoTexture = detailMode_{STD_DIFFUSEDETAIL_DETAILMODE}(albedoTexture, albedoDetail);\n #endif\n dAlbedo *= albedoTexture;\n #endif\n #ifdef STD_DIFFUSE_VERTEX\n dAlbedo *= gammaCorrectInput(saturate(vVertexColor.{STD_DIFFUSE_VERTEX_CHANNEL}));\n #endif\n}\n',decodePS:"\n#ifndef _DECODE_INCLUDED_\n#define _DECODE_INCLUDED_\nvec3 decodeLinear(vec4 raw) {\n return raw.rgb;\n}\nfloat decodeGamma(float raw) {\n return pow(raw, 2.2);\n}\nvec3 decodeGamma(vec3 raw) {\n return pow(raw, vec3(2.2));\n}\nvec3 decodeGamma(vec4 raw) {\n return pow(raw.xyz, vec3(2.2));\n}\nvec3 decodeRGBM(vec4 raw) {\n vec3 color = (8.0 * raw.a) * raw.rgb;\n return color * color;\n}\nvec3 decodeRGBP(vec4 raw) {\n vec3 color = raw.rgb * (-raw.a * 7.0 + 8.0);\n return color * color;\n}\nvec3 decodeRGBE(vec4 raw) {\n if (raw.a == 0.0) {\n return vec3(0.0, 0.0, 0.0);\n } else {\n return raw.xyz * pow(2.0, raw.w * 255.0 - 128.0);\n }\n}\nvec4 passThrough(vec4 raw) {\n return raw;\n}\nvec3 unpackNormalXYZ(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackNormalXY(vec4 nmap) {\n vec3 normal;\n normal.xy = nmap.wy * 2.0 - 1.0;\n normal.z = sqrt(1.0 - clamp(dot(normal.xy, normal.xy), 0.0, 1.0));\n return normal;\n}\n#endif\n",emissivePS:"\nuniform vec3 material_emissive;\nuniform float material_emissiveIntensity;\nvoid getEmission() {\n dEmission = material_emissive * material_emissiveIntensity;\n #ifdef STD_EMISSIVE_TEXTURE\n dEmission *= {STD_EMISSIVE_TEXTURE_DECODE}(texture2DBias({STD_EMISSIVE_TEXTURE_NAME}, {STD_EMISSIVE_TEXTURE_UV}, textureBias)).{STD_EMISSIVE_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_EMISSIVE_VERTEX\n dEmission *= gammaCorrectInput(saturate(vVertexColor.{STD_EMISSIVE_VERTEX_CHANNEL}));\n #endif\n}\n",encodePS:"\nvec4 encodeLinear(vec3 source) {\n return vec4(source, 1.0);\n}\nvec4 encodeGamma(vec3 source) {\n return vec4(pow(source + 0.0000001, vec3(1.0 / 2.2)), 1.0);\n}\nvec4 encodeRGBM(vec3 source) {\n vec4 result;\n result.rgb = pow(source.rgb, vec3(0.5));\n result.rgb *= 1.0 / 8.0;\n result.a = saturate( max( max( result.r, result.g ), max( result.b, 1.0 / 255.0 ) ) );\n result.a = ceil(result.a * 255.0) / 255.0;\n result.rgb /= result.a;\n return result;\n}\nvec4 encodeRGBP(vec3 source) {\n vec3 gamma = pow(source, vec3(0.5));\n float maxVal = min(8.0, max(1.0, max(gamma.x, max(gamma.y, gamma.z))));\n float v = 1.0 - ((maxVal - 1.0) / 7.0);\n v = ceil(v * 255.0) / 255.0;\n return vec4(gamma / (-v * 7.0 + 8.0), v); \n}\nvec4 encodeRGBE(vec3 source) {\n float maxVal = max(source.x, max(source.y, source.z));\n if (maxVal < 1e-32) {\n return vec4(0, 0, 0, 0);\n } else {\n float e = ceil(log2(maxVal));\n return vec4(source / pow(2.0, e), (e + 128.0) / 255.0);\n }\n}\n",endPS:"\n gl_FragColor.rgb = combineColor(litArgs_albedo, litArgs_sheen_specularity, litArgs_clearcoat_specularity);\n gl_FragColor.rgb += litArgs_emission;\n gl_FragColor.rgb = addFog(gl_FragColor.rgb);\n gl_FragColor.rgb = toneMap(gl_FragColor.rgb);\n gl_FragColor.rgb = gammaCorrectOutput(gl_FragColor.rgb);\n",envAtlasPS:"\n#ifndef _ENVATLAS_INCLUDED_\n#define _ENVATLAS_INCLUDED_\nconst float atlasSize = 512.0;\nconst float seamSize = 1.0 / atlasSize;\nvec2 mapUv(vec2 uv, vec4 rect) {\n return vec2(mix(rect.x + seamSize, rect.x + rect.z - seamSize, uv.x),\n mix(rect.y + seamSize, rect.y + rect.w - seamSize, uv.y));\n}\nvec2 mapRoughnessUv(vec2 uv, float level) {\n float t = 1.0 / exp2(level);\n return mapUv(uv, vec4(0, 1.0 - t, t, t * 0.5));\n}\nvec2 mapShinyUv(vec2 uv, float level) {\n float t = 1.0 / exp2(level);\n return mapUv(uv, vec4(1.0 - t, 1.0 - t, t, t * 0.5));\n}\n#endif\n",envProcPS:"\n#ifdef LIT_SKYBOX_INTENSITY\n uniform float skyboxIntensity;\n#endif\nvec3 processEnvironment(vec3 color) {\n #ifdef LIT_SKYBOX_INTENSITY\n return color * skyboxIntensity;\n #else\n return color;\n #endif\n}\n",falloffInvSquaredPS:"\nfloat getFalloffWindow(float lightRadius, vec3 lightDir) {\n float sqrDist = dot(lightDir, lightDir);\n float invRadius = 1.0 / lightRadius;\n return square(saturate(1.0 - square(sqrDist * square(invRadius))));\n}\nfloat getFalloffInvSquared(float lightRadius, vec3 lightDir) {\n float sqrDist = dot(lightDir, lightDir);\n float falloff = 1.0 / (sqrDist + 1.0);\n float invRadius = 1.0 / lightRadius;\n falloff *= 16.0;\n falloff *= square(saturate(1.0 - square(sqrDist * square(invRadius))));\n return falloff;\n}\n",falloffLinearPS:"\nfloat getFalloffLinear(float lightRadius, vec3 lightDir) {\n float d = length(lightDir);\n return max(((lightRadius - d) / lightRadius), 0.0);\n}\n",floatAsUintPS:"\n#ifndef FLOAT_AS_UINT\n#define FLOAT_AS_UINT\nvec4 float2uint(float value) {\n uint intBits = floatBitsToUint(value);\n return vec4(\n float((intBits >> 24u) & 0xFFu) / 255.0,\n float((intBits >> 16u) & 0xFFu) / 255.0,\n float((intBits >> 8u) & 0xFFu) / 255.0,\n float(intBits & 0xFFu) / 255.0\n );\n}\nfloat uint2float(vec4 value) {\n uint intBits = \n (uint(value.r * 255.0) << 24u) |\n (uint(value.g * 255.0) << 16u) |\n (uint(value.b * 255.0) << 8u) |\n uint(value.a * 255.0);\n return uintBitsToFloat(intBits);\n}\nvec4 float2vec4(float value) {\n #if defined(CAPS_TEXTURE_FLOAT_RENDERABLE)\n return vec4(value, 1.0, 1.0, 1.0);\n #else\n return float2uint(value);\n #endif\n}\n#endif\n",fogPS:"\nfloat dBlendModeFogFactor = 1.0;\n#if (FOG != NONE)\n uniform vec3 fog_color;\n #if (FOG == LINEAR)\n uniform float fog_start;\n uniform float fog_end;\n #else\n uniform float fog_density;\n #endif\n#endif\nfloat getFogFactor() {\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n float fogFactor = 0.0;\n #if (FOG == LINEAR)\n fogFactor = (fog_end - depth) / (fog_end - fog_start);\n #elif (FOG == EXP)\n fogFactor = exp(-depth * fog_density);\n #elif (FOG == EXP2)\n fogFactor = exp(-depth * depth * fog_density * fog_density);\n #endif\n return clamp(fogFactor, 0.0, 1.0);\n}\nvec3 addFog(vec3 color) {\n #if (FOG != NONE)\n return mix(fog_color * dBlendModeFogFactor, color, getFogFactor());\n #endif\n return color;\n}\n",fresnelSchlickPS:"\nvec3 getFresnel(\n float cosTheta, \n float gloss, \n vec3 specularity\n#if defined(LIT_IRIDESCENCE)\n , vec3 iridescenceFresnel, \n float iridescenceIntensity\n#endif\n ) {\n float fresnel = pow(1.0 - saturate(cosTheta), 5.0);\n float glossSq = gloss * gloss;\n vec3 ret = specularity + (max(vec3(glossSq), specularity) - specularity) * fresnel;\n#if defined(LIT_IRIDESCENCE)\n return mix(ret, iridescenceFresnel, iridescenceIntensity);\n#else\n return ret;\n#endif \n}\nfloat getFresnelCC(float cosTheta) {\n float fresnel = pow(1.0 - saturate(cosTheta), 5.0);\n return 0.04 + (1.0 - 0.04) * fresnel;\n}\n",frontendCodePS:"",frontendDeclPS:"",fullscreenQuadVS:"\nattribute vec2 vertex_position;\nvarying vec2 vUv0;\nvoid main(void)\n{\n gl_Position = vec4(vertex_position, 0.5, 1.0);\n vUv0 = vertex_position.xy * 0.5 + 0.5;\n}\n",gammaPS:'\n#include "decodePS"\n#if (GAMMA == SRGB)\n float gammaCorrectInput(float color) {\n return decodeGamma(color);\n }\n vec3 gammaCorrectInput(vec3 color) {\n return decodeGamma(color);\n }\n vec4 gammaCorrectInput(vec4 color) {\n return vec4(decodeGamma(color.xyz), color.w);\n }\n vec3 gammaCorrectOutput(vec3 color) {\n return pow(color + 0.0000001, vec3(1.0 / 2.2));\n }\n#else\n float gammaCorrectInput(float color) {\n return color;\n }\n vec3 gammaCorrectInput(vec3 color) {\n return color;\n }\n vec4 gammaCorrectInput(vec4 color) {\n return color;\n }\n vec3 gammaCorrectOutput(vec3 color) {\n return color;\n }\n#endif\n',gles3PS:rH,gles3VS:rW,glossPS:"\n#ifdef STD_GLOSS_CONSTANT\nuniform float material_gloss;\n#endif\nvoid getGlossiness() {\n dGlossiness = 1.0;\n #ifdef STD_GLOSS_CONSTANT\n dGlossiness *= material_gloss;\n #endif\n #ifdef STD_GLOSS_TEXTURE\n dGlossiness *= texture2DBias({STD_GLOSS_TEXTURE_NAME}, {STD_GLOSS_TEXTURE_UV}, textureBias).{STD_GLOSS_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_GLOSS_VERTEX\n dGlossiness *= saturate(vVertexColor.{STD_GLOSS_VERTEX_CHANNEL});\n #endif\n #ifdef STD_GLOSS_INVERT\n dGlossiness = 1.0 - dGlossiness;\n #endif\n dGlossiness += 0.0000001;\n}\n",gsplatCenterVS:"\nuniform mat4 matrix_model;\nuniform mat4 matrix_view;\nuniform mat4 matrix_projection;\nbool initCenter(vec3 modelCenter, out SplatCenter center) {\n mat4 modelView = matrix_view * matrix_model;\n vec4 centerView = modelView * vec4(modelCenter, 1.0);\n if (centerView.z > 0.0) {\n return false;\n }\n vec4 centerProj = matrix_projection * centerView;\n #if WEBGPU\n centerProj.z = clamp(centerProj.z, 0, abs(centerProj.w));\n #else\n centerProj.z = clamp(centerProj.z, -abs(centerProj.w), abs(centerProj.w));\n #endif\n center.view = centerView.xyz / centerView.w;\n center.proj = centerProj;\n center.projMat00 = matrix_projection[0][0];\n center.modelView = modelView;\n return true;\n}\n",gsplatCornerVS:"\nuniform vec2 viewport;\nuniform vec4 camera_params;\nbool initCorner(SplatSource source, SplatCenter center, out SplatCorner corner) {\n vec3 covA, covB;\n readCovariance(source, covA, covB);\n mat3 Vrk = mat3(\n covA.x, covA.y, covA.z, \n covA.y, covB.x, covB.y,\n covA.z, covB.y, covB.z\n );\n float focal = viewport.x * center.projMat00;\n vec3 v = camera_params.w == 1.0 ? vec3(0.0, 0.0, 1.0) : center.view.xyz;\n float J1 = focal / v.z;\n vec2 J2 = -J1 / v.z * v.xy;\n mat3 J = mat3(\n J1, 0.0, J2.x, \n 0.0, J1, J2.y, \n 0.0, 0.0, 0.0\n );\n mat3 W = transpose(mat3(center.modelView));\n mat3 T = W * J;\n mat3 cov = transpose(T) * Vrk * T;\n #if GSPLAT_AA\n float detOrig = cov[0][0] * cov[1][1] - cov[0][1] * cov[0][1];\n float detBlur = (cov[0][0] + 0.3) * (cov[1][1] + 0.3) - cov[0][1] * cov[0][1];\n corner.aaFactor = sqrt(max(detOrig / detBlur, 0.0));\n #endif\n float diagonal1 = cov[0][0] + 0.3;\n float offDiagonal = cov[0][1];\n float diagonal2 = cov[1][1] + 0.3;\n float mid = 0.5 * (diagonal1 + diagonal2);\n float radius = length(vec2((diagonal1 - diagonal2) / 2.0, offDiagonal));\n float lambda1 = mid + radius;\n float lambda2 = max(mid - radius, 0.1);\n float vmin = min(1024.0, min(viewport.x, viewport.y));\n float l1 = 2.0 * min(sqrt(2.0 * lambda1), vmin);\n float l2 = 2.0 * min(sqrt(2.0 * lambda2), vmin);\n if (l1 < 2.0 && l2 < 2.0) {\n return false;\n }\n vec2 c = center.proj.ww / viewport;\n if (any(greaterThan(abs(center.proj.xy) - vec2(max(l1, l2)) * c, center.proj.ww))) {\n return false;\n }\n vec2 diagonalVector = normalize(vec2(offDiagonal, lambda1 - diagonal1));\n vec2 v1 = l1 * diagonalVector;\n vec2 v2 = l2 * vec2(diagonalVector.y, -diagonalVector.x);\n corner.offset = (source.cornerUV.x * v1 + source.cornerUV.y * v2) * c;\n corner.uv = source.cornerUV;\n return true;\n}\n",gsplatColorVS:"\nuniform mediump sampler2D splatColor;\nvec4 readColor(in SplatSource source) {\n return texelFetch(splatColor, source.uv, 0);\n}\n",gsplatCommonVS:'\nstruct SplatSource {\n uint order;\n uint id;\n ivec2 uv;\n vec2 cornerUV;\n};\nstruct SplatCenter {\n vec3 view;\n vec4 proj;\n mat4 modelView;\n float projMat00;\n};\nmat3 quatToMat3(vec4 R) {\n vec4 R2 = R + R;\n float X = R2.x * R.w;\n vec4 Y = R2.y * R;\n vec4 Z = R2.z * R;\n float W = R2.w * R.w;\n return mat3(\n 1.0 - Z.z - W,\n Y.z + X,\n Y.w - Z.x,\n Y.z - X,\n 1.0 - Y.y - W,\n Z.w + Y.x,\n Y.w + Z.x,\n Z.w - Y.x,\n 1.0 - Y.y - Z.z\n );\n}\nstruct SplatCorner {\n vec2 offset;\n vec2 uv;\n #if GSPLAT_AA\n float aaFactor;\n #endif\n};\n#if SH_BANDS == 1\n #define SH_COEFFS 3\n#elif SH_BANDS == 2\n #define SH_COEFFS 8\n#elif SH_BANDS == 3\n #define SH_COEFFS 15\n#else\n #define SH_COEFFS 0\n#endif\n#if GSPLAT_COMPRESSED_DATA == true\n #include "gsplatCompressedDataVS"\n #if SH_COEFFS > 0\n #include "gsplatCompressedSHVS"\n #endif\n#elif GSPLAT_SOGS_DATA == true\n #include "gsplatSogsDataVS"\n #include "gsplatSogsColorVS"\n #if SH_COEFFS > 0\n #include "gsplatSogsSHVS"\n #endif\n#else\n #include "gsplatDataVS"\n #include "gsplatColorVS"\n #if SH_COEFFS > 0\n #include "gsplatSHVS"\n #endif\n#endif\n#include "gsplatSourceVS"\n#include "gsplatCenterVS"\n#include "gsplatCornerVS"\n#include "gsplatOutputVS"\nvoid clipCorner(inout SplatCorner corner, float alpha) {\n float clip = min(1.0, sqrt(-log(1.0 / 255.0 / alpha)) / 2.0);\n corner.offset *= clip;\n corner.uv *= clip;\n}\n#if SH_BANDS > 0\n #define SH_C1 0.4886025119029199f\n #if SH_BANDS > 1\n #define SH_C2_0 1.0925484305920792f\n #define SH_C2_1 -1.0925484305920792f\n #define SH_C2_2 0.31539156525252005f\n #define SH_C2_3 -1.0925484305920792f\n #define SH_C2_4 0.5462742152960396f\n #endif\n #if SH_BANDS > 2\n #define SH_C3_0 -0.5900435899266435f\n #define SH_C3_1 2.890611442640554f\n #define SH_C3_2 -0.4570457994644658f\n #define SH_C3_3 0.3731763325901154f\n #define SH_C3_4 -0.4570457994644658f\n #define SH_C3_5 1.445305721320277f\n #define SH_C3_6 -0.5900435899266435f\n #endif\n vec3 evalSH(in SplatSource source, in vec3 dir) {\n vec3 sh[SH_COEFFS];\n float scale;\n readSHData(source, sh, scale);\n float x = dir.x;\n float y = dir.y;\n float z = dir.z;\n vec3 result = SH_C1 * (-sh[0] * y + sh[1] * z - sh[2] * x);\n #if SH_BANDS > 1\n float xx = x * x;\n float yy = y * y;\n float zz = z * z;\n float xy = x * y;\n float yz = y * z;\n float xz = x * z;\n result +=\n sh[3] * (SH_C2_0 * xy) +\n sh[4] * (SH_C2_1 * yz) +\n sh[5] * (SH_C2_2 * (2.0 * zz - xx - yy)) +\n sh[6] * (SH_C2_3 * xz) +\n sh[7] * (SH_C2_4 * (xx - yy));\n #endif\n #if SH_BANDS > 2\n result +=\n sh[8] * (SH_C3_0 * y * (3.0 * xx - yy)) +\n sh[9] * (SH_C3_1 * xy * z) +\n sh[10] * (SH_C3_2 * y * (4.0 * zz - xx - yy)) +\n sh[11] * (SH_C3_3 * z * (2.0 * zz - 3.0 * xx - 3.0 * yy)) +\n sh[12] * (SH_C3_4 * x * (4.0 * zz - xx - yy)) +\n sh[13] * (SH_C3_5 * z * (xx - yy)) +\n sh[14] * (SH_C3_6 * x * (xx - 3.0 * yy));\n #endif\n return result * scale;\n }\n#endif\n',gsplatCompressedDataVS:"\nuniform highp usampler2D packedTexture;\nuniform highp sampler2D chunkTexture;\nvec4 chunkDataA;\nvec4 chunkDataB;\nvec4 chunkDataC;\nvec4 chunkDataD;\nvec4 chunkDataE;\nuvec4 packedData;\nvec3 unpack111011(uint bits) {\n return vec3(\n float(bits >> 21u) / 2047.0,\n float((bits >> 11u) & 0x3ffu) / 1023.0,\n float(bits & 0x7ffu) / 2047.0\n );\n}\nvec4 unpack8888(uint bits) {\n return vec4(\n float(bits >> 24u) / 255.0,\n float((bits >> 16u) & 0xffu) / 255.0,\n float((bits >> 8u) & 0xffu) / 255.0,\n float(bits & 0xffu) / 255.0\n );\n}\nconst float norm = 1.0 / (sqrt(2.0) * 0.5);\nvec4 unpackRotation(uint bits) {\n float a = (float((bits >> 20u) & 0x3ffu) / 1023.0 - 0.5) * norm;\n float b = (float((bits >> 10u) & 0x3ffu) / 1023.0 - 0.5) * norm;\n float c = (float(bits & 0x3ffu) / 1023.0 - 0.5) * norm;\n float m = sqrt(1.0 - (a * a + b * b + c * c));\n uint mode = bits >> 30u;\n if (mode == 0u) return vec4(m, a, b, c);\n if (mode == 1u) return vec4(a, m, b, c);\n if (mode == 2u) return vec4(a, b, m, c);\n return vec4(a, b, c, m);\n}\nvec3 readCenter(SplatSource source) {\n uint w = uint(textureSize(chunkTexture, 0).x) / 5u;\n uint chunkId = source.id / 256u;\n ivec2 chunkUV = ivec2((chunkId % w) * 5u, chunkId / w);\n chunkDataA = texelFetch(chunkTexture, chunkUV, 0);\n chunkDataB = texelFetch(chunkTexture, chunkUV + ivec2(1, 0), 0);\n chunkDataC = texelFetch(chunkTexture, chunkUV + ivec2(2, 0), 0);\n chunkDataD = texelFetch(chunkTexture, chunkUV + ivec2(3, 0), 0);\n chunkDataE = texelFetch(chunkTexture, chunkUV + ivec2(4, 0), 0);\n packedData = texelFetch(packedTexture, source.uv, 0);\n return mix(chunkDataA.xyz, vec3(chunkDataA.w, chunkDataB.xy), unpack111011(packedData.x));\n}\nvec4 readColor(in SplatSource source) {\n vec4 r = unpack8888(packedData.w);\n return vec4(mix(chunkDataD.xyz, vec3(chunkDataD.w, chunkDataE.xy), r.rgb), r.w);\n}\nvec4 getRotation() {\n return unpackRotation(packedData.y);\n}\nvec3 getScale() {\n return exp(mix(vec3(chunkDataB.zw, chunkDataC.x), chunkDataC.yzw, unpack111011(packedData.z)));\n}\nvoid readCovariance(in SplatSource source, out vec3 covA, out vec3 covB) {\n mat3 rot = quatToMat3(getRotation());\n vec3 scale = getScale();\n mat3 M = transpose(mat3(\n scale.x * rot[0],\n scale.y * rot[1],\n scale.z * rot[2]\n ));\n covA = vec3(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2]));\n covB = vec3(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2]));\n}\n",gsplatCompressedSHVS:"\n#if SH_BANDS > 0\nuniform highp usampler2D shTexture0;\nuniform highp usampler2D shTexture1;\nuniform highp usampler2D shTexture2;\nvec4 unpack8888s(in uint bits) {\n return vec4((uvec4(bits) >> uvec4(0u, 8u, 16u, 24u)) & 0xffu) * (8.0 / 255.0) - 4.0;\n}\nvoid readSHData(in SplatSource source, out vec3 sh[15], out float scale) {\n uvec4 shData0 = texelFetch(shTexture0, source.uv, 0);\n uvec4 shData1 = texelFetch(shTexture1, source.uv, 0);\n uvec4 shData2 = texelFetch(shTexture2, source.uv, 0);\n vec4 r0 = unpack8888s(shData0.x);\n vec4 r1 = unpack8888s(shData0.y);\n vec4 r2 = unpack8888s(shData0.z);\n vec4 r3 = unpack8888s(shData0.w);\n vec4 g0 = unpack8888s(shData1.x);\n vec4 g1 = unpack8888s(shData1.y);\n vec4 g2 = unpack8888s(shData1.z);\n vec4 g3 = unpack8888s(shData1.w);\n vec4 b0 = unpack8888s(shData2.x);\n vec4 b1 = unpack8888s(shData2.y);\n vec4 b2 = unpack8888s(shData2.z);\n vec4 b3 = unpack8888s(shData2.w);\n sh[0] = vec3(r0.x, g0.x, b0.x);\n sh[1] = vec3(r0.y, g0.y, b0.y);\n sh[2] = vec3(r0.z, g0.z, b0.z);\n sh[3] = vec3(r0.w, g0.w, b0.w);\n sh[4] = vec3(r1.x, g1.x, b1.x);\n sh[5] = vec3(r1.y, g1.y, b1.y);\n sh[6] = vec3(r1.z, g1.z, b1.z);\n sh[7] = vec3(r1.w, g1.w, b1.w);\n sh[8] = vec3(r2.x, g2.x, b2.x);\n sh[9] = vec3(r2.y, g2.y, b2.y);\n sh[10] = vec3(r2.z, g2.z, b2.z);\n sh[11] = vec3(r2.w, g2.w, b2.w);\n sh[12] = vec3(r3.x, g3.x, b3.x);\n sh[13] = vec3(r3.y, g3.y, b3.y);\n sh[14] = vec3(r3.z, g3.z, b3.z);\n scale = 1.0;\n}\n#endif\n",gsplatSogsColorVS:"\nuniform mediump sampler2D sh0;\nuniform vec4 sh0_mins;\nuniform vec4 sh0_maxs;\nfloat SH_C0 = 0.28209479177387814;\nvec4 readColor(in SplatSource source) {\n vec4 clr = mix(sh0_mins, sh0_maxs, texelFetch(sh0, source.uv, 0));\n return vec4(vec3(0.5) + clr.xyz * SH_C0, 1.0 / (1.0 + exp(-clr.w)));\n}\n",gsplatSogsDataVS:"\nuniform highp sampler2D means_u;\nuniform highp sampler2D means_l;\nuniform highp sampler2D quats;\nuniform highp sampler2D scales;\nuniform vec3 means_mins;\nuniform vec3 means_maxs;\nuniform vec3 scales_mins;\nuniform vec3 scales_maxs;\nvec3 readCenter(SplatSource source) {\n vec3 u = texelFetch(means_u, source.uv, 0).xyz;\n vec3 l = texelFetch(means_l, source.uv, 0).xyz;\n vec3 n = (l * 255.0 + u * 255.0 * 256.0) / 65535.0;\n vec3 v = mix(means_mins, means_maxs, n);\n return sign(v) * (exp(abs(v)) - 1.0);\n}\nconst float norm = 2.0 / sqrt(2.0);\nvoid readCovariance(in SplatSource source, out vec3 covA, out vec3 covB) {\n vec4 qdata = texelFetch(quats, source.uv, 0);\n vec3 abc = (qdata.xyz - 0.5) * norm;\n float d = sqrt(max(0.0, 1.0 - dot(abc, abc)));\n uint mode = uint(qdata.w * 255.0 + 0.5) - 252u;\n vec4 quat = (mode == 0u) ? vec4(d, abc) :\n ((mode == 1u) ? vec4(abc.x, d, abc.yz) :\n ((mode == 2u) ? vec4(abc.xy, d, abc.z) : vec4(abc, d)));\n mat3 rot = quatToMat3(quat);\n vec3 scale = exp(mix(scales_mins, scales_maxs, texelFetch(scales, source.uv, 0).xyz));\n mat3 M = transpose(mat3(\n scale.x * rot[0],\n scale.y * rot[1],\n scale.z * rot[2]\n ));\n covA = vec3(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2]));\n covB = vec3(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2]));\n}\n",gsplatSogsSHVS:"\nuniform highp sampler2D sh_labels;\nuniform highp sampler2D sh_centroids;\nuniform float shN_mins;\nuniform float shN_maxs;\nvoid readSHData(in SplatSource source, out vec3 sh[SH_COEFFS], out float scale) {\n ivec2 t = ivec2(texelFetch(sh_labels, source.uv, 0).xy * 255.0);\n int n = t.x + t.y * 256;\n int u = (n % 64) * SH_COEFFS;\n int v = n / 64;\n for (int i = 0; i < SH_COEFFS; i++) {\n sh[i] = mix(vec3(shN_mins), vec3(shN_maxs), texelFetch(sh_centroids, ivec2(u + i, v), 0).xyz);\n }\n scale = 1.0;\n}\n",gsplatDataVS:"\nuniform highp usampler2D transformA;\nuniform highp sampler2D transformB;\nuint tAw;\nvec3 readCenter(SplatSource source) {\n uvec4 tA = texelFetch(transformA, source.uv, 0);\n tAw = tA.w;\n return uintBitsToFloat(tA.xyz);\n}\nvec4 unpackRotation(vec3 packed) {\n return vec4(packed.xyz, sqrt(max(0.0, 1.0 - dot(packed, packed))));\n}\nvoid readCovariance(in SplatSource source, out vec3 covA, out vec3 covB) {\n vec4 tB = texelFetch(transformB, source.uv, 0);\n mat3 rot = quatToMat3(unpackRotation(vec3(unpackHalf2x16(tAw), tB.w)).wxyz);\n vec3 scale = tB.xyz;\n \n mat3 M = transpose(mat3(\n scale.x * rot[0],\n scale.y * rot[1],\n scale.z * rot[2]\n ));\n covA = vec3(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2]));\n covB = vec3(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2]));\n}\n",gsplatOutputVS:'\n#include "tonemappingPS"\n#include "decodePS"\n#include "gammaPS"\nvec3 prepareOutputFromGamma(vec3 gammaColor) {\n #if TONEMAP == NONE\n #if GAMMA == NONE\n return decodeGamma(gammaColor);\n #else\n return gammaColor;\n #endif\n #else\n return gammaCorrectOutput(toneMap(decodeGamma(gammaColor)));\n #endif\n}\n',gsplatPS:'\n#ifndef DITHER_NONE\n #include "bayerPS"\n #include "opacityDitherPS"\n varying float id;\n#endif\n#ifdef PICK_PASS\n #include "pickPS"\n#endif\n#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS)\n uniform float alphaClip;\n#endif\n#ifdef PREPASS_PASS\n varying float vLinearDepth;\n #include "floatAsUintPS"\n#endif\nconst float EXP_A = 12102203.0;\nconst int EXP_BC_RMS = 1064866808;\nfloat fastExp(float x) {\n int i = int(EXP_A * x) + EXP_BC_RMS;\n return intBitsToFloat(i);\n}\nvarying mediump vec2 gaussianUV;\nvarying mediump vec4 gaussianColor;\nvoid main(void) {\n mediump float A = dot(gaussianUV, gaussianUV);\n if (A > 1.0) {\n discard;\n }\n mediump float alpha = fastExp(-A * 4.0) * gaussianColor.a;\n #if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS)\n if (alpha < alphaClip) {\n discard;\n }\n #endif\n #ifdef PICK_PASS\n gl_FragColor = getPickOutput();\n #elif SHADOW_PASS\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n #elif PREPASS_PASS\n gl_FragColor = float2vec4(vLinearDepth);\n #else\n if (alpha < 1.0 / 255.0) {\n discard;\n }\n #ifndef DITHER_NONE\n opacityDither(alpha, id * 0.013);\n #endif\n gl_FragColor = vec4(gaussianColor.xyz * alpha, alpha);\n #endif\n}\n',gsplatSHVS:"\n#if SH_BANDS > 0\nvec3 unpack111011s(uint bits) {\n return vec3((uvec3(bits) >> uvec3(21u, 11u, 0u)) & uvec3(0x7ffu, 0x3ffu, 0x7ffu)) / vec3(2047.0, 1023.0, 2047.0) * 2.0 - 1.0;\n}\nvoid fetchScale(in uvec4 t, out float scale, out vec3 a, out vec3 b, out vec3 c) {\n scale = uintBitsToFloat(t.x);\n a = unpack111011s(t.y);\n b = unpack111011s(t.z);\n c = unpack111011s(t.w);\n}\nvoid fetch(in uvec4 t, out vec3 a, out vec3 b, out vec3 c, out vec3 d) {\n a = unpack111011s(t.x);\n b = unpack111011s(t.y);\n c = unpack111011s(t.z);\n d = unpack111011s(t.w);\n}\nvoid fetch(in uint t, out vec3 a) {\n a = unpack111011s(t);\n}\n#if SH_BANDS == 1\n uniform highp usampler2D splatSH_1to3;\n void readSHData(in SplatSource source, out vec3 sh[3], out float scale) {\n fetchScale(texelFetch(splatSH_1to3, source.uv, 0), scale, sh[0], sh[1], sh[2]);\n }\n#elif SH_BANDS == 2\n uniform highp usampler2D splatSH_1to3;\n uniform highp usampler2D splatSH_4to7;\n uniform highp usampler2D splatSH_8to11;\n void readSHData(in SplatSource source, out vec3 sh[8], out float scale) {\n fetchScale(texelFetch(splatSH_1to3, source.uv, 0), scale, sh[0], sh[1], sh[2]);\n fetch(texelFetch(splatSH_4to7, source.uv, 0), sh[3], sh[4], sh[5], sh[6]);\n fetch(texelFetch(splatSH_8to11, source.uv, 0).x, sh[7]);\n }\n#else\n uniform highp usampler2D splatSH_1to3;\n uniform highp usampler2D splatSH_4to7;\n uniform highp usampler2D splatSH_8to11;\n uniform highp usampler2D splatSH_12to15;\n void readSHData(in SplatSource source, out vec3 sh[15], out float scale) {\n fetchScale(texelFetch(splatSH_1to3, source.uv, 0), scale, sh[0], sh[1], sh[2]);\n fetch(texelFetch(splatSH_4to7, source.uv, 0), sh[3], sh[4], sh[5], sh[6]);\n fetch(texelFetch(splatSH_8to11, source.uv, 0), sh[7], sh[8], sh[9], sh[10]);\n fetch(texelFetch(splatSH_12to15, source.uv, 0), sh[11], sh[12], sh[13], sh[14]);\n }\n#endif\n#endif\n",gsplatSourceVS:"\nattribute vec3 vertex_position;\nattribute uint vertex_id_attrib;\nuniform uint numSplats;\nuniform highp usampler2D splatOrder;\nbool initSource(out SplatSource source) {\n uint w = uint(textureSize(splatOrder, 0).x);\n source.order = vertex_id_attrib + uint(vertex_position.z);\n if (source.order >= numSplats) {\n return false;\n }\n ivec2 orderUV = ivec2(source.order % w, source.order / w);\n source.id = texelFetch(splatOrder, orderUV, 0).r;\n source.uv = ivec2(source.id % w, source.id / w);\n source.cornerUV = vertex_position.xy;\n return true;\n}\n",gsplatVS:'\n#include "gsplatCommonVS"\nvarying mediump vec2 gaussianUV;\nvarying mediump vec4 gaussianColor;\n#ifndef DITHER_NONE\n varying float id;\n#endif\nmediump vec4 discardVec = vec4(0.0, 0.0, 2.0, 1.0);\n#ifdef PREPASS_PASS\n varying float vLinearDepth;\n#endif\nvoid main(void) {\n SplatSource source;\n if (!initSource(source)) {\n gl_Position = discardVec;\n return;\n }\n vec3 modelCenter = readCenter(source);\n SplatCenter center;\n if (!initCenter(modelCenter, center)) {\n gl_Position = discardVec;\n return;\n }\n SplatCorner corner;\n if (!initCorner(source, center, corner)) {\n gl_Position = discardVec;\n return;\n }\n vec4 clr = readColor(source);\n #if GSPLAT_AA\n clr.a *= corner.aaFactor;\n #endif\n #if SH_BANDS > 0\n vec3 dir = normalize(center.view * mat3(center.modelView));\n clr.xyz += evalSH(source, dir);\n #endif\n clipCorner(corner, clr.w);\n gl_Position = center.proj + vec4(corner.offset, 0, 0);\n gaussianUV = corner.uv;\n gaussianColor = vec4(prepareOutputFromGamma(max(clr.xyz, 0.0)), clr.w);\n #ifndef DITHER_NONE\n id = float(source.id);\n #endif\n #ifdef PREPASS_PASS\n vLinearDepth = -center.view.z;\n #endif\n}\n',quadVS:"\n attribute vec2 aPosition;\n varying vec2 uv0;\n void main(void)\n {\n gl_Position = vec4(aPosition, 0.0, 1.0);\n uv0 = getImageEffectUV((aPosition.xy + 1.0) * 0.5);\n }\n",immediateLinePS:'\n #include "gammaPS"\n varying vec4 color;\n void main(void) {\n gl_FragColor = vec4(gammaCorrectOutput(decodeGamma(color.rgb)), color.a);\n }\n',immediateLineVS:"\n attribute vec4 vertex_position;\n attribute vec4 vertex_color;\n uniform mat4 matrix_model;\n uniform mat4 matrix_viewProjection;\n varying vec4 color;\n void main(void) {\n color = vertex_color;\n gl_Position = matrix_viewProjection * matrix_model * vertex_position;\n }\n",iridescenceDiffractionPS:"\nuniform float material_iridescenceRefractionIndex;\nfloat iridescence_iorToFresnel(float transmittedIor, float incidentIor) {\n return pow((transmittedIor - incidentIor) / (transmittedIor + incidentIor), 2.0);\n}\nvec3 iridescence_iorToFresnel(vec3 transmittedIor, float incidentIor) {\n return pow((transmittedIor - vec3(incidentIor)) / (transmittedIor + vec3(incidentIor)), vec3(2.0));\n}\nvec3 iridescence_fresnelToIor(vec3 f0) {\n vec3 sqrtF0 = sqrt(f0);\n return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0);\n}\nvec3 iridescence_sensitivity(float opd, vec3 shift) {\n float PI = 3.141592653589793;\n float phase = 2.0 * PI * opd * 1.0e-9;\n const vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13);\n const vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06);\n const vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09);\n vec3 xyz = val * sqrt(2.0 * PI * var) * cos(pos * phase + shift) * exp(-pow(phase, 2.0) * var);\n xyz.x += 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift[0]) * exp(-4.5282e+09 * pow(phase, 2.0));\n xyz /= vec3(1.0685e-07);\n const mat3 XYZ_TO_REC709 = mat3(\n 3.2404542, -0.9692660, 0.0556434,\n -1.5371385, 1.8760108, -0.2040259,\n -0.4985314, 0.0415560, 1.0572252\n );\n return XYZ_TO_REC709 * xyz;\n}\nfloat iridescence_fresnel(float cosTheta, float f0) {\n float x = clamp(1.0 - cosTheta, 0.0, 1.0);\n float x2 = x * x;\n float x5 = x * x2 * x2;\n return f0 + (1.0 - f0) * x5;\n} \nvec3 iridescence_fresnel(float cosTheta, vec3 f0) {\n float x = clamp(1.0 - cosTheta, 0.0, 1.0);\n float x2 = x * x;\n float x5 = x * x2 * x2; \n return f0 + (vec3(1.0) - f0) * x5;\n}\nvec3 calcIridescence(float outsideIor, float cosTheta, vec3 base_f0, float iridescenceThickness) {\n float PI = 3.141592653589793;\n float iridescenceIor = mix(outsideIor, material_iridescenceRefractionIndex, smoothstep(0.0, 0.03, iridescenceThickness));\n float sinTheta2Sq = pow(outsideIor / iridescenceIor, 2.0) * (1.0 - pow(cosTheta, 2.0));\n float cosTheta2Sq = 1.0 - sinTheta2Sq;\n if (cosTheta2Sq < 0.0) {\n return vec3(1.0);\n }\n float cosTheta2 = sqrt(cosTheta2Sq);\n float r0 = iridescence_iorToFresnel(iridescenceIor, outsideIor);\n float r12 = iridescence_fresnel(cosTheta, r0);\n float r21 = r12;\n float t121 = 1.0 - r12;\n float phi12 = iridescenceIor < outsideIor ? PI : 0.0;\n float phi21 = PI - phi12;\n vec3 baseIor = iridescence_fresnelToIor(base_f0 + vec3(0.0001));\n vec3 r1 = iridescence_iorToFresnel(baseIor, iridescenceIor);\n vec3 r23 = iridescence_fresnel(cosTheta2, r1);\n vec3 phi23 = vec3(0.0);\n if (baseIor[0] < iridescenceIor) phi23[0] = PI;\n if (baseIor[1] < iridescenceIor) phi23[1] = PI;\n if (baseIor[2] < iridescenceIor) phi23[2] = PI;\n float opd = 2.0 * iridescenceIor * iridescenceThickness * cosTheta2;\n vec3 phi = vec3(phi21) + phi23; \n vec3 r123Sq = clamp(r12 * r23, 1e-5, 0.9999);\n vec3 r123 = sqrt(r123Sq);\n vec3 rs = pow(t121, 2.0) * r23 / (1.0 - r123Sq);\n vec3 c0 = r12 + rs;\n vec3 i = c0;\n vec3 cm = rs - t121;\n for (int m = 1; m <= 2; m++) {\n cm *= r123;\n vec3 sm = 2.0 * iridescence_sensitivity(float(m) * opd, float(m) * phi);\n i += cm * sm;\n }\n return max(i, vec3(0.0));\n}\nvec3 getIridescence(float cosTheta, vec3 specularity, float iridescenceThickness) {\n return calcIridescence(1.0, cosTheta, specularity, iridescenceThickness);\n}\n",iridescencePS:"\n#ifdef STD_IRIDESCENCE_CONSTANT\nuniform float material_iridescence;\n#endif\nvoid getIridescence() {\n float iridescence = 1.0;\n #ifdef STD_IRIDESCENCE_CONSTANT\n iridescence *= material_iridescence;\n #endif\n #ifdef STD_IRIDESCENCE_TEXTURE\n iridescence *= texture2DBias({STD_IRIDESCENCE_TEXTURE_NAME}, {STD_IRIDESCENCE_TEXTURE_UV}, textureBias).{STD_IRIDESCENCE_TEXTURE_CHANNEL};\n #endif\n dIridescence = iridescence; \n}\n",iridescenceThicknessPS:"\nuniform float material_iridescenceThicknessMax;\n#ifdef STD_IRIDESCENCETHICKNESS_TEXTURE\nuniform float material_iridescenceThicknessMin;\n#endif\nvoid getIridescenceThickness() {\n #ifdef STD_IRIDESCENCETHICKNESS_TEXTURE\n float blend = texture2DBias({STD_IRIDESCENCETHICKNESS_TEXTURE_NAME}, {STD_IRIDESCENCETHICKNESS_TEXTURE_UV}, textureBias).{STD_IRIDESCENCETHICKNESS_TEXTURE_CHANNEL};\n float iridescenceThickness = mix(material_iridescenceThicknessMin, material_iridescenceThicknessMax, blend);\n #else\n float iridescenceThickness = material_iridescenceThicknessMax;\n #endif\n dIridescenceThickness = iridescenceThickness; \n}\n",iorPS:"\n#ifdef STD_IOR_CONSTANT\nuniform float material_refractionIndex;\n#endif\nvoid getIor() {\n#ifdef STD_IOR_CONSTANT\n dIor = material_refractionIndex;\n#else\n dIor = 1.0 / 1.5;\n#endif\n}\n",lightDeclarationPS:"\n#if defined(LIGHT{i})\n uniform vec3 light{i}_color;\n #if LIGHT{i}TYPE == DIRECTIONAL\n uniform vec3 light{i}_direction;\n #else\n #define LIT_CODE_LIGHTS_POINT\n uniform vec3 light{i}_position;\n uniform float light{i}_radius;\n #if LIGHT{i}TYPE == SPOT\n #define LIT_CODE_LIGHTS_SPOT\n uniform vec3 light{i}_direction;\n uniform float light{i}_innerConeAngle;\n uniform float light{i}_outerConeAngle;\n #endif\n #endif\n #if LIGHT{i}SHAPE != PUNCTUAL\n #define LIT_CODE_FALLOFF_SQUARED\n #if LIGHT{i}TYPE == DIRECTIONAL\n uniform vec3 light{i}_position;\n #endif\n uniform vec3 light{i}_halfWidth;\n uniform vec3 light{i}_halfHeight;\n #else\n #if LIGHT{i}FALLOFF == LINEAR\n #define LIT_CODE_FALLOFF_LINEAR\n #endif\n #if LIGHT{i}FALLOFF == INVERSESQUARED\n #define LIT_CODE_FALLOFF_SQUARED\n #endif\n #endif\n #if defined(LIGHT{i}CASTSHADOW)\n uniform mat4 light{i}_shadowMatrix;\n uniform float light{i}_shadowIntensity;\n uniform vec4 light{i}_shadowParams;\n #if LIGHT{i}SHADOWTYPE == PCSS_32F\n uniform float light{i}_shadowSearchArea;\n uniform vec4 light{i}_cameraParams;\n #if LIGHT{i}TYPE == DIRECTIONAL\n uniform vec4 light{i}_softShadowParams;\n #endif\n #endif\n #if LIGHT{i}TYPE == DIRECTIONAL\n uniform mat4 light{i}_shadowMatrixPalette[4];\n uniform vec4 light{i}_shadowCascadeDistances;\n uniform int light{i}_shadowCascadeCount;\n uniform float light{i}_shadowCascadeBlend;\n #endif\n #if LIGHT{i}TYPE == OMNI\n #if defined(LIGHT{i}SHADOW_PCF)\n uniform samplerCubeShadow light{i}_shadowMap;\n #else\n uniform samplerCube light{i}_shadowMap;\n #endif\n #else\n #if defined(LIGHT{i}SHADOW_PCF)\n uniform sampler2DShadow light{i}_shadowMap;\n #else\n uniform sampler2D light{i}_shadowMap;\n #endif\n #endif\n #endif\n #if defined(LIGHT{i}COOKIE)\n #define LIT_CODE_COOKIE\n #if LIGHT{i}TYPE == OMNI\n uniform samplerCube light{i}_cookie;\n uniform float light{i}_cookieIntensity;\n #if !defined(LIGHT{i}CASTSHADOW)\n uniform mat4 light{i}_shadowMatrix;\n #endif\n #endif\n #if LIGHT{i}TYPE == SPOT\n uniform sampler2D light{i}_cookie;\n uniform float light{i}_cookieIntensity;\n #if !defined(LIGHT{i}CASTSHADOW)\n uniform mat4 light{i}_shadowMatrix;\n #endif\n #if defined(LIGHT{i}COOKIE_TRANSFORM)\n uniform vec4 light{i}_cookieMatrix;\n uniform vec2 light{i}_cookieOffset;\n #endif\n #endif\n #endif\n#endif\n",lightDiffuseLambertPS:"\nfloat getLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm) {\n return max(dot(worldNormal, -lightDirNorm), 0.0);\n}\n",lightDirPointPS:"\nvec3 evalOmniLight(vec3 lightPosW) {\n return vPositionW - lightPosW;\n}\n",lightEvaluationPS:"\n#if defined(LIGHT{i})\n evaluateLight{i}(\n #if defined(LIT_IRIDESCENCE)\n iridescenceFresnel\n #endif\n );\n#endif\n",lightFunctionLightPS:"\n#if defined(LIGHT{i})\nvoid evaluateLight{i}(\n #if defined(LIT_IRIDESCENCE)\n vec3 iridescenceFresnel\n #endif\n) {\n vec3 lightColor = light{i}_color;\n #if LIGHT{i}TYPE == DIRECTIONAL && !defined(LIT_SHADOW_CATCHER)\n if (all(equal(lightColor, vec3(0.0)))) {\n return;\n }\n #endif\n #if LIGHT{i}TYPE == DIRECTIONAL\n dLightDirNormW = light{i}_direction;\n dAtten = 1.0;\n #else\n \n vec3 lightDirW = evalOmniLight(light{i}_position);\n dLightDirNormW = normalize(lightDirW);\n #if defined(LIGHT{i}COOKIE)\n #if LIGHT{i}TYPE == SPOT\n #ifdef LIGHT{i}COOKIE_FALLOFF\n #ifdef LIGHT{i}COOKIE_TRANSFORM\n vec3 cookieAttenuation = getCookie2DXform(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity, light{i}_cookieMatrix, light{i}_cookieOffset).{LIGHT{i}COOKIE_CHANNEL};\n #else\n vec3 cookieAttenuation = getCookie2D(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};\n #endif\n #else\n #ifdef LIGHT{i}COOKIE_TRANSFORM\n vec3 cookieAttenuation = getCookie2DClipXform(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity, light{i}_cookieMatrix, light{i}_cookieOffset).{LIGHT{i}COOKIE_CHANNEL};\n #else\n vec3 cookieAttenuation = getCookie2DClip(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};\n #endif\n #endif\n #endif\n #if LIGHT{i}TYPE == OMNI\n vec3 cookieAttenuation = getCookieCube(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};\n #endif\n lightColor *= cookieAttenuation;\n #endif\n #if LIGHT{i}SHAPE == PUNCTUAL\n #if LIGHT{i}FALLOFF == LINEAR\n dAtten = getFalloffLinear(light{i}_radius, lightDirW);\n #else\n dAtten = getFalloffInvSquared(light{i}_radius, lightDirW);\n #endif\n #else\n dAtten = getFalloffWindow(light{i}_radius, lightDirW);\n #endif\n #if LIGHT{i}TYPE == SPOT\n #if !defined(LIGHT{i}COOKIE) || defined(LIGHT{i}COOKIE_FALLOFF)\n dAtten *= getSpotEffect(light{i}_direction, light{i}_innerConeAngle, light{i}_outerConeAngle, dLightDirNormW);\n #endif\n #endif\n #endif\n if (dAtten < 0.00001) {\n return;\n }\n #if LIGHT{i}SHAPE != PUNCTUAL\n #if LIGHT{i}SHAPE == RECT\n calcRectLightValues(light{i}_position, light{i}_halfWidth, light{i}_halfHeight);\n #elif LIGHT{i}SHAPE == DISK\n calcDiskLightValues(light{i}_position, light{i}_halfWidth, light{i}_halfHeight);\n #elif LIGHT{i}SHAPE == SPHERE\n calcSphereLightValues(light{i}_position, light{i}_halfWidth, light{i}_halfHeight);\n #endif\n #endif\n #if LIGHT{i}SHAPE != PUNCTUAL\n #if LIGHT{i}TYPE == DIRECTIONAL\n float attenDiffuse = getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirNormW);\n #else\n #if LIGHT{i}SHAPE == RECT\n float attenDiffuse = getRectLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;\n #elif LIGHT{i}SHAPE == DISK\n float attenDiffuse = getDiskLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;\n #elif LIGHT{i}SHAPE == SPHERE\n float attenDiffuse = getSphereLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;\n #endif\n #endif\n #else\n dAtten *= getLightDiffuse(litArgs_worldNormal, vec3(0.0), dLightDirNormW);\n #endif\n #ifdef LIGHT{i}CASTSHADOW\n #if LIGHT{i}TYPE == DIRECTIONAL\n float shadow = getShadow{i}(vec3(0.0));\n #else\n float shadow = getShadow{i}(lightDirW);\n #endif\n shadow = mix(1.0, shadow, light{i}_shadowIntensity);\n dAtten *= shadow;\n #if defined(LIT_SHADOW_CATCHER) && LIGHT{i}TYPE == DIRECTIONAL\n dShadowCatcher *= shadow;\n #endif \n #endif\n #if LIGHT{i}SHAPE != PUNCTUAL\n #ifdef LIT_SPECULAR\n dDiffuseLight += ((attenDiffuse * dAtten) * lightColor) * (1.0 - dLTCSpecFres);\n #else\n dDiffuseLight += (attenDiffuse * dAtten) * lightColor;\n #endif \n #else\n #if defined(AREA_LIGHTS) && defined(LIT_SPECULAR)\n dDiffuseLight += (dAtten * lightColor) * (1.0 - litArgs_specularity);\n #else\n dDiffuseLight += dAtten * lightColor;\n #endif\n #endif\n #ifdef LIGHT{i}AFFECT_SPECULARITY\n #if LIGHT{i}SHAPE != PUNCTUAL\n #ifdef LIT_CLEARCOAT\n #if LIGHT{i}SHAPE == RECT\n ccSpecularLight += ccLTCSpecFres * getRectLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor;\n #elif LIGHT{i}SHAPE == DISK\n ccSpecularLight += ccLTCSpecFres * getDiskLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor;\n #elif LIGHT{i}SHAPE == SPHERE\n ccSpecularLight += ccLTCSpecFres * getSphereLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor;\n #endif\n #endif\n #ifdef LIT_SPECULAR\n #if LIGHT{i}SHAPE == RECT\n dSpecularLight += dLTCSpecFres * getRectLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor;\n #elif LIGHT{i}SHAPE == DISK\n dSpecularLight += dLTCSpecFres * getDiskLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor;\n #elif LIGHT{i}SHAPE == SPHERE\n dSpecularLight += dLTCSpecFres * getSphereLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor;\n #endif\n #endif\n #else\n #if LIGHT{i}TYPE == DIRECTIONAL && LIT_FRESNEL_MODEL != NONE\n #define LIGHT{i}FRESNEL\n #endif\n #ifdef LIT_SPECULAR\n vec3 halfDirW = normalize(-dLightDirNormW + dViewDirW);\n #endif\n #ifdef LIT_CLEARCOAT\n vec3 lightspecularCC = getLightSpecular(halfDirW, ccReflDirW, litArgs_clearcoat_worldNormal, dViewDirW, dLightDirNormW, litArgs_clearcoat_gloss, dTBN) * dAtten * lightColor;\n #ifdef LIGHT{i}FRESNEL\n lightspecularCC *= getFresnelCC(dot(dViewDirW, halfDirW));\n #endif\n ccSpecularLight += lightspecularCC;\n #endif\n #ifdef LIT_SHEEN\n sSpecularLight += getLightSpecularSheen(halfDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_sheen_gloss) * dAtten * lightColor;\n #endif\n #ifdef LIT_SPECULAR\n vec3 lightSpecular = getLightSpecular(halfDirW, dReflDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_gloss, dTBN) * dAtten * lightColor;\n #ifdef LIGHT{i}FRESNEL\n #if defined(LIT_IRIDESCENCE)\n lightSpecular *= getFresnel(dot(dViewDirW, halfDirW), litArgs_gloss, litArgs_specularity, iridescenceFresnel, litArgs_iridescence_intensity);\n #else\n lightSpecular *= getFresnel(dot(dViewDirW, halfDirW), litArgs_gloss, litArgs_specularity);\n #endif\n #else\n lightSpecular *= litArgs_specularity;\n #endif\n \n dSpecularLight += lightSpecular;\n #endif\n #endif\n #endif\n}\n#endif\n",lightFunctionShadowPS:"\n#ifdef LIGHT{i}CASTSHADOW\n vec3 getShadowSampleCoord{i}(mat4 shadowTransform, vec4 shadowParams, vec3 worldPosition, vec3 lightPos, inout vec3 lightDir, vec3 lightDirNorm, vec3 normal) {\n vec3 surfacePosition = worldPosition;\n #ifdef LIGHT{i}_SHADOW_SAMPLE_POINT\n #ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET\n float distScale = length(lightDir);\n surfacePosition = surfacePosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;\n lightDir = surfacePosition - lightPos;\n return lightDir;\n #endif\n #else\n #ifdef LIGHT{i}_SHADOW_SAMPLE_SOURCE_ZBUFFER\n #ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET\n surfacePosition = surfacePosition + normal * shadowParams.y;\n #endif\n #else\n #ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET\n #ifdef LIGHT{i}_SHADOW_SAMPLE_ORTHO\n float distScale = 1.0;\n #else\n float distScale = abs(dot(vPositionW - lightPos, lightDirNorm));\n #endif\n surfacePosition = surfacePosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;\n #endif\n #endif\n vec4 positionInShadowSpace = shadowTransform * vec4(surfacePosition, 1.0);\n #ifdef LIGHT{i}_SHADOW_SAMPLE_ORTHO\n positionInShadowSpace.z = saturate(positionInShadowSpace.z) - 0.0001;\n #else\n #ifdef LIGHT{i}_SHADOW_SAMPLE_SOURCE_ZBUFFER\n positionInShadowSpace.xyz /= positionInShadowSpace.w;\n #else\n positionInShadowSpace.xy /= positionInShadowSpace.w;\n positionInShadowSpace.z = length(lightDir) * shadowParams.w;\n #endif\n #endif\n #ifdef SHADOW_SAMPLE_Z_BIAS\n #endif\n surfacePosition = positionInShadowSpace.xyz;\n #endif\n return surfacePosition;\n }\n float getShadow{i}(vec3 lightDirW) {\n #ifdef LIGHT{i}_SHADOW_CASCADES\n int cascadeIndex = getShadowCascadeIndex(light{i}_shadowCascadeDistances, light{i}_shadowCascadeCount);\n #ifdef LIGHT{i}_SHADOW_CASCADE_BLEND\n cascadeIndex = ditherShadowCascadeIndex(cascadeIndex, light{i}_shadowCascadeDistances, light{i}_shadowCascadeCount, light{i}_shadowCascadeBlend);\n #endif\n mat4 shadowMatrix = light{i}_shadowMatrixPalette[cascadeIndex];\n #else\n mat4 shadowMatrix = light{i}_shadowMatrix;\n #endif\n #if LIGHT{i}TYPE == DIRECTIONAL\n vec3 shadowCoord = getShadowSampleCoord{i}(shadowMatrix, light{i}_shadowParams, vPositionW, vec3(0.0), lightDirW, dLightDirNormW, dVertexNormalW);\n #else\n vec3 shadowCoord = getShadowSampleCoord{i}(shadowMatrix, light{i}_shadowParams, vPositionW, light{i}_position, lightDirW, dLightDirNormW, dVertexNormalW);\n #endif\n #if LIGHT{i}TYPE == DIRECTIONAL\n shadowCoord = fadeShadow(shadowCoord, light{i}_shadowCascadeDistances);\n #endif\n #if LIGHT{i}TYPE == DIRECTIONAL\n #if LIGHT{i}SHADOWTYPE == VSM_16F\n return getShadowVSM16(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, 5.54);\n #endif\n #if LIGHT{i}SHADOWTYPE == VSM_32F\n return getShadowVSM32(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, 15.0);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCSS_32F\n #if LIGHT{i}SHAPE != PUNCTUAL\n vec2 shadowSearchArea = vec2(length(light{i}_halfWidth), length(light{i}_halfHeight)) * light{i}_shadowSearchArea;\n return getShadowPCSS(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, light{i}_cameraParams, shadowSearchArea, lightDirW);\n #else\n return getShadowPCSS(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, light{i}_cameraParams, light{i}_softShadowParams, lightDirW);\n #endif\n #endif\n #if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F\n return getShadowPCF1x1(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F\n return getShadowPCF3x3(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCF5_16F || LIGHT{i}SHADOWTYPE == PCF5_32F\n return getShadowPCF5x5(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);\n #endif\n #endif\n #if LIGHT{i}TYPE == SPOT\n #if LIGHT{i}SHADOWTYPE == VSM_16F\n return getShadowSpotVSM16(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, 5.54, lightDirW);\n #endif\n #if LIGHT{i}SHADOWTYPE == VSM_32F\n return getShadowSpotVSM32(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, 15.0, lightDirW);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCSS_32F\n #if LIGHT{i}SHAPE != PUNCTUAL\n vec2 shadowSearchArea = vec2(length(light{i}_halfWidth), length(light{i}_halfHeight)) * light{i}_shadowSearchArea;\n #else\n vec2 shadowSearchArea = vec2(light{i}_shadowSearchArea);\n #endif\n return getShadowSpotPCSS(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, light{i}_cameraParams, shadowSearchArea, lightDirW);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F\n return getShadowSpotPCF1x1(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F\n return getShadowSpotPCF3x3(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCF5_16F || LIGHT{i}SHADOWTYPE == PCF5_32F\n return getShadowSpotPCF5x5(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);\n #endif\n #endif\n #if LIGHT{i}TYPE == OMNI\n #if LIGHT{i}SHADOWTYPE == PCSS_32F\n #if LIGHT{i}SHAPE != PUNCTUAL\n vec2 shadowSearchArea = vec2(length(light{i}_halfWidth), length(light{i}_halfHeight)) * light{i}_shadowSearchArea;\n #else\n vec2 shadowSearchArea = vec2(light{i}_shadowSearchArea);\n #endif\n return getShadowOmniPCSS(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, light{i}_cameraParams, shadowSearchArea, lightDirW);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F\n return getShadowOmniPCF1x1(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, lightDirW);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F\n return getShadowOmniPCF3x3(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, lightDirW);\n #endif\n #endif\n }\n#endif\n",lightingPS:'\n#ifdef LIT_CLUSTERED_LIGHTS\n #define LIT_CODE_FALLOFF_LINEAR\n #define LIT_CODE_FALLOFF_SQUARED\n #define LIT_CODE_LIGHTS_POINT\n #define LIT_CODE_LIGHTS_SPOT\n#endif\n#ifdef AREA_LIGHTS\n uniform highp sampler2D areaLightsLutTex1;\n uniform highp sampler2D areaLightsLutTex2;\n#endif\n#ifdef LIT_LIGHTING\n #include "lightDiffuseLambertPS"\n #if defined(AREA_LIGHTS) || defined(LIT_CLUSTERED_AREA_LIGHTS)\n #include "ltcPS"\n #endif\n#endif\n#ifdef SHADOW_DIRECTIONAL\n #include "shadowCascadesPS"\n#endif\n#if defined(SHADOW_KIND_PCF1)\n #include "shadowPCF1PS"\n#endif\n#if defined(SHADOW_KIND_PCF3)\n #include "shadowPCF3PS"\n#endif\n#if defined(SHADOW_KIND_PCF5)\n #include "shadowPCF5PS"\n#endif\n#if defined(SHADOW_KIND_PCSS)\n #include "linearizeDepthPS"\n #include "shadowPCSSPS"\n #include "shadowSoftPS"\n#endif\n#if defined(SHADOW_KIND_VSM)\n #include "shadowEVSMPS"\n#endif\n#ifdef LIT_CODE_FALLOFF_LINEAR\n #include "falloffLinearPS"\n#endif\n#ifdef LIT_CODE_FALLOFF_SQUARED\n #include "falloffInvSquaredPS"\n#endif\n#ifdef LIT_CODE_LIGHTS_POINT\n #include "lightDirPointPS"\n#endif\n#ifdef LIT_CODE_LIGHTS_SPOT\n #include "spotPS"\n#endif\n#ifdef LIT_CODE_COOKIE\n #include "cookiePS"\n#endif\n#ifdef LIT_CLUSTERED_LIGHTS\n #include "clusteredLightPS"\n#endif\n#ifdef LIGHT_COUNT > 0\n #include "lightFunctionShadowPS, LIGHT_COUNT"\n #include "lightFunctionLightPS, LIGHT_COUNT"\n#endif\n',lightmapAddPS:"\nvoid addLightMap(\n vec3 lightmap, \n vec3 dir, \n vec3 worldNormal, \n vec3 viewDir, \n vec3 reflectionDir, \n float gloss, \n vec3 specularity, \n vec3 vertexNormal, \n mat3 tbn\n#if defined(LIT_IRIDESCENCE)\n vec3 iridescenceFresnel, \n float iridescenceIntensity\n#endif\n) {\n #if defined(LIT_SPECULAR) && defined(LIT_DIR_LIGHTMAP)\n if (dot(dir, dir) < 0.0001) {\n dDiffuseLight += lightmap;\n } else {\n float vlight = saturate(dot(dir, -vertexNormal));\n float flight = saturate(dot(dir, -worldNormal));\n float nlight = (flight / max(vlight, 0.01)) * 0.5;\n dDiffuseLight += lightmap * nlight * 2.0;\n vec3 halfDir = normalize(-dir + viewDir);\n vec3 specularLight = lightmap * getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, dir, gloss, tbn);\n #ifdef LIT_SPECULAR_FRESNEL\n specularLight *= \n getFresnel(dot(viewDir, halfDir), \n gloss, \n specularity\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n iridescenceIntensity\n #endif\n );\n #endif\n dSpecularLight += specularLight;\n }\n #else\n dDiffuseLight += lightmap;\n #endif\n}\n",lightmapPS:"\n#ifdef STD_LIGHTMAP_DIR\n vec3 dLightmapDir;\n uniform sampler2D texture_dirLightMap;\n#endif\nvoid getLightMap() {\n dLightmap = vec3(1.0);\n #ifdef STD_LIGHT_TEXTURE\n dLightmap *= {STD_LIGHT_TEXTURE_DECODE}(texture2DBias({STD_LIGHT_TEXTURE_NAME}, {STD_LIGHT_TEXTURE_UV}, textureBias)).{STD_LIGHT_TEXTURE_CHANNEL};\n #ifdef STD_LIGHTMAP_DIR\n vec3 dir = texture2DBias(texture_dirLightMap, {STD_LIGHT_TEXTURE_UV}, textureBias).xyz * 2.0 - 1.0;\n float dirDot = dot(dir, dir);\n dLightmapDir = (dirDot > 0.001) ? dir / sqrt(dirDot) : vec3(0.0);\n #endif\n #endif\n #ifdef STD_LIGHT_VERTEX\n dLightmap *= saturate(vVertexColor.{STD_LIGHT_VERTEX_CHANNEL});\n #endif\n}\n",lightSpecularAnisoGGXPS:"\nfloat calcLightSpecular(float gloss, vec3 worldNormal, vec3 viewDir, vec3 h, vec3 lightDirNorm, mat3 tbn) {\n float PI = 3.141592653589793;\n float roughness = max((1.0 - gloss) * (1.0 - gloss), 0.001);\n float alphaRoughness = roughness * roughness;\n float anisotropy = dAnisotropy;\n vec2 direction = dAnisotropyRotation;\n float at = mix(alphaRoughness, 1.0, anisotropy * anisotropy);\n float ab = clamp(alphaRoughness, 0.001, 1.0);\n vec3 anisotropicT = normalize(tbn * vec3(direction, 0.0));\n vec3 anisotropicB = normalize(cross(tbn[2], anisotropicT));\n float NoH = dot(worldNormal, h);\n float ToH = dot(anisotropicT, h);\n float BoH = dot(anisotropicB, h);\n float a2 = at * ab;\n vec3 v = vec3(ab * ToH, at * BoH, a2 * NoH);\n float v2 = dot(v, v);\n float w2 = a2 / v2;\n float D = a2 * w2 * w2 * (1.0 / PI);\n float ToV = dot(anisotropicT, viewDir);\n float BoV = dot(anisotropicB, viewDir);\n float ToL = dot(anisotropicT, -lightDirNorm);\n float BoL = dot(anisotropicB, -lightDirNorm);\n float NoV = dot(worldNormal, viewDir);\n float NoL = dot(worldNormal, -lightDirNorm);\n float lambdaV = NoL * length(vec3(at * ToV, ab * BoV, NoV));\n float lambdaL = NoV * length(vec3(at * ToL, ab * BoL, NoL));\n float G = 0.5 / (lambdaV + lambdaL);\n return D * G;\n}\nfloat getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) {\n return calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm, tbn);\n}\n",lightSpecularBlinnPS:"\nfloat calcLightSpecular(float gloss, vec3 worldNormal, vec3 h) {\n float nh = max( dot( h, worldNormal ), 0.0 );\n float specPow = exp2(gloss * 11.0);\n specPow = max(specPow, 0.0001);\n return pow(nh, specPow) * (specPow + 2.0) / 8.0;\n}\nfloat getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) {\n return calcLightSpecular(gloss, worldNormal, h);\n}\n",lightSheenPS:"\nfloat sheenD(vec3 normal, vec3 h, float roughness) {\n const float PI = 3.141592653589793;\n float invR = 1.0 / (roughness * roughness);\n float cos2h = max(dot(normal, h), 0.0);\n cos2h *= cos2h;\n float sin2h = max(1.0 - cos2h, 0.0078125);\n return (2.0 + invR) * pow(sin2h, invR * 0.5) / (2.0 * PI);\n}\nfloat sheenV(vec3 normal, vec3 viewDir, vec3 light) {\n float NoV = max(dot(normal, viewDir), 0.000001);\n float NoL = max(dot(normal, light), 0.000001);\n return 1.0 / (4.0 * (NoL + NoV - NoL * NoV));\n}\nfloat getLightSpecularSheen(vec3 h, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float sheenGloss) {\n float D = sheenD(worldNormal, h, sheenGloss);\n float V = sheenV(worldNormal, viewDir, -lightDirNorm);\n return D * V;\n}\n",linearizeDepthPS:"\n#ifndef LINEARIZE_DEPTH\n#define LINEARIZE_DEPTH\nfloat linearizeDepthWithParams(float z, vec4 cameraParams) {\n if (cameraParams.w == 0.0)\n return (cameraParams.z * cameraParams.y) / (cameraParams.y + z * (cameraParams.z - cameraParams.y));\n else\n return cameraParams.z + z * (cameraParams.y - cameraParams.z);\n}\n#ifndef CAMERAPLANES\n #define CAMERAPLANES\n uniform vec4 camera_params;\n#endif\nfloat linearizeDepth(float z) {\n return linearizeDepthWithParams(z, camera_params);\n}\n#endif\n",litForwardBackendPS:'\nvoid evaluateBackend() {\n #ifdef LIT_SSAO\n litArgs_ao *= texture2DLod(ssaoTexture, gl_FragCoord.xy * ssaoTextureSizeInv, 0.0).r;\n #endif\n #ifdef LIT_NEEDS_NORMAL\n #ifdef LIT_SPECULAR\n getReflDir(litArgs_worldNormal, dViewDirW, litArgs_gloss, dTBN);\n #endif\n #ifdef LIT_CLEARCOAT\n ccReflDirW = normalize(-reflect(dViewDirW, litArgs_clearcoat_worldNormal));\n #endif\n #endif\n #ifdef LIT_SPECULAR_OR_REFLECTION\n #ifdef LIT_METALNESS\n float f0 = 1.0 / litArgs_ior;\n f0 = (f0 - 1.0) / (f0 + 1.0);\n f0 *= f0;\n litArgs_specularity = getSpecularModulate(litArgs_specularity, litArgs_albedo, litArgs_metalness, f0);\n litArgs_albedo = getAlbedoModulate(litArgs_albedo, litArgs_metalness);\n #endif\n #ifdef LIT_IRIDESCENCE\n vec3 iridescenceFresnel = getIridescence(saturate(dot(dViewDirW, litArgs_worldNormal)), litArgs_specularity, litArgs_iridescence_thickness);\n #endif\n #endif\n #ifdef LIT_ADD_AMBIENT\n addAmbient(litArgs_worldNormal);\n #ifdef LIT_SPECULAR\n dDiffuseLight = dDiffuseLight * (1.0 - litArgs_specularity);\n #endif\n #ifdef LIT_SEPARATE_AMBIENT\n vec3 dAmbientLight = dDiffuseLight;\n dDiffuseLight = vec3(0);\n #endif\n #endif\n #ifndef LIT_OLD_AMBIENT\n dDiffuseLight *= material_ambient;\n #endif\n #ifdef LIT_AO\n #ifndef LIT_OCCLUDE_DIRECT\n occludeDiffuse(litArgs_ao);\n #endif\n #endif\n #ifdef LIT_LIGHTMAP\n addLightMap(\n litArgs_lightmap, \n litArgs_lightmapDir, \n litArgs_worldNormal, \n dViewDirW, \n dReflDirW, \n litArgs_gloss, \n litArgs_specularity, \n dVertexNormalW,\n dTBN\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n litArgs_iridescence_intensity\n #endif\n );\n #endif\n #ifdef LIT_LIGHTING || LIT_REFLECTIONS\n #ifdef LIT_REFLECTIONS\n #ifdef LIT_CLEARCOAT\n addReflectionCC(ccReflDirW, litArgs_clearcoat_gloss);\n \n #ifdef LIT_SPECULAR_FRESNEL\n ccFresnel = getFresnelCC(dot(dViewDirW, litArgs_clearcoat_worldNormal));\n ccReflection *= ccFresnel;\n #else\n ccFresnel = 0.0;\n #endif\n #endif\n #ifdef LIT_SPECULARITY_FACTOR\n ccReflection *= litArgs_specularityFactor;\n #endif\n #ifdef LIT_SHEEN\n addReflectionSheen(litArgs_worldNormal, dViewDirW, litArgs_sheen_gloss);\n #endif\n addReflection(dReflDirW, litArgs_gloss);\n #ifdef LIT_FRESNEL_MODEL\n dReflection.rgb *= getFresnel(\n dot(dViewDirW, litArgs_worldNormal), \n litArgs_gloss, \n litArgs_specularity\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n litArgs_iridescence_intensity\n #endif\n );\n #else\n dReflection.rgb *= litArgs_specularity;\n #endif\n #ifdef LIT_SPECULARITY_FACTOR\n dReflection.rgb *= litArgs_specularityFactor;\n #endif\n #endif\n #ifdef AREA_LIGHTS\n dSpecularLight *= litArgs_specularity;\n #ifdef LIT_SPECULAR\n calcLTCLightValues(litArgs_gloss, litArgs_worldNormal, dViewDirW, litArgs_specularity, litArgs_clearcoat_gloss, litArgs_clearcoat_worldNormal, litArgs_clearcoat_specularity);\n #endif\n #endif\n \n #ifdef LIGHT_COUNT > 0\n #include "lightEvaluationPS, LIGHT_COUNT"\n #endif\n #ifdef LIT_CLUSTERED_LIGHTS\n addClusteredLights(litArgs_worldNormal, dViewDirW, dReflDirW,\n #if defined(LIT_CLEARCOAT)\n ccReflDirW,\n #endif\n litArgs_gloss, litArgs_specularity, dVertexNormalW, dTBN, \n #if defined(LIT_IRIDESCENCE)\n iridescenceFresnel,\n #endif\n litArgs_clearcoat_worldNormal, litArgs_clearcoat_gloss, litArgs_sheen_gloss, litArgs_iridescence_intensity\n );\n #endif\n #ifdef AREA_LIGHTS\n #ifdef LIT_CLEARCOAT\n litArgs_clearcoat_specularity = 1.0;\n #endif\n #ifdef LIT_SPECULAR\n litArgs_specularity = vec3(1);\n #endif\n #endif\n #ifdef LIT_REFRACTION\n addRefraction(\n litArgs_worldNormal, \n dViewDirW, \n litArgs_thickness, \n litArgs_gloss, \n litArgs_specularity, \n litArgs_albedo, \n litArgs_transmission,\n litArgs_ior,\n litArgs_dispersion\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel, \n litArgs_iridescence_intensity\n #endif\n );\n #endif\n #endif\n #ifdef LIT_AO\n #ifdef LIT_OCCLUDE_DIRECT\n occludeDiffuse(litArgs_ao);\n #endif\n #if LIT_OCCLUDE_SPECULAR != NONE\n occludeSpecular(litArgs_gloss, litArgs_ao, litArgs_worldNormal, dViewDirW);\n #endif\n #endif\n #ifdef LIT_SPECULARITY_FACTOR\n dSpecularLight *= litArgs_specularityFactor;\n #endif\n #if !defined(LIT_OPACITY_FADES_SPECULAR)\n #if LIT_BLEND_TYPE == NORMAL || LIT_BLEND_TYPE == PREMULTIPLIED\n float specLum = dot((dSpecularLight + dReflection.rgb * dReflection.a), vec3( 0.2126, 0.7152, 0.0722 ));\n #ifdef LIT_CLEARCOAT\n specLum += dot(ccSpecularLight * litArgs_clearcoat_specularity + ccReflection * litArgs_clearcoat_specularity, vec3( 0.2126, 0.7152, 0.0722 ));\n #endif\n litArgs_opacity = clamp(litArgs_opacity + gammaCorrectInput(specLum), 0.0, 1.0);\n #endif\n litArgs_opacity *= material_alphaFade;\n #endif\n #ifdef LIT_LIGHTMAP_BAKING\n #ifdef LIT_LIGHTMAP_BAKING_COLOR\n #include "bakeLmEndPS"\n #endif\n #ifdef LIT_LIGHTMAP_BAKING_DIR\n #include "bakeDirLmEndPS"\n #endif\n #else\n #include "endPS"\n #include "outputAlphaPS"\n #endif\n #ifdef LIT_MSDF\n gl_FragColor = applyMsdf(gl_FragColor);\n #endif\n #include "outputPS"\n #include "debugOutputPS"\n #ifdef LIT_SHADOW_CATCHER\n gl_FragColor.rgb = vec3(dShadowCatcher);\n #endif\n}\n',litForwardDeclarationPS:'\nvec3 sReflection;\nvec3 dVertexNormalW;\nvec3 dTangentW;\nvec3 dBinormalW;\nvec3 dViewDirW;\nvec3 dReflDirW;\nvec3 ccReflDirW;\nvec3 dLightDirNormW;\nfloat dAtten;\nmat3 dTBN;\nvec4 dReflection;\nvec3 dDiffuseLight;\nvec3 dSpecularLight;\nfloat ccFresnel;\nvec3 ccReflection;\nvec3 ccSpecularLight;\nfloat ccSpecularityNoFres;\nvec3 sSpecularLight;\n#ifdef LIT_DISPERSION\n uniform float material_dispersion;\n#endif\n#ifndef LIT_OPACITY_FADES_SPECULAR\n uniform float material_alphaFade;\n#endif\n#ifdef LIT_SSAO\n uniform sampler2D ssaoTexture;\n uniform vec2 ssaoTextureSizeInv;\n#endif\n#ifdef LIT_SHADOW_CATCHER\n float dShadowCatcher = 1.0;\n#endif\n#if LIGHT_COUNT > 0\n #include "lightDeclarationPS, LIGHT_COUNT"\n#endif\n#ifdef LIT_SPECULAR\n #if LIT_FRESNEL_MODEL == NONE && !defined(LIT_REFLECTIONS) && !defined(LIT_DIFFUSE_MAP) \n #define LIT_OLD_AMBIENT\n #endif\n#endif\n#ifdef STD_LIGHTMAP_DIR\n uniform float bakeDir;\n#endif\n#ifdef LIT_LIGHTMAP_BAKING_ADD_AMBIENT\n uniform float ambientBakeOcclusionContrast;\n uniform float ambientBakeOcclusionBrightness;\n#endif\n',litForwardMainPS:'\nvoid main(void) {\n #include "litUserMainStartPS"\n dReflection = vec4(0);\n #ifdef LIT_CLEARCOAT\n ccSpecularLight = vec3(0);\n ccReflection = vec3(0);\n #endif\n #if LIT_NONE_SLICE_MODE == SLICED\n #include "startNineSlicedPS"\n #elif LIT_NONE_SLICE_MODE == TILED\n #include "startNineSlicedTiledPS"\n #endif\n #ifdef LIT_NEEDS_NORMAL\n dVertexNormalW = normalize(vNormalW);\n #ifdef LIT_TANGENTS\n #if defined(LIT_HEIGHTS) || defined(LIT_USE_NORMALS) || defined(LIT_USE_CLEARCOAT_NORMALS) || defined(LIT_GGX_SPECULAR)\n dTangentW = vTangentW;\n dBinormalW = vBinormalW;\n #endif\n #endif\n getViewDir();\n #ifdef LIT_TBN\n getTBN(dTangentW, dBinormalW, dVertexNormalW);\n #ifdef LIT_TWO_SIDED_LIGHTING\n handleTwoSidedLighting();\n #endif\n #endif\n #endif\n evaluateFrontend();\n #include "debugProcessFrontendPS"\n evaluateBackend();\n #include "litUserMainEndPS"\n}\n',litForwardPostCodePS:'\n#ifdef LIT_NEEDS_NORMAL\n #include "cubeMapRotatePS"\n #include "cubeMapProjectPS"\n #include "envProcPS"\n#endif\n#ifdef LIT_SPECULAR_OR_REFLECTION\n #ifdef LIT_METALNESS\n #include "metalnessModulatePS"\n #endif\n #if LIT_FRESNEL_MODEL == SCHLICK\n #include "fresnelSchlickPS"\n #endif\n #ifdef LIT_IRIDESCENCE\n #include "iridescenceDiffractionPS"\n #endif\n#endif\n#ifdef LIT_AO\n #include "aoDiffuseOccPS"\n #include "aoSpecOccPS"\n#endif\n#if LIT_REFLECTION_SOURCE == ENVATLASHQ\n #include "envAtlasPS"\n #include "reflectionEnvHQPS"\n#elif LIT_REFLECTION_SOURCE == ENVATLAS\n #include "envAtlasPS"\n #include "reflectionEnvPS"\n#elif LIT_REFLECTION_SOURCE == CUBEMAP\n #include "reflectionCubePS"\n#elif LIT_REFLECTION_SOURCE == SPHEREMAP\n #include "reflectionSpherePS"\n#endif\n#ifdef LIT_REFLECTIONS\n #ifdef LIT_CLEARCOAT\n #include "reflectionCCPS"\n #endif\n #ifdef LIT_SHEEN\n #include "reflectionSheenPS"\n #endif\n#endif\n#ifdef LIT_REFRACTION\n #if defined(LIT_DYNAMIC_REFRACTION)\n #include "refractionDynamicPS"\n #elif defined(LIT_REFLECTIONS)\n #include "refractionCubePS"\n #endif\n#endif\n#ifdef LIT_SHEEN\n #include "lightSheenPS"\n#endif\nuniform vec3 material_ambient;\n#ifdef LIT_SPECULAR\n #ifdef LIT_LIGHTING\n #ifdef LIT_GGX_SPECULAR\n #include "lightSpecularAnisoGGXPS"\n #else\n #include "lightSpecularBlinnPS"\n #endif\n #endif\n#endif\n#include "combinePS"\n#ifdef LIT_LIGHTMAP\n #include "lightmapAddPS"\n#endif\n#ifdef LIT_ADD_AMBIENT\n #include "ambientPS"\n#endif\n#ifdef LIT_MSDF\n #include "msdfPS"\n#endif\n#ifdef LIT_NEEDS_NORMAL\n #include "viewDirPS"\n #ifdef LIT_SPECULAR\n #ifdef LIT_GGX_SPECULAR\n #include "reflDirAnisoPS"\n #else\n #include "reflDirPS"\n #endif\n #endif\n#endif\n#include "lightingPS"\n',litForwardPreCodePS:'\n#include "basePS"\n#include "sphericalPS"\n#include "decodePS"\n#include "gammaPS"\n#include "tonemappingPS"\n#include "fogPS"\n#if LIT_NONE_SLICE_MODE == SLICED\n #include "baseNineSlicedPS"\n#elif LIT_NONE_SLICE_MODE == TILED\n #include "baseNineSlicedTiledPS"\n#endif\n#ifdef LIT_TBN\n #include "TBNPS"\n #ifdef LIT_TWO_SIDED_LIGHTING\n #include "twoSidedLightingPS"\n #endif\n#endif\n',litMainPS:'\n#include "varyingsPS"\n#include "litUserDeclarationPS"\n#include "frontendDeclPS"\n#if defined(PICK_PASS) || defined(PREPASS_PASS)\n #include "frontendCodePS"\n #include "litUserCodePS"\n #include "litOtherMainPS"\n#elif defined(SHADOW_PASS)\n #include "frontendCodePS"\n #include "litUserCodePS"\n #include "litShadowMainPS"\n#else\n #include "litForwardDeclarationPS"\n #include "litForwardPreCodePS"\n #include "frontendCodePS"\n #include "litForwardPostCodePS"\n #include "litForwardBackendPS"\n #include "litUserCodePS"\n #include "litForwardMainPS"\n#endif\n',litMainVS:'\n#include "varyingsVS"\n#include "litUserDeclarationVS"\n#ifdef VERTEX_COLOR\n attribute vec4 vertex_color;\n#endif\n#ifdef NINESLICED\n varying vec2 vMask;\n varying vec2 vTiledUv;\n uniform mediump vec4 innerOffset;\n uniform mediump vec2 outerScale;\n uniform mediump vec4 atlasRect;\n#endif\nvec3 dPositionW;\nmat4 dModelMatrix;\n#include "transformCoreVS"\n#ifdef UV0\n attribute vec2 vertex_texCoord0;\n #include "uv0VS"\n#endif\n#ifdef UV1\n attribute vec2 vertex_texCoord1;\n #include "uv1VS"\n#endif\n#ifdef LINEAR_DEPTH\n #ifndef VIEWMATRIX\n #define VIEWMATRIX\n uniform mat4 matrix_view;\n #endif\n#endif\n#include "transformVS"\n#ifdef NORMALS\n #include "normalCoreVS"\n #include "normalVS"\n#endif\n#ifdef TANGENTS\n attribute vec4 vertex_tangent;\n#endif\n#include "uvTransformUniformsPS, UV_TRANSFORMS_COUNT"\n#ifdef MSDF\n #include "msdfVS"\n#endif\n#include "litUserCodeVS"\nvoid main(void) {\n #include "litUserMainStartVS"\n gl_PointSize = 1.0;\n gl_Position = getPosition();\n vPositionW = getWorldPosition();\n #ifdef NORMALS\n vNormalW = getNormal();\n #endif\n #ifdef TANGENTS\n vTangentW = normalize(dNormalMatrix * vertex_tangent.xyz);\n vBinormalW = cross(vNormalW, vTangentW) * vertex_tangent.w;\n #elif defined(GGX_SPECULAR)\n vObjectSpaceUpW = normalize(dNormalMatrix * vec3(0, 1, 0));\n #endif\n #ifdef UV0\n vec2 uv0 = getUv0();\n #ifdef UV0_UNMODIFIED\n vUv0 = uv0;\n #endif\n #endif\n #ifdef UV1\n vec2 uv1 = getUv1();\n #ifdef UV1_UNMODIFIED\n vUv1 = uv1;\n #endif\n #endif\n #include "uvTransformVS, UV_TRANSFORMS_COUNT"\n #ifdef VERTEX_COLOR\n vVertexColor = vertex_color;\n #endif\n #ifdef LINEAR_DEPTH\n vLinearDepth = -(matrix_view * vec4(vPositionW, 1.0)).z;\n #endif\n #ifdef MSDF\n unpackMsdfParams();\n #endif\n #include "litUserMainEndVS"\n}\n',litOtherMainPS:'\n#ifdef PICK_PASS\n #include "pickPS"\n#endif\n#ifdef PREPASS_PASS\n #include "floatAsUintPS"\n#endif\nvoid main(void) {\n #include "litUserMainStartPS"\n evaluateFrontend();\n #ifdef PICK_PASS\n gl_FragColor = getPickOutput();\n #endif\n #ifdef PREPASS_PASS\n gl_FragColor = float2vec4(vLinearDepth);\n #endif\n #include "litUserMainEndPS"\n}\n',litShaderArgsPS:"\nvec3 litArgs_albedo;\nfloat litArgs_opacity;\nvec3 litArgs_emission;\nvec3 litArgs_worldNormal;\nfloat litArgs_ao;\nvec3 litArgs_lightmap;\nvec3 litArgs_lightmapDir;\nfloat litArgs_metalness;\nvec3 litArgs_specularity;\nfloat litArgs_specularityFactor;\nfloat litArgs_gloss;\nfloat litArgs_sheen_gloss;\nvec3 litArgs_sheen_specularity;\nfloat litArgs_transmission;\nfloat litArgs_thickness;\nfloat litArgs_ior;\nfloat litArgs_dispersion;\nfloat litArgs_iridescence_intensity;\nfloat litArgs_iridescence_thickness;\nvec3 litArgs_clearcoat_worldNormal;\nfloat litArgs_clearcoat_specularity;\nfloat litArgs_clearcoat_gloss;\n",litShaderCorePS:'\n #if LIT_NONE_SLICE_MODE == TILED\n const float textureBias = -1000.0;\n #else\n uniform float textureBias;\n #endif\n #include "litShaderArgsPS"\n',litShadowMainPS:'\n#if LIGHT_TYPE != DIRECTIONAL\n uniform vec3 view_position;\n uniform float light_radius;\n#endif\n#if SHADOW_TYPE == PCSS_32F\n #include "linearizeDepthPS"\n#endif\nvoid main(void) {\n #include "litUserMainStartPS"\n evaluateFrontend();\n #ifdef PERSPECTIVE_DEPTH\n float depth = gl_FragCoord.z;\n #if SHADOW_TYPE == PCSS_32F\n #if LIGHT_TYPE != DIRECTIONAL\n depth = linearizeDepthWithParams(depth, camera_params);\n #endif\n #endif\n #else\n float depth = min(distance(view_position, vPositionW) / light_radius, 0.99999);\n #define MODIFIED_DEPTH\n #endif\n #if SHADOW_TYPE == VSM_16F || SHADOW_TYPE == VSM_32F\n #if SHADOW_TYPE == VSM_32F\n float exponent = 15.0;\n #else\n float exponent = 5.54;\n #endif\n depth = 2.0 * depth - 1.0;\n depth = exp(exponent * depth);\n gl_FragColor = vec4(depth, depth*depth, 1.0, 1.0);\n #else\n #if SHADOW_TYPE == PCSS_32F\n gl_FragColor.r = depth;\n #else\n #ifdef MODIFIED_DEPTH\n gl_FragDepth = depth;\n #endif\n gl_FragColor = vec4(1.0);\n #endif\n #endif\n #include "litUserMainEndPS"\n}\n',litUserDeclarationPS:"",litUserDeclarationVS:"",litUserCodePS:"",litUserCodeVS:"",litUserMainStartPS:"",litUserMainStartVS:"",litUserMainEndPS:"",litUserMainEndVS:"",ltcPS:"\nmat3 transposeMat3( const in mat3 m ) {\n mat3 tmp;\n tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n return tmp;\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n const float LUT_SIZE = 64.0;\n const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n const float LUT_BIAS = 0.5 / LUT_SIZE;\n float dotNV = saturate( dot( N, V ) );\n vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n uv = uv * LUT_SCALE + LUT_BIAS;\n return uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n float l = length( f );\n return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n float x = dot( v1, v2 );\n float y = abs( x );\n float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n float b = 3.4175940 + ( 4.1616724 + y ) * y;\n float v = a / b;\n float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n return cross( v1, v2 ) * theta_sintheta;\n}\nstruct Coords {\n vec3 coord0;\n vec3 coord1;\n vec3 coord2;\n vec3 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 vec3 v1 = rectCoords.coord1 - rectCoords.coord0;\n vec3 v2 = rectCoords.coord3 - rectCoords.coord0;\n \n vec3 lightNormal = cross( v1, v2 );\n float factor = sign(-dot( lightNormal, P - rectCoords.coord0 ));\n vec3 T1, T2;\n T1 = normalize( V - N * dot( V, N ) );\n T2 = factor * cross( N, T1 );\n mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n vec3 coords[ 4 ];\n coords[ 0 ] = mat * ( rectCoords.coord0 - P );\n coords[ 1 ] = mat * ( rectCoords.coord1 - P );\n coords[ 2 ] = mat * ( rectCoords.coord2 - P );\n coords[ 3 ] = mat * ( rectCoords.coord3 - P );\n coords[ 0 ] = normalize( coords[ 0 ] );\n coords[ 1 ] = normalize( coords[ 1 ] );\n coords[ 2 ] = normalize( coords[ 2 ] );\n coords[ 3 ] = normalize( coords[ 3 ] );\n vec3 vectorFormFactor = vec3( 0.0 );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n float result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n return result;\n}\nCoords dLTCCoords;\nCoords getLTCLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){\n Coords coords;\n coords.coord0 = lightPos + halfWidth - halfHeight;\n coords.coord1 = lightPos - halfWidth - halfHeight;\n coords.coord2 = lightPos - halfWidth + halfHeight;\n coords.coord3 = lightPos + halfWidth + halfHeight;\n return coords;\n}\nfloat dSphereRadius;\nCoords getSphereLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){\n dSphereRadius = max(length(halfWidth), length(halfHeight));\n vec3 f = reflect(normalize(lightPos - view_position), vNormalW);\n vec3 w = normalize(cross(f, halfHeight));\n vec3 h = normalize(cross(f, w));\n return getLTCLightCoords(lightPos, w * dSphereRadius, h * dSphereRadius);\n}\nvec2 dLTCUV;\n#ifdef LIT_CLEARCOAT\n vec2 ccLTCUV;\n#endif\nvec2 getLTCLightUV(float gloss, vec3 worldNormal, vec3 viewDir)\n{\n float roughness = max((1.0 - gloss) * (1.0 - gloss), 0.001);\n return LTC_Uv( worldNormal, viewDir, roughness );\n}\nvec3 dLTCSpecFres;\n#ifdef LIT_CLEARCOAT\n vec3 ccLTCSpecFres;\n#endif\nvec3 getLTCLightSpecFres(vec2 uv, vec3 specularity)\n{\n vec4 t2 = texture2DLod(areaLightsLutTex2, uv, 0.0);\n return specularity * t2.x + ( vec3( 1.0 ) - specularity) * t2.y;\n}\nvoid calcLTCLightValues(float gloss, vec3 worldNormal, vec3 viewDir, vec3 specularity, float clearcoatGloss, vec3 clearcoatWorldNormal, float clearcoatSpecularity)\n{\n dLTCUV = getLTCLightUV(gloss, worldNormal, viewDir);\n dLTCSpecFres = getLTCLightSpecFres(dLTCUV, specularity); \n#ifdef LIT_CLEARCOAT\n ccLTCUV = getLTCLightUV(clearcoatGloss, clearcoatWorldNormal, viewDir);\n ccLTCSpecFres = getLTCLightSpecFres(ccLTCUV, vec3(clearcoatSpecularity));\n#endif\n}\nvoid calcRectLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight) {\n dLTCCoords = getLTCLightCoords(lightPos, halfWidth, halfHeight);\n}\nvoid calcDiskLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight) {\n calcRectLightValues(lightPos, halfWidth, halfHeight);\n}\nvoid calcSphereLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight) {\n dLTCCoords = getSphereLightCoords(lightPos, halfWidth, halfHeight);\n}\nvec3 SolveCubic(vec4 Coefficient)\n{\n float pi = 3.14159;\n Coefficient.xyz /= Coefficient.w;\n Coefficient.yz /= 3.0;\n float A = Coefficient.w;\n float B = Coefficient.z;\n float C = Coefficient.y;\n float D = Coefficient.x;\n vec3 Delta = vec3(\n -Coefficient.z * Coefficient.z + Coefficient.y,\n -Coefficient.y * Coefficient.z + Coefficient.x,\n dot(vec2(Coefficient.z, -Coefficient.y), Coefficient.xy)\n );\n float Discriminant = dot(vec2(4.0 * Delta.x, -Delta.y), Delta.zy);\n vec2 xlc, xsc;\n {\n float A_a = 1.0;\n float C_a = Delta.x;\n float D_a = -2.0 * B * Delta.x + Delta.y;\n float Theta = atan(sqrt(Discriminant), -D_a) / 3.0;\n float x_1a = 2.0 * sqrt(-C_a) * cos(Theta);\n float x_3a = 2.0 * sqrt(-C_a) * cos(Theta + (2.0 / 3.0) * pi);\n float xl;\n if ((x_1a + x_3a) > 2.0 * B)\n xl = x_1a;\n else\n xl = x_3a;\n xlc = vec2(xl - B, A);\n }\n {\n float A_d = D;\n float C_d = Delta.z;\n float D_d = -D * Delta.y + 2.0 * C * Delta.z;\n float Theta = atan(D * sqrt(Discriminant), -D_d) / 3.0;\n float x_1d = 2.0 * sqrt(-C_d) * cos(Theta);\n float x_3d = 2.0 * sqrt(-C_d) * cos(Theta + (2.0 / 3.0) * pi);\n float xs;\n if (x_1d + x_3d < 2.0 * C)\n xs = x_1d;\n else\n xs = x_3d;\n xsc = vec2(-D, xs + C);\n }\n float E = xlc.y * xsc.y;\n float F = -xlc.x * xsc.y - xlc.y * xsc.x;\n float G = xlc.x * xsc.x;\n vec2 xmc = vec2(C * F - B * G, -B * F + C * E);\n vec3 Root = vec3(xsc.x / xsc.y, xmc.x / xmc.y, xlc.x / xlc.y);\n if (Root.x < Root.y && Root.x < Root.z)\n Root.xyz = Root.yxz;\n else if (Root.z < Root.x && Root.z < Root.y)\n Root.xyz = Root.xzy;\n return Root;\n}\nfloat LTC_EvaluateDisk(vec3 N, vec3 V, vec3 P, mat3 Minv, Coords points)\n{\n vec3 T1 = normalize(V - N * dot(V, N));\n vec3 T2 = cross(N, T1);\n mat3 R = transposeMat3( mat3( T1, T2, N ) );\n vec3 L_[ 3 ];\n L_[ 0 ] = R * ( points.coord0 - P );\n L_[ 1 ] = R * ( points.coord1 - P );\n L_[ 2 ] = R * ( points.coord2 - P );\n vec3 C = 0.5 * (L_[0] + L_[2]);\n vec3 V1 = 0.5 * (L_[1] - L_[2]);\n vec3 V2 = 0.5 * (L_[1] - L_[0]);\n C = Minv * C;\n V1 = Minv * V1;\n V2 = Minv * V2;\n float a, b;\n float d11 = dot(V1, V1);\n float d22 = dot(V2, V2);\n float d12 = dot(V1, V2);\n if (abs(d12) / sqrt(d11 * d22) > 0.0001)\n {\n float tr = d11 + d22;\n float det = -d12 * d12 + d11 * d22;\n det = sqrt(det);\n float u = 0.5 * sqrt(tr - 2.0 * det);\n float v = 0.5 * sqrt(tr + 2.0 * det);\n float e_max = (u + v) * (u + v);\n float e_min = (u - v) * (u - v);\n vec3 V1_, V2_;\n if (d11 > d22)\n {\n V1_ = d12 * V1 + (e_max - d11) * V2;\n V2_ = d12 * V1 + (e_min - d11) * V2;\n }\n else\n {\n V1_ = d12*V2 + (e_max - d22)*V1;\n V2_ = d12*V2 + (e_min - d22)*V1;\n }\n a = 1.0 / e_max;\n b = 1.0 / e_min;\n V1 = normalize(V1_);\n V2 = normalize(V2_);\n }\n else\n {\n a = 1.0 / dot(V1, V1);\n b = 1.0 / dot(V2, V2);\n V1 *= sqrt(a);\n V2 *= sqrt(b);\n }\n vec3 V3 = normalize(cross(V1, V2));\n if (dot(C, V3) < 0.0)\n V3 *= -1.0;\n float L = dot(V3, C);\n float x0 = dot(V1, C) / L;\n float y0 = dot(V2, C) / L;\n float E1 = inversesqrt(a);\n float E2 = inversesqrt(b);\n a *= L * L;\n b *= L * L;\n float c0 = a * b;\n float c1 = a * b * (1.0 + x0 * x0 + y0 * y0) - a - b;\n float c2 = 1.0 - a * (1.0 + x0 * x0) - b * (1.0 + y0 * y0);\n float c3 = 1.0;\n vec3 roots = SolveCubic(vec4(c0, c1, c2, c3));\n float e1 = roots.x;\n float e2 = roots.y;\n float e3 = roots.z;\n vec3 avgDir = vec3(a * x0 / (a - e2), b * y0 / (b - e2), 1.0);\n mat3 rotate = mat3(V1, V2, V3);\n avgDir = rotate * avgDir;\n avgDir = normalize(avgDir);\n float L1 = sqrt(-e2 / e3);\n float L2 = sqrt(-e2 / e1);\n float formFactor = max(0.0, L1 * L2 * inversesqrt((1.0 + L1 * L1) * (1.0 + L2 * L2)));\n \n const float LUT_SIZE = 64.0;\n const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n const float LUT_BIAS = 0.5 / LUT_SIZE;\n vec2 uv = vec2(avgDir.z * 0.5 + 0.5, formFactor);\n uv = uv*LUT_SCALE + LUT_BIAS;\n float scale = texture2DLod(areaLightsLutTex2, uv, 0.0).w;\n return formFactor*scale;\n}\nfloat FixNan(float value) {\n #ifdef WEBGPU\n return value != value ? 0.0 : value;\n #else\n return isnan(value) ? 0.0 : value;\n #endif\n}\nfloat getRectLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {\n return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mat3( 1.0 ), dLTCCoords );\n}\nfloat getDiskLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {\n return FixNan(LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mat3( 1.0 ), dLTCCoords ));\n}\nfloat getSphereLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {\n float falloff = dSphereRadius / (dot(lightDir, lightDir) + dSphereRadius);\n return FixNan(getLightDiffuse(worldNormal, viewDir, lightDirNorm) * falloff);\n}\nmat3 getLTCLightInvMat(vec2 uv)\n{\n vec4 t1 = texture2DLod(areaLightsLutTex1, uv, 0.0);\n return mat3(\n vec3( t1.x, 0, t1.y ),\n vec3( 0, 1, 0 ),\n vec3( t1.z, 0, t1.w )\n );\n}\nfloat calcRectLightSpecular(vec3 worldNormal, vec3 viewDir, vec2 uv) {\n mat3 mInv = getLTCLightInvMat(uv);\n return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );\n}\nfloat getRectLightSpecular(vec3 worldNormal, vec3 viewDir) {\n return calcRectLightSpecular(worldNormal, viewDir, dLTCUV);\n}\nfloat calcDiskLightSpecular(vec3 worldNormal, vec3 viewDir, vec2 uv) {\n mat3 mInv = getLTCLightInvMat(uv);\n return LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );\n}\nfloat getDiskLightSpecular(vec3 worldNormal, vec3 viewDir) {\n return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);\n}\nfloat getSphereLightSpecular(vec3 worldNormal, vec3 viewDir) {\n return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);\n}\n",metalnessPS:"\n#ifdef STD_METALNESS_CONSTANT\nuniform float material_metalness;\n#endif\nvoid getMetalness() {\n float metalness = 1.0;\n #ifdef STD_METALNESS_CONSTANT\n metalness *= material_metalness;\n #endif\n #ifdef STD_METALNESS_TEXTURE\n metalness *= texture2DBias({STD_METALNESS_TEXTURE_NAME}, {STD_METALNESS_TEXTURE_UV}, textureBias).{STD_METALNESS_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_METALNESS_VERTEX\n metalness *= saturate(vVertexColor.{STD_METALNESS_VERTEX_CHANNEL});\n #endif\n dMetalness = metalness;\n}\n",metalnessModulatePS:"\nvec3 getSpecularModulate(in vec3 specularity, in vec3 albedo, in float metalness, in float f0) {\n vec3 dielectricF0 = f0 * specularity;\n return mix(dielectricF0, albedo, metalness);\n}\nvec3 getAlbedoModulate(in vec3 albedo, in float metalness) {\n return albedo * (1.0 - metalness);\n}\n",morphPS:"\n varying vec2 uv0;\n uniform sampler2DArray morphTexture;\n uniform highp float morphFactor[{MORPH_TEXTURE_MAX_COUNT}];\n uniform highp uint morphIndex[{MORPH_TEXTURE_MAX_COUNT}];\n uniform int count;\n #ifdef MORPH_INT\n uniform vec3 aabbSize;\n uniform vec3 aabbMin;\n #endif\n void main (void) {\n highp vec3 color = vec3(0, 0, 0);\n for (int i = 0; i < count; i++) {\n uint textureIndex = morphIndex[i];\n vec3 delta = texture(morphTexture, vec3(uv0, textureIndex)).xyz;\n color += morphFactor[i] * delta;\n }\n #ifdef MORPH_INT\n color = (color - aabbMin) / aabbSize * 65535.0;\n gl_FragColor = uvec4(color, 1u);\n #else\n gl_FragColor = vec4(color, 1.0);\n #endif\n }\n",morphVS:"\n attribute vec2 vertex_position;\n varying vec2 uv0;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.5, 1.0);\n uv0 = vertex_position.xy * 0.5 + 0.5;\n }\n",msdfPS:"\nuniform sampler2D texture_msdfMap;\nfloat median(float r, float g, float b) {\n return max(min(r, g), min(max(r, g), b));\n}\nfloat map (float min, float max, float v) {\n return (v - min) / (max - min);\n}\nuniform float font_sdfIntensity;\nuniform float font_pxrange;\nuniform float font_textureWidth;\n#ifndef LIT_MSDF_TEXT_ATTRIBUTE\n uniform vec4 outline_color;\n uniform float outline_thickness;\n uniform vec4 shadow_color;\n uniform vec2 shadow_offset;\n#else\n varying vec4 outline_color;\n varying float outline_thickness;\n varying vec4 shadow_color;\n varying vec2 shadow_offset;\n#endif\nvec4 applyMsdf(vec4 color) {\n color.rgb = gammaCorrectInput(color.rgb);\n vec3 tsample = texture2D(texture_msdfMap, vUv0).rgb;\n vec2 uvShdw = vUv0 - shadow_offset;\n vec3 ssample = texture2D(texture_msdfMap, uvShdw).rgb;\n float sigDist = median(tsample.r, tsample.g, tsample.b);\n float sigDistShdw = median(ssample.r, ssample.g, ssample.b);\n float smoothingMax = 0.2;\n vec2 w = fwidth(vUv0);\n float smoothing = clamp(w.x * font_textureWidth / font_pxrange, 0.0, smoothingMax);\n float mapMin = 0.05;\n float mapMax = clamp(1.0 - font_sdfIntensity, mapMin, 1.0);\n float sigDistInner = map(mapMin, mapMax, sigDist);\n float sigDistOutline = map(mapMin, mapMax, sigDist + outline_thickness);\n sigDistShdw = map(mapMin, mapMax, sigDistShdw + outline_thickness);\n float center = 0.5;\n float inside = smoothstep(center-smoothing, center+smoothing, sigDistInner);\n float outline = smoothstep(center-smoothing, center+smoothing, sigDistOutline);\n float shadow = smoothstep(center-smoothing, center+smoothing, sigDistShdw);\n vec4 tcolor = (outline > inside) ? outline * vec4(outline_color.a * outline_color.rgb, outline_color.a) : vec4(0.0);\n tcolor = mix(tcolor, color, inside);\n vec4 scolor = (shadow > outline) ? shadow * vec4(shadow_color.a * shadow_color.rgb, shadow_color.a) : tcolor;\n tcolor = mix(scolor, tcolor, outline);\n tcolor.rgb = gammaCorrectOutput(tcolor.rgb);\n \n return tcolor;\n}\n",msdfVS:"\nattribute vec3 vertex_outlineParameters;\nattribute vec3 vertex_shadowParameters;\nvarying vec4 outline_color;\nvarying float outline_thickness;\nvarying vec4 shadow_color;\nvarying vec2 shadow_offset;\nvoid unpackMsdfParams() {\n vec3 little = mod(vertex_outlineParameters, 256.);\n vec3 big = (vertex_outlineParameters - little) / 256.;\n outline_color.rb = little.xy / 255.;\n outline_color.ga = big.xy / 255.;\n outline_thickness = little.z / 255. * 0.2;\n little = mod(vertex_shadowParameters, 256.);\n big = (vertex_shadowParameters - little) / 256.;\n shadow_color.rb = little.xy / 255.;\n shadow_color.ga = big.xy / 255.;\n shadow_offset = (vec2(little.z, big.z) / 127. - 1.) * 0.005;\n}\n",normalVS:"\nmat3 dNormalMatrix;\nvec3 getNormal() {\n dNormalMatrix = getNormalMatrix(dModelMatrix);\n vec3 localNormal = getLocalNormal(vertex_normal);\n return normalize(dNormalMatrix * localNormal);\n}\n",normalCoreVS:"\nattribute vec3 vertex_normal;\nuniform mat3 matrix_normal;\n#ifdef MORPHING_NORMAL\n #ifdef MORPHING_INT\n uniform highp usampler2D morphNormalTex;\n #else\n uniform highp sampler2D morphNormalTex;\n #endif\n#endif\nvec3 getLocalNormal(vec3 vertexNormal) {\n vec3 localNormal = vertex_normal;\n #ifdef MORPHING_NORMAL\n ivec2 morphUV = getTextureMorphCoords();\n #ifdef MORPHING_INT\n vec3 morphNormal = vec3(texelFetch(morphNormalTex, ivec2(morphUV), 0).xyz) / 65535.0 * 2.0 - 1.0;\n #else\n vec3 morphNormal = texelFetch(morphNormalTex, ivec2(morphUV), 0).xyz;\n #endif\n localNormal += morphNormal;\n #endif\n return localNormal;\n}\n#if defined(SKIN) || defined(BATCH)\n mat3 getNormalMatrix(mat4 modelMatrix) {\n return mat3(modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz);\n }\n#elif defined(INSTANCING)\n mat3 getNormalMatrix(mat4 modelMatrix) {\n return mat3(modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz);\n }\n#else\n mat3 getNormalMatrix(mat4 modelMatrix) {\n return matrix_normal;\n }\n#endif\n",normalMapPS:"\n#ifdef STD_NORMAL_TEXTURE\n uniform float material_bumpiness;\n#endif\n#ifdef STD_NORMALDETAIL_TEXTURE\n uniform float material_normalDetailMapBumpiness;\n vec3 blendNormals(vec3 n1, vec3 n2) {\n n1 += vec3(0, 0, 1);\n n2 *= vec3(-1, -1, 1);\n return n1 * dot(n1, n2) / n1.z - n2;\n }\n#endif\nvoid getNormal() {\n#ifdef STD_NORMAL_TEXTURE\n vec3 normalMap = {STD_NORMAL_TEXTURE_DECODE}(texture2DBias({STD_NORMAL_TEXTURE_NAME}, {STD_NORMAL_TEXTURE_UV}, textureBias));\n normalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, material_bumpiness);\n #ifdef STD_NORMALDETAIL_TEXTURE\n vec3 normalDetailMap = {STD_NORMALDETAIL_TEXTURE_DECODE}(texture2DBias({STD_NORMALDETAIL_TEXTURE_NAME}, {STD_NORMALDETAIL_TEXTURE_UV}, textureBias));\n normalDetailMap = mix(vec3(0.0, 0.0, 1.0), normalDetailMap, material_normalDetailMapBumpiness);\n normalMap = blendNormals(normalMap, normalDetailMap);\n #endif\n dNormalW = normalize(dTBN * normalMap);\n#else\n dNormalW = dVertexNormalW;\n#endif\n}\n",opacityPS:"\nuniform float material_opacity;\nvoid getOpacity() {\n dAlpha = material_opacity;\n #ifdef STD_OPACITY_TEXTURE\n dAlpha *= texture2DBias({STD_OPACITY_TEXTURE_NAME}, {STD_OPACITY_TEXTURE_UV}, textureBias).{STD_OPACITY_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_OPACITY_VERTEX\n dAlpha *= clamp(vVertexColor.{STD_OPACITY_VERTEX_CHANNEL}, 0.0, 1.0);\n #endif\n}\n",opacityDitherPS:'\n#if STD_OPACITY_DITHER == BAYER8\n #include "bayerPS"\n#endif\nuniform vec4 blueNoiseJitter;\n#if STD_OPACITY_DITHER == BLUENOISE\n uniform sampler2D blueNoiseTex32;\n#endif\nvoid opacityDither(float alpha, float id) {\n #if STD_OPACITY_DITHER == BAYER8\n float noise = bayer8(floor(mod(gl_FragCoord.xy + blueNoiseJitter.xy + id, 8.0))) / 64.0;\n #else\n #if STD_OPACITY_DITHER == BLUENOISE\n vec2 uv = fract(gl_FragCoord.xy / 32.0 + blueNoiseJitter.xy + id);\n float noise = texture2DLod(blueNoiseTex32, uv, 0.0).y;\n #endif\n #if STD_OPACITY_DITHER == IGNNOISE\n vec3 magic = vec3(0.06711056, 0.00583715, 52.9829189);\n float noise = fract(magic.z * fract(dot(gl_FragCoord.xy + blueNoiseJitter.xy + id, magic.xy)));\n #endif\n #endif\n noise = pow(noise, 2.2);\n if (alpha < noise)\n discard;\n}\n',outputPS:"\n",outputAlphaPS:"\n#if LIT_BLEND_TYPE == NORMAL || LIT_BLEND_TYPE == ADDITIVEALPHA || defined(LIT_ALPHA_TO_COVERAGE)\n gl_FragColor.a = litArgs_opacity;\n#elif LIT_BLEND_TYPE == PREMULTIPLIED\n gl_FragColor.rgb *= litArgs_opacity;\n gl_FragColor.a = litArgs_opacity;\n#else\n gl_FragColor.a = 1.0;\n#endif\n",outputTex2DPS:"\nvarying vec2 vUv0;\nuniform sampler2D source;\nvoid main(void) {\n gl_FragColor = texture2D(source, vUv0);\n}\n",sheenPS:"\nuniform vec3 material_sheen;\nvoid getSheen() {\n vec3 sheenColor = material_sheen;\n #ifdef STD_SHEEN_TEXTURE\n sheenColor *= {STD_SHEEN_TEXTURE_DECODE}(texture2DBias({STD_SHEEN_TEXTURE_NAME}, {STD_SHEEN_TEXTURE_UV}, textureBias)).{STD_SHEEN_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_SHEEN_VERTEX\n sheenColor *= saturate(vVertexColor.{STD_SHEEN_VERTEX_CHANNEL});\n #endif\n sSpecularity = sheenColor;\n}\n",sheenGlossPS:"\nuniform float material_sheenGloss;\nvoid getSheenGlossiness() {\n float sheenGlossiness = material_sheenGloss;\n #ifdef STD_SHEENGLOSS_TEXTURE\n sheenGlossiness *= texture2DBias({STD_SHEENGLOSS_TEXTURE_NAME}, {STD_SHEENGLOSS_TEXTURE_UV}, textureBias).{STD_SHEENGLOSS_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_SHEENGLOSS_VERTEX\n sheenGlossiness *= saturate(vVertexColor.{STD_SHEENGLOSS_VERTEX_CHANNEL});\n #endif\n #ifdef STD_SHEENGLOSS_INVERT\n sheenGlossiness = 1.0 - sheenGlossiness;\n #endif\n sGlossiness = sheenGlossiness + 0.0000001;\n}\n",parallaxPS:"\nuniform float material_heightMapFactor;\nvoid getParallax() {\n float parallaxScale = material_heightMapFactor;\n float height = texture2DBias({STD_HEIGHT_TEXTURE_NAME}, {STD_HEIGHT_TEXTURE_UV}, textureBias).{STD_HEIGHT_TEXTURE_CHANNEL};\n height = height * parallaxScale - parallaxScale * 0.5;\n vec3 viewDirT = dViewDirW * dTBN;\n viewDirT.z += 0.42;\n dUvOffset = height * (viewDirT.xy / viewDirT.z);\n}\n",pickPS:"\nuniform uint meshInstanceId;\nvec4 getPickOutput() {\n const vec4 inv = vec4(1.0 / 255.0);\n const uvec4 shifts = uvec4(16, 8, 0, 24);\n uvec4 col = (uvec4(meshInstanceId) >> shifts) & uvec4(0xff);\n return vec4(col) * inv;\n}\n",reflDirPS:"\nvoid getReflDir(vec3 worldNormal, vec3 viewDir, float gloss, mat3 tbn) {\n dReflDirW = normalize(-reflect(viewDir, worldNormal));\n}\n",reflDirAnisoPS:"\nvoid getReflDir(vec3 worldNormal, vec3 viewDir, float gloss, mat3 tbn) {\n float roughness = sqrt(1.0 - min(gloss, 1.0));\n vec2 direction = dAnisotropyRotation;\n vec3 anisotropicT = normalize(tbn * vec3(direction, 0.0));\n vec3 anisotropicB = normalize(cross(tbn[2], anisotropicT));\n float anisotropy = dAnisotropy;\n vec3 anisotropicDirection = anisotropicB;\n vec3 anisotropicTangent = cross(anisotropicDirection, viewDir);\n vec3 anisotropicNormal = cross(anisotropicTangent, anisotropicDirection);\n float bendFactor = 1.0 - anisotropy * (1.0 - roughness);\n float bendFactor4 = bendFactor * bendFactor * bendFactor * bendFactor;\n vec3 bentNormal = normalize(mix(normalize(anisotropicNormal), normalize(worldNormal), bendFactor4));\n dReflDirW = reflect(-viewDir, bentNormal);\n}\n",reflectionCCPS:"\n#ifdef LIT_CLEARCOAT\nvoid addReflectionCC(vec3 reflDir, float gloss) {\n ccReflection += calcReflection(reflDir, gloss);\n}\n#endif\n",reflectionCubePS:"\nuniform samplerCube texture_cubeMap;\nuniform float material_reflectivity;\nvec3 calcReflection(vec3 reflDir, float gloss) {\n vec3 lookupVec = cubeMapProject(reflDir);\n lookupVec.x *= -1.0;\n return {reflectionDecode}(textureCube(texture_cubeMap, lookupVec));\n}\nvoid addReflection(vec3 reflDir, float gloss) { \n dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);\n}\n",reflectionEnvHQPS:"\n#ifndef ENV_ATLAS\n #define ENV_ATLAS\n uniform sampler2D texture_envAtlas;\n#endif\nuniform samplerCube texture_cubeMap;\nuniform float material_reflectivity;\nvec3 calcReflection(vec3 reflDir, float gloss) {\n vec3 dir = cubeMapProject(reflDir) * vec3(-1.0, 1.0, 1.0);\n vec2 uv = toSphericalUv(dir);\n float level = saturate(1.0 - gloss) * 5.0;\n float ilevel = floor(level);\n float flevel = level - ilevel;\n vec3 sharp = {reflectionCubemapDecode}(textureCube(texture_cubeMap, dir));\n vec3 roughA = {reflectionDecode}(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel)));\n vec3 roughB = {reflectionDecode}(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0)));\n return processEnvironment(mix(sharp, mix(roughA, roughB, flevel), min(level, 1.0)));\n}\nvoid addReflection(vec3 reflDir, float gloss) { \n dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);\n}\n",reflectionEnvPS:"\n#ifndef ENV_ATLAS\n#define ENV_ATLAS\n uniform sampler2D texture_envAtlas;\n#endif\nuniform float material_reflectivity;\nfloat shinyMipLevel(vec2 uv) {\n vec2 dx = dFdx(uv);\n vec2 dy = dFdy(uv);\n vec2 uv2 = vec2(fract(uv.x + 0.5), uv.y);\n vec2 dx2 = dFdx(uv2);\n vec2 dy2 = dFdy(uv2);\n float maxd = min(max(dot(dx, dx), dot(dy, dy)), max(dot(dx2, dx2), dot(dy2, dy2)));\n return clamp(0.5 * log2(maxd) - 1.0 + textureBias, 0.0, 5.0);\n}\nvec3 calcReflection(vec3 reflDir, float gloss) {\n vec3 dir = cubeMapProject(reflDir) * vec3(-1.0, 1.0, 1.0);\n vec2 uv = toSphericalUv(dir);\n float level = saturate(1.0 - gloss) * 5.0;\n float ilevel = floor(level);\n float level2 = shinyMipLevel(uv * atlasSize);\n float ilevel2 = floor(level2);\n vec2 uv0, uv1;\n float weight;\n if (ilevel == 0.0) {\n uv0 = mapShinyUv(uv, ilevel2);\n uv1 = mapShinyUv(uv, ilevel2 + 1.0);\n weight = level2 - ilevel2;\n } else {\n uv0 = uv1 = mapRoughnessUv(uv, ilevel);\n weight = 0.0;\n }\n vec3 linearA = {reflectionDecode}(texture2D(texture_envAtlas, uv0));\n vec3 linearB = {reflectionDecode}(texture2D(texture_envAtlas, uv1));\n vec3 linear0 = mix(linearA, linearB, weight);\n vec3 linear1 = {reflectionDecode}(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0)));\n return processEnvironment(mix(linear0, linear1, level - ilevel));\n}\nvoid addReflection(vec3 reflDir, float gloss) { \n dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);\n}\n",reflectionSpherePS:"\n#ifndef VIEWMATRIX\n #define VIEWMATRIX\n uniform mat4 matrix_view;\n#endif\nuniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\nvec3 calcReflection(vec3 reflDir, float gloss) {\n vec3 reflDirV = (mat3(matrix_view) * reflDir);\n float m = 2.0 * sqrt(dot(reflDirV.xy, reflDirV.xy) + (reflDirV.z + 1.0) * (reflDirV.z + 1.0));\n vec2 sphereMapUv = reflDirV.xy / m + 0.5;\n return {reflectionDecode}(texture2D(texture_sphereMap, sphereMapUv));\n}\nvoid addReflection(vec3 reflDir, float gloss) { \n dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);\n}\n",reflectionSheenPS:"\nvoid addReflectionSheen(vec3 worldNormal, vec3 viewDir, float gloss) {\n float NoV = dot(worldNormal, viewDir);\n float alphaG = gloss * gloss;\n float a = gloss < 0.25 ? -339.2 * alphaG + 161.4 * gloss - 25.9 : -8.48 * alphaG + 14.3 * gloss - 9.95;\n float b = gloss < 0.25 ? 44.0 * alphaG - 23.7 * gloss + 3.26 : 1.97 * alphaG - 3.27 * gloss + 0.72;\n float DG = exp( a * NoV + b ) + ( gloss < 0.25 ? 0.0 : 0.1 * ( gloss - 0.25 ) );\n sReflection += calcReflection(worldNormal, 0.0) * saturate(DG);\n}\n",refractionCubePS:"\nvec3 refract2(vec3 viewVec, vec3 normal, float IOR) {\n float vn = dot(viewVec, normal);\n float k = 1.0 - IOR * IOR * (1.0 - vn * vn);\n vec3 refrVec = IOR * viewVec - (IOR * vn + sqrt(k)) * normal;\n return refrVec;\n}\nvoid addRefraction(\n vec3 worldNormal, \n vec3 viewDir, \n float thickness, \n float gloss, \n vec3 specularity, \n vec3 albedo, \n float transmission,\n float refractionIndex,\n float dispersion\n#if defined(LIT_IRIDESCENCE)\n , vec3 iridescenceFresnel,\n float iridescenceIntensity\n#endif \n) {\n vec4 tmpRefl = dReflection;\n vec3 reflectionDir = refract2(-viewDir, worldNormal, refractionIndex);\n dReflection = vec4(0);\n addReflection(reflectionDir, gloss);\n dDiffuseLight = mix(dDiffuseLight, dReflection.rgb * albedo, transmission);\n dReflection = tmpRefl;\n}\n",refractionDynamicPS:"\nuniform float material_invAttenuationDistance;\nuniform vec3 material_attenuation;\nvec3 evalRefractionColor(vec3 refractionVector, float gloss, float refractionIndex) {\n vec4 pointOfRefraction = vec4(vPositionW + refractionVector, 1.0);\n vec4 projectionPoint = matrix_viewProjection * pointOfRefraction;\n vec2 uv = getGrabScreenPos(projectionPoint);\n float iorToRoughness = (1.0 - gloss) * clamp((1.0 / refractionIndex) * 2.0 - 2.0, 0.0, 1.0);\n float refractionLod = log2(uScreenSize.x) * iorToRoughness;\n vec3 refraction = texture2DLod(uSceneColorMap, uv, refractionLod).rgb;\n return refraction;\n}\nvoid addRefraction(\n vec3 worldNormal, \n vec3 viewDir, \n float thickness, \n float gloss, \n vec3 specularity, \n vec3 albedo, \n float transmission,\n float refractionIndex,\n float dispersion\n#if defined(LIT_IRIDESCENCE)\n , vec3 iridescenceFresnel,\n float iridescenceIntensity\n#endif\n) {\n vec3 modelScale;\n modelScale.x = length(vec3(matrix_model[0].xyz));\n modelScale.y = length(vec3(matrix_model[1].xyz));\n modelScale.z = length(vec3(matrix_model[2].xyz));\n vec3 scale = thickness * modelScale;\n vec3 refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndex)) * scale;\n vec3 refraction = evalRefractionColor(refractionVector, gloss, refractionIndex);\n #ifdef LIT_DISPERSION\n float halfSpread = (1.0 / refractionIndex - 1.0) * 0.025 * dispersion;\n float refractionIndexR = refractionIndex - halfSpread;\n refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndexR)) * scale;\n refraction.r = evalRefractionColor(refractionVector, gloss, refractionIndexR).r;\n float refractionIndexB = refractionIndex + halfSpread;\n refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndexB)) * scale;\n refraction.b = evalRefractionColor(refractionVector, gloss, refractionIndexB).b;\n #endif\n vec3 transmittance;\n if (material_invAttenuationDistance != 0.0)\n {\n vec3 attenuation = -log(material_attenuation) * material_invAttenuationDistance;\n transmittance = exp(-attenuation * length(refractionVector));\n }\n else\n {\n transmittance = refraction;\n }\n vec3 fresnel = vec3(1.0) - \n getFresnel(\n dot(viewDir, worldNormal), \n gloss, \n specularity\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n iridescenceIntensity\n #endif\n );\n dDiffuseLight = mix(dDiffuseLight, refraction * transmittance * fresnel, transmission);\n}\n",reprojectPS:'\nvarying vec2 vUv0;\n#ifdef CUBEMAP_SOURCE\n uniform samplerCube sourceCube;\n#else\n uniform sampler2D sourceTex;\n#endif\n#ifdef USE_SAMPLES_TEX\n uniform sampler2D samplesTex;\n uniform vec2 samplesTexInverseSize;\n#endif\nuniform vec3 params;\nfloat targetFace() { return params.x; }\nfloat targetTotalPixels() { return params.y; }\nfloat sourceTotalPixels() { return params.z; }\nfloat PI = 3.141592653589793;\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n#include "decodePS"\n#include "encodePS"\nvec3 modifySeams(vec3 dir, float scale) {\n vec3 adir = abs(dir);\n float M = max(max(adir.x, adir.y), adir.z);\n return dir / M * vec3(\n adir.x == M ? 1.0 : scale,\n adir.y == M ? 1.0 : scale,\n adir.z == M ? 1.0 : scale\n );\n}\nvec2 toSpherical(vec3 dir) {\n return vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y));\n}\nvec3 fromSpherical(vec2 uv) {\n return vec3(cos(uv.y) * sin(uv.x),\n sin(uv.y),\n cos(uv.y) * cos(uv.x));\n}\nvec3 getDirectionEquirect() {\n return fromSpherical((vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0) * vec2(PI, PI * 0.5));\n}\nfloat signNotZero(float k){\n return(k >= 0.0) ? 1.0 : -1.0;\n}\nvec2 signNotZero(vec2 v) {\n return vec2(signNotZero(v.x), signNotZero(v.y));\n}\nvec3 octDecode(vec2 o) {\n vec3 v = vec3(o.x, 1.0 - abs(o.x) - abs(o.y), o.y);\n if (v.y < 0.0) {\n v.xz = (1.0 - abs(v.zx)) * signNotZero(v.xz);\n }\n return normalize(v);\n}\nvec3 getDirectionOctahedral() {\n return octDecode(vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0);\n}\nvec2 octEncode(in vec3 v) {\n float l1norm = abs(v.x) + abs(v.y) + abs(v.z);\n vec2 result = v.xz * (1.0 / l1norm);\n if (v.y < 0.0) {\n result = (1.0 - abs(result.yx)) * signNotZero(result.xy);\n }\n return result;\n}\n#ifdef CUBEMAP_SOURCE\n vec4 sampleCubemap(vec3 dir) {\n return textureCube(sourceCube, modifySeams(dir, 1.0));\n }\n vec4 sampleCubemap(vec2 sph) {\n return sampleCubemap(fromSpherical(sph));\n }\n vec4 sampleCubemap(vec3 dir, float mipLevel) {\n return textureCubeLod(sourceCube, modifySeams(dir, 1.0), mipLevel);\n }\n vec4 sampleCubemap(vec2 sph, float mipLevel) {\n return sampleCubemap(fromSpherical(sph), mipLevel);\n }\n#else\n vec4 sampleEquirect(vec2 sph) {\n vec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;\n return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n }\n vec4 sampleEquirect(vec3 dir) {\n return sampleEquirect(toSpherical(dir));\n }\n vec4 sampleEquirect(vec2 sph, float mipLevel) {\n vec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;\n return texture2DLod(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);\n }\n vec4 sampleEquirect(vec3 dir, float mipLevel) {\n return sampleEquirect(toSpherical(dir), mipLevel);\n }\n vec4 sampleOctahedral(vec3 dir) {\n vec2 uv = octEncode(dir) * 0.5 + 0.5;\n return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));\n }\n vec4 sampleOctahedral(vec2 sph) {\n return sampleOctahedral(fromSpherical(sph));\n }\n vec4 sampleOctahedral(vec3 dir, float mipLevel) {\n vec2 uv = octEncode(dir) * 0.5 + 0.5;\n return texture2DLod(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);\n }\n vec4 sampleOctahedral(vec2 sph, float mipLevel) {\n return sampleOctahedral(fromSpherical(sph), mipLevel);\n }\n#endif\nvec3 getDirectionCubemap() {\n vec2 st = vUv0 * 2.0 - 1.0;\n float face = targetFace();\n vec3 vec;\n if (face == 0.0) {\n vec = vec3(1, -st.y, -st.x);\n } else if (face == 1.0) {\n vec = vec3(-1, -st.y, st.x);\n } else if (face == 2.0) {\n vec = vec3(st.x, 1, st.y);\n } else if (face == 3.0) {\n vec = vec3(st.x, -1, -st.y);\n } else if (face == 4.0) {\n vec = vec3(st.x, -st.y, 1);\n } else {\n vec = vec3(-st.x, -st.y, -1);\n }\n return normalize(modifySeams(vec, 1.0));\n}\nmat3 matrixFromVector(vec3 n) {\n float a = 1.0 / (1.0 + n.z);\n float b = -n.x * n.y * a;\n vec3 b1 = vec3(1.0 - n.x * n.x * a, b, -n.x);\n vec3 b2 = vec3(b, 1.0 - n.y * n.y * a, -n.y);\n return mat3(b1, b2, n);\n}\nmat3 matrixFromVectorSlow(vec3 n) {\n vec3 up = (1.0 - abs(n.y) <= 0.0000001) ? vec3(0.0, 0.0, n.y > 0.0 ? 1.0 : -1.0) : vec3(0.0, 1.0, 0.0);\n vec3 x = normalize(cross(up, n));\n vec3 y = cross(n, x);\n return mat3(x, y, n);\n}\nvec4 reproject() {\n if ({NUM_SAMPLES} <= 1) {\n return {ENCODE_FUNC}({DECODE_FUNC}({SOURCE_FUNC}({TARGET_FUNC}())));\n } else {\n vec3 t = {TARGET_FUNC}();\n vec3 tu = dFdx(t);\n vec3 tv = dFdy(t);\n vec3 result = vec3(0.0);\n for (float u = 0.0; u < {NUM_SAMPLES_SQRT}; ++u) {\n for (float v = 0.0; v < {NUM_SAMPLES_SQRT}; ++v) {\n result += {DECODE_FUNC}({SOURCE_FUNC}(normalize(t +\n tu * (u / {NUM_SAMPLES_SQRT} - 0.5) +\n tv * (v / {NUM_SAMPLES_SQRT} - 0.5))));\n }\n }\n return {ENCODE_FUNC}(result / ({NUM_SAMPLES_SQRT} * {NUM_SAMPLES_SQRT}));\n }\n}\nvec4 unpackFloat = vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0);\n#ifdef USE_SAMPLES_TEX\n void unpackSample(int i, out vec3 L, out float mipLevel) {\n float u = (float(i * 4) + 0.5) * samplesTexInverseSize.x;\n float v = (floor(u) + 0.5) * samplesTexInverseSize.y;\n vec4 raw;\n raw.x = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n raw.y = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n raw.z = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n raw.w = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat);\n L.xyz = raw.xyz * 2.0 - 1.0;\n mipLevel = raw.w * 8.0;\n }\n vec4 prefilterSamples() {\n mat3 vecSpace = matrixFromVectorSlow({TARGET_FUNC}());\n vec3 L;\n float mipLevel;\n vec3 result = vec3(0.0);\n float totalWeight = 0.0;\n for (int i = 0; i < {NUM_SAMPLES}; ++i) {\n unpackSample(i, L, mipLevel);\n result += {DECODE_FUNC}({SOURCE_FUNC}(vecSpace * L, mipLevel)) * L.z;\n totalWeight += L.z;\n }\n return {ENCODE_FUNC}(result / totalWeight);\n }\n vec4 prefilterSamplesUnweighted() {\n mat3 vecSpace = matrixFromVectorSlow({TARGET_FUNC}());\n vec3 L;\n float mipLevel;\n vec3 result = vec3(0.0);\n float totalWeight = 0.0;\n for (int i = 0; i < {NUM_SAMPLES}; ++i) {\n unpackSample(i, L, mipLevel);\n result += {DECODE_FUNC}({SOURCE_FUNC}(vecSpace * L, mipLevel));\n }\n return {ENCODE_FUNC}(result / float({NUM_SAMPLES}));\n }\n#endif\nvoid main(void) {\n gl_FragColor = {PROCESS_FUNC}();\n}\n',reprojectVS:"\nattribute vec2 vertex_position;\nuniform vec4 uvMod;\nvarying vec2 vUv0;\nvoid main(void) {\n gl_Position = vec4(vertex_position, 0.5, 1.0);\n vUv0 = getImageEffectUV((vertex_position.xy * 0.5 + 0.5) * uvMod.xy + uvMod.zw);\n}\n",screenDepthPS:"\nuniform highp sampler2D uSceneDepthMap;\n#ifndef SCREENSIZE\n #define SCREENSIZE\n uniform vec4 uScreenSize;\n#endif\n#ifndef VIEWMATRIX\n #define VIEWMATRIX\n uniform mat4 matrix_view;\n#endif\n#ifndef LINEARIZE_DEPTH\n #define LINEARIZE_DEPTH\n \n #ifndef CAMERAPLANES\n #define CAMERAPLANES\n uniform vec4 camera_params;\n #endif\n float linearizeDepth(float z) {\n if (camera_params.w == 0.0)\n return (camera_params.z * camera_params.y) / (camera_params.y + z * (camera_params.z - camera_params.y));\n else\n return camera_params.z + z * (camera_params.y - camera_params.z);\n }\n#endif\nfloat delinearizeDepth(float linearDepth) {\n if (camera_params.w == 0.0) {\n return (camera_params.y * (camera_params.z - linearDepth)) / (linearDepth * (camera_params.z - camera_params.y));\n } else {\n return (linearDepth - camera_params.z) / (camera_params.y - camera_params.z);\n }\n}\nfloat getLinearScreenDepth(vec2 uv) {\n #ifdef SCENE_DEPTHMAP_LINEAR\n #ifdef SCENE_DEPTHMAP_FLOAT\n return texture2D(uSceneDepthMap, uv).r;\n #else\n ivec2 textureSize = textureSize(uSceneDepthMap, 0);\n ivec2 texel = ivec2(uv * vec2(textureSize));\n vec4 data = texelFetch(uSceneDepthMap, texel, 0);\n uint intBits = \n (uint(data.r * 255.0) << 24u) |\n (uint(data.g * 255.0) << 16u) |\n (uint(data.b * 255.0) << 8u) |\n uint(data.a * 255.0);\n return uintBitsToFloat(intBits);\n #endif\n #else\n return linearizeDepth(texture2D(uSceneDepthMap, uv).r);\n #endif\n}\n#ifndef VERTEXSHADER\n float getLinearScreenDepth() {\n vec2 uv = gl_FragCoord.xy * uScreenSize.zw;\n return getLinearScreenDepth(uv);\n }\n#endif\nfloat getLinearDepth(vec3 pos) {\n return -(matrix_view * vec4(pos, 1.0)).z;\n}\n",shadowCascadesPS:"\nint getShadowCascadeIndex(vec4 shadowCascadeDistances, int shadowCascadeCount) {\n float depth = 1.0 / gl_FragCoord.w;\n vec4 comparisons = step(shadowCascadeDistances, vec4(depth));\n int cascadeIndex = int(dot(comparisons, vec4(1.0)));\n return min(cascadeIndex, shadowCascadeCount - 1);\n}\nint ditherShadowCascadeIndex(int cascadeIndex, vec4 shadowCascadeDistances, int shadowCascadeCount, float blendFactor) {\n \n if (cascadeIndex < shadowCascadeCount - 1) {\n float currentRangeEnd = shadowCascadeDistances[cascadeIndex];\n float transitionStart = blendFactor * currentRangeEnd;\n float depth = 1.0 / gl_FragCoord.w;\n if (depth > transitionStart) {\n float transitionFactor = smoothstep(transitionStart, currentRangeEnd, depth);\n float dither = fract(sin(dot(gl_FragCoord.xy, vec2(12.9898, 78.233))) * 43758.5453);\n if (dither < transitionFactor) {\n cascadeIndex += 1;\n }\n }\n }\n return cascadeIndex;\n}\nvec3 fadeShadow(vec3 shadowCoord, vec4 shadowCascadeDistances) { \n float depth = 1.0 / gl_FragCoord.w;\n if (depth > shadowCascadeDistances.w) {\n shadowCoord.z = -9999999.0;\n }\n return shadowCoord;\n}\n",shadowEVSMPS:"\nfloat linstep(float a, float b, float v) {\n return 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 float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, minVariance);\n float d = mean - moments.x;\n float pMax = variance / (variance + (d * d));\n pMax = reduceLightBleeding(pMax, lightBleedingReduction);\n return (mean <= moments.x ? 1.0 : pMax);\n}\nfloat calculateEVSM(vec3 moments, float Z, float vsmBias, float exponent) {\n Z = 2.0 * Z - 1.0;\n float warpedDepth = exp(exponent * Z);\n moments.xy += vec2(warpedDepth, warpedDepth*warpedDepth) * (1.0 - moments.z);\n float VSMBias = vsmBias;\n float depthScale = VSMBias * exponent * warpedDepth;\n float minVariance1 = depthScale * depthScale;\n return chebyshevUpperBound(moments.xy, warpedDepth, minVariance1, 0.1);\n}\nfloat VSM16(TEXTURE_ACCEPT(tex), vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n vec3 moments = texture2DLod(tex, texCoords, 0.0).xyz;\n return calculateEVSM(moments, Z, vsmBias, exponent);\n}\nfloat getShadowVSM16(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent) {\n return VSM16(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);\n}\nfloat getShadowSpotVSM16(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n return VSM16(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, length(lightDir) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);\n}\nfloat VSM32(TEXTURE_ACCEPT(tex), vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n #ifdef CAPS_TEXTURE_FLOAT_FILTERABLE\n vec3 moments = texture2DLod(tex, texCoords, 0.0).xyz;\n #else\n float pixelSize = 1.0 / resolution;\n texCoords -= vec2(pixelSize);\n vec3 s00 = texture2DLod(tex, texCoords, 0.0).xyz;\n vec3 s10 = texture2DLod(tex, texCoords + vec2(pixelSize, 0), 0.0).xyz;\n vec3 s01 = texture2DLod(tex, texCoords + vec2(0, pixelSize), 0.0).xyz;\n vec3 s11 = texture2DLod(tex, texCoords + vec2(pixelSize), 0.0).xyz;\n vec2 fr = fract(texCoords * resolution);\n vec3 h0 = mix(s00, s10, fr.x);\n vec3 h1 = mix(s01, s11, fr.x);\n vec3 moments = mix(h0, h1, fr.y);\n #endif\n return calculateEVSM(moments, Z, vsmBias, exponent);\n}\nfloat getShadowVSM32(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent) {\n return VSM32(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);\n}\nfloat getShadowSpotVSM32(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n float Z = length(lightDir) * shadowParams.w + shadowParams.z;\n return VSM32(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, Z, shadowParams.y, exponent);\n}\n",shadowPCF1PS:"\nfloat getShadowPCF1x1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return textureShadow(shadowMap, shadowCoord);\n}\nfloat getShadowSpotPCF1x1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return textureShadow(shadowMap, shadowCoord);\n}\n#ifndef WEBGPU\nfloat getShadowOmniPCF1x1(samplerCubeShadow shadowMap, vec3 shadowCoord, vec4 shadowParams, vec3 lightDir) {\n float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;\n return texture(shadowMap, vec4(lightDir, shadowZ));\n}\n#endif\n",shadowPCF3PS:"\nfloat _getShadowPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec3 shadowParams) {\n float z = shadowCoord.z;\n vec2 uv = shadowCoord.xy * shadowParams.x;\n float shadowMapSizeInv = 1.0 / shadowParams.x;\n vec2 base_uv = floor(uv + 0.5);\n float s = (uv.x + 0.5 - base_uv.x);\n float t = (uv.y + 0.5 - base_uv.y); \n base_uv -= vec2(0.5);\n base_uv *= shadowMapSizeInv;\n float sum = 0.0;\n float uw0 = (3.0 - 2.0 * s);\n float uw1 = (1.0 + 2.0 * s);\n float u0 = (2.0 - s) / uw0 - 1.0;\n float u1 = s / uw1 + 1.0;\n float vw0 = (3.0 - 2.0 * t);\n float vw1 = (1.0 + 2.0 * t);\n float v0 = (2.0 - t) / vw0 - 1.0;\n float v1 = t / vw1 + 1.0;\n u0 = u0 * shadowMapSizeInv + base_uv.x;\n v0 = v0 * shadowMapSizeInv + base_uv.y;\n u1 = u1 * shadowMapSizeInv + base_uv.x;\n v1 = v1 * shadowMapSizeInv + base_uv.y;\n sum += uw0 * vw0 * textureShadow(shadowMap, vec3(u0, v0, z));\n sum += uw1 * vw0 * textureShadow(shadowMap, vec3(u1, v0, z));\n sum += uw0 * vw1 * textureShadow(shadowMap, vec3(u0, v1, z));\n sum += uw1 * vw1 * textureShadow(shadowMap, vec3(u1, v1, z));\n sum *= 1.0f / 16.0;\n return sum;\n}\nfloat getShadowPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return _getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);\n}\nfloat getShadowSpotPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return _getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);\n}\n#ifndef WEBGPU\nfloat getShadowOmniPCF3x3(samplerCubeShadow shadowMap, vec4 shadowParams, vec3 dir) {\n \n float shadowZ = length(dir) * shadowParams.w + shadowParams.z;\n float z = 1.0 / float(textureSize(shadowMap, 0));\n vec3 tc = normalize(dir);\n mediump vec4 shadows;\n shadows.x = texture(shadowMap, vec4(tc + vec3( z, z, z), shadowZ));\n shadows.y = texture(shadowMap, vec4(tc + vec3(-z,-z, z), shadowZ));\n shadows.z = texture(shadowMap, vec4(tc + vec3(-z, z,-z), shadowZ));\n shadows.w = texture(shadowMap, vec4(tc + vec3( z,-z,-z), shadowZ));\n return dot(shadows, vec4(0.25));\n}\nfloat getShadowOmniPCF3x3(samplerCubeShadow shadowMap, vec3 shadowCoord, vec4 shadowParams, vec3 lightDir) {\n return getShadowOmniPCF3x3(shadowMap, shadowParams, lightDir);\n}\n#endif\n",shadowPCF5PS:"\nfloat _getShadowPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec3 shadowParams) {\n float z = shadowCoord.z;\n vec2 uv = shadowCoord.xy * shadowParams.x;\n float shadowMapSizeInv = 1.0 / shadowParams.x;\n vec2 base_uv = floor(uv + 0.5);\n float s = (uv.x + 0.5 - base_uv.x);\n float t = (uv.y + 0.5 - base_uv.y);\n base_uv -= vec2(0.5);\n base_uv *= shadowMapSizeInv;\n float uw0 = (4.0 - 3.0 * s);\n float uw1 = 7.0;\n float uw2 = (1.0 + 3.0 * s);\n float u0 = (3.0 - 2.0 * s) / uw0 - 2.0;\n float u1 = (3.0 + s) / uw1;\n float u2 = s / uw2 + 2.0;\n float vw0 = (4.0 - 3.0 * t);\n float vw1 = 7.0;\n float vw2 = (1.0 + 3.0 * t);\n float v0 = (3.0 - 2.0 * t) / vw0 - 2.0;\n float v1 = (3.0 + t) / vw1;\n float v2 = t / vw2 + 2.0;\n float sum = 0.0;\n u0 = u0 * shadowMapSizeInv + base_uv.x;\n v0 = v0 * shadowMapSizeInv + base_uv.y;\n u1 = u1 * shadowMapSizeInv + base_uv.x;\n v1 = v1 * shadowMapSizeInv + base_uv.y;\n u2 = u2 * shadowMapSizeInv + base_uv.x;\n v2 = v2 * shadowMapSizeInv + base_uv.y;\n sum += uw0 * vw0 * textureShadow(shadowMap, vec3(u0, v0, z));\n sum += uw1 * vw0 * textureShadow(shadowMap, vec3(u1, v0, z));\n sum += uw2 * vw0 * textureShadow(shadowMap, vec3(u2, v0, z));\n sum += uw0 * vw1 * textureShadow(shadowMap, vec3(u0, v1, z));\n sum += uw1 * vw1 * textureShadow(shadowMap, vec3(u1, v1, z));\n sum += uw2 * vw1 * textureShadow(shadowMap, vec3(u2, v1, z));\n sum += uw0 * vw2 * textureShadow(shadowMap, vec3(u0, v2, z));\n sum += uw1 * vw2 * textureShadow(shadowMap, vec3(u1, v2, z));\n sum += uw2 * vw2 * textureShadow(shadowMap, vec3(u2, v2, z));\n sum *= 1.0f / 144.0;\n sum = saturate(sum);\n return sum;\n}\nfloat getShadowPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return _getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);\n}\nfloat getShadowSpotPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return _getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);\n}\n",shadowPCSSPS:"\n#define PCSS_SAMPLE_COUNT 16\nuniform float pcssDiskSamples[PCSS_SAMPLE_COUNT];\nuniform float pcssSphereSamples[PCSS_SAMPLE_COUNT];\nvec2 vogelDisk(int sampleIndex, float count, float phi, float r) {\n const float GoldenAngle = 2.4;\n float theta = float(sampleIndex) * GoldenAngle + phi;\n float sine = sin(theta);\n float cosine = cos(theta);\n return vec2(r * cosine, r * sine);\n}\nvec3 vogelSphere(int sampleIndex, float count, float phi, float r) {\n const float GoldenAngle = 2.4;\n float theta = float(sampleIndex) * GoldenAngle + phi;\n float weight = float(sampleIndex) / count;\n return vec3(cos(theta) * r, weight, sin(theta) * r);\n}\nfloat noise(vec2 screenPos) {\n const float PHI = 1.61803398874989484820459;\n return fract(sin(dot(screenPos * PHI, screenPos)) * screenPos.x);\n}\nfloat viewSpaceDepth(float depth, mat4 invProjection) {\n float z = depth * 2.0 - 1.0;\n vec4 clipSpace = vec4(0.0, 0.0, z, 1.0);\n vec4 viewSpace = invProjection * clipSpace;\n return viewSpace.z;\n}\nfloat PCSSBlockerDistance(TEXTURE_ACCEPT(shadowMap), vec2 sampleCoords[PCSS_SAMPLE_COUNT], vec2 shadowCoords, vec2 searchSize, float z, vec4 cameraParams) {\n float blockers = 0.0;\n float averageBlocker = 0.0;\n for (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {\n vec2 offset = sampleCoords[i] * searchSize;\n vec2 sampleUV = shadowCoords + offset;\n float blocker = texture2DLod(shadowMap, sampleUV, 0.0).r;\n float isBlocking = step(blocker, z);\n blockers += isBlocking;\n averageBlocker += blocker * isBlocking;\n }\n if (blockers > 0.0)\n return averageBlocker / blockers;\n return -1.0;\n}\nfloat PCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoords, vec4 cameraParams, vec2 shadowSearchArea) {\n float receiverDepth = linearizeDepthWithParams(shadowCoords.z, cameraParams);\n vec2 samplePoints[PCSS_SAMPLE_COUNT];\n const float PI = 3.141592653589793;\n float noise = noise( gl_FragCoord.xy ) * 2.0 * PI;\n for (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {\n float pcssPresample = pcssDiskSamples[i];\n samplePoints[i] = vogelDisk(i, float(PCSS_SAMPLE_COUNT), noise, pcssPresample);\n }\n float averageBlocker = PCSSBlockerDistance(TEXTURE_PASS(shadowMap), samplePoints, shadowCoords.xy, shadowSearchArea, receiverDepth, cameraParams);\n if (averageBlocker == -1.0) {\n return 1.0;\n } else {\n float depthDifference = (receiverDepth - averageBlocker) / 3.0;\n vec2 filterRadius = depthDifference * shadowSearchArea;\n float shadow = 0.0;\n for (int i = 0; i < PCSS_SAMPLE_COUNT; i ++)\n {\n vec2 sampleUV = samplePoints[i] * filterRadius;\n sampleUV = shadowCoords.xy + sampleUV;\n float depth = texture2DLod(shadowMap, sampleUV, 0.0).r;\n shadow += step(receiverDepth, depth);\n }\n return shadow / float(PCSS_SAMPLE_COUNT);\n } \n}\n#ifndef WEBGPU\nfloat PCSSCubeBlockerDistance(samplerCube shadowMap, vec3 lightDirNorm, vec3 samplePoints[PCSS_SAMPLE_COUNT], float z, float shadowSearchArea) {\n float blockers = 0.0;\n float averageBlocker = 0.0;\n for (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {\n vec3 sampleDir = lightDirNorm + samplePoints[i] * shadowSearchArea;\n sampleDir = normalize(sampleDir);\n float blocker = textureCubeLod(shadowMap, sampleDir, 0.0).r;\n float isBlocking = step(blocker, z);\n blockers += isBlocking;\n averageBlocker += blocker * isBlocking;\n }\n if (blockers > 0.0)\n return averageBlocker / blockers;\n return -1.0;\n}\nfloat PCSSCube(samplerCube shadowMap, vec4 shadowParams, vec3 shadowCoords, vec4 cameraParams, float shadowSearchArea, vec3 lightDir) {\n \n vec3 samplePoints[PCSS_SAMPLE_COUNT];\n const float PI = 3.141592653589793;\n float noise = noise( gl_FragCoord.xy ) * 2.0 * PI;\n for (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {\n float r = pcssSphereSamples[i];\n samplePoints[i] = vogelSphere(i, float(PCSS_SAMPLE_COUNT), noise, r);\n }\n float receiverDepth = length(lightDir) * shadowParams.w + shadowParams.z;\n vec3 lightDirNorm = normalize(lightDir);\n \n float averageBlocker = PCSSCubeBlockerDistance(shadowMap, lightDirNorm, samplePoints, receiverDepth, shadowSearchArea);\n if (averageBlocker == -1.0) {\n return 1.0;\n } else {\n float filterRadius = ((receiverDepth - averageBlocker) / averageBlocker) * shadowSearchArea;\n float shadow = 0.0;\n for (int i = 0; i < PCSS_SAMPLE_COUNT; i++)\n {\n vec3 offset = samplePoints[i] * filterRadius;\n vec3 sampleDir = lightDirNorm + offset;\n sampleDir = normalize(sampleDir);\n float depth = textureCubeLod(shadowMap, sampleDir, 0.0).r;\n shadow += step(receiverDepth, depth);\n }\n return shadow / float(PCSS_SAMPLE_COUNT);\n }\n}\nfloat getShadowOmniPCSS(samplerCube shadowMap, vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec2 shadowSearchArea, vec3 lightDir) {\n return PCSSCube(shadowMap, shadowParams, shadowCoord, cameraParams, shadowSearchArea.x, lightDir);\n}\n#endif\nfloat getShadowSpotPCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec2 shadowSearchArea, vec3 lightDir) {\n return PCSS(TEXTURE_PASS(shadowMap), shadowCoord, cameraParams, shadowSearchArea);\n}\n",shadowSoftPS:"\nhighp float fractSinRand(const in vec2 uv) {\n const float PI = 3.141592653589793;\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot(uv.xy, vec2(a, b)), sn = mod(dt, PI);\n return fract(sin(sn) * c);\n}\nstruct VogelDiskData {\n float invNumSamples;\n float initialAngle;\n float currentPointId;\n};\nvoid prepareDiskConstants(out VogelDiskData data, int sampleCount, float randomSeed) {\n const float pi2 = 6.28318530718;\n data.invNumSamples = 1.0 / float(sampleCount);\n data.initialAngle = randomSeed * pi2;\n data.currentPointId = 0.0;\n}\nvec2 generateDiskSample(inout VogelDiskData data) {\n const float GOLDEN_ANGLE = 2.399963;\n float r = sqrt((data.currentPointId + 0.5) * data.invNumSamples);\n float theta = data.currentPointId * GOLDEN_ANGLE + data.initialAngle;\n vec2 offset = vec2(cos(theta), sin(theta)) * pow(r, 1.33);\n data.currentPointId += 1.0;\n return offset;\n}\nvoid PCSSFindBlocker(TEXTURE_ACCEPT(shadowMap), out float avgBlockerDepth, out int numBlockers,\n vec2 shadowCoords, float z, int shadowBlockerSamples, float penumbraSize, float invShadowMapSize, float randomSeed) {\n VogelDiskData diskData;\n prepareDiskConstants(diskData, shadowBlockerSamples, randomSeed);\n float searchWidth = penumbraSize * invShadowMapSize;\n float blockerSum = 0.0;\n numBlockers = 0;\n for( int i = 0; i < shadowBlockerSamples; ++i ) {\n vec2 diskUV = generateDiskSample(diskData);\n vec2 sampleUV = shadowCoords + diskUV * searchWidth;\n float shadowMapDepth = texture2DLod(shadowMap, sampleUV, 0.0).r;\n if ( shadowMapDepth < z ) {\n blockerSum += shadowMapDepth;\n numBlockers++;\n }\n }\n avgBlockerDepth = blockerSum / float(numBlockers);\n}\nfloat PCSSFilter(TEXTURE_ACCEPT(shadowMap), vec2 uv, float receiverDepth, int shadowSamples, float filterRadius, float randomSeed) {\n VogelDiskData diskData;\n prepareDiskConstants(diskData, shadowSamples, randomSeed);\n float sum = 0.0;\n for (int i = 0; i < shadowSamples; i++) {\n vec2 offsetUV = generateDiskSample(diskData) * filterRadius;\n float depth = texture2DLod(shadowMap, uv + offsetUV, 0.0).r;\n sum += step(receiverDepth, depth);\n }\n return sum / float(shadowSamples);\n}\nfloat getPenumbra(float dblocker, float dreceiver, float penumbraSize, float penumbraFalloff) {\n float dist = dreceiver - dblocker;\n float penumbra = 1.0 - pow(1.0 - dist, penumbraFalloff);\n return penumbra * penumbraSize;\n}\nfloat PCSSDirectional(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoords, vec4 cameraParams, vec4 softShadowParams) {\n float receiverDepth = shadowCoords.z;\n float randomSeed = fractSinRand(gl_FragCoord.xy);\n int shadowSamples = int(softShadowParams.x);\n int shadowBlockerSamples = int(softShadowParams.y);\n float penumbraSize = softShadowParams.z;\n float penumbraFalloff = softShadowParams.w;\n int shadowMapSize = textureSize(shadowMap, 0).x;\n float invShadowMapSize = 1.0 / float(shadowMapSize);\n invShadowMapSize *= float(shadowMapSize) / 2048.0;\n float penumbra;\n if (shadowBlockerSamples > 0) {\n float avgBlockerDepth = 0.0;\n int numBlockers = 0;\n PCSSFindBlocker(TEXTURE_PASS(shadowMap), avgBlockerDepth, numBlockers, shadowCoords.xy, receiverDepth, shadowBlockerSamples, penumbraSize, invShadowMapSize, randomSeed);\n if (numBlockers < 1)\n return 1.0f;\n penumbra = getPenumbra(avgBlockerDepth, shadowCoords.z, penumbraSize, penumbraFalloff);\n } else {\n penumbra = penumbraSize;\n }\n float filterRadius = penumbra * invShadowMapSize;\n return PCSSFilter(TEXTURE_PASS(shadowMap), shadowCoords.xy, receiverDepth, shadowSamples, filterRadius, randomSeed);\n}\nfloat getShadowPCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec4 softShadowParams, vec3 lightDir) {\n return PCSSDirectional(TEXTURE_PASS(shadowMap), shadowCoord, cameraParams, softShadowParams);\n}\n",skinBatchVS:"\nattribute float vertex_boneIndices;\nuniform highp sampler2D texture_poseMap;\nmat4 getBoneMatrix(const in float indexFloat) {\n int width = textureSize(texture_poseMap, 0).x;\n int index = int(indexFloat + 0.5) * 3;\n int iy = index / width;\n int ix = index % width;\n vec4 v1 = texelFetch(texture_poseMap, ivec2(ix + 0, iy), 0);\n vec4 v2 = texelFetch(texture_poseMap, ivec2(ix + 1, iy), 0);\n vec4 v3 = texelFetch(texture_poseMap, ivec2(ix + 2, iy), 0);\n return mat4(\n v1.x, v2.x, v3.x, 0,\n v1.y, v2.y, v3.y, 0,\n v1.z, v2.z, v3.z, 0,\n v1.w, v2.w, v3.w, 1\n );\n}\n",skinVS:"\nattribute vec4 vertex_boneWeights;\nattribute vec4 vertex_boneIndices;\nuniform highp sampler2D texture_poseMap;\nvoid getBoneMatrix(const in int width, const in int index, out vec4 v1, out vec4 v2, out vec4 v3) {\n int v = index / width;\n int u = index % width;\n v1 = texelFetch(texture_poseMap, ivec2(u + 0, v), 0);\n v2 = texelFetch(texture_poseMap, ivec2(u + 1, v), 0);\n v3 = texelFetch(texture_poseMap, ivec2(u + 2, v), 0);\n}\nmat4 getSkinMatrix(const in vec4 indicesFloat, const in vec4 weights) {\n int width = textureSize(texture_poseMap, 0).x;\n ivec4 indices = ivec4(indicesFloat + 0.5) * 3;\n vec4 a1, a2, a3;\n getBoneMatrix(width, indices.x, a1, a2, a3);\n vec4 b1, b2, b3;\n getBoneMatrix(width, indices.y, b1, b2, b3);\n vec4 c1, c2, c3;\n getBoneMatrix(width, indices.z, c1, c2, c3);\n vec4 d1, d2, d3;\n getBoneMatrix(width, indices.w, d1, d2, d3);\n vec4 v1 = a1 * weights.x + b1 * weights.y + c1 * weights.z + d1 * weights.w;\n vec4 v2 = a2 * weights.x + b2 * weights.y + c2 * weights.z + d2 * weights.w;\n vec4 v3 = a3 * weights.x + b3 * weights.y + c3 * weights.z + d3 * weights.w;\n float one = dot(weights, vec4(1.0));\n return mat4(\n v1.x, v2.x, v3.x, 0,\n v1.y, v2.y, v3.y, 0,\n v1.z, v2.z, v3.z, 0,\n v1.w, v2.w, v3.w, one\n );\n}\n",skyboxPS:'\n #define LIT_SKYBOX_INTENSITY\n #include "envProcPS"\n #include "gammaPS"\n #include "tonemappingPS"\n #ifdef PREPASS_PASS\n varying float vLinearDepth;\n #include "floatAsUintPS"\n #endif\n varying vec3 vViewDir;\n uniform float skyboxHighlightMultiplier;\n #ifdef SKY_CUBEMAP\n uniform samplerCube texture_cubeMap;\n #ifdef SKYMESH\n varying vec3 vWorldPos;\n uniform mat3 cubeMapRotationMatrix;\n uniform vec3 projectedSkydomeCenter;\n #endif\n #else\n #include "sphericalPS"\n #include "envAtlasPS"\n uniform sampler2D texture_envAtlas;\n uniform float mipLevel;\n #endif\n void main(void) {\n #ifdef PREPASS_PASS\n gl_FragColor = float2vec4(vLinearDepth);\n #else\n #ifdef SKY_CUBEMAP\n #ifdef SKYMESH\n vec3 envDir = normalize(vWorldPos - projectedSkydomeCenter);\n vec3 dir = envDir * cubeMapRotationMatrix;\n #else\n vec3 dir = vViewDir;\n #endif\n dir.x *= -1.0;\n vec3 linear = {SKYBOX_DECODE_FNC}(textureCube(texture_cubeMap, dir));\n #else\n vec3 dir = vViewDir * vec3(-1.0, 1.0, 1.0);\n vec2 uv = toSphericalUv(normalize(dir));\n vec3 linear = {SKYBOX_DECODE_FNC}(texture2D(texture_envAtlas, mapRoughnessUv(uv, mipLevel)));\n #endif\n if (any(greaterThanEqual(linear, vec3(64.0)))) {\n linear *= skyboxHighlightMultiplier;\n }\n gl_FragColor = vec4(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0);\n #endif\n }\n',skyboxVS:"\nattribute vec4 aPosition;\nuniform mat4 matrix_view;\nuniform mat4 matrix_projectionSkybox;\nuniform mat3 cubeMapRotationMatrix;\nvarying vec3 vViewDir;\n#ifdef PREPASS_PASS\n varying float vLinearDepth;\n#endif\n#ifdef SKYMESH\n uniform mat4 matrix_model;\n varying vec3 vWorldPos;\n#endif\nvoid main(void) {\n mat4 view = matrix_view;\n #ifdef SKYMESH\n vec4 worldPos = matrix_model * aPosition;\n vWorldPos = worldPos.xyz;\n gl_Position = matrix_projectionSkybox * (view * worldPos);\n #ifdef PREPASS_PASS\n vLinearDepth = -(matrix_view * vec4(vWorldPos, 1.0)).z;\n #endif\n #else\n view[3][0] = view[3][1] = view[3][2] = 0.0;\n gl_Position = matrix_projectionSkybox * (view * aPosition);\n vViewDir = aPosition.xyz * cubeMapRotationMatrix;\n #ifdef PREPASS_PASS\n vLinearDepth = -gl_Position.w;\n #endif\n #endif\n gl_Position.z = gl_Position.w - 1.0e-7;\n}\n",specularPS:"\n#ifdef STD_SPECULAR_CONSTANT\nuniform vec3 material_specular;\n#endif\nvoid getSpecularity() {\n vec3 specularColor = vec3(1,1,1);\n #ifdef STD_SPECULAR_CONSTANT\n specularColor *= material_specular;\n #endif\n #ifdef STD_SPECULAR_TEXTURE\n specularColor *= {STD_SPECULAR_TEXTURE_DECODE}(texture2DBias({STD_SPECULAR_TEXTURE_NAME}, {STD_SPECULAR_TEXTURE_UV}, textureBias)).{STD_SPECULAR_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_SPECULAR_VERTEX\n specularColor *= saturate(vVertexColor.{STD_SPECULAR_VERTEX_CHANNEL});\n #endif\n dSpecularity = specularColor;\n}\n",sphericalPS:"\nvec2 toSpherical(vec3 dir) {\n return vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y));\n}\nvec2 toSphericalUv(vec3 dir) {\n const float PI = 3.141592653589793;\n vec2 uv = toSpherical(dir) / vec2(PI * 2.0, PI) + 0.5;\n return vec2(uv.x, 1.0 - uv.y);\n}\n",specularityFactorPS:"\n#ifdef STD_SPECULARITYFACTOR_CONSTANT\nuniform float material_specularityFactor;\n#endif\nvoid getSpecularityFactor() {\n float specularityFactor = 1.0;\n #ifdef STD_SPECULARITYFACTOR_CONSTANT\n specularityFactor *= material_specularityFactor;\n #endif\n #ifdef STD_SPECULARITYFACTOR_TEXTURE\n specularityFactor *= texture2DBias({STD_SPECULARITYFACTOR_TEXTURE_NAME}, {STD_SPECULARITYFACTOR_TEXTURE_UV}, textureBias).{STD_SPECULARITYFACTOR_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_SPECULARITYFACTOR_VERTEX\n specularityFactor *= saturate(vVertexColor.{STD_SPECULARITYFACTOR_VERTEX_CHANNEL});\n #endif\n dSpecularityFactor = specularityFactor;\n}\n",spotPS:"\nfloat getSpotEffect(vec3 lightSpotDir, float lightInnerConeAngle, float lightOuterConeAngle, vec3 lightDirNorm) {\n float cosAngle = dot(lightDirNorm, lightSpotDir);\n return smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle);\n}\n",startNineSlicedPS:"\n nineSlicedUv = vec2(vUv0.x, 1.0 - vUv0.y);\n",startNineSlicedTiledPS:"\n vec2 tileMask = step(vMask, vec2(0.99999));\n vec2 tileSize = 0.5 * (innerOffset.xy + innerOffset.zw);\n vec2 tileScale = vec2(1.0) / (vec2(1.0) - tileSize);\n vec2 clampedUv = mix(innerOffset.xy * 0.5, vec2(1.0) - innerOffset.zw * 0.5, fract((vTiledUv - tileSize) * tileScale));\n clampedUv = clampedUv * atlasRect.zw + atlasRect.xy;\n nineSlicedUv = vUv0 * tileMask + clampedUv * (vec2(1.0) - tileMask);\n nineSlicedUv.y = 1.0 - nineSlicedUv.y;\n \n",stdDeclarationPS:'\n float dAlpha = 1.0;\n #if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE\n #ifdef STD_OPACITY_TEXTURE_ALLOCATE\n uniform sampler2D texture_opacityMap;\n #endif\n #endif\n #ifdef FORWARD_PASS\n vec3 dAlbedo;\n vec3 dNormalW;\n vec3 dSpecularity = vec3(0.0);\n float dGlossiness = 0.0;\n #ifdef LIT_REFRACTION\n float dTransmission;\n float dThickness;\n #endif\n #ifdef LIT_SCENE_COLOR\n uniform sampler2D uSceneColorMap;\n #endif\n #ifdef LIT_SCREEN_SIZE\n uniform vec4 uScreenSize;\n #endif\n #ifdef LIT_TRANSFORMS\n uniform mat4 matrix_viewProjection;\n uniform mat4 matrix_model;\n #endif\n #ifdef STD_HEIGHT_MAP\n vec2 dUvOffset;\n #ifdef STD_DIFFUSE_TEXTURE_ALLOCATE\n uniform sampler2D texture_heightMap;\n #endif\n #endif\n #ifdef STD_DIFFUSE_TEXTURE_ALLOCATE\n uniform sampler2D texture_diffuseMap;\n #endif\n #ifdef STD_DIFFUSEDETAIL_TEXTURE_ALLOCATE\n uniform sampler2D texture_diffuseDetailMap;\n #endif\n #ifdef STD_NORMAL_TEXTURE_ALLOCATE\n uniform sampler2D texture_normalMap;\n #endif\n #ifdef STD_NORMALDETAIL_TEXTURE_ALLOCATE\n uniform sampler2D texture_normalDetailMap;\n #endif\n #ifdef STD_THICKNESS_TEXTURE_ALLOCATE\n uniform sampler2D texture_thicknessMap;\n #endif\n #ifdef STD_REFRACTION_TEXTURE_ALLOCATE\n uniform sampler2D texture_refractionMap;\n #endif\n #ifdef LIT_IRIDESCENCE\n float dIridescence;\n float dIridescenceThickness;\n #ifdef STD_IRIDESCENCE_THICKNESS_TEXTURE_ALLOCATE\n uniform sampler2D texture_iridescenceThicknessMap;\n #endif\n #ifdef STD_IRIDESCENCE_TEXTURE_ALLOCATE\n uniform sampler2D texture_iridescenceMap;\n #endif\n #endif\n #ifdef LIT_CLEARCOAT\n float ccSpecularity;\n float ccGlossiness;\n vec3 ccNormalW;\n #endif\n #ifdef LIT_GGX_SPECULAR\n float dAnisotropy;\n vec2 dAnisotropyRotation;\n #endif\n #ifdef LIT_SPECULAR_OR_REFLECTION\n #ifdef LIT_SHEEN\n vec3 sSpecularity;\n float sGlossiness;\n #ifdef STD_SHEEN_TEXTURE_ALLOCATE\n uniform sampler2D texture_sheenMap;\n #endif\n #ifdef STD_SHEENGLOSS_TEXTURE_ALLOCATE\n uniform sampler2D texture_sheenGlossMap;\n #endif\n #endif\n #ifdef LIT_METALNESS\n float dMetalness;\n float dIor;\n #ifdef STD_METALNESS_TEXTURE_ALLOCATE\n uniform sampler2D texture_metalnessMap;\n #endif\n #endif\n #ifdef LIT_SPECULARITY_FACTOR\n float dSpecularityFactor;\n #ifdef STD_SPECULARITYFACTOR_TEXTURE_ALLOCATE\n uniform sampler2D texture_specularityFactorMap;\n #endif\n #endif\n #ifdef STD_SPECULAR_COLOR\n #ifdef STD_SPECULAR_TEXTURE_ALLOCATE\n uniform sampler2D texture_specularMap;\n #endif\n #endif\n #ifdef STD_GLOSS_TEXTURE_ALLOCATE\n uniform sampler2D texture_glossMap;\n #endif\n #endif\n #ifdef STD_AO\n float dAo;\n #ifdef STD_AO_TEXTURE_ALLOCATE\n uniform sampler2D texture_aoMap;\n #endif\n #ifdef STD_AODETAIL_TEXTURE_ALLOCATE\n uniform sampler2D texture_aoDetailMap;\n #endif\n #endif\n vec3 dEmission;\n #ifdef STD_EMISSIVE_TEXTURE_ALLOCATE\n uniform sampler2D texture_emissiveMap;\n #endif\n #ifdef LIT_CLEARCOAT\n #ifdef STD_CLEARCOAT_TEXTURE_ALLOCATE\n uniform sampler2D texture_clearCoatMap;\n #endif\n #ifdef STD_CLEARCOATGLOSS_TEXTURE_ALLOCATE\n uniform sampler2D texture_clearCoatGlossMap;\n #endif\n #ifdef STD_CLEARCOATNORMAL_TEXTURE_ALLOCATE\n uniform sampler2D texture_clearCoatNormalMap;\n #endif\n #endif\n \n #ifdef LIT_GGX_SPECULAR\n #ifdef STD_ANISOTROPY_TEXTURE_ALLOCATE\n uniform sampler2D texture_anisotropyMap;\n #endif\n #endif\n #if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)\n vec3 dLightmap;\n #ifdef STD_LIGHT_TEXTURE_ALLOCATE\n uniform sampler2D texture_lightMap;\n #endif\n #endif\n #endif\n #include "litShaderCorePS"\n',stdFrontEndPS:'\n #if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE\n #include "opacityPS"\n #if defined(LIT_ALPHA_TEST)\n #include "alphaTestPS"\n #endif\n #if STD_OPACITY_DITHER != NONE\n #include "opacityDitherPS"\n #endif\n #endif\n #ifdef FORWARD_PASS\n #ifdef STD_HEIGHT_MAP\n #include "parallaxPS"\n #endif\n #include "diffusePS"\n #ifdef LIT_NEEDS_NORMAL\n #include "normalMapPS"\n #endif\n #ifdef LIT_REFRACTION\n #include "transmissionPS"\n #include "thicknessPS"\n #endif\n #ifdef LIT_IRIDESCENCE\n #include "iridescencePS"\n #include "iridescenceThicknessPS"\n #endif\n #ifdef LIT_SPECULAR_OR_REFLECTION\n #ifdef LIT_SHEEN\n #include "sheenPS"\n #include "sheenGlossPS"\n #endif\n #ifdef LIT_METALNESS\n #include "metalnessPS"\n #include "iorPS"\n #endif\n #ifdef LIT_SPECULARITY_FACTOR\n #include "specularityFactorPS"\n #endif\n #ifdef STD_SPECULAR_COLOR\n #include "specularPS"\n #else\n void getSpecularity() { \n dSpecularity = vec3(1);\n }\n #endif\n #include "glossPS"\n #endif\n #ifdef STD_AO\n #include "aoPS"\n #endif\n #include "emissivePS"\n #ifdef LIT_CLEARCOAT\n #include "clearCoatPS"\n #include "clearCoatGlossPS"\n #include "clearCoatNormalPS"\n #endif\n #if defined(LIT_SPECULAR) && defined(LIT_LIGHTING) && defined(LIT_GGX_SPECULAR)\n #include "anisotropyPS"\n #endif\n #if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)\n #include "lightmapPS"\n #endif\n #endif\n void evaluateFrontend() {\n #if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE\n getOpacity();\n #if defined(LIT_ALPHA_TEST)\n alphaTest(dAlpha);\n #endif\n #if STD_OPACITY_DITHER != NONE\n opacityDither(dAlpha, 0.0);\n #endif\n litArgs_opacity = dAlpha;\n #endif\n #ifdef FORWARD_PASS\n #ifdef STD_HEIGHT_MAP\n getParallax();\n #endif\n getAlbedo();\n litArgs_albedo = dAlbedo;\n #ifdef LIT_NEEDS_NORMAL\n getNormal();\n litArgs_worldNormal = dNormalW;\n #endif\n #ifdef LIT_REFRACTION\n getRefraction();\n litArgs_transmission = dTransmission;\n getThickness();\n litArgs_thickness = dThickness;\n #ifdef LIT_DISPERSION\n litArgs_dispersion = material_dispersion;\n #endif\n #endif\n #ifdef LIT_IRIDESCENCE\n getIridescence();\n getIridescenceThickness();\n litArgs_iridescence_intensity = dIridescence;\n litArgs_iridescence_thickness = dIridescenceThickness;\n #endif\n #ifdef LIT_SPECULAR_OR_REFLECTION\n #ifdef LIT_SHEEN\n getSheen();\n litArgs_sheen_specularity = sSpecularity;\n getSheenGlossiness();\n litArgs_sheen_gloss = sGlossiness;\n #endif\n #ifdef LIT_METALNESS\n getMetalness();\n litArgs_metalness = dMetalness;\n getIor();\n litArgs_ior = dIor;\n #endif\n #ifdef LIT_SPECULARITY_FACTOR\n getSpecularityFactor();\n litArgs_specularityFactor = dSpecularityFactor;\n #endif\n getGlossiness();\n getSpecularity();\n litArgs_specularity = dSpecularity;\n litArgs_gloss = dGlossiness;\n #endif\n #ifdef STD_AO\n getAO();\n litArgs_ao = dAo;\n #endif\n getEmission();\n litArgs_emission = dEmission;\n #ifdef LIT_CLEARCOAT\n getClearCoat();\n getClearCoatGlossiness();\n getClearCoatNormal();\n litArgs_clearcoat_specularity = ccSpecularity;\n litArgs_clearcoat_gloss = ccGlossiness;\n litArgs_clearcoat_worldNormal = ccNormalW;\n #endif\n #if defined(LIT_SPECULAR) && defined(LIT_LIGHTING) && defined(LIT_GGX_SPECULAR)\n getAnisotropy();\n #endif\n #if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)\n getLightMap();\n litArgs_lightmap = dLightmap;\n #ifdef STD_LIGHTMAP_DIR\n litArgs_lightmapDir = dLightmapDir;\n #endif\n #endif\n #endif\n }\n',TBNPS:"\n#ifdef LIT_TANGENTS\n #define TBN_TANGENTS\n#else\n #if defined(LIT_USE_NORMALS) || defined(LIT_USE_CLEARCOAT_NORMALS)\n #define TBN_DERIVATIVES\n #endif\n#endif\n#if defined(TBN_DERIVATIVES)\n uniform float tbnBasis;\n#endif\nvoid getTBN(vec3 tangent, vec3 binormal, vec3 normal) {\n #ifdef TBN_TANGENTS\n dTBN = mat3(normalize(tangent), normalize(binormal), normalize(normal));\n #elif defined(TBN_DERIVATIVES)\n vec2 uv = {lightingUv};\n vec3 dp1 = dFdx( vPositionW );\n vec3 dp2 = dFdy( vPositionW );\n vec2 duv1 = dFdx( uv );\n vec2 duv2 = dFdy( uv );\n vec3 dp2perp = cross( dp2, normal );\n vec3 dp1perp = cross( normal, dp1 );\n vec3 T = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 B = dp2perp * duv1.y + dp1perp * duv2.y;\n float denom = max( dot(T,T), dot(B,B) );\n float invmax = (denom == 0.0) ? 0.0 : tbnBasis / sqrt( denom );\n dTBN = mat3(T * invmax, -B * invmax, normal );\n #else\n vec3 B = cross(normal, vObjectSpaceUpW);\n vec3 T = cross(normal, B);\n if (dot(B,B)==0.0)\n {\n float major=max(max(normal.x, normal.y), normal.z);\n if (normal.x == major)\n {\n B = cross(normal, vec3(0,1,0));\n T = cross(normal, B);\n }\n else if (normal.y == major)\n {\n B = cross(normal, vec3(0,0,1));\n T = cross(normal, B);\n }\n else if (normal.z == major)\n {\n B = cross(normal, vec3(1,0,0));\n T = cross(normal, B);\n }\n }\n dTBN = mat3(normalize(T), normalize(B), normalize(normal));\n #endif\n}\n",thicknessPS:"\n#ifdef STD_THICKNESS_CONSTANT\nuniform float material_thickness;\n#endif\nvoid getThickness() {\n dThickness = 1.0;\n #ifdef STD_THICKNESS_CONSTANT\n dThickness *= material_thickness;\n #endif\n #ifdef STD_THICKNESS_TEXTURE\n dThickness *= texture2DBias({STD_THICKNESS_TEXTURE_NAME}, {STD_THICKNESS_TEXTURE_UV}, textureBias).{STD_THICKNESS_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_THICKNESS_VERTEX\n dThickness *= saturate(vVertexColor.{STD_THICKNESS_VERTEX_CHANNEL});\n #endif\n}\n",tonemappingPS:'\n#if (TONEMAP == NONE)\n #include "tonemappingNonePS"\n#elif TONEMAP == FILMIC\n #include "tonemappingFilmicPS"\n#elif TONEMAP == LINEAR\n #include "tonemappingLinearPS"\n#elif TONEMAP == HEJL\n #include "tonemappingHejlPS"\n#elif TONEMAP == ACES\n #include "tonemappingAcesPS"\n#elif TONEMAP == ACES2\n #include "tonemappingAces2PS"\n#elif TONEMAP == NEUTRAL\n #include "tonemappingNeutralPS"\n#endif\n',tonemappingAcesPS:"\nuniform float exposure;\nvec3 toneMap(vec3 color) {\n float tA = 2.51;\n float tB = 0.03;\n float tC = 2.43;\n float tD = 0.59;\n float tE = 0.14;\n vec3 x = color * exposure;\n return (x*(tA*x+tB))/(x*(tC*x+tD)+tE);\n}\n",tonemappingAces2PS:"\nuniform float exposure;\nconst mat3 ACESInputMat = mat3(\n 0.59719, 0.35458, 0.04823,\n 0.07600, 0.90834, 0.01566,\n 0.02840, 0.13383, 0.83777\n);\nconst mat3 ACESOutputMat = mat3(\n 1.60475, -0.53108, -0.07367,\n -0.10208, 1.10813, -0.00605,\n -0.00327, -0.07276, 1.07602\n);\nvec3 RRTAndODTFit(vec3 v) {\n vec3 a = v * (v + 0.0245786) - 0.000090537;\n vec3 b = v * (0.983729 * v + 0.4329510) + 0.238081;\n return a / b;\n}\nvec3 toneMap(vec3 color) {\n color *= exposure / 0.6;\n color = color * ACESInputMat;\n color = RRTAndODTFit(color);\n color = color * ACESOutputMat;\n color = clamp(color, 0.0, 1.0);\n return color;\n}\n",tonemappingFilmicPS:"\nconst float A = 0.15;\nconst float B = 0.50;\nconst float C = 0.10;\nconst float D = 0.20;\nconst float E = 0.02;\nconst float F = 0.30;\nconst float W = 11.2;\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 color = uncharted2Tonemap(color * exposure);\n vec3 whiteScale = 1.0 / uncharted2Tonemap(vec3(W,W,W));\n color = color * whiteScale;\n return color;\n}\n",tonemappingHejlPS:"\nuniform float exposure;\nvec3 toneMap(vec3 color) {\n color *= exposure;\n const float A = 0.22, B = 0.3, C = .1, D = 0.2, E = .01, F = 0.3;\n const float Scl = 1.25;\n vec3 h = max( vec3(0.0), color - vec3(0.004) );\n return (h*((Scl*A)*h+Scl*vec3(C*B,C*B,C*B))+Scl*vec3(D*E,D*E,D*E)) / (h*(A*h+vec3(B,B,B))+vec3(D*F,D*F,D*F)) - Scl*vec3(E/F,E/F,E/F);\n}\n",tonemappingLinearPS:"\nuniform float exposure;\nvec3 toneMap(vec3 color) {\n return color * exposure;\n}\n",tonemappingNeutralPS:"\nuniform float exposure;\nvec3 toneMap(vec3 color) {\n color *= exposure;\n float startCompression = 0.8 - 0.04;\n float desaturation = 0.15;\n float x = min(color.r, min(color.g, color.b));\n float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n color -= offset;\n float peak = max(color.r, max(color.g, color.b));\n if (peak < startCompression) return color;\n float d = 1. - startCompression;\n float newPeak = 1. - d * d / (peak + d - startCompression);\n color *= newPeak / peak;\n float g = 1. - 1. / (desaturation * (peak - newPeak) + 1.);\n return mix(color, newPeak * vec3(1, 1, 1), g);\n}\n",tonemappingNonePS:"\nvec3 toneMap(vec3 color) {\n return color;\n}\n",transformVS:"\n#ifdef PIXELSNAP\nuniform vec4 uScreenSize;\n#endif\n#ifdef SCREENSPACE\nuniform float projectionFlipY;\n#endif\nvec4 evalWorldPosition(vec3 vertexPosition, mat4 modelMatrix) {\n vec3 localPos = getLocalPosition(vertexPosition);\n #ifdef NINESLICED\n localPos.xz *= outerScale;\n vec2 positiveUnitOffset = clamp(vertexPosition.xz, vec2(0.0), vec2(1.0));\n vec2 negativeUnitOffset = clamp(-vertexPosition.xz, vec2(0.0), vec2(1.0));\n localPos.xz += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;\n vTiledUv = (localPos.xz - outerScale + innerOffset.xy) * -0.5 + 1.0;\n localPos.xz *= -0.5;\n localPos = localPos.xzy;\n #endif\n vec4 posW = modelMatrix * vec4(localPos, 1.0);\n #ifdef SCREENSPACE\n posW.zw = vec2(0.0, 1.0);\n #endif\n return posW;\n}\nvec4 getPosition() {\n dModelMatrix = getModelMatrix();\n vec4 posW = evalWorldPosition(vertex_position.xyz, dModelMatrix);\n dPositionW = posW.xyz;\n vec4 screenPos;\n #ifdef UV1LAYOUT\n screenPos = vec4(vertex_texCoord1.xy * 2.0 - 1.0, 0.5, 1);\n #ifdef WEBGPU\n screenPos.y *= -1.0;\n #endif\n #else\n #ifdef SCREENSPACE\n screenPos = posW;\n screenPos.y *= projectionFlipY;\n #else\n screenPos = matrix_viewProjection * posW;\n #endif\n #ifdef PIXELSNAP\n screenPos.xy = (screenPos.xy * 0.5) + 0.5;\n screenPos.xy *= uScreenSize.xy;\n screenPos.xy = floor(screenPos.xy);\n screenPos.xy *= uScreenSize.zw;\n screenPos.xy = (screenPos.xy * 2.0) - 1.0;\n #endif\n #endif\n return screenPos;\n}\nvec3 getWorldPosition() {\n return dPositionW;\n}\n",transformCoreVS:'\nattribute vec4 vertex_position;\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\n#ifdef MORPHING\n uniform vec2 morph_tex_params;\n attribute uint morph_vertex_id;\n ivec2 getTextureMorphCoords() {\n ivec2 textureSize = ivec2(morph_tex_params);\n int morphGridV = int(morph_vertex_id) / textureSize.x;\n int morphGridU = int(morph_vertex_id) - (morphGridV * textureSize.x);\n #ifdef WEBGPU\n morphGridV = textureSize.y - morphGridV - 1;\n #endif\n return ivec2(morphGridU, morphGridV);\n }\n #ifdef MORPHING_POSITION\n #ifdef MORPHING_INT\n uniform vec3 aabbSize;\n uniform vec3 aabbMin;\n uniform usampler2D morphPositionTex;\n #else\n uniform highp sampler2D morphPositionTex;\n #endif\n #endif\n#endif\n#ifdef defined(BATCH)\n #include "skinBatchVS"\n mat4 getModelMatrix() {\n return getBoneMatrix(vertex_boneIndices);\n }\n#elif defined(SKIN)\n #include "skinVS"\n mat4 getModelMatrix() {\n return matrix_model * getSkinMatrix(vertex_boneIndices, vertex_boneWeights);\n }\n#elif defined(INSTANCING)\n #include "transformInstancingVS"\n#else\n mat4 getModelMatrix() {\n return matrix_model;\n }\n#endif\nvec3 getLocalPosition(vec3 vertexPosition) {\n vec3 localPos = vertexPosition;\n #ifdef MORPHING_POSITION\n ivec2 morphUV = getTextureMorphCoords();\n #ifdef MORPHING_INT\n vec3 morphPos = vec3(texelFetch(morphPositionTex, ivec2(morphUV), 0).xyz) / 65535.0 * aabbSize + aabbMin;\n #else\n vec3 morphPos = texelFetch(morphPositionTex, ivec2(morphUV), 0).xyz;\n #endif\n localPos += morphPos;\n #endif\n return localPos;\n}\n',transformInstancingVS:"\nattribute vec4 instance_line1;\nattribute vec4 instance_line2;\nattribute vec4 instance_line3;\nattribute vec4 instance_line4;\nmat4 getModelMatrix() {\n return matrix_model * mat4(instance_line1, instance_line2, instance_line3, instance_line4);\n}\n",transmissionPS:"\n#ifdef STD_REFRACTION_CONSTANT\nuniform float material_refraction;\n#endif\nvoid getRefraction() {\n float refraction = 1.0;\n #ifdef STD_REFRACTION_CONSTANT\n refraction = material_refraction;\n #endif\n #ifdef STD_REFRACTION_TEXTURE\n refraction *= texture2DBias({STD_REFRACTION_TEXTURE_NAME}, {STD_REFRACTION_TEXTURE_UV}, textureBias).{STD_REFRACTION_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_REFRACTION_VERTEX\n refraction *= saturate(vVertexColor.{STD_REFRACTION_VERTEX_CHANNEL});\n #endif\n dTransmission = refraction;\n}\n",twoSidedLightingPS:"\nuniform float twoSidedLightingNegScaleFactor;\nvoid handleTwoSidedLighting() {\n dTBN[2] *= gl_FrontFacing ? twoSidedLightingNegScaleFactor : -twoSidedLightingNegScaleFactor;\n}\n",uv0VS:"\n#ifdef NINESLICED\n vec2 getUv0() {\n vec2 uv = vertex_position.xz;\n vec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0));\n vec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0));\n uv += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;\n uv = uv * -0.5 + 0.5;\n uv = uv * atlasRect.zw + atlasRect.xy;\n vMask = vertex_texCoord0.xy;\n return uv;\n }\n#else\n vec2 getUv0() {\n return vertex_texCoord0;\n }\n#endif\n",uv1VS:"\nvec2 getUv1() {\n return vertex_texCoord1;\n}\n",uvTransformVS:"\nvUV{TRANSFORM_UV_{i}}_{TRANSFORM_ID_{i}} = vec2(\n dot(vec3(uv{TRANSFORM_UV_{i}}, 1), {TRANSFORM_NAME_{i}}0),\n dot(vec3(uv{TRANSFORM_UV_{i}}, 1), {TRANSFORM_NAME_{i}}1)\n);\n",uvTransformUniformsPS:"\n uniform vec3 {TRANSFORM_NAME_{i}}0;\n uniform vec3 {TRANSFORM_NAME_{i}}1;\n",viewDirPS:"\nvoid getViewDir() {\n dViewDirW = normalize(view_position - vPositionW);\n}\n",webgpuPS:rj,webgpuVS:rX},md={alphaTestPS:"\nuniform alpha_ref: f32;\nfn alphaTest(a: f32) {\n if (a < uniform.alpha_ref) {\n discard;\n }\n}\n",ambientPS:'\n#if LIT_AMBIENT_SOURCE == AMBIENTSH\n uniform ambientSH: array;\n#endif\n#if LIT_AMBIENT_SOURCE == ENVALATLAS\n #include "envAtlasPS"\n #ifndef ENV_ATLAS\n #define ENV_ATLAS\n var texture_envAtlas: texture_2d;\n var texture_envAtlasSampler: sampler;\n #endif\n#endif\nfn addAmbient(worldNormal: vec3f) {\n #ifdef LIT_AMBIENT_SOURCE == AMBIENTSH\n let n: vec3f = cubeMapRotate(worldNormal);\n let color: vec3f =\n uniform.ambientSH[0] +\n uniform.ambientSH[1] * n.x +\n uniform.ambientSH[2] * n.y +\n uniform.ambientSH[3] * n.z +\n uniform.ambientSH[4] * n.x * n.z +\n uniform.ambientSH[5] * n.z * n.y +\n uniform.ambientSH[6] * n.y * n.x +\n uniform.ambientSH[7] * (3.0 * n.z * n.z - 1.0) +\n uniform.ambientSH[8] * (n.x * n.x - n.y * n.y);\n dDiffuseLight += processEnvironment(max(color, vec3f(0.0)));\n #endif\n #if LIT_AMBIENT_SOURCE == ENVALATLAS\n let dir: vec3f = normalize(cubeMapRotate(worldNormal) * vec3f(-1.0, 1.0, 1.0));\n let uv: vec2f = mapUv(toSphericalUv(dir), vec4f(128.0, 256.0 + 128.0, 64.0, 32.0) / atlasSize);\n let raw: vec4f = textureSample(texture_envAtlas, texture_envAtlasSampler, uv);\n let linear: vec3f = {ambientDecode}(raw);\n dDiffuseLight += processEnvironment(linear);\n #endif\n #if LIT_AMBIENT_SOURCE == CONSTANT\n dDiffuseLight += uniform.light_globalAmbient;\n #endif\n}\n',anisotropyPS:"\n#ifdef LIT_GGX_SPECULAR\n uniform material_anisotropyIntensity: f32;\n uniform material_anisotropyRotation: vec2f;\n#endif\nfn getAnisotropy() {\n dAnisotropy = 0.0;\n dAnisotropyRotation = vec2f(1.0, 0.0);\n#ifdef LIT_GGX_SPECULAR\n dAnisotropy = uniform.material_anisotropyIntensity;\n dAnisotropyRotation = uniform.material_anisotropyRotation;\n#endif\n#ifdef STD_ANISOTROPY_TEXTURE\n let anisotropyTex: vec3f = textureSampleBias({STD_ANISOTROPY_TEXTURE_NAME}, {STD_ANISOTROPY_TEXTURE_NAME}Sampler, {STD_ANISOTROPY_TEXTURE_UV}, uniform.textureBias).rgb;\n dAnisotropy *= anisotropyTex.b;\n let anisotropyRotationFromTex: vec2f = anisotropyTex.rg * 2.0 - vec2f(1.0);\n let rotationMatrix: mat2x2f = mat2x2f(dAnisotropyRotation.x, dAnisotropyRotation.y, -dAnisotropyRotation.y, dAnisotropyRotation.x);\n dAnisotropyRotation = rotationMatrix * anisotropyRotationFromTex;\n#endif\n dAnisotropy = clamp(dAnisotropy, 0.0, 1.0);\n}\n",aoPS:'\n#if defined(STD_AO_TEXTURE) || defined(STD_AO_VERTEX)\n uniform material_aoIntensity: f32;\n#endif\n#ifdef STD_AODETAIL_TEXTURE\n #include "detailModesPS"\n#endif\nfn getAO() {\n dAo = 1.0;\n #ifdef STD_AO_TEXTURE\n var aoBase: f32 = textureSampleBias({STD_AO_TEXTURE_NAME}, {STD_AO_TEXTURE_NAME}Sampler, {STD_AO_TEXTURE_UV}, uniform.textureBias).{STD_AO_TEXTURE_CHANNEL};\n #ifdef STD_AODETAIL_TEXTURE\n var aoDetail: f32 = textureSampleBias({STD_AODETAIL_TEXTURE_NAME}, {STD_AODETAIL_TEXTURE_NAME}Sampler, {STD_AODETAIL_TEXTURE_UV}, uniform.textureBias).{STD_AODETAIL_TEXTURE_CHANNEL};\n aoBase = detailMode_{STD_AODETAIL_DETAILMODE}(vec3f(aoBase), vec3f(aoDetail)).r;\n #endif\n dAo = dAo * aoBase;\n #endif\n #ifdef STD_AO_VERTEX\n dAo = dAo * saturate(vVertexColor.{STD_AO_VERTEX_CHANNEL});\n #endif\n #if defined(STD_AO_TEXTURE) || defined(STD_AO_VERTEX)\n dAo = mix(1.0, dAo, uniform.material_aoIntensity);\n #endif\n}\n',aoDiffuseOccPS:"\nfn occludeDiffuse(ao: f32) {\n dDiffuseLight = dDiffuseLight * ao;\n}\n",aoSpecOccPS:"\n#if LIT_OCCLUDE_SPECULAR != NONE\n #ifdef LIT_OCCLUDE_SPECULAR_FLOAT\n uniform material_occludeSpecularIntensity: f32;\n #endif\n#endif\nfn occludeSpecular(gloss: f32, ao: f32, worldNormal: vec3f, viewDir: vec3f) {\n #if LIT_OCCLUDE_SPECULAR == AO\n #ifdef LIT_OCCLUDE_SPECULAR_FLOAT\n var specOcc: f32 = mix(1.0, ao, uniform.material_occludeSpecularIntensity);\n #else\n var specOcc: f32 = ao;\n #endif\n #endif\n #if LIT_OCCLUDE_SPECULAR == GLOSSDEPENDENT\n var specPow: f32 = exp2(gloss * 11.0);\n var specOcc: f32 = saturate(pow(dot(worldNormal, viewDir) + ao, 0.01 * specPow) - 1.0 + ao);\n #ifdef LIT_OCCLUDE_SPECULAR_FLOAT\n specOcc = mix(1.0, specOcc, uniform.material_occludeSpecularIntensity);\n #endif\n #endif\n #if LIT_OCCLUDE_SPECULAR != NONE\n dSpecularLight = dSpecularLight * specOcc;\n dReflection = dReflection * specOcc;\n #ifdef LIT_SHEEN\n sSpecularLight = sSpecularLight * specOcc;\n sReflection = sReflection * specOcc;\n #endif\n #endif\n}\n",bakeDirLmEndPS:"\n let dirLm = textureSample(texture_dirLightMap, texture_dirLightMapSampler, vUv1);\n if (uniform.bakeDir > 0.5) {\n if (dAtten > 0.00001) {\n let unpacked_dir = dirLm.xyz * 2.0 - vec3f(1.0);\n dAtten = clamp(dAtten, 0.0, 1.0);\n let combined_dir = dLightDirNormW.xyz * dAtten + unpacked_dir * dirLm.w;\n let finalRgb = normalize(combined_dir) * 0.5 + vec3f(0.5);\n let finalA = max(dirLm.w + dAtten, 1.0 / 255.0);\n output.color = vec4f(finalRgb, finalA);\n } else {\n output.color = dirLm;\n }\n } else {\n let alpha_min = select(0.0, 1.0 / 255.0, dAtten > 0.00001);\n let finalA = max(dirLm.w, alpha_min);\n output.color = vec4f(dirLm.rgb, finalA);\n }\n",bakeLmEndPS:"\n#ifdef LIT_LIGHTMAP_BAKING_ADD_AMBIENT\n dDiffuseLight = ((dDiffuseLight - 0.5) * max(uniform.ambientBakeOcclusionContrast + 1.0, 0.0)) + 0.5;\n dDiffuseLight = dDiffuseLight + vec3f(uniform.ambientBakeOcclusionBrightness);\n dDiffuseLight = saturate3(dDiffuseLight);\n dDiffuseLight = dDiffuseLight * dAmbientLight;\n#endif\n#ifdef LIGHTMAP_RGBM\n var temp_color_rgbm = vec4f(dDiffuseLight, 1.0);\n temp_color_rgbm = vec4f(pow(temp_color_rgbm.rgb, vec3f(0.5)), temp_color_rgbm.a);\n temp_color_rgbm = vec4f(temp_color_rgbm.rgb / 8.0, temp_color_rgbm.a);\n let max_g_b = max(temp_color_rgbm.g, max(temp_color_rgbm.b, 1.0 / 255.0));\n let max_rgb = max(temp_color_rgbm.r, max_g_b);\n temp_color_rgbm.a = clamp(max_rgb, 0.0, 1.0);\n temp_color_rgbm.a = ceil(temp_color_rgbm.a * 255.0) / 255.0;\n temp_color_rgbm = vec4f(temp_color_rgbm.rgb / temp_color_rgbm.a, temp_color_rgbm.a);\n output.color = temp_color_rgbm;\n#else\n output.color = vec4f(dDiffuseLight, 1.0);\n#endif\n",basePS:"\nuniform view_position: vec3f;\nuniform light_globalAmbient: vec3f;\nfn square(x: f32) -> f32 {\n return x*x;\n}\nfn saturate(x: f32) -> f32 {\n return clamp(x, 0.0, 1.0);\n}\nfn saturate3(x: vec3f) -> vec3f {\n return clamp(x, vec3f(0.0), vec3f(1.0));\n}\n",baseNineSlicedPS:"\n#define NINESLICED\nvarying vMask: vec2f;\nvarying vTiledUv: vec2f;\nuniform innerOffset: vec4f;\nuniform outerScale: vec2f;\nuniform atlasRect: vec4f;\nvar nineSlicedUv: vec2f;\n",baseNineSlicedTiledPS:"\n#define NINESLICED\n#define NINESLICETILED\nvarying vMask: vec2f;\nvarying vTiledUv: vec2f;\nuniform innerOffset: vec4f;\nuniform outerScale: vec2f;\nuniform atlasRect: vec4f;\nvar nineSlicedUv: vec2f;\n",bayerPS:"\nfn bayer2(p: vec2f) -> f32 {\n return (2.0 * p.y + p.x + 1.0) % 4.0;\n}\nfn bayer4(p: vec2f) -> f32 {\n let p1: vec2f = p % vec2f(2.0);\n let p2: vec2f = floor(0.5 * (p % vec2f(4.0)));\n return 4.0 * bayer2(p1) + bayer2(p2);\n}\nfn bayer8(p: vec2f) -> f32 {\n let p1: vec2f = p % vec2f(2.0);\n let p2: vec2f = floor(0.5 * (p % vec2f(4.0)));\n let p4: vec2f = floor(0.25 * (p % vec2f(8.0)));\n return 4.0 * (4.0 * bayer2(p1) + bayer2(p2)) + bayer2(p4);\n}\n",blurVSMPS:"\nvarying vUv0: vec2f;\nvar source: texture_2d;\nvar sourceSampler: sampler;\n#ifdef GAUSS\n uniform weight: array;\n#endif\nuniform pixelOffset: vec2f;\n@fragment\nfn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n var moments: vec3f = vec3f(0.0);\n let uv: vec2f = input.vUv0 - uniform.pixelOffset * (f32({SAMPLES}) * 0.5);\n for (var i: i32 = 0; i < {SAMPLES}; i = i + 1) {\n let c: vec4f = textureSample(source, sourceSampler, uv + uniform.pixelOffset * f32(i));\n #ifdef GAUSS\n moments = moments + c.xyz * uniform.weight[i].element;\n #else\n moments = moments + c.xyz;\n #endif\n }\n #ifndef GAUSS\n moments = moments * (1.0 / f32({SAMPLES}));\n #endif\n output.color = vec4f(moments, 1.0);\n return output;\n}\n",clearCoatPS:"\n#ifdef STD_CLEARCOAT_CONSTANT\n uniform material_clearCoat: f32;\n#endif\nfn getClearCoat() {\n ccSpecularity = 1.0;\n #ifdef STD_CLEARCOAT_CONSTANT\n ccSpecularity = ccSpecularity * uniform.material_clearCoat;\n #endif\n #ifdef STD_CLEARCOAT_TEXTURE\n ccSpecularity = ccSpecularity * textureSampleBias({STD_CLEARCOAT_TEXTURE_NAME}, {STD_CLEARCOAT_TEXTURE_NAME}Sampler, {STD_CLEARCOAT_TEXTURE_UV}, uniform.textureBias).{STD_CLEARCOAT_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_CLEARCOAT_VERTEX\n ccSpecularity = ccSpecularity * saturate(vVertexColor.{STD_CLEARCOAT_VERTEX_CHANNEL});\n #endif\n}\n",clearCoatGlossPS:"\n#ifdef STD_CLEARCOATGLOSS_CONSTANT\n uniform material_clearCoatGloss: f32;\n#endif\nfn getClearCoatGlossiness() {\n ccGlossiness = 1.0;\n #ifdef STD_CLEARCOATGLOSS_CONSTANT\n ccGlossiness = ccGlossiness * uniform.material_clearCoatGloss;\n #endif\n #ifdef STD_CLEARCOATGLOSS_TEXTURE\n ccGlossiness = ccGlossiness * textureSampleBias({STD_CLEARCOATGLOSS_TEXTURE_NAME}, {STD_CLEARCOATGLOSS_TEXTURE_NAME}Sampler, {STD_CLEARCOATGLOSS_TEXTURE_UV}, uniform.textureBias).{STD_CLEARCOATGLOSS_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_CLEARCOATGLOSS_VERTEX\n ccGlossiness = ccGlossiness * saturate(vVertexColor.{STD_CLEARCOATGLOSS_VERTEX_CHANNEL});\n #endif\n #ifdef STD_CLEARCOATGLOSS_INVERT\n ccGlossiness = 1.0 - ccGlossiness;\n #endif\n ccGlossiness += 0.0000001;\n}\n",clearCoatNormalPS:"\n#ifdef STD_CLEARCOATNORMAL_TEXTURE\n uniform material_clearCoatBumpiness: f32;\n#endif\nfn getClearCoatNormal() {\n#ifdef STD_CLEARCOATNORMAL_TEXTURE\n var normalMap: vec3f = {STD_CLEARCOATNORMAL_TEXTURE_DECODE}(textureSampleBias({STD_CLEARCOATNORMAL_TEXTURE_NAME}, {STD_CLEARCOATNORMAL_TEXTURE_NAME}Sampler, {STD_CLEARCOATNORMAL_TEXTURE_UV}, uniform.textureBias));\n normalMap = mix(vec3f(0.0, 0.0, 1.0), normalMap, uniform.material_clearCoatBumpiness);\n ccNormalW = normalize(dTBN * normalMap);\n#else\n ccNormalW = dVertexNormalW;\n#endif\n}\n",clusteredLightCookiesPS:"\nfn _getCookieClustered(tex: texture_2d, texSampler: sampler, uv: vec2f, intensity: f32, cookieChannel: vec4f) -> vec3f {\n let pixel: vec4f = mix(vec4f(1.0), textureSampleLevel(tex, texSampler, uv, 0.0), intensity);\n let isRgb: bool = dot(cookieChannel.rgb, vec3f(1.0)) == 3.0;\n return select(vec3f(dot(pixel, cookieChannel)), pixel.rgb, isRgb);\n}\nfn getCookie2DClustered(tex: texture_2d, texSampler: sampler, transform: mat4x4f, worldPosition: vec3f, intensity: f32, cookieChannel: vec4f) -> vec3f {\n let projPos: vec4f = transform * vec4f(worldPosition, 1.0);\n return _getCookieClustered(tex, texSampler, projPos.xy / projPos.w, intensity, cookieChannel);\n}\nfn getCookieCubeClustered(tex: texture_2d, texSampler: sampler, dir: vec3f, intensity: f32, cookieChannel: vec4f, shadowTextureResolution: f32, shadowEdgePixels: f32, omniAtlasViewport: vec3f) -> vec3f {\n let uv: vec2f = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);\n return _getCookieClustered(tex, texSampler, uv, intensity, cookieChannel);\n}\n",clusteredLightShadowsPS:"\nfn _getShadowCoordPerspZbuffer(shadowMatrix: mat4x4f, shadowParams: vec4f, wPos: vec3f) -> vec3f {\n var projPos = shadowMatrix * vec4f(wPos, 1.0);\n return projPos.xyz / projPos.w;\n}\nfn getShadowCoordPerspZbufferNormalOffset(shadowMatrix: mat4x4f, shadowParams: vec4f, normal: vec3f) -> vec3f {\n let wPos: vec3f = vPositionW + normal * shadowParams.y;\n return _getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, wPos);\n}\nfn normalOffsetPointShadow(shadowParams: vec4f, lightPos: vec3f, lightDir: vec3f, lightDirNorm: vec3f, normal: vec3f) -> vec3f {\n let distScale: f32 = length(lightDir);\n let wPos: vec3f = vPositionW + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;\n let dir: vec3f = wPos - lightPos;\n return dir;\n}\n#if defined(CLUSTER_SHADOW_TYPE_PCF1)\n fn getShadowOmniClusteredPCF1(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowParams: vec4f, omniAtlasViewport: vec3f, shadowEdgePixels: f32, lightDir: vec3f) -> f32 {\n let shadowTextureResolution: f32 = shadowParams.x;\n let uv: vec2f = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n let shadowZ: f32 = length(lightDir) * shadowParams.w + shadowParams.z;\n return textureSampleCompareLevel(shadowMap, shadowMapSampler, uv, shadowZ);\n }\n#endif\n#if defined(CLUSTER_SHADOW_TYPE_PCF3)\n fn getShadowOmniClusteredPCF3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowParams: vec4f, omniAtlasViewport: vec3f, shadowEdgePixels: f32, lightDir: vec3f) -> f32 {\n let shadowTextureResolution: f32 = shadowParams.x;\n let uv: vec2f = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n let shadowZ: f32 = length(lightDir) * shadowParams.w + shadowParams.z;\n let shadowCoord: vec3f = vec3f(uv, shadowZ);\n return getShadowPCF3x3(shadowMap, shadowMapSampler, shadowCoord, shadowParams);\n }\n#endif\n#if defined(CLUSTER_SHADOW_TYPE_PCF5)\n fn getShadowOmniClusteredPCF5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowParams: vec4f, omniAtlasViewport: vec3f, shadowEdgePixels: f32, lightDir: vec3f) -> f32 {\n let shadowTextureResolution: f32 = shadowParams.x;\n let uv: vec2f = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n let shadowZ: f32 = length(lightDir) * shadowParams.w + shadowParams.z;\n let shadowCoord: vec3f = vec3f(uv, shadowZ);\n return getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams);\n }\n#endif\n#if defined(CLUSTER_SHADOW_TYPE_PCF1)\n fn getShadowSpotClusteredPCF1(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {\n return textureSampleCompareLevel(shadowMap, shadowMapSampler, shadowCoord.xy, shadowCoord.z);\n }\n#endif\n #if defined(CLUSTER_SHADOW_TYPE_PCF3)\n fn getShadowSpotClusteredPCF3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {\n return getShadowSpotPCF3x3(shadowMap, shadowMapSampler, shadowCoord, shadowParams);\n }\n#endif\n #if defined(CLUSTER_SHADOW_TYPE_PCF5)\n fn getShadowSpotClusteredPCF5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {\n return getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams);\n }\n#endif\n",clusteredLightUtilsPS:"\nstruct FaceCoords {\n uv: vec2f,\n faceIndex: f32,\n tileOffset: vec2f,\n}\nfn getCubemapFaceCoordinates(dir: vec3f) -> FaceCoords {\n var faceIndex: f32;\n var tileOffset: vec2f;\n var uv: vec2f;\n let vAbs: vec3f = abs(dir);\n var ma: f32;\n if (vAbs.z >= vAbs.x && vAbs.z >= vAbs.y) {\n let is_neg_z = dir.z < 0.0;\n faceIndex = select(4.0, 5.0, is_neg_z);\n ma = 0.5 / vAbs.z;\n uv = vec2f(select(dir.x, -dir.x, is_neg_z), -dir.y);\n tileOffset = vec2f(2.0, select(0.0, 1.0, is_neg_z));\n } else if (vAbs.y >= vAbs.x) {\n let is_neg_y = dir.y < 0.0;\n faceIndex = select(2.0, 3.0, is_neg_y);\n ma = 0.5 / vAbs.y;\n uv = vec2f(dir.x, select(dir.z, -dir.z, is_neg_y));\n tileOffset = vec2f(1.0, select(0.0, 1.0, is_neg_y));\n } else {\n let is_neg_x = dir.x < 0.0;\n faceIndex = select(0.0, 1.0, is_neg_x);\n ma = 0.5 / vAbs.x;\n uv = vec2f(select(-dir.z, dir.z, is_neg_x), -dir.y);\n tileOffset = vec2f(0.0, select(0.0, 1.0, is_neg_x));\n }\n uv = uv * ma + 0.5;\n return FaceCoords(uv, faceIndex, tileOffset);\n}\nfn getCubemapAtlasCoordinates(omniAtlasViewport: vec3f, shadowEdgePixels: f32, shadowTextureResolution: f32, dir: vec3f) -> vec2f {\n let faceData: FaceCoords = getCubemapFaceCoordinates(dir);\n var uv: vec2f = faceData.uv;\n let tileOffset: vec2f = faceData.tileOffset;\n let atlasFaceSize: f32 = omniAtlasViewport.z;\n let tileSize: f32 = shadowTextureResolution * atlasFaceSize;\n var offset: f32 = shadowEdgePixels / tileSize;\n uv = uv * (1.0 - offset * 2.0) + offset;\n uv = uv * atlasFaceSize;\n uv = uv + tileOffset * atlasFaceSize;\n uv = uv + omniAtlasViewport.xy;\n return uv;\n}\n",clusteredLightPS:'\n#include "lightBufferDefinesPS"\n#include "clusteredLightUtilsPS"\n#ifdef CLUSTER_COOKIES\n #include "clusteredLightCookiesPS"\n#endif\n#ifdef CLUSTER_SHADOWS\n #include "clusteredLightShadowsPS"\n#endif\nvar clusterWorldTexture: texture_2d;\nvar lightsTexture: texture_2d;\n#ifdef CLUSTER_SHADOWS\n var shadowAtlasTexture: texture_depth_2d;\n var shadowAtlasTextureSampler: sampler_comparison;\n#endif\n#ifdef CLUSTER_COOKIES\n var cookieAtlasTexture: texture_2d;\n var cookieAtlasTextureSampler: sampler;\n#endif\nuniform clusterMaxCells: i32;\nuniform clusterSkip: f32;\nuniform clusterCellsCountByBoundsSize: vec3f;\nuniform clusterTextureSize: vec3f;\nuniform clusterBoundsMin: vec3f;\nuniform clusterBoundsDelta: vec3f;\nuniform clusterCellsDot: vec3f;\nuniform clusterCellsMax: vec3f;\nuniform shadowAtlasParams: vec2f;\nstruct ClusterLightData {\n flags: u32,\n halfWidth: vec3f,\n isSpot: bool,\n halfHeight: vec3f,\n lightIndex: i32,\n position: vec3f,\n shape: u32,\n direction: vec3f,\n falloffModeLinear: bool,\n color: vec3f,\n shadowIntensity: f32,\n omniAtlasViewport: vec3f,\n range: f32,\n cookieChannelMask: vec4f,\n biasesData: f32,\n shadowBias: f32,\n shadowNormalBias: f32,\n anglesData: f32,\n innerConeAngleCos: f32,\n outerConeAngleCos: f32,\n cookieIntensity: f32,\n isDynamic: bool,\n isLightmapped: bool\n}\nvar lightProjectionMatrix: mat4x4f;\nfn sampleLightTextureF(lightIndex: i32, index: i32) -> vec4f {\n return textureLoad(lightsTexture, vec2(index, lightIndex), 0);\n}\nfn decodeClusterLightCore(clusterLightData: ptr, lightIndex: f32) {\n clusterLightData.lightIndex = i32(lightIndex);\n let halfData: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_COLOR_ANGLES_BIAS});\n clusterLightData.anglesData = halfData.z;\n clusterLightData.biasesData = halfData.w;\n let colorRG: vec2f = unpack2x16float(bitcast(halfData.x));\n let colorB_: vec2f = unpack2x16float(bitcast(halfData.y));\n clusterLightData.color = vec3f(colorRG, colorB_.x) * {LIGHT_COLOR_DIVIDER};\n let lightPosRange: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_POSITION_RANGE});\n clusterLightData.position = lightPosRange.xyz;\n clusterLightData.range = lightPosRange.w;\n let lightDir_Flags: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_DIRECTION_FLAGS});\n clusterLightData.direction = lightDir_Flags.xyz;\n let flags_uint: u32 = bitcast(lightDir_Flags.w);\n clusterLightData.flags = flags_uint;\n clusterLightData.isSpot = (flags_uint & (1u << 30u)) != 0u;\n clusterLightData.shape = (flags_uint >> 28u) & 0x3u;\n clusterLightData.falloffModeLinear = (flags_uint & (1u << 27u)) == 0u;\n clusterLightData.shadowIntensity = f32((flags_uint >> 0u) & 0xFFu) / 255.0;\n clusterLightData.cookieIntensity = f32((flags_uint >> 8u) & 0xFFu) / 255.0;\n clusterLightData.isDynamic = (flags_uint & (1u << 22u)) != 0u;\n clusterLightData.isLightmapped = (flags_uint & (1u << 21u)) != 0u;\n}\nfn decodeClusterLightSpot(clusterLightData: ptr) {\n let angles: vec2f = unpack2x16float(bitcast(clusterLightData.anglesData));\n clusterLightData.innerConeAngleCos = angles.x;\n clusterLightData.outerConeAngleCos = angles.y;\n}\nfn decodeClusterLightOmniAtlasViewport(clusterLightData: ptr) {\n clusterLightData.omniAtlasViewport = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_0}).xyz;\n}\nfn decodeClusterLightAreaData(clusterLightData: ptr) {\n clusterLightData.halfWidth = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_AREA_DATA_WIDTH}).xyz;\n clusterLightData.halfHeight = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_AREA_DATA_HEIGHT}).xyz;\n}\nfn decodeClusterLightProjectionMatrixData(clusterLightData: ptr) {\n let m0: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_0});\n let m1: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_1});\n let m2: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_2});\n let m3: vec4f = sampleLightTextureF(clusterLightData.lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_3});\n lightProjectionMatrix = mat4x4f(m0, m1, m2, m3);\n}\nfn decodeClusterLightShadowData(clusterLightData: ptr) {\n let biases: vec2f = unpack2x16float(bitcast(clusterLightData.biasesData));\n clusterLightData.shadowBias = biases.x;\n clusterLightData.shadowNormalBias = biases.y;\n}\nfn decodeClusterLightCookieData(clusterLightData: ptr) {\n let cookieFlags: u32 = (clusterLightData.flags >> 23u) & 0x0Fu;\n let mask_uvec: vec4 = vec4(cookieFlags) & vec4(1u, 2u, 4u, 8u);\n clusterLightData.cookieChannelMask = step(vec4f(1.0), vec4f(mask_uvec));\n}\nfn evaluateLight(\n light: ptr,\n worldNormal: vec3f,\n viewDir: vec3f,\n reflectionDir: vec3f,\n#if defined(LIT_CLEARCOAT)\n clearcoatReflectionDir: vec3f,\n#endif\n gloss: f32,\n specularity: vec3f,\n geometricNormal: vec3f,\n tbn: mat3x3f,\n#if defined(LIT_IRIDESCENCE)\n iridescenceFresnel: vec3f,\n#endif\n clearcoat_worldNormal: vec3f,\n clearcoat_gloss: f32,\n sheen_gloss: f32,\n iridescence_intensity: f32\n) {\n var cookieAttenuation: vec3f = vec3f(1.0);\n var diffuseAttenuation: f32 = 1.0;\n var falloffAttenuation: f32 = 1.0;\n let lightDirW: vec3f = evalOmniLight(light.position);\n let lightDirNormW: vec3f = normalize(lightDirW);\n #ifdef CLUSTER_AREALIGHTS\n if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {\n decodeClusterLightAreaData(light);\n if (light.shape == {LIGHTSHAPE_RECT}) {\n calcRectLightValues(light.position, light.halfWidth, light.halfHeight);\n } else if (light.shape == {LIGHTSHAPE_DISK}) {\n calcDiskLightValues(light.position, light.halfWidth, light.halfHeight);\n } else {\n calcSphereLightValues(light.position, light.halfWidth, light.halfHeight);\n }\n falloffAttenuation = getFalloffWindow(light.range, lightDirW);\n } else\n #endif\n {\n if (light.falloffModeLinear) {\n falloffAttenuation = getFalloffLinear(light.range, lightDirW);\n } else {\n falloffAttenuation = getFalloffInvSquared(light.range, lightDirW);\n }\n }\n if (falloffAttenuation > 0.00001) {\n #ifdef CLUSTER_AREALIGHTS\n if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {\n if (light.shape == {LIGHTSHAPE_RECT}) {\n diffuseAttenuation = getRectLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;\n } else if (light.shape == {LIGHTSHAPE_DISK}) {\n diffuseAttenuation = getDiskLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;\n } else {\n diffuseAttenuation = getSphereLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;\n }\n } else\n #endif\n {\n falloffAttenuation = falloffAttenuation * getLightDiffuse(worldNormal, viewDir, lightDirNormW);\n }\n if (light.isSpot) {\n decodeClusterLightSpot(light);\n falloffAttenuation = falloffAttenuation * getSpotEffect(light.direction, light.innerConeAngleCos, light.outerConeAngleCos, lightDirNormW);\n }\n #if defined(CLUSTER_COOKIES) || defined(CLUSTER_SHADOWS)\n if (falloffAttenuation > 0.00001) {\n if (light.shadowIntensity > 0.0 || light.cookieIntensity > 0.0) {\n if (light.isSpot) {\n decodeClusterLightProjectionMatrixData(light);\n } else {\n decodeClusterLightOmniAtlasViewport(light);\n }\n let shadowTextureResolution: f32 = uniform.shadowAtlasParams.x;\n let shadowEdgePixels: f32 = uniform.shadowAtlasParams.y;\n #ifdef CLUSTER_COOKIES\n if (light.cookieIntensity > 0.0) {\n decodeClusterLightCookieData(light);\n if (light.isSpot) {\n cookieAttenuation = getCookie2DClustered(cookieAtlasTexture, cookieAtlasTextureSampler, lightProjectionMatrix, vPositionW, light.cookieIntensity, light.cookieChannelMask);\n } else {\n cookieAttenuation = getCookieCubeClustered(cookieAtlasTexture, cookieAtlasTextureSampler, lightDirW, light.cookieIntensity, light.cookieChannelMask, shadowTextureResolution, shadowEdgePixels, light.omniAtlasViewport);\n }\n }\n #endif\n #ifdef CLUSTER_SHADOWS\n if (light.shadowIntensity > 0.0) {\n decodeClusterLightShadowData(light);\n let shadowParams: vec4f = vec4f(shadowTextureResolution, light.shadowNormalBias, light.shadowBias, 1.0 / light.range);\n if (light.isSpot) {\n let shadowCoord: vec3f = getShadowCoordPerspZbufferNormalOffset(lightProjectionMatrix, shadowParams, geometricNormal);\n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n let shadow: f32 = getShadowSpotClusteredPCF1(shadowAtlasTexture, shadowAtlasTextureSampler, shadowCoord, shadowParams);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF3)\n let shadow: f32 = getShadowSpotClusteredPCF3(shadowAtlasTexture, shadowAtlasTextureSampler, shadowCoord, shadowParams);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF5)\n let shadow: f32 = getShadowSpotClusteredPCF5(shadowAtlasTexture, shadowAtlasTextureSampler, shadowCoord, shadowParams);\n #elif defined(CLUSTER_SHADOW_TYPE_PCSS)\n let shadow: f32 = getShadowSpotClusteredPCSS(shadowAtlasTexture, shadowAtlasTextureSampler, shadowCoord, shadowParams);\n #endif\n falloffAttenuation = falloffAttenuation * mix(1.0, shadow, light.shadowIntensity);\n } else {\n let dir: vec3f = normalOffsetPointShadow(shadowParams, light.position, lightDirW, lightDirNormW, geometricNormal);\n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n let shadow: f32 = getShadowOmniClusteredPCF1(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF3)\n let shadow: f32 = getShadowOmniClusteredPCF3(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF5)\n let shadow: f32 = getShadowOmniClusteredPCF5(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, light.omniAtlasViewport, shadowEdgePixels, dir);\n #endif\n falloffAttenuation = falloffAttenuation * mix(1.0, shadow, light.shadowIntensity);\n }\n }\n #endif\n }\n }\n #endif\n #ifdef CLUSTER_AREALIGHTS\n if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {\n {\n var areaDiffuse: vec3f = (diffuseAttenuation * falloffAttenuation) * light.color * cookieAttenuation;\n #if defined(LIT_SPECULAR)\n areaDiffuse = mix(areaDiffuse, vec3f(0.0), dLTCSpecFres);\n #endif\n dDiffuseLight = dDiffuseLight + areaDiffuse;\n }\n #ifdef LIT_SPECULAR\n var areaLightSpecular: f32;\n if (light.shape == {LIGHTSHAPE_RECT}) {\n areaLightSpecular = getRectLightSpecular(worldNormal, viewDir);\n } else if (light.shape == {LIGHTSHAPE_DISK}) {\n areaLightSpecular = getDiskLightSpecular(worldNormal, viewDir);\n } else {\n areaLightSpecular = getSphereLightSpecular(worldNormal, viewDir);\n }\n dSpecularLight = dSpecularLight + dLTCSpecFres * areaLightSpecular * falloffAttenuation * light.color * cookieAttenuation;\n #ifdef LIT_CLEARCOAT\n var areaLightSpecularCC: f32;\n if (light.shape == {LIGHTSHAPE_RECT}) {\n areaLightSpecularCC = getRectLightSpecular(clearcoat_worldNormal, viewDir);\n } else if (light.shape == {LIGHTSHAPE_DISK}) {\n areaLightSpecularCC = getDiskLightSpecular(clearcoat_worldNormal, viewDir);\n } else {\n areaLightSpecularCC = getSphereLightSpecular(clearcoat_worldNormal, viewDir);\n }\n ccSpecularLight = ccSpecularLight + ccLTCSpecFres * areaLightSpecularCC * falloffAttenuation * light.color * cookieAttenuation;\n #endif\n #endif\n } else\n #endif\n {\n {\n var punctualDiffuse: vec3f = falloffAttenuation * light.color * cookieAttenuation;\n #if defined(CLUSTER_AREALIGHTS)\n #if defined(LIT_SPECULAR)\n punctualDiffuse = mix(punctualDiffuse, vec3f(0.0), specularity);\n #endif\n #endif\n dDiffuseLight = dDiffuseLight + punctualDiffuse;\n }\n #ifdef LIT_SPECULAR\n let halfDir: vec3f = normalize(-lightDirNormW + viewDir);\n #ifdef LIT_SPECULAR_FRESNEL\n dSpecularLight = dSpecularLight +\n getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, lightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation *\n getFresnel(\n dot(viewDir, halfDir),\n gloss,\n specularity\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n iridescence_intensity\n #endif\n );\n #else\n dSpecularLight = dSpecularLight + getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, lightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * specularity;\n #endif\n #ifdef LIT_CLEARCOAT\n #ifdef LIT_SPECULAR_FRESNEL\n ccSpecularLight = ccSpecularLight + getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, lightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * getFresnelCC(dot(viewDir, halfDir));\n #else\n ccSpecularLight = ccSpecularLight + getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, lightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation;\n #endif\n #endif\n #ifdef LIT_SHEEN\n sSpecularLight = sSpecularLight + getLightSpecularSheen(halfDir, worldNormal, viewDir, lightDirNormW, sheen_gloss) * falloffAttenuation * light.color * cookieAttenuation;\n #endif\n #endif\n }\n }\n dAtten = falloffAttenuation;\n dLightDirNormW = lightDirNormW;\n}\nfn evaluateClusterLight(\n lightIndex: f32,\n worldNormal: vec3f,\n viewDir: vec3f,\n reflectionDir: vec3f,\n#if defined(LIT_CLEARCOAT)\n clearcoatReflectionDir: vec3f,\n#endif\n gloss: f32,\n specularity: vec3f,\n geometricNormal: vec3f,\n tbn: mat3x3f,\n#if defined(LIT_IRIDESCENCE)\n iridescenceFresnel: vec3f,\n#endif\n clearcoat_worldNormal: vec3f,\n clearcoat_gloss: f32,\n sheen_gloss: f32,\n iridescence_intensity: f32\n) {\n var clusterLightData: ClusterLightData;\n decodeClusterLightCore(&clusterLightData, lightIndex);\n #ifdef CLUSTER_MESH_DYNAMIC_LIGHTS\n let acceptLightMask: bool = clusterLightData.isDynamic;\n #else\n let acceptLightMask: bool = clusterLightData.isLightmapped;\n #endif\n if (acceptLightMask) {\n evaluateLight(\n &clusterLightData,\n worldNormal,\n viewDir,\n reflectionDir,\n#if defined(LIT_CLEARCOAT)\n clearcoatReflectionDir,\n#endif\n gloss,\n specularity,\n geometricNormal,\n tbn,\n#if defined(LIT_IRIDESCENCE)\n iridescenceFresnel,\n#endif\n clearcoat_worldNormal,\n clearcoat_gloss,\n sheen_gloss,\n iridescence_intensity\n );\n }\n}\nfn addClusteredLights(\n worldNormal: vec3f,\n viewDir: vec3f,\n reflectionDir: vec3f,\n#if defined(LIT_CLEARCOAT)\n clearcoatReflectionDir: vec3f,\n#endif\n gloss: f32,\n specularity: vec3f,\n geometricNormal: vec3f,\n tbn: mat3x3f,\n#if defined(LIT_IRIDESCENCE)\n iridescenceFresnel: vec3f,\n#endif\n clearcoat_worldNormal: vec3f,\n clearcoat_gloss: f32,\n sheen_gloss: f32,\n iridescence_intensity: f32\n) {\n if (uniform.clusterSkip > 0.5) {\n return;\n }\n let cellCoords: vec3f = floor((vPositionW - uniform.clusterBoundsMin) * uniform.clusterCellsCountByBoundsSize);\n if (!(any(cellCoords < vec3f(0.0)) || any(cellCoords >= uniform.clusterCellsMax))) {\n let cellIndex: f32 = dot(uniform.clusterCellsDot, cellCoords);\n let clusterV: f32 = floor(cellIndex * uniform.clusterTextureSize.y);\n let clusterU: f32 = cellIndex - (clusterV * uniform.clusterTextureSize.x);\n for (var lightCellIndex: i32 = 0; lightCellIndex < uniform.clusterMaxCells; lightCellIndex = lightCellIndex + 1) {\n let lightIndexPacked: f32 = textureLoad(clusterWorldTexture, vec2(i32(clusterU) + lightCellIndex, i32(clusterV)), 0).r;\n if (lightIndexPacked <= 0.0) {\n break;\n }\n evaluateClusterLight(\n lightIndexPacked * 255.0,\n worldNormal,\n viewDir,\n reflectionDir,\n#if defined(LIT_CLEARCOAT)\n clearcoatReflectionDir,\n#endif\n gloss,\n specularity,\n geometricNormal,\n tbn,\n#if defined(LIT_IRIDESCENCE)\n iridescenceFresnel,\n#endif\n clearcoat_worldNormal,\n clearcoat_gloss,\n sheen_gloss,\n iridescence_intensity\n );\n }\n }\n}',combinePS:"\nfn combineColor(albedo: vec3f, sheenSpecularity: vec3f, clearcoatSpecularity: f32) -> vec3f {\n var ret: vec3f = vec3f(0.0);\n #ifdef LIT_OLD_AMBIENT\n ret = ret + ((dDiffuseLight - uniform.light_globalAmbient) * albedo + uniform.material_ambient * uniform.light_globalAmbient);\n #else\n ret = ret + (albedo * dDiffuseLight);\n #endif\n #ifdef LIT_SPECULAR\n ret = ret + dSpecularLight;\n #endif\n #ifdef LIT_REFLECTIONS\n ret = ret + (dReflection.rgb * dReflection.a);\n #endif\n #ifdef LIT_SHEEN\n let sheenScaling: f32 = 1.0 - max(max(sheenSpecularity.r, sheenSpecularity.g), sheenSpecularity.b) * 0.157;\n ret = ret * sheenScaling + (sSpecularLight + sReflection.rgb) * sheenSpecularity;\n #endif\n #ifdef LIT_CLEARCOAT\n let clearCoatScaling: f32 = 1.0 - ccFresnel * clearcoatSpecularity;\n ret = ret * clearCoatScaling + (ccSpecularLight + ccReflection) * clearcoatSpecularity;\n #endif\n return ret;\n}\n",cookieBlit2DPS:"\n varying uv0: vec2f;\n var blitTexture: texture_2d;\n var blitTextureSampler : sampler;\n @fragment\n fn fragmentMain(input : FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n output.color = textureSample(blitTexture, blitTextureSampler, input.uv0);\n return output;\n }\n",cookieBlitCubePS:"\n varying uv0: vec2f;\n uniform invViewProj: mat4x4;\n var blitTexture: texture_cube;\n var blitTextureSampler : sampler;\n @fragment\n fn fragmentMain(input : FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n var projPos = vec4f(input.uv0 * 2.0 - 1.0, 0.5, 1.0);\n var worldPos = uniform.invViewProj * projPos;\n output.color = textureSample(blitTexture, blitTextureSampler, worldPos.xyz);\n return output;\n }\n",cookieBlitVS:"\n attribute vertex_position: vec2f;\n varying uv0: vec2f;\n @vertex\n fn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n output.position = vec4f(input.vertex_position, 0.5, 1.0);\n output.uv0 = input.vertex_position * 0.5 + vec2f(0.5, 0.5);\n output.uv0.y = 1.0 - output.uv0.y;\n return output;\n }\n",cubeMapProjectPS:"\n#if LIT_CUBEMAP_PROJECTION == BOX\n uniform envBoxMin: vec3f;\n uniform envBoxMax: vec3f;\n#endif\nfn cubeMapProject(nrdir: vec3f) -> vec3f {\n #if LIT_CUBEMAP_PROJECTION == NONE\n return cubeMapRotate(nrdir);\n #endif\n #if LIT_CUBEMAP_PROJECTION == BOX\n let nrdir_rotated: vec3f = cubeMapRotate(nrdir);\n let rbmax: vec3f = (uniform.envBoxMax - vPositionW) / nrdir_rotated;\n let rbmin: vec3f = (uniform.envBoxMin - vPositionW) / nrdir_rotated;\n let rbminmax: vec3f = select(rbmin, rbmax, nrdir_rotated > vec3f(0.0));\n let fa: f32 = min(min(rbminmax.x, rbminmax.y), rbminmax.z);\n let posonbox: vec3f = vPositionW + nrdir_rotated * fa;\n let envBoxPos: vec3f = (uniform.envBoxMin + uniform.envBoxMax) * 0.5;\n return normalize(posonbox - envBoxPos);\n #endif\n}\n",cubeMapRotatePS:"\n#ifdef CUBEMAP_ROTATION\nuniform cubeMapRotationMatrix: mat3x3f;\n#endif\nfn cubeMapRotate(refDir: vec3f) -> vec3f {\n#ifdef CUBEMAP_ROTATION\n return refDir * uniform.cubeMapRotationMatrix;\n#else\n return refDir;\n#endif\n}\n",debugOutputPS:"\n#ifdef DEBUG_ALBEDO_PASS\noutput.color = vec4(gammaCorrectOutput(dAlbedo), 1.0);\n#endif\n#ifdef DEBUG_UV0_PASS\noutput.color = vec4f(litArgs_albedo , 1.0);\n#endif\n#ifdef DEBUG_WORLD_NORMAL_PASS\noutput.color = vec4f(litArgs_worldNormal * 0.5 + 0.5, 1.0);\n#endif\n#ifdef DEBUG_OPACITY_PASS\noutput.color = vec4f(vec3f(litArgs_opacity) , 1.0);\n#endif\n#ifdef DEBUG_SPECULARITY_PASS\noutput.color = vec4f(litArgs_specularity, 1.0);\n#endif\n#ifdef DEBUG_GLOSS_PASS\noutput.color = vec4f(vec3f(litArgs_gloss) , 1.0);\n#endif\n#ifdef DEBUG_METALNESS_PASS\noutput.color = vec4f(vec3f(litArgs_metalness) , 1.0);\n#endif\n#ifdef DEBUG_AO_PASS\noutput.color = vec4f(vec3f(litArgs_ao) , 1.0);\n#endif\n#ifdef DEBUG_EMISSION_PASS\noutput.color = vec4f(gammaCorrectOutput(litArgs_emission), 1.0);\n#endif\n",debugProcessFrontendPS:"\n#ifdef DEBUG_LIGHTING_PASS\n litArgs_albedo = vec3f(0.5);\n#endif\n#ifdef DEBUG_UV0_PASS\n#ifdef VARYING_VUV0\n litArgs_albedo = vec3f(vUv0, 0.0);\n#else\n litArgs_albedo = vec3f(0.0);\n#endif\n#endif\n",detailModesPS:"\n#ifndef _DETAILMODES_INCLUDED_\n#define _DETAILMODES_INCLUDED_\nfn detailMode_mul(c1: vec3f, c2: vec3f) -> vec3f {\n return c1 * c2;\n}\nfn detailMode_add(c1: vec3f, c2: vec3f) -> vec3f {\n return c1 + c2;\n}\nfn detailMode_screen(c1: vec3f, c2: vec3f) -> vec3f {\n return 1.0 - (1.0 - c1)*(1.0 - c2);\n}\nfn detailMode_overlay(c1: vec3f, c2: vec3f) -> vec3f {\n return mix(1.0 - 2.0 * (1.0 - c1)*(1.0 - c2), 2.0 * c1 * c2, step(c1, vec3f(0.5)));\n}\nfn detailMode_min(c1: vec3f, c2: vec3f) -> vec3f {\n return min(c1, c2);\n}\nfn detailMode_max(c1: vec3f, c2: vec3f) -> vec3f {\n return max(c1, c2);\n}\n#endif\n",diffusePS:'\nuniform material_diffuse: vec3f;\n#ifdef STD_DIFFUSEDETAIL_TEXTURE\n #include "detailModesPS"\n#endif\nfn getAlbedo() {\n dAlbedo = uniform.material_diffuse.rgb;\n #ifdef STD_DIFFUSE_TEXTURE\n var albedoTexture: vec3f = {STD_DIFFUSE_TEXTURE_DECODE}(textureSampleBias({STD_DIFFUSE_TEXTURE_NAME}, {STD_DIFFUSE_TEXTURE_NAME}Sampler, {STD_DIFFUSE_TEXTURE_UV}, uniform.textureBias)).{STD_DIFFUSE_TEXTURE_CHANNEL};\n #ifdef STD_DIFFUSEDETAIL_TEXTURE\n var albedoDetail: vec3f = {STD_DIFFUSEDETAIL_TEXTURE_DECODE}(textureSampleBias({STD_DIFFUSEDETAIL_TEXTURE_NAME}, {STD_DIFFUSEDETAIL_TEXTURE_NAME}Sampler, {STD_DIFFUSEDETAIL_TEXTURE_UV}, uniform.textureBias)).{STD_DIFFUSEDETAIL_TEXTURE_CHANNEL};\n albedoTexture = detailMode_{STD_DIFFUSEDETAIL_DETAILMODE}(albedoTexture, albedoDetail);\n #endif\n dAlbedo = dAlbedo * albedoTexture;\n #endif\n #ifdef STD_DIFFUSE_VERTEX\n dAlbedo = dAlbedo * gammaCorrectInputVec3(saturate3(vVertexColor.{STD_DIFFUSE_VERTEX_CHANNEL}));\n #endif\n}\n',decodePS:"\n#ifndef _DECODE_INCLUDED_\n#define _DECODE_INCLUDED_\nfn decodeLinear(raw: vec4f) -> vec3f {\n return raw.rgb;\n}\nfn decodeGammaFloat(raw: f32) -> f32 {\n return pow(raw, 2.2);\n}\nfn decodeGamma3(raw: vec3f) -> vec3f {\n return pow(raw, vec3f(2.2));\n}\nfn decodeGamma(raw: vec4f) -> vec3f {\n return pow(raw.xyz, vec3f(2.2));\n}\nfn decodeRGBM(raw: vec4f) -> vec3f {\n let color = (8.0 * raw.a) * raw.rgb;\n return color * color;\n}\nfn decodeRGBP(raw: vec4f) -> vec3f {\n let color = raw.rgb * (-raw.a * 7.0 + 8.0);\n return color * color;\n}\nfn decodeRGBE(raw: vec4f) -> vec3f {\n return select(vec3f(0.0), raw.xyz * pow(2.0, raw.w * 255.0 - 128.0), raw.a != 0.0);\n}\nfn passThrough(raw: vec4f) -> vec4f {\n return raw;\n}\nfn unpackNormalXYZ(nmap: vec4f) -> vec3f {\n return nmap.xyz * 2.0 - 1.0;\n}\nfn unpackNormalXY(nmap: vec4f) -> vec3f {\n var xy = nmap.wy * 2.0 - 1.0;\n return vec3f(xy, sqrt(1.0 - clamp(dot(xy, xy), 0.0, 1.0)));\n}\n#endif\n",emissivePS:"\nuniform material_emissive: vec3f;\nuniform material_emissiveIntensity: f32;\nfn getEmission() {\n dEmission = uniform.material_emissive * uniform.material_emissiveIntensity;\n #ifdef STD_EMISSIVE_TEXTURE\n dEmission *= {STD_EMISSIVE_TEXTURE_DECODE}(textureSampleBias({STD_EMISSIVE_TEXTURE_NAME}, {STD_EMISSIVE_TEXTURE_NAME}Sampler, {STD_EMISSIVE_TEXTURE_UV}, uniform.textureBias)).{STD_EMISSIVE_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_EMISSIVE_VERTEX\n dEmission = dEmission * gammaCorrectInputVec3(saturate3(vVertexColor.{STD_EMISSIVE_VERTEX_CHANNEL}));\n #endif\n}\n",encodePS:"\nfn encodeLinear(source: vec3f) -> vec4f {\n return vec4f(source, 1.0);\n}\nfn encodeGamma(source: vec3f) -> vec4f {\n return vec4f(pow(source + vec3f(0.0000001), vec3f(1.0 / 2.2)), 1.0);\n}\nfn encodeRGBM(source: vec3f) -> vec4f {\n var color: vec3f = pow(source, vec3f(0.5));\n color *= 1.0 / 8.0;\n var a: f32 = saturate(max(max(color.r, color.g), max(color.b, 1.0 / 255.0)));\n a = ceil(a * 255.0) / 255.0;\n color /= a;\n return vec4f(color, a);\n}\nfn encodeRGBP(source: vec3f) -> vec4f {\n var gamma: vec3f = pow(source, vec3f(0.5));\n var maxVal: f32 = min(8.0, max(1.0, max(gamma.x, max(gamma.y, gamma.z))));\n var v: f32 = 1.0 - ((maxVal - 1.0) / 7.0);\n v = ceil(v * 255.0) / 255.0;\n return vec4f(gamma / (-v * 7.0 + 8.0), v);\n}\nfn encodeRGBE(source: vec3f) -> vec4f {\n var maxVal: f32 = max(source.x, max(source.y, source.z));\n if (maxVal < 1e-32) {\n return vec4f(0.0, 0.0, 0.0, 0.0);\n } else {\n var e: f32 = ceil(log2(maxVal));\n return vec4f(source / pow(2.0, e), (e + 128.0) / 255.0);\n }\n}\n",endPS:"\n var finalRgb: vec3f = combineColor(litArgs_albedo, litArgs_sheen_specularity, litArgs_clearcoat_specularity);\n finalRgb = finalRgb + litArgs_emission;\n finalRgb = addFog(finalRgb);\n finalRgb = toneMap(finalRgb);\n finalRgb = gammaCorrectOutput(finalRgb);\n output.color = vec4f(finalRgb, output.color.a);\n",envAtlasPS:"\n#ifndef _ENVATLAS_INCLUDED_\n#define _ENVATLAS_INCLUDED_\nconst atlasSize : f32 = 512.0;\nconst seamSize : f32 = 1.0 / atlasSize;\nfn mapUv(uv : vec2f, rect : vec4f) -> vec2f {\n return vec2f(mix(rect.x + seamSize, rect.x + rect.z - seamSize, uv.x),\n mix(rect.y + seamSize, rect.y + rect.w - seamSize, uv.y));\n}\nfn mapRoughnessUv(uv : vec2f, level : f32) -> vec2f {\n let t : f32 = 1.0 / exp2(level);\n return mapUv(uv, vec4f(0.0, 1.0 - t, t, t * 0.5));\n}\nfn mapShinyUv(uv : vec2f, level : f32) -> vec2f {\n let t : f32 = 1.0 / exp2(level);\n return mapUv(uv, vec4f(1.0 - t, 1.0 - t, t, t * 0.5));\n}\n#endif\n",envProcPS:"\n#ifdef LIT_SKYBOX_INTENSITY\n uniform skyboxIntensity : f32;\n#endif\nfn processEnvironment(color : vec3f) -> vec3f {\n #ifdef LIT_SKYBOX_INTENSITY\n return color * uniform.skyboxIntensity;\n #else\n return color;\n #endif\n}\n",falloffInvSquaredPS:"\nfn getFalloffWindow(lightRadius: f32, lightDir: vec3f) -> f32 {\n let sqrDist: f32 = dot(lightDir, lightDir);\n let invRadius: f32 = 1.0 / lightRadius;\n return square(saturate(1.0 - square(sqrDist * square(invRadius))));\n}\nfn getFalloffInvSquared(lightRadius: f32, lightDir: vec3f) -> f32 {\n let sqrDist: f32 = dot(lightDir, lightDir);\n var falloff: f32 = 1.0 / (sqrDist + 1.0);\n let invRadius: f32 = 1.0 / lightRadius;\n falloff = falloff * 16.0;\n falloff = falloff * square(saturate(1.0 - square(sqrDist * square(invRadius))));\n return falloff;\n}\n",falloffLinearPS:"\nfn getFalloffLinear(lightRadius: f32, lightDir: vec3f) -> f32 {\n let d: f32 = length(lightDir);\n return max(((lightRadius - d) / lightRadius), 0.0);\n}\n",floatAsUintPS:"\n#ifndef FLOAT_AS_UINT\n#define FLOAT_AS_UINT\nfn float2uint(value: f32) -> vec4f {\n let intBits = bitcast(value);\n return vec4f(\n f32((intBits >> 24u) & 0xffu),\n f32((intBits >> 16u) & 0xffu),\n f32((intBits >> 8u) & 0xffu),\n f32(intBits & 0xffu)\n ) / 255.0;\n}\nfn uint2float(value: vec4f) -> f32 {\n let rgba_u32 = vec4(value * 255.0);\n let intBits: u32 =\n (rgba_u32.r << 24u) |\n (rgba_u32.g << 16u) |\n (rgba_u32.b << 8u) |\n rgba_u32.a;\n return bitcast(intBits);\n}\nfn float2vec4(value: f32) -> vec4f {\n #if defined(CAPS_TEXTURE_FLOAT_RENDERABLE)\n return vec4f(value, 1.0, 1.0, 1.0);\n #else\n return float2uint(value);\n #endif\n}\n#endif\n",fogPS:"\nvar dBlendModeFogFactor : f32 = 1.0;\n#if (FOG != NONE)\n uniform fog_color : vec3f;\n \n #if (FOG == LINEAR)\n uniform fog_start : f32;\n uniform fog_end : f32;\n #else\n uniform fog_density : f32;\n #endif\n#endif\nfn getFogFactor() -> f32 {\n let depth = pcPosition.z / pcPosition.w;\n var fogFactor : f32 = 0.0;\n #if (FOG == LINEAR)\n fogFactor = (uniform.fog_end - depth) / (uniform.fog_end - uniform.fog_start);\n #elif (FOG == EXP)\n fogFactor = exp(-depth * uniform.fog_density);\n #elif (FOG == EXP2)\n fogFactor = exp(-depth * depth * uniform.fog_density * uniform.fog_density);\n #endif\n return clamp(fogFactor, 0.0, 1.0);\n}\nfn addFog(color : vec3f) -> vec3f {\n #if (FOG != NONE)\n return mix(uniform.fog_color * dBlendModeFogFactor, color, getFogFactor());\n #else\n return color;\n #endif\n}\n",fresnelSchlickPS:"\nfn getFresnel(\n cosTheta: f32,\n gloss: f32,\n specularity: vec3f\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel: vec3f,\n iridescenceIntensity: f32\n #endif\n) -> vec3f {\n let fresnel: f32 = pow(1.0 - saturate(cosTheta), 5.0);\n let glossSq: f32 = gloss * gloss;\n let ret: vec3f = specularity + (max(vec3f(glossSq), specularity) - specularity) * fresnel;\n #if defined(LIT_IRIDESCENCE)\n return mix(ret, iridescenceFresnel, iridescenceIntensity);\n #else\n return ret;\n #endif\n}\nfn getFresnelCC(cosTheta: f32) -> f32 {\n let fresnel: f32 = pow(1.0 - saturate(cosTheta), 5.0);\n return 0.04 + (1.0 - 0.04) * fresnel;\n}",frontendCodePS:"",frontendDeclPS:"",fullscreenQuadVS:"\nattribute vertex_position: vec2f;\nvarying vUv0: vec2f;\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n output.position = vec4f(input.vertex_position, 0.5, 1.0);\n output.vUv0 = input.vertex_position.xy * 0.5 + vec2f(0.5);\n return output;\n}\n",gammaPS:'\n#include "decodePS"\n#if (GAMMA == SRGB)\n fn gammaCorrectInput(color: f32) -> f32 {\n return decodeGammaFloat(color);\n }\n fn gammaCorrectInputVec3(color: vec3f) -> vec3f {\n return decodeGamma3(color);\n }\n fn gammaCorrectInputVec4(color: vec4f) -> vec4f {\n return vec4f(decodeGamma3(color.xyz), color.w);\n }\n fn gammaCorrectOutput(color: vec3f) -> vec3f {\n return pow(color + 0.0000001, vec3f(1.0 / 2.2));\n }\n#else\n fn gammaCorrectInput(color: f32) -> f32 {\n return color;\n }\n fn gammaCorrectInputVec3(color: vec3f) -> vec3f {\n return color;\n }\n fn gammaCorrectInputVec4(color: vec4f) -> vec4f {\n return color;\n }\n fn gammaCorrectOutput(color: vec3f) -> vec3f {\n return color;\n }\n#endif\n',glossPS:"\n#ifdef STD_GLOSS_CONSTANT\n uniform material_gloss: f32;\n#endif\nfn getGlossiness() {\n dGlossiness = 1.0;\n #ifdef STD_GLOSS_CONSTANT\n dGlossiness = dGlossiness * uniform.material_gloss;\n #endif\n #ifdef STD_GLOSS_TEXTURE\n dGlossiness = dGlossiness * textureSampleBias({STD_GLOSS_TEXTURE_NAME}, {STD_GLOSS_TEXTURE_NAME}Sampler, {STD_GLOSS_TEXTURE_UV}, uniform.textureBias).{STD_GLOSS_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_GLOSS_VERTEX\n dGlossiness = dGlossiness * saturate(vVertexColor.{STD_GLOSS_VERTEX_CHANNEL});\n #endif\n #ifdef STD_GLOSS_INVERT\n dGlossiness = 1.0 - dGlossiness;\n #endif\n dGlossiness = dGlossiness + 0.0000001;\n}\n",gsplatCenterVS:"\nuniform matrix_model: mat4x4f;\nuniform matrix_view: mat4x4f;\nuniform matrix_projection: mat4x4f;\nfn initCenter(modelCenter: vec3f, center: ptr) -> bool {\n let modelView: mat4x4f = uniform.matrix_view * uniform.matrix_model;\n let centerView: vec4f = modelView * vec4f(modelCenter, 1.0);\n if (centerView.z > 0.0) {\n return false;\n }\n var centerProj: vec4f = uniform.matrix_projection * centerView;\n centerProj.z = clamp(centerProj.z, 0.0, abs(centerProj.w));\n center.view = centerView.xyz / centerView.w;\n center.proj = centerProj;\n center.projMat00 = uniform.matrix_projection[0][0];\n center.modelView = modelView;\n return true;\n}\n",gsplatCornerVS:"\nuniform viewport: vec2f;\nuniform camera_params: vec4f;\nfn initCorner(source: ptr, center: ptr, corner: ptr) -> bool {\n var covA: vec3f;\n var covB: vec3f;\n readCovariance(source, &covA, &covB);\n let Vrk = mat3x3f(\n vec3f(covA.x, covA.y, covA.z),\n vec3f(covA.y, covB.x, covB.y),\n vec3f(covA.z, covB.y, covB.z)\n );\n let focal = uniform.viewport.x * center.projMat00;\n let v = select(center.view.xyz, vec3f(0.0, 0.0, 1.0), uniform.camera_params.w == 1.0);\n let J1 = focal / v.z;\n let J2 = -J1 / v.z * v.xy;\n let J = mat3x3f(\n vec3f(J1, 0.0, J2.x),\n vec3f(0.0, J1, J2.y),\n vec3f(0.0, 0.0, 0.0)\n );\n let W = transpose(mat3x3f(center.modelView[0].xyz, center.modelView[1].xyz, center.modelView[2].xyz));\n let T = W * J;\n let cov = transpose(T) * Vrk * T;\n #if GSPLAT_AA\n let detOrig = cov[0][0] * cov[1][1] - cov[0][1] * cov[1][0];\n let detBlur = (cov[0][0] + 0.3) * (cov[1][1] + 0.3) - cov[0][1] * cov[1][0];\n corner.aaFactor = sqrt(detOrig / detBlur);\n #endif\n let diagonal1 = cov[0][0] + 0.3;\n let offDiagonal = cov[0][1];\n let diagonal2 = cov[1][1] + 0.3;\n let mid = 0.5 * (diagonal1 + diagonal2);\n let radius = length(vec2f((diagonal1 - diagonal2) / 2.0, offDiagonal));\n let lambda1 = mid + radius;\n let lambda2 = max(mid - radius, 0.1);\n let vmin = min(1024.0, min(uniform.viewport.x, uniform.viewport.y));\n let l1 = 2.0 * min(sqrt(2.0 * lambda1), vmin);\n let l2 = 2.0 * min(sqrt(2.0 * lambda2), vmin);\n if (l1 < 2.0 && l2 < 2.0) {\n return false;\n }\n let c = center.proj.ww / uniform.viewport;\n if (any((abs(center.proj.xy) - vec2f(max(l1, l2)) * c) > center.proj.ww)) {\n return false;\n }\n let diagonalVector = normalize(vec2f(offDiagonal, lambda1 - diagonal1));\n let v1 = l1 * diagonalVector;\n let v2 = l2 * vec2f(diagonalVector.y, -diagonalVector.x);\n corner.offset = (source.cornerUV.x * v1 + source.cornerUV.y * v2) * c;\n corner.uv = source.cornerUV;\n return true;\n}\n",gsplatColorVS:"\nvar splatColor: texture_2d;\nfn readColor(source: ptr) -> vec4f {\n return textureLoad(splatColor, source.uv, 0);\n}\n",gsplatCommonVS:'\nstruct SplatSource {\n order: u32,\n id: u32,\n uv: vec2,\n cornerUV: vec2f,\n}\nstruct SplatCenter {\n view: vec3f,\n proj: vec4f,\n modelView: mat4x4f,\n projMat00: f32,\n}\nstruct SplatCorner {\n offset: vec2f,\n uv: vec2f,\n #if GSPLAT_AA\n aaFactor: f32,\n #endif\n}\nfn quatToMat3(R: vec4) -> mat3x3 {\n let R2: vec4 = R + R;\n let X: f32 = R2.x * R.w;\n let Y: vec4 = R2.y * R;\n let Z: vec4 = R2.z * R;\n let W: f32 = R2.w * R.w;\n return mat3x3(\n 1.0 - Z.z - W, Y.z + X, Y.w - Z.x,\n Y.z - X, 1.0 - Y.y - W, Z.w + Y.x,\n Y.w + Z.x, Z.w - Y.x, 1.0 - Y.y - Z.z\n );\n}\n#if SH_BANDS == 1\n const SH_COEFFS: i32 = 3;\n#elif SH_BANDS == 2\n const SH_COEFFS: i32 = 8;\n#elif SH_BANDS == 3\n const SH_COEFFS: i32 = 15;\n#else\n const SH_COEFFS: i32 = 0;\n#endif\n#if GSPLAT_COMPRESSED_DATA\n #include "gsplatCompressedDataVS"\n #if SH_BANDS > 0\n #include "gsplatCompressedSHVS"\n #endif\n#elif GSPLAT_SOGS_DATA\n #include "gsplatSogsDataVS"\n #include "gsplatSogsColorVS"\n #if SH_BANDS > 0\n #include "gsplatSogsSHVS"\n #endif\n#else\n #include "gsplatDataVS"\n #include "gsplatColorVS"\n #if SH_BANDS > 0\n #include "gsplatSHVS"\n #endif\n#endif\n#include "gsplatSourceVS"\n#include "gsplatCenterVS"\n#include "gsplatCornerVS"\n#include "gsplatOutputVS"\nfn clipCorner(corner: ptr, alpha: f32) {\n let clip: f32 = min(1.0, sqrt(-log(1.0 / (255.0 * alpha))) / 2.0);\n corner.offset = corner.offset * clip;\n corner.uv = corner.uv * clip;\n}\n#if SH_BANDS > 0\n const SH_C1: f32 = 0.4886025119029199;\n #if SH_BANDS > 1\n const SH_C2_0: f32 = 1.0925484305920792;\n const SH_C2_1: f32 = -1.0925484305920792;\n const SH_C2_2: f32 = 0.31539156525252005;\n const SH_C2_3: f32 = -1.0925484305920792;\n const SH_C2_4: f32 = 0.5462742152960396;\n #endif\n #if SH_BANDS > 2\n const SH_C3_0: f32 = -0.5900435899266435;\n const SH_C3_1: f32 = 2.890611442640554;\n const SH_C3_2: f32 = -0.4570457994644658;\n const SH_C3_3: f32 = 0.3731763325901154;\n const SH_C3_4: f32 = -0.4570457994644658;\n const SH_C3_5: f32 = 1.445305721320277;\n const SH_C3_6: f32 = -0.5900435899266435;\n #endif\n fn evalSH(source: ptr, dir: vec3f) -> vec3f {\n var sh: array;\n var scale: f32;\n readSHData(source, &sh, &scale);\n let x = dir.x;\n let y = dir.y;\n let z = dir.z;\n var result = SH_C1 * (-sh[0] * y + sh[1] * z - sh[2] * x);\n #if SH_BANDS > 1\n let xx = x * x;\n let yy = y * y;\n let zz = z * z;\n let xy = x * y;\n let yz = y * z;\n let xz = x * z;\n result = result + (\n sh[3] * (SH_C2_0 * xy) +\n sh[4] * (SH_C2_1 * yz) +\n sh[5] * (SH_C2_2 * (2.0 * zz - xx - yy)) +\n sh[6] * (SH_C2_3 * xz) +\n sh[7] * (SH_C2_4 * (xx - yy))\n );\n #endif\n #if SH_BANDS > 2\n result = result + (\n sh[8] * (SH_C3_0 * y * (3.0 * xx - yy)) +\n sh[9] * (SH_C3_1 * xy * z) +\n sh[10] * (SH_C3_2 * y * (4.0 * zz - xx - yy)) +\n sh[11] * (SH_C3_3 * z * (2.0 * zz - 3.0 * xx - 3.0 * yy)) +\n sh[12] * (SH_C3_4 * x * (4.0 * zz - xx - yy)) +\n sh[13] * (SH_C3_5 * z * (xx - yy)) +\n sh[14] * (SH_C3_6 * x * (xx - 3.0 * yy))\n );\n #endif\n return result * scale;\n }\n#endif\n',gsplatCompressedDataVS:"\nvar packedTexture: texture_2d;\nvar chunkTexture: texture_2d;\nvar chunkDataA: vec4f;\nvar chunkDataB: vec4f;\nvar chunkDataC: vec4f;\nvar chunkDataD: vec4f;\nvar chunkDataE: vec4f;\nvar packedData: vec4u;\nfn unpack111011(bits: u32) -> vec3f {\n return (vec3f((vec3(bits) >> vec3(21u, 11u, 0u)) & vec3(0x7ffu, 0x3ffu, 0x7ffu))) / vec3f(2047.0, 1023.0, 2047.0);\n}\nfn unpack8888(bits: u32) -> vec4f {\n return vec4f(\n f32((bits >> 24u) & 0xffu),\n f32((bits >> 16u) & 0xffu),\n f32((bits >> 8u) & 0xffu),\n f32(bits & 0xffu)\n ) / 255.0;\n}\nconst norm_const: f32 = 1.0 / (sqrt(2.0) * 0.5);\nfn unpackRotation(bits: u32) -> vec4f {\n let a = (f32((bits >> 20u) & 0x3ffu) / 1023.0 - 0.5) * norm_const;\n let b = (f32((bits >> 10u) & 0x3ffu) / 1023.0 - 0.5) * norm_const;\n let c = (f32(bits & 0x3ffu) / 1023.0 - 0.5) * norm_const;\n let m = sqrt(1.0 - (a * a + b * b + c * c));\n let mode = bits >> 30u;\n if (mode == 0u) { return vec4f(m, a, b, c); }\n if (mode == 1u) { return vec4f(a, m, b, c); }\n if (mode == 2u) { return vec4f(a, b, m, c); }\n return vec4f(a, b, c, m);\n}\nfn readCenter(source: ptr) -> vec3f {\n let tex_size_u = textureDimensions(chunkTexture, 0);\n let w: u32 = tex_size_u.x / 5u;\n let chunkId: u32 = source.id / 256u;\n let chunkUV: vec2 = vec2(i32((chunkId % w) * 5u), i32(chunkId / w));\n chunkDataA = textureLoad(chunkTexture, chunkUV + vec2(0, 0), 0);\n chunkDataB = textureLoad(chunkTexture, chunkUV + vec2(1, 0), 0);\n chunkDataC = textureLoad(chunkTexture, chunkUV + vec2(2, 0), 0);\n chunkDataD = textureLoad(chunkTexture, chunkUV + vec2(3, 0), 0);\n chunkDataE = textureLoad(chunkTexture, chunkUV + vec2(4, 0), 0);\n packedData = textureLoad(packedTexture, source.uv, 0);\n return mix(chunkDataA.xyz, vec3f(chunkDataA.w, chunkDataB.xy), unpack111011(packedData.x));\n}\nfn readColor(source: ptr) -> vec4f {\n let r = unpack8888(packedData.w);\n return vec4f(mix(chunkDataD.xyz, vec3f(chunkDataD.w, chunkDataE.xy), r.rgb), r.w);\n}\nfn getRotation() -> vec4f {\n return unpackRotation(packedData.y);\n}\nfn getScale() -> vec3f {\n return exp(mix(vec3f(chunkDataB.zw, chunkDataC.x), chunkDataC.yzw, unpack111011(packedData.z)));\n}\nfn readCovariance(source: ptr, covA_ptr: ptr, covB_ptr: ptr) {\n let rot = quatToMat3(getRotation());\n let scale = getScale();\n let M = transpose(mat3x3f(\n scale.x * rot[0],\n scale.y * rot[1],\n scale.z * rot[2]\n ));\n *covA_ptr = vec3f(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2]));\n *covB_ptr = vec3f(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2]));\n}\n",gsplatCompressedSHVS:"\n#if SH_BANDS > 0\nvar shTexture0: texture_2d;\nvar shTexture1: texture_2d;\nvar shTexture2: texture_2d;\nfn unpack8888s(bits: u32) -> vec4f {\n let unpacked_u = (vec4(bits) >> vec4(0u, 8u, 16u, 24u)) & vec4(0xffu);\n return vec4f(unpacked_u) * (8.0 / 255.0) - 4.0;\n}\nfn readSHData(source: ptr, sh: ptr>, scale: ptr) {\n let shData0: vec4 = textureLoad(shTexture0, source.uv, 0);\n let shData1: vec4 = textureLoad(shTexture1, source.uv, 0);\n let shData2: vec4 = textureLoad(shTexture2, source.uv, 0);\n let r0 = unpack8888s(shData0.x);\n let r1 = unpack8888s(shData0.y);\n let r2 = unpack8888s(shData0.z);\n let r3 = unpack8888s(shData0.w);\n let g0 = unpack8888s(shData1.x);\n let g1 = unpack8888s(shData1.y);\n let g2 = unpack8888s(shData1.z);\n let g3 = unpack8888s(shData1.w);\n let b0 = unpack8888s(shData2.x);\n let b1 = unpack8888s(shData2.y);\n let b2 = unpack8888s(shData2.z);\n let b3 = unpack8888s(shData2.w);\n sh[0] = vec3f(r0.x, g0.x, b0.x);\n sh[1] = vec3f(r0.y, g0.y, b0.y);\n sh[2] = vec3f(r0.z, g0.z, b0.z);\n sh[3] = vec3f(r0.w, g0.w, b0.w);\n sh[4] = vec3f(r1.x, g1.x, b1.x);\n sh[5] = vec3f(r1.y, g1.y, b1.y);\n sh[6] = vec3f(r1.z, g1.z, b1.z);\n sh[7] = vec3f(r1.w, g1.w, b1.w);\n sh[8] = vec3f(r2.x, g2.x, b2.x);\n sh[9] = vec3f(r2.y, g2.y, b2.y);\n sh[10] = vec3f(r2.z, g2.z, b2.z);\n sh[11] = vec3f(r2.w, g2.w, b2.w);\n sh[12] = vec3f(r3.x, g3.x, b3.x);\n sh[13] = vec3f(r3.y, g3.y, b3.y);\n sh[14] = vec3f(r3.z, g3.z, b3.z);\n *scale = 1.0;\n}\n#endif\n",gsplatSogsColorVS:"\nvar sh0: texture_2d;\nuniform sh0_mins: vec4f;\nuniform sh0_maxs: vec4f;\nconst SH_C0: f32 = 0.28209479177387814;\nfn readColor(source: ptr) -> vec4f {\n let clr: vec4f = mix(uniform.sh0_mins, uniform.sh0_maxs, textureLoad(sh0, source.uv, 0));\n return vec4f(vec3f(0.5) + clr.xyz * SH_C0, 1.0 / (1.0 + exp(-clr.w)));\n}\n",gsplatSogsDataVS:"\nvar means_u: texture_2d;\nvar means_l: texture_2d;\nvar quats: texture_2d;\nvar scales: texture_2d;\nuniform means_mins: vec3f;\nuniform means_maxs: vec3f;\nuniform scales_mins: vec3f;\nuniform scales_maxs: vec3f;\nfn readCenter(source: ptr) -> vec3f {\n let u: vec3f = textureLoad(means_u, source.uv, 0).xyz;\n let l: vec3f = textureLoad(means_l, source.uv, 0).xyz;\n let n: vec3f = (l * 255.0 + u * 255.0 * 256.0) / 65535.0;\n let v: vec3f = mix(uniform.means_mins, uniform.means_maxs, n);\n return sign(v) * (exp(abs(v)) - 1.0);\n}\nconst norm: f32 = 2.0 / sqrt(2.0);\nfn readCovariance(source: ptr, covA_ptr: ptr, covB_ptr: ptr) {\n let qdata: vec4f = textureLoad(quats, source.uv, 0);\n let abc: vec3f = (qdata.xyz - 0.5) * norm;\n let d: f32 = sqrt(max(0.0, 1.0 - dot(abc, abc)));\n let mode: u32 = u32(qdata.w * 255.0 + 0.5) - 252u;\n var quat: vec4f;\n if (mode == 0u) {\n quat = vec4f(d, abc);\n } else if (mode == 1u) {\n quat = vec4f(abc.x, d, abc.y, abc.z);\n } else if (mode == 2u) {\n quat = vec4f(abc.x, abc.y, d, abc.z);\n } else {\n quat = vec4f(abc.x, abc.y, abc.z, d);\n }\n let rot: mat3x3f = quatToMat3(quat);\n let scale: vec3f = exp(mix(uniform.scales_mins, uniform.scales_maxs, textureLoad(scales, source.uv, 0).xyz));\n let M: mat3x3f = transpose(mat3x3f(\n scale.x * rot[0],\n scale.y * rot[1],\n scale.z * rot[2]\n ));\n *covA_ptr = vec3f(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2]));\n *covB_ptr = vec3f(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2]));\n}\n",gsplatSogsSHVS:"\nvar sh_labels: texture_2d;\nvar sh_centroids: texture_2d;\nuniform shN_mins: f32;\nuniform shN_maxs: f32;\nfn readSHData(source: ptr, sh: ptr>, scale: ptr) {\n let t: vec2 = vec2(textureLoad(sh_labels, source.uv, 0).xy * 255.0);\n let n: i32 = t.x + t.y * 256;\n let u: i32 = (n % 64) * SH_COEFFS;\n let v: i32 = n / 64;\n for (var i: i32 = 0; i < SH_COEFFS; i = i + 1) {\n sh[i] = mix(vec3f(uniform.shN_mins), vec3f(uniform.shN_maxs), textureLoad(sh_centroids, vec2(u + i, v), 0).xyz);\n }\n *scale = 1.0;\n}\n",gsplatDataVS:"\nvar transformA: texture_2d;\nvar transformB: texture_2d;\nvar tAw: u32;\nfn readCenter(source: ptr) -> vec3f {\n let tA: vec4 = textureLoad(transformA, source.uv, 0);\n tAw = tA.w;\n return bitcast(tA.xyz);\n}\nfn unpackRotation(packed: vec3f) -> vec4f {\n return vec4f(packed.xyz, sqrt(max(0.0, 1.0 - dot(packed, packed))));\n}\nfn readCovariance(source: ptr, covA_ptr: ptr, covB_ptr: ptr) {\n let tB: vec4f = textureLoad(transformB, source.uv, 0);\n let rot: mat3x3f = quatToMat3(unpackRotation(vec3f(unpack2x16float(bitcast(tAw)), tB.w)).wxyz);\n let scale: vec3f = tB.xyz;\n let M = transpose(mat3x3f(\n scale.x * rot[0],\n scale.y * rot[1],\n scale.z * rot[2]\n ));\n *covA_ptr = vec3f(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2]));\n *covB_ptr = vec3f(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2]));\n}\n",gsplatOutputVS:'\n#include "tonemappingPS"\n#include "decodePS"\n#include "gammaPS"\nfn prepareOutputFromGamma(gammaColor: vec3f) -> vec3f {\n #if TONEMAP == NONE\n #if GAMMA == NONE\n return decodeGamma3(gammaColor);\n #else \n return gammaColor;\n #endif\n #else\n return gammaCorrectOutput(toneMap(decodeGamma3(gammaColor)));\n #endif\n}\n',gsplatPS:'\n#ifndef DITHER_NONE\n #include "bayerPS"\n #include "opacityDitherPS"\n varying id: f32;\n#endif\n#ifdef PICK_PASS\n #include "pickPS"\n#endif\n#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS)\n uniform alphaClip: f32;\n#endif\n#ifdef PREPASS_PASS\n varying vLinearDepth: f32;\n #include "floatAsUintPS"\n#endif\nconst EXP_A: f32 = 12102203.0;\nconst EXP_BC_RMS: i32 = 1064866808;\nfn fastExp(x: f32) -> f32 {\n var i: i32 = i32(EXP_A * x) + EXP_BC_RMS;\n return bitcast(i);\n}\nvarying gaussianUV: vec2f;\nvarying gaussianColor: vec4f;\n@fragment\nfn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n let A: f32 = dot(gaussianUV, gaussianUV);\n if (A > 1.0) {\n discard;\n return output;\n }\n var alpha: f32 = fastExp(-A * 4.0) * gaussianColor.a;\n #if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS)\n if (alpha < uniform.alphaClip) {\n discard;\n return output;\n }\n #endif\n #ifdef PICK_PASS\n output.color = getPickOutput();\n #elif SHADOW_PASS\n output.color = vec4f(0.0, 0.0, 0.0, 1.0);\n #elif PREPASS_PASS\n output.color = float2vec4(vLinearDepth);\n #else\n if (alpha < (1.0 / 255.0)) {\n discard;\n return output;\n }\n #ifndef DITHER_NONE\n opacityDither(&alpha, id * 0.013);\n #endif\n output.color = vec4f(input.gaussianColor.xyz * alpha, alpha);\n #endif\n return output;\n}',gsplatSHVS:"\n#if SH_BANDS > 0\nfn unpack111011s(bits: u32) -> vec3f {\n return (vec3f((vec3(bits) >> vec3(21u, 11u, 0u)) & vec3(0x7ffu, 0x3ffu, 0x7ffu)) / vec3f(2047.0, 1023.0, 2047.0)) * 2.0 - 1.0;\n}\nstruct ScaleAndSH {\n scale: f32,\n a: vec3f,\n b: vec3f,\n c: vec3f\n};\nfn fetchScale(t_in: vec4) -> ScaleAndSH {\n var result: ScaleAndSH;\n result.scale = bitcast(t_in.x);\n result.a = unpack111011s(t_in.y);\n result.b = unpack111011s(t_in.z);\n result.c = unpack111011s(t_in.w);\n return result;\n}\nstruct SH {\n a: vec3f,\n b: vec3f,\n c: vec3f,\n d: vec3f\n};\nfn fetch4(t_in: vec4) -> SH {\n var result: SH;\n result.a = unpack111011s(t_in.x);\n result.b = unpack111011s(t_in.y);\n result.c = unpack111011s(t_in.z);\n result.d = unpack111011s(t_in.w);\n return result;\n}\nfn fetch1(t_in: u32) -> vec3f {\n return unpack111011s(t_in);\n}\n#if SH_BANDS == 1\n var splatSH_1to3: texture_2d;\n fn readSHData(source: ptr, sh: ptr>, scale: ptr) {\n let result = fetchScale(textureLoad(splatSH_1to3, source.uv, 0));\n *scale = result.scale;\n sh[0] = result.a;\n sh[1] = result.b;\n sh[2] = result.c;\n }\n#elif SH_BANDS == 2\n var splatSH_1to3: texture_2d;\n var splatSH_4to7: texture_2d;\n var splatSH_8to11: texture_2d;\n fn readSHData(source: ptr, sh: ptr>, scale: ptr) {\n let first: ScaleAndSH = fetchScale(textureLoad(splatSH_1to3, source.uv, 0));\n *scale = first.scale;\n sh[0] = first.a;\n sh[1] = first.b;\n sh[2] = first.c;\n let second: SH = fetch4(textureLoad(splatSH_4to7, source.uv, 0));\n sh[3] = second.a;\n sh[4] = second.b;\n sh[5] = second.c;\n sh[6] = second.d;\n sh[7] = fetch1(textureLoad(splatSH_8to11, source.uv, 0).x);\n }\n#else\n var splatSH_1to3: texture_2d;\n var splatSH_4to7: texture_2d;\n var splatSH_8to11: texture_2d;\n var splatSH_12to15: texture_2d;\n fn readSHData(source: ptr, sh: ptr>, scale: ptr) {\n let first: ScaleAndSH = fetchScale(textureLoad(splatSH_1to3, source.uv, 0));\n *scale = first.scale;\n sh[0] = first.a;\n sh[1] = first.b;\n sh[2] = first.c;\n let second: SH = fetch4(textureLoad(splatSH_4to7, source.uv, 0));\n sh[3] = second.a;\n sh[4] = second.b;\n sh[5] = second.c;\n sh[6] = second.d;\n let third: SH = fetch4(textureLoad(splatSH_8to11, source.uv, 0));\n sh[7] = third.a;\n sh[8] = third.b;\n sh[9] = third.c;\n sh[10] = third.d;\n let fourth: SH = fetch4(textureLoad(splatSH_12to15, source.uv, 0));\n sh[11] = fourth.a;\n sh[12] = fourth.b;\n sh[13] = fourth.c;\n sh[14] = fourth.d;\n }\n#endif\n#endif\n",gsplatSourceVS:"\nattribute vertex_position: vec3f;\nattribute vertex_id_attrib: u32;\nuniform numSplats: u32;\nvar splatOrder: texture_2d;\nfn initSource(source: ptr) -> bool {\n let w: u32 = textureDimensions(splatOrder, 0).x;\n source.order = vertex_id_attrib + u32(vertex_position.z);\n if (source.order >= uniform.numSplats) {\n return false;\n }\n let orderUV = vec2i(vec2u(source.order % w, source.order / w));\n source.id = textureLoad(splatOrder, orderUV, 0).r;\n source.uv = vec2i(vec2u(source.id % w, source.id / w));\n source.cornerUV = vertex_position.xy;\n return true;\n}\n",gsplatVS:'\n#include "gsplatCommonVS"\nvarying gaussianUV: vec2f;\nvarying gaussianColor: vec4f;\n#ifndef DITHER_NONE\n varying id: f32;\n#endif\nconst discardVec: vec4f = vec4f(0.0, 0.0, 2.0, 1.0);\n#ifdef PREPASS_PASS\n varying vLinearDepth: f32;\n#endif\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n var source: SplatSource;\n if (!initSource(&source)) {\n output.position = discardVec;\n return output;\n }\n let modelCenter: vec3f = readCenter(&source);\n var center: SplatCenter;\n if (!initCenter(modelCenter, ¢er)) {\n output.position = discardVec;\n return output;\n }\n var corner: SplatCorner;\n if (!initCorner(&source, ¢er, &corner)) {\n output.position = discardVec;\n return output;\n }\n var clr: vec4f = readColor(&source);\n #if GSPLAT_AA\n clr.a = clr.a * corner.aaFactor;\n #endif\n #if SH_BANDS > 0\n let modelView3x3 = mat3x3f(center.modelView[0].xyz, center.modelView[1].xyz, center.modelView[2].xyz);\n let dir = normalize(modelView3x3 * center.view);\n clr = vec4f(clr.xyz + evalSH(&source, dir), clr.a);\n #endif\n clipCorner(&corner, clr.w);\n output.position = center.proj + vec4f(corner.offset, 0.0, 0.0);\n output.gaussianUV = corner.uv;\n output.gaussianColor = vec4f(prepareOutputFromGamma(max(clr.xyz, vec3f(0.0))), clr.w);\n #ifndef DITHER_NONE\n output.id = f32(source.id);\n #endif\n #ifdef PREPASS_PASS\n output.vLinearDepth = -center.view.z;\n #endif\n return output;\n}\n',quadVS:"\n attribute aPosition: vec2f;\n varying uv0: vec2f;\n @vertex fn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n output.position = vec4f(input.aPosition, 0.0, 1.0);\n output.uv0 = getImageEffectUV((input.aPosition + 1.0) * 0.5);\n return output;\n }\n",immediateLinePS:'\n #include "gammaPS"\n varying color: vec4f;\n @fragment\n fn fragmentMain(input : FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n output.color = vec4f(gammaCorrectOutput(decodeGamma3(input.color.rgb)), input.color.a);\n return output;\n }\n',immediateLineVS:"\n attribute vertex_position: vec4f;\n attribute vertex_color: vec4f;\n uniform matrix_model: mat4x4f;\n uniform matrix_viewProjection: mat4x4f;\n varying color: vec4f;\n @vertex\n fn vertexMain(input : VertexInput) -> VertexOutput {\n var output : VertexOutput;\n output.color = input.vertex_color;\n output.position = uniform.matrix_viewProjection * uniform.matrix_model * input.vertex_position;\n return output;\n }\n",iridescenceDiffractionPS:"\nuniform material_iridescenceRefractionIndex: f32;\nfn iridescence_iorToFresnelScalar(transmittedIor: f32, incidentIor: f32) -> f32 {\n return pow((transmittedIor - incidentIor) / (transmittedIor + incidentIor), 2.0);\n}\nfn iridescence_iorToFresnelVec3(transmittedIor: vec3f, incidentIor: f32) -> vec3f {\n return pow((transmittedIor - vec3f(incidentIor)) / (transmittedIor + vec3f(incidentIor)), vec3f(2.0));\n}\nfn iridescence_fresnelToIor(f0: vec3f) -> vec3f {\n let sqrtF0: vec3f = sqrt(f0);\n return (vec3f(1.0) + sqrtF0) / (vec3f(1.0) - sqrtF0);\n}\nconst XYZ_TO_REC709: mat3x3f = mat3x3f(\n vec3f(3.2404542, -1.5371385, -0.4985314),\n vec3f(-0.9692660, 1.8760108, 0.0415560),\n vec3f(0.0556434, -0.2040259, 1.0572252)\n);\nfn iridescence_sensitivity(opd: f32, shift: vec3f) -> vec3f {\n let PI: f32 = 3.141592653589793;\n let phase: f32 = 2.0 * PI * opd * 1.0e-9;\n const val: vec3f = vec3f(5.4856e-13, 4.4201e-13, 5.2481e-13);\n const pos: vec3f = vec3f(1.6810e+06, 1.7953e+06, 2.2084e+06);\n const var_: vec3f = vec3f(4.3278e+09, 9.3046e+09, 6.6121e+09);\n var xyz: vec3f = val * sqrt(2.0 * PI * var_) * cos(pos * phase + shift) * exp(-pow(phase, 2.0) * var_);\n xyz.x = xyz.x + 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift[0]) * exp(-4.5282e+09 * pow(phase, 2.0));\n xyz = xyz / vec3f(1.0685e-07);\n return XYZ_TO_REC709 * xyz;\n}\nfn iridescence_fresnelScalar(cosTheta: f32, f0: f32) -> f32 {\n let x: f32 = clamp(1.0 - cosTheta, 0.0, 1.0);\n let x2: f32 = x * x;\n let x5: f32 = x * x2 * x2;\n return f0 + (1.0 - f0) * x5;\n}\nfn iridescence_fresnelVec3(cosTheta: f32, f0: vec3f) -> vec3f {\n let x: f32 = clamp(1.0 - cosTheta, 0.0, 1.0);\n let x2: f32 = x * x;\n let x5: f32 = x * x2 * x2;\n return f0 + (vec3f(1.0) - f0) * x5;\n}\nfn calcIridescence(outsideIor: f32, cosTheta: f32, base_f0: vec3f, iridescenceThickness: f32) -> vec3f {\n let PI: f32 = 3.141592653589793;\n let iridescenceIor: f32 = mix(outsideIor, uniform.material_iridescenceRefractionIndex, smoothstep(0.0, 0.03, iridescenceThickness));\n let sinTheta2Sq: f32 = pow(outsideIor / iridescenceIor, 2.0) * (1.0 - pow(cosTheta, 2.0));\n let cosTheta2Sq: f32 = 1.0 - sinTheta2Sq;\n if (cosTheta2Sq < 0.0) {\n return vec3f(1.0);\n }\n let cosTheta2: f32 = sqrt(cosTheta2Sq);\n let r0: f32 = iridescence_iorToFresnelScalar(iridescenceIor, outsideIor);\n let r12: f32 = iridescence_fresnelScalar(cosTheta, r0);\n let r21: f32 = r12;\n let t121: f32 = 1.0 - r12;\n let phi12: f32 = select(0.0, PI, iridescenceIor < outsideIor);\n let phi21: f32 = PI - phi12;\n let baseIor: vec3f = iridescence_fresnelToIor(base_f0 + vec3f(0.0001));\n let r1: vec3f = iridescence_iorToFresnelVec3(baseIor, iridescenceIor);\n let r23: vec3f = iridescence_fresnelVec3(cosTheta2, r1);\n let phi23: vec3f = select(vec3f(0.0), vec3f(PI), baseIor < vec3f(iridescenceIor));\n let opd: f32 = 2.0 * iridescenceIor * iridescenceThickness * cosTheta2;\n let phi: vec3f = vec3f(phi21) + phi23;\n let r123Sq: vec3f = clamp(vec3f(r12) * r23, vec3f(1e-5), vec3f(0.9999));\n let r123: vec3f = sqrt(r123Sq);\n let rs: vec3f = pow(vec3f(t121), vec3f(2.0)) * r23 / (vec3f(1.0) - r123Sq);\n let c0: vec3f = vec3f(r12) + rs;\n var i_irid: vec3f = c0;\n var cm: vec3f = rs - vec3f(t121);\n cm = cm * r123;\n let sm1: vec3f = 2.0 * iridescence_sensitivity(1.0 * opd, 1.0 * phi);\n i_irid = i_irid + cm * sm1;\n cm = cm * r123;\n let sm2: vec3f = 2.0 * iridescence_sensitivity(2.0 * opd, 2.0 * phi);\n i_irid = i_irid + cm * sm2;\n return max(i_irid, vec3f(0.0));\n}\nfn getIridescenceDiffraction(cosTheta: f32, specularity: vec3f, iridescenceThickness: f32) -> vec3f {\n return calcIridescence(1.0, cosTheta, specularity, iridescenceThickness);\n}\n",iridescencePS:"\n#ifdef STD_IRIDESCENCE_CONSTANT\n uniform material_iridescence: f32;\n#endif\nfn getIridescence() {\n var iridescence = 1.0;\n #ifdef STD_IRIDESCENCE_CONSTANT\n iridescence = iridescence * uniform.material_iridescence;\n #endif\n #ifdef STD_IRIDESCENCE_TEXTURE\n iridescence = iridescence * textureSampleBias({STD_IRIDESCENCE_TEXTURE_NAME}, {STD_IRIDESCENCE_TEXTURE_NAME}Sampler, {STD_IRIDESCENCE_TEXTURE_UV}, uniform.textureBias).{STD_IRIDESCENCE_TEXTURE_CHANNEL};\n #endif\n dIridescence = iridescence; \n}\n",iridescenceThicknessPS:"\nuniform material_iridescenceThicknessMax: f32;\n#ifdef STD_IRIDESCENCETHICKNESS_TEXTURE\n uniform material_iridescenceThicknessMin: f32;\n#endif\nfn getIridescenceThickness() {\n #ifdef STD_IRIDESCENCETHICKNESS_TEXTURE\n var blend: f32 = textureSampleBias({STD_IRIDESCENCETHICKNESS_TEXTURE_NAME}, {STD_IRIDESCENCETHICKNESS_TEXTURE_NAME}Sampler, {STD_IRIDESCENCETHICKNESS_TEXTURE_UV}, uniform.textureBias).{STD_IRIDESCENCETHICKNESS_TEXTURE_CHANNEL};\n var iridescenceThickness: f32 = mix(uniform.material_iridescenceThicknessMin, uniform.material_iridescenceThicknessMax, blend);\n #else\n var iridescenceThickness: f32 = uniform.material_iridescenceThicknessMax;\n #endif\n dIridescenceThickness = iridescenceThickness; \n}\n",iorPS:"\n#ifdef STD_IOR_CONSTANT\n uniform material_refractionIndex: f32;\n#endif\nfn getIor() {\n#ifdef STD_IOR_CONSTANT\n dIor = uniform.material_refractionIndex;\n#else\n dIor = 1.0 / 1.5;\n#endif\n}\n",lightDeclarationPS:"\n#if defined(LIGHT{i})\n uniform light{i}_color: vec3f;\n #if LIGHT{i}TYPE == DIRECTIONAL\n uniform light{i}_direction: vec3f;\n #else\n #define LIT_CODE_LIGHTS_POINT\n uniform light{i}_position: vec3f;\n uniform light{i}_radius: f32;\n #if LIGHT{i}TYPE == SPOT\n #define LIT_CODE_LIGHTS_SPOT\n uniform light{i}_direction: vec3f;\n uniform light{i}_innerConeAngle: f32;\n uniform light{i}_outerConeAngle: f32;\n #endif\n #endif\n #if LIGHT{i}SHAPE != PUNCTUAL\n #define LIT_CODE_FALLOFF_SQUARED\n #if LIGHT{i}TYPE == DIRECTIONAL\n uniform light{i}_position: vec3f;\n #endif\n uniform light{i}_halfWidth: vec3f;\n uniform light{i}_halfHeight: vec3f;\n #else\n #if LIGHT{i}FALLOFF == LINEAR\n #define LIT_CODE_FALLOFF_LINEAR\n #endif\n #if LIGHT{i}FALLOFF == INVERSESQUARED\n #define LIT_CODE_FALLOFF_SQUARED\n #endif\n #endif\n #if defined(LIGHT{i}CASTSHADOW)\n uniform light{i}_shadowMatrix: mat4x4f;\n uniform light{i}_shadowIntensity: f32;\n uniform light{i}_shadowParams: vec4f;\n #if LIGHT{i}SHADOWTYPE == PCSS_32F\n uniform light{i}_shadowSearchArea: f32;\n uniform light{i}_cameraParams: vec4f;\n #if LIGHT{i}TYPE == DIRECTIONAL\n uniform light{i}_softShadowParams: vec4f;\n #endif\n #endif\n #if LIGHT{i}TYPE == DIRECTIONAL\n uniform light{i}_shadowMatrixPalette: array;\n uniform light{i}_shadowCascadeDistances: vec4f;\n uniform light{i}_shadowCascadeCount: i32;\n uniform light{i}_shadowCascadeBlend: f32;\n #endif\n #if LIGHT{i}TYPE == OMNI\n NOT SUPPORTED\n \n #else\n #if defined(LIGHT{i}SHADOW_PCF)\n var light{i}_shadowMap: texture_depth_2d;\n var light{i}_shadowMapSampler: sampler_comparison;\n #else\n var light{i}_shadowMap: texture_2d;\n var light{i}_shadowMapSampler: sampler;\n #endif\n #endif\n #endif\n #if defined(LIGHT{i}COOKIE)\n #define LIT_CODE_COOKIE\n #if LIGHT{i}TYPE == OMNI\n NOT SUPPORTED\n #endif\n #if LIGHT{i}TYPE == SPOT\n NOT SUPPORTED\n #endif\n #endif\n#endif\n",lightDiffuseLambertPS:"\nfn getLightDiffuse(worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f) -> f32 {\n return max(dot(worldNormal, -lightDirNorm), 0.0);\n}\n",lightDirPointPS:"\nfn evalOmniLight(lightPosW: vec3f) -> vec3f {\n return vPositionW - lightPosW;\n}\n",lightEvaluationPS:"\n#if defined(LIGHT{i})\n evaluateLight{i}(\n #if defined(LIT_IRIDESCENCE)\n iridescenceFresnel\n #endif\n );\n#endif\n",lightFunctionLightPS:"\n#if defined(LIGHT{i})\nfn evaluateLight{i}(\n #if defined(LIT_IRIDESCENCE)\n iridescenceFresnel: vec3f\n #endif\n) {\n var lightColor: vec3f = uniform.light{i}_color;\n #if LIGHT{i}TYPE == DIRECTIONAL && !defined(LIT_SHADOW_CATCHER)\n if (all(lightColor == vec3f(0.0, 0.0, 0.0))) {\n return;\n }\n #endif\n #if LIGHT{i}TYPE == DIRECTIONAL\n dLightDirNormW = uniform.light{i}_direction;\n dAtten = 1.0;\n #else\n var lightDirW: vec3f = evalOmniLight(uniform.light{i}_position);\n dLightDirNormW = normalize(lightDirW);\n #if defined(LIGHT{i}COOKIE)\n #if LIGHT{i}TYPE == SPOT\n #ifdef LIGHT{i}COOKIE_FALLOFF\n #ifdef LIGHT{i}COOKIE_TRANSFORM\n var cookieAttenuation: vec3f = getCookie2DXform(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity, uniform.light{i}_cookieMatrix, uniform.light{i}_cookieOffset).{LIGHT{i}COOKIE_CHANNEL};\n #else\n var cookieAttenuation: vec3f = getCookie2D(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};\n #endif\n #else\n #ifdef LIGHT{i}COOKIE_TRANSFORM\n var cookieAttenuation: vec3f = getCookie2DClipXform(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity, uniform.light{i}_cookieMatrix, uniform.light{i}_cookieOffset).{LIGHT{i}COOKIE_CHANNEL};\n #else\n var cookieAttenuation: vec3f = getCookie2DClip(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};\n #endif\n #endif\n #endif\n #if LIGHT{i}TYPE == OMNI\n var cookieAttenuation: vec3f = getCookieCube(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};\n #endif\n lightColor = lightColor * cookieAttenuation;\n #endif\n #if LIGHT{i}SHAPE == PUNCTUAL\n #if LIGHT{i}FALLOFF == LINEAR\n dAtten = getFalloffLinear(uniform.light{i}_radius, lightDirW);\n #else\n dAtten = getFalloffInvSquared(uniform.light{i}_radius, lightDirW);\n #endif\n #else\n dAtten = getFalloffWindow(uniform.light{i}_radius, lightDirW);\n #endif\n #if LIGHT{i}TYPE == SPOT\n #if !defined(LIGHT{i}COOKIE) || defined(LIGHT{i}COOKIE_FALLOFF)\n dAtten = dAtten * getSpotEffect(uniform.light{i}_direction, uniform.light{i}_innerConeAngle, uniform.light{i}_outerConeAngle, dLightDirNormW);\n #endif\n #endif\n #endif\n if (dAtten < 0.00001) {\n return;\n }\n #if LIGHT{i}SHAPE != PUNCTUAL\n #if LIGHT{i}SHAPE == RECT\n calcRectLightValues(uniform.light{i}_position, uniform.light{i}_halfWidth, uniform.light{i}_halfHeight);\n #elif LIGHT{i}SHAPE == DISK\n calcDiskLightValues(uniform.light{i}_position, uniform.light{i}_halfWidth, uniform.light{i}_halfHeight);\n #elif LIGHT{i}SHAPE == SPHERE\n calcSphereLightValues(uniform.light{i}_position, uniform.light{i}_halfWidth, uniform.light{i}_halfHeight);\n #endif\n #endif\n #if LIGHT{i}SHAPE != PUNCTUAL\n #if LIGHT{i}TYPE == DIRECTIONAL\n var attenDiffuse: f32 = getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirNormW);\n #else\n #if LIGHT{i}SHAPE == RECT\n var attenDiffuse: f32 = getRectLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;\n #elif LIGHT{i}SHAPE == DISK\n var attenDiffuse: f32 = getDiskLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;\n #elif LIGHT{i}SHAPE == SPHERE\n var attenDiffuse: f32 = getSphereLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;\n #endif\n #endif\n #else\n dAtten = dAtten * getLightDiffuse(litArgs_worldNormal, vec3(0.0), dLightDirNormW);\n #endif\n #ifdef LIGHT{i}CASTSHADOW\n #if LIGHT{i}TYPE == DIRECTIONAL\n var shadow: f32 = getShadow{i}(vec3(0.0));\n #else\n var shadow: f32 = getShadow{i}(lightDirW);\n #endif\n shadow = mix(1.0, shadow, uniform.light{i}_shadowIntensity);\n dAtten = dAtten * shadow;\n #if defined(LIT_SHADOW_CATCHER) && LIGHT{i}TYPE == DIRECTIONAL\n dShadowCatcher = dShadowCatcher * shadow;\n #endif \n #endif\n #if LIGHT{i}SHAPE != PUNCTUAL\n #ifdef LIT_SPECULAR\n dDiffuseLight = dDiffuseLight + (((attenDiffuse * dAtten) * lightColor) * (1.0 - dLTCSpecFres));\n #else\n dDiffuseLight = dDiffuseLight + ((attenDiffuse * dAtten) * lightColor);\n #endif \n #else\n #if defined(AREA_LIGHTS) && defined(LIT_SPECULAR)\n dDiffuseLight = dDiffuseLight + ((dAtten * lightColor) * (1.0 - litArgs_specularity));\n #else\n dDiffuseLight = dDiffuseLight + (dAtten * lightColor);\n #endif\n #endif\n #ifdef LIGHT{i}AFFECT_SPECULARITY\n #if LIGHT{i}SHAPE != PUNCTUAL\n #ifdef LIT_CLEARCOAT\n #if LIGHT{i}SHAPE == RECT\n ccSpecularLight = ccSpecularLight + (ccLTCSpecFres * getRectLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor);\n #elif LIGHT{i}SHAPE == DISK\n ccSpecularLight = ccSpecularLight + (ccLTCSpecFres * getDiskLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor);\n #elif LIGHT{i}SHAPE == SPHERE\n ccSpecularLight = ccSpecularLight + (ccLTCSpecFres * getSphereLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor);\n #endif\n #endif\n #ifdef LIT_SPECULAR\n #if LIGHT{i}SHAPE == RECT\n dSpecularLight = dSpecularLight + (dLTCSpecFres * getRectLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor);\n #elif LIGHT{i}SHAPE == DISK\n dSpecularLight = dSpecularLight + (dLTCSpecFres * getDiskLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor);\n #elif LIGHT{i}SHAPE == SPHERE\n dSpecularLight = dSpecularLight + (dLTCSpecFres * getSphereLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor);\n #endif\n #endif\n #else\n #if LIGHT{i}TYPE == DIRECTIONAL && LIT_FRESNEL_MODEL != NONE\n #define LIGHT{i}FRESNEL\n #endif\n #ifdef LIT_SPECULAR\n var halfDirW: vec3f = normalize(-dLightDirNormW + dViewDirW);\n #endif\n #ifdef LIT_CLEARCOAT\n var lightspecularCC: vec3f = getLightSpecular(halfDirW, ccReflDirW, litArgs_clearcoat_worldNormal, dViewDirW, dLightDirNormW, litArgs_clearcoat_gloss, dTBN) * dAtten * lightColor;\n #ifdef LIGHT{i}FRESNEL\n lightspecularCC = lightspecularCC * getFresnelCC(dot(dViewDirW, halfDirW));\n #endif\n ccSpecularLight = ccSpecularLight + lightspecularCC;\n #endif\n #ifdef LIT_SHEEN\n sSpecularLight = sSpecularLight + (getLightSpecularSheen(halfDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_sheen_gloss) * dAtten * lightColor);\n #endif\n #ifdef LIT_SPECULAR\n var lightSpecular: vec3f = getLightSpecular(halfDirW, dReflDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_gloss, dTBN) * dAtten * lightColor;\n #ifdef LIGHT{i}FRESNEL\n #if defined(LIT_IRIDESCENCE)\n lightSpecular = lightSpecular * getFresnel(dot(dViewDirW, halfDirW), litArgs_gloss, litArgs_specularity, iridescenceFresnel, litArgs_iridescence_intensity);\n #else\n lightSpecular = lightSpecular * getFresnel(dot(dViewDirW, halfDirW), litArgs_gloss, litArgs_specularity);\n #endif\n #else\n lightSpecular = lightSpecular * litArgs_specularity;\n #endif\n \n dSpecularLight = dSpecularLight + lightSpecular;\n #endif\n #endif\n #endif\n}\n#endif\n",lightFunctionShadowPS:"\n#ifdef LIGHT{i}CASTSHADOW\n fn getShadowSampleCoord{i}(shadowTransform: mat4x4f, shadowParams: vec4f, worldPosition: vec3f, lightPos: vec3f, lightDir: ptr, lightDirNorm: vec3f, normal: vec3f) -> vec3f {\n var surfacePosition = worldPosition;\n #ifdef LIGHT{i}_SHADOW_SAMPLE_POINT\n #ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET\n let distScale: f32 = length(*lightDir);\n surfacePosition = surfacePosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;\n *lightDir = surfacePosition - lightPos;\n return *lightDir;\n #endif\n #else\n #ifdef LIGHT{i}_SHADOW_SAMPLE_SOURCE_ZBUFFER\n #ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET\n surfacePosition = surfacePosition + normal * shadowParams.y;\n #endif\n #else\n #ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET\n #ifdef LIGHT{i}_SHADOW_SAMPLE_ORTHO\n var distScale: f32 = 1.0;\n #else\n var distScale: f32 = abs(dot(vPositionW - lightPos, lightDirNorm));\n #endif\n surfacePosition = surfacePosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;\n #endif\n #endif\n var positionInShadowSpace: vec4f = shadowTransform * vec4f(surfacePosition, 1.0);\n #ifdef LIGHT{i}_SHADOW_SAMPLE_ORTHO\n positionInShadowSpace.z = saturate(positionInShadowSpace.z) - 0.0001;\n #else\n #ifdef LIGHT{i}_SHADOW_SAMPLE_SOURCE_ZBUFFER\n positionInShadowSpace.xyz = positionInShadowSpace.xyz / positionInShadowSpace.w;\n #else\n positionInShadowSpace.xy = positionInShadowSpace.xy / positionInShadowSpace.w;\n positionInShadowSpace.z = length(*lightDir) * shadowParams.w;\n #endif\n #endif\n #ifdef SHADOW_SAMPLE_Z_BIAS\n #endif\n surfacePosition = positionInShadowSpace.xyz;\n #endif\n return surfacePosition;\n }\n fn getShadow{i}(lightDirW_in: vec3f) -> f32 {\n #ifdef LIGHT{i}_SHADOW_CASCADES\n var cascadeIndex: i32 = getShadowCascadeIndex(uniform.light{i}_shadowCascadeDistances, uniform.light{i}_shadowCascadeCount);\n #ifdef LIGHT{i}_SHADOW_CASCADE_BLEND\n cascadeIndex = ditherShadowCascadeIndex(cascadeIndex, uniform.light{i}_shadowCascadeDistances, uniform.light{i}_shadowCascadeCount, uniform.light{i}_shadowCascadeBlend);\n #endif\n var shadowMatrix: mat4x4f = uniform.light{i}_shadowMatrixPalette[cascadeIndex];\n #else\n var shadowMatrix: mat4x4f = uniform.light{i}_shadowMatrix;\n #endif\n var lightDirArg = lightDirW_in;\n #if LIGHT{i}TYPE == DIRECTIONAL\n var shadowCoord: vec3f = getShadowSampleCoord{i}(shadowMatrix, uniform.light{i}_shadowParams, vPositionW, vec3f(0.0), &lightDirArg, dLightDirNormW, dVertexNormalW);\n #else\n var shadowCoord: vec3f = getShadowSampleCoord{i}(shadowMatrix, uniform.light{i}_shadowParams, vPositionW, uniform.light{i}_position, &lightDirArg, dLightDirNormW, dVertexNormalW);\n #endif\n #if LIGHT{i}TYPE == DIRECTIONAL\n shadowCoord = fadeShadow(shadowCoord, uniform.light{i}_shadowCascadeDistances);\n #endif\n #if LIGHT{i}TYPE == DIRECTIONAL\n #if LIGHT{i}SHADOWTYPE == VSM_16F\n return getShadowVSM16(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, 5.54);\n #endif\n #if LIGHT{i}SHADOWTYPE == VSM_32F\n return getShadowVSM32(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, 15.0);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCSS_32F\n #if LIGHT{i}SHAPE != PUNCTUAL\n let shadowSearchArea = vec2f(length(uniform.light{i}_halfWidth), length(uniform.light{i}_halfHeight)) * uniform.light{i}_shadowSearchArea;\n return getShadowPCSS(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, uniform.light{i}_cameraParams, shadowSearchArea, lightDirW_in);\n #else\n return getShadowPCSS(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, uniform.light{i}_cameraParams, uniform.light{i}_softShadowParams, lightDirW_in);\n #endif\n #endif\n #if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F\n return getShadowPCF1x1(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F\n return getShadowPCF3x3(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCF5_16F || LIGHT{i}SHADOWTYPE == PCF5_32F\n return getShadowPCF5x5(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);\n #endif\n #endif\n #if LIGHT{i}TYPE == SPOT\n #if LIGHT{i}SHADOWTYPE == VSM_16F\n return getShadowSpotVSM16(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, 5.54, lightDirW_in);\n #endif\n #if LIGHT{i}SHADOWTYPE == VSM_32F\n return getShadowSpotVSM32(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, 15.0, lightDirW_in);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCSS_32F\n #if LIGHT{i}SHAPE != PUNCTUAL\n var shadowSearchArea: vec2f = vec2f(length(uniform.light{i}_halfWidth), length(uniform.light{i}_halfHeight)) * uniform.light{i}_shadowSearchArea;\n #else\n var shadowSearchArea: vec2f = vec2f(uniform.light{i}_shadowSearchArea);\n #endif\n return getShadowSpotPCSS(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, uniform.light{i}_cameraParams, shadowSearchArea, lightDirW_in);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F\n return getShadowSpotPCF1x1(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F\n return getShadowSpotPCF3x3(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCF5_16F || LIGHT{i}SHADOWTYPE == PCF5_32F\n return getShadowSpotPCF5x5(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);\n #endif\n #endif\n #if LIGHT{i}TYPE == OMNI\n #if LIGHT{i}SHADOWTYPE == PCSS_32F\n var shadowSearchArea: vec2f;\n #if LIGHT{i}SHAPE != PUNCTUAL\n var shadowSearchArea: vec2f = vec2f(length(uniform.light{i}_halfWidth), length(uniform.light{i}_halfHeight)) * uniform.light{i}_shadowSearchArea;\n #else\n var shadowSearchArea: vec2f = vec2f(uniform.light{i}_shadowSearchArea);\n #endif\n return getShadowOmniPCSS(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, uniform.light{i}_cameraParams, shadowSearchArea, lightDirW_in);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F\n return getShadowOmniPCF1x1(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, lightDirW_in);\n #endif\n #if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F\n return getShadowOmniPCF3x3(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, lightDirW_in);\n #endif\n #endif\n }\n#endif\n",lightingPS:'\n#ifdef LIT_CLUSTERED_LIGHTS\n #define LIT_CODE_FALLOFF_LINEAR\n #define LIT_CODE_FALLOFF_SQUARED\n #define LIT_CODE_LIGHTS_POINT\n #define LIT_CODE_LIGHTS_SPOT\n#endif\n#ifdef AREA_LIGHTS\n var areaLightsLutTex1: texture_2d;\n var areaLightsLutTex1Sampler: sampler;\n var areaLightsLutTex2: texture_2d;\n var areaLightsLutTex2Sampler: sampler;\n#endif\n#ifdef LIT_LIGHTING\n #include "lightDiffuseLambertPS"\n #if defined(AREA_LIGHTS) || defined(LIT_CLUSTERED_AREA_LIGHTS)\n #include "ltcPS"\n #endif\n#endif\n#ifdef SHADOW_DIRECTIONAL\n #include "shadowCascadesPS"\n#endif\n#if defined(SHADOW_KIND_PCF1)\n #include "shadowPCF1PS"\n#endif\n#if defined(SHADOW_KIND_PCF3)\n #include "shadowPCF3PS"\n#endif\n#if defined(SHADOW_KIND_PCF5)\n #include "shadowPCF5PS"\n#endif\n#if defined(SHADOW_KIND_PCSS)\n #include "linearizeDepthPS"\n #include "shadowSoftPS"\n#endif\n#if defined(SHADOW_KIND_VSM)\n #include "shadowEVSMPS"\n#endif\n#ifdef LIT_CODE_FALLOFF_LINEAR\n #include "falloffLinearPS"\n#endif\n#ifdef LIT_CODE_FALLOFF_SQUARED\n #include "falloffInvSquaredPS"\n#endif\n#ifdef LIT_CODE_LIGHTS_POINT\n #include "lightDirPointPS"\n#endif\n#ifdef LIT_CODE_LIGHTS_SPOT\n #include "spotPS"\n#endif\n#ifdef LIT_CODE_COOKIE\n #include "cookiePS"\n#endif\n#ifdef LIT_CLUSTERED_LIGHTS\n #include "clusteredLightPS"\n#endif\n#ifdef LIGHT_COUNT > 0\n #include "lightFunctionShadowPS, LIGHT_COUNT"\n #include "lightFunctionLightPS, LIGHT_COUNT"\n#endif\n',lightmapAddPS:"\nfn addLightMap(\n lightmap: vec3f,\n dir: vec3f,\n worldNormal: vec3f,\n viewDir: vec3f,\n reflectionDir: vec3f,\n gloss: f32,\n specularity: vec3f,\n vertexNormal: vec3f,\n tbn: mat3x3f\n#if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel: vec3f,\n iridescenceIntensity: f32\n#endif\n) {\n #if defined(LIT_SPECULAR) && defined(LIT_DIR_LIGHTMAP)\n if (dot(dir, dir) < 0.0001) {\n dDiffuseLight = dDiffuseLight + lightmap;\n } else {\n let vlight: f32 = saturate(dot(dir, -vertexNormal));\n let flight: f32 = saturate(dot(dir, -worldNormal));\n let nlight: f32 = (flight / max(vlight, 0.01)) * 0.5;\n dDiffuseLight = dDiffuseLight + lightmap * nlight * 2.0;\n let halfDir: vec3f = normalize(-dir + viewDir);\n var specularLight: vec3f = lightmap * getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, dir, gloss, tbn);\n #ifdef LIT_SPECULAR_FRESNEL\n specularLight = specularLight *\n getFresnel(dot(viewDir, halfDir),\n gloss,\n specularity\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n iridescenceIntensity\n #endif\n );\n #endif\n dSpecularLight = dSpecularLight + specularLight;\n }\n #else\n dDiffuseLight = dDiffuseLight + lightmap;\n #endif\n}\n",lightmapPS:"\n#ifdef STD_LIGHTMAP_DIR\n var dLightmapDir: vec3f;\n var texture_dirLightMap: texture_2d;\n var texture_dirLightMapSampler: sampler;\n#endif\nfn getLightMap() {\n dLightmap = vec3f(1.0);\n #ifdef STD_LIGHT_TEXTURE\n dLightmap = dLightmap * {STD_LIGHT_TEXTURE_DECODE}(textureSampleBias({STD_LIGHT_TEXTURE_NAME}, {STD_LIGHT_TEXTURE_NAME}Sampler, {STD_LIGHT_TEXTURE_UV}, uniform.textureBias)).{STD_LIGHT_TEXTURE_CHANNEL};\n #ifdef STD_LIGHTMAP_DIR\n var dir: vec3f = textureSampleBias(texture_dirLightMap, texture_dirLightMapSampler, {STD_LIGHT_TEXTURE_UV}, uniform.textureBias).xyz * 2.0 - 1.0;\n var dirDot = dot(dir, dir);\n dLightmapDir = select(vec3(0.0), dir / sqrt(dirDot), dirDot > 0.001);\n #endif\n #endif\n #ifdef STD_LIGHT_VERTEX\n dLightmap = dLightmap * saturate(vVertexColor.{STD_LIGHT_VERTEX_CHANNEL});\n #endif\n}\n",lightSpecularAnisoGGXPS:"\nfn calcLightSpecular(gloss: f32, worldNormal: vec3f, viewDir: vec3f, h: vec3f, lightDirNorm: vec3f, tbn: mat3x3f) -> f32 {\n let PI: f32 = 3.141592653589793;\n let roughness: f32 = max((1.0 - gloss) * (1.0 - gloss), 0.001);\n let alphaRoughness: f32 = roughness * roughness;\n let anisotropy: f32 = dAnisotropy;\n let direction: vec2f = dAnisotropyRotation;\n let at: f32 = mix(alphaRoughness, 1.0, anisotropy * anisotropy);\n let ab: f32 = clamp(alphaRoughness, 0.001, 1.0);\n let anisotropicT: vec3f = normalize(tbn * vec3f(direction, 0.0));\n let anisotropicB: vec3f = normalize(cross(tbn[2], anisotropicT));\n let NoH: f32 = dot(worldNormal, h);\n let ToH: f32 = dot(anisotropicT, h);\n let BoH: f32 = dot(anisotropicB, h);\n let a2: f32 = at * ab;\n let v: vec3f = vec3f(ab * ToH, at * BoH, a2 * NoH);\n let v2: f32 = dot(v, v);\n let w2: f32 = a2 / v2;\n let D: f32 = a2 * w2 * w2 * (1.0 / PI);\n let ToV: f32 = dot(anisotropicT, viewDir);\n let BoV: f32 = dot(anisotropicB, viewDir);\n let ToL: f32 = dot(anisotropicT, -lightDirNorm);\n let BoL: f32 = dot(anisotropicB, -lightDirNorm);\n let NoV: f32 = dot(worldNormal, viewDir);\n let NoL: f32 = dot(worldNormal, -lightDirNorm);\n let lambdaV: f32 = NoL * length(vec3f(at * ToV, ab * BoV, NoV));\n let lambdaL: f32 = NoV * length(vec3f(at * ToL, ab * BoL, NoL));\n let G: f32 = 0.5 / (lambdaV + lambdaL);\n return D * G;\n}\nfn getLightSpecular(h: vec3f, reflDir: vec3f, worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f, gloss: f32, tbn: mat3x3f) -> f32 {\n return calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm, tbn);\n}\n",lightSpecularBlinnPS:"\nfn calcLightSpecular(gloss: f32, worldNormal: vec3f, h: vec3f) -> f32 {\n let nh: f32 = max( dot( h, worldNormal ), 0.0 );\n var specPow: f32 = exp2(gloss * 11.0);\n specPow = max(specPow, 0.0001);\n return pow(nh, specPow) * (specPow + 2.0) / 8.0;\n}\nfn getLightSpecular(h: vec3f, reflDir: vec3f, worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f, gloss: f32, tbn: mat3x3f) -> f32 {\n return calcLightSpecular(gloss, worldNormal, h);\n}\n",lightSheenPS:"\nfn sheenD(normal: vec3f, h: vec3f, roughness: f32) -> f32 {\n let PI: f32 = 3.141592653589793;\n let invR: f32 = 1.0 / (roughness * roughness);\n var cos2h: f32 = max(dot(normal, h), 0.0);\n cos2h = cos2h * cos2h;\n let sin2h: f32 = max(1.0 - cos2h, 0.0078125);\n return (2.0 + invR) * pow(sin2h, invR * 0.5) / (2.0 * PI);\n}\nfn sheenV(normal: vec3f, viewDir: vec3f, light: vec3f) -> f32 {\n let NoV: f32 = max(dot(normal, viewDir), 0.000001);\n let NoL: f32 = max(dot(normal, light), 0.000001);\n return 1.0 / (4.0 * (NoL + NoV - NoL * NoV));\n}\nfn getLightSpecularSheen(h: vec3f, worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f, sheenGloss: f32) -> f32 {\n let D: f32 = sheenD(worldNormal, h, sheenGloss);\n let V: f32 = sheenV(worldNormal, viewDir, -lightDirNorm);\n return D * V;\n}",linearizeDepthPS:"\n#ifndef LINEARIZE_DEPTH\n#define LINEARIZE_DEPTH\nfn linearizeDepthWithParams(z: f32, cameraParams: vec4f) -> f32 {\n if (cameraParams.w == 0.0) {\n return (cameraParams.z * cameraParams.y) / (cameraParams.y + z * (cameraParams.z - cameraParams.y));\n } else {\n return cameraParams.z + z * (cameraParams.y - cameraParams.z);\n }\n}\n#ifndef CAMERAPLANES\n #define CAMERAPLANES\n uniform camera_params: vec4f;\n#endif\nfn linearizeDepth(z: f32) -> f32 {\n return linearizeDepthWithParams(z, uniform.camera_params);\n}\n#endif\n",litForwardBackendPS:'\nfn evaluateBackend() -> FragmentOutput {\n var output: FragmentOutput;\n #ifdef LIT_SSAO\n litArgs_ao = litArgs_ao * textureSampleLevel(ssaoTexture, ssaoTextureSampler, pcPosition.xy * uniform.ssaoTextureSizeInv, 0.0).r;\n #endif\n #ifdef LIT_NEEDS_NORMAL\n #ifdef LIT_SPECULAR\n getReflDir(litArgs_worldNormal, dViewDirW, litArgs_gloss, dTBN);\n #endif\n #ifdef LIT_CLEARCOAT\n ccReflDirW = normalize(-reflect(dViewDirW, litArgs_clearcoat_worldNormal));\n #endif\n #endif\n #ifdef LIT_SPECULAR_OR_REFLECTION\n #ifdef LIT_METALNESS\n var f0: f32 = 1.0 / litArgs_ior;\n f0 = (f0 - 1.0) / (f0 + 1.0);\n f0 = f0 * f0;\n litArgs_specularity = getSpecularModulate(litArgs_specularity, litArgs_albedo, litArgs_metalness, f0);\n litArgs_albedo = getAlbedoModulate(litArgs_albedo, litArgs_metalness);\n #endif\n #ifdef LIT_IRIDESCENCE\n var iridescenceFresnel: vec3f = getIridescenceDiffraction(saturate(dot(dViewDirW, litArgs_worldNormal)), litArgs_specularity, litArgs_iridescence_thickness);\n #endif\n #endif\n #ifdef LIT_ADD_AMBIENT\n addAmbient(litArgs_worldNormal);\n #ifdef LIT_SPECULAR\n dDiffuseLight = dDiffuseLight * (1.0 - litArgs_specularity);\n #endif\n #ifdef LIT_SEPARATE_AMBIENT\n var dAmbientLight: vec3f = dDiffuseLight;\n dDiffuseLight = vec3(0.0);\n #endif\n #endif\n #ifndef LIT_OLD_AMBIENT\n dDiffuseLight = dDiffuseLight * uniform.material_ambient;\n #endif\n #ifdef LIT_AO\n #ifndef LIT_OCCLUDE_DIRECT\n occludeDiffuse(litArgs_ao);\n #endif\n #endif\n #ifdef LIT_LIGHTMAP\n addLightMap(\n litArgs_lightmap, \n litArgs_lightmapDir, \n litArgs_worldNormal, \n dViewDirW, \n dReflDirW, \n litArgs_gloss, \n litArgs_specularity, \n dVertexNormalW,\n dTBN\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n litArgs_iridescence_intensity\n #endif\n );\n #endif\n #ifdef LIT_LIGHTING || LIT_REFLECTIONS\n #ifdef LIT_REFLECTIONS\n #ifdef LIT_CLEARCOAT\n addReflectionCC(ccReflDirW, litArgs_clearcoat_gloss);\n \n #ifdef LIT_SPECULAR_FRESNEL\n ccFresnel = getFresnelCC(dot(dViewDirW, litArgs_clearcoat_worldNormal));\n ccReflection = ccReflection * ccFresnel;\n #else\n ccFresnel = 0.0;\n #endif\n #endif\n #ifdef LIT_SPECULARITY_FACTOR\n ccReflection = ccReflection * litArgs_specularityFactor;\n #endif\n #ifdef LIT_SHEEN\n addReflectionSheen(litArgs_worldNormal, dViewDirW, litArgs_sheen_gloss);\n #endif\n addReflection(dReflDirW, litArgs_gloss);\n #ifdef LIT_FRESNEL_MODEL\n dReflection = vec4f(\n dReflection.rgb * getFresnel(\n dot(dViewDirW, litArgs_worldNormal),\n litArgs_gloss,\n litArgs_specularity\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n litArgs_iridescence_intensity\n #endif\n ),\n dReflection.a\n );\n #else\n dReflection = vec4f(dReflection.rgb * litArgs_specularity, dReflection.a);\n #endif\n #ifdef LIT_SPECULARITY_FACTOR\n dReflection = vec4f(dReflection.rgb * litArgs_specularityFactor, dReflection.a);\n #endif\n #endif\n #ifdef AREA_LIGHTS\n dSpecularLight = dSpecularLight * litArgs_specularity;\n #ifdef LIT_SPECULAR\n calcLTCLightValues(litArgs_gloss, litArgs_worldNormal, dViewDirW, litArgs_specularity, litArgs_clearcoat_gloss, litArgs_clearcoat_worldNormal, litArgs_clearcoat_specularity);\n #endif\n #endif\n \n #ifdef LIGHT_COUNT > 0\n #include "lightEvaluationPS, LIGHT_COUNT"\n #endif\n #ifdef LIT_CLUSTERED_LIGHTS\n addClusteredLights(litArgs_worldNormal, dViewDirW, dReflDirW,\n #if defined(LIT_CLEARCOAT)\n ccReflDirW,\n #endif\n litArgs_gloss, litArgs_specularity, dVertexNormalW, dTBN, \n #if defined(LIT_IRIDESCENCE)\n iridescenceFresnel,\n #endif\n litArgs_clearcoat_worldNormal, litArgs_clearcoat_gloss, litArgs_sheen_gloss, litArgs_iridescence_intensity\n );\n #endif\n #ifdef AREA_LIGHTS\n #ifdef LIT_CLEARCOAT\n litArgs_clearcoat_specularity = 1.0;\n #endif\n #ifdef LIT_SPECULAR\n litArgs_specularity = vec3(1.0);\n #endif\n #endif\n #ifdef LIT_REFRACTION\n addRefraction(\n litArgs_worldNormal, \n dViewDirW, \n litArgs_thickness, \n litArgs_gloss, \n litArgs_specularity, \n litArgs_albedo, \n litArgs_transmission,\n litArgs_ior,\n litArgs_dispersion\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel, \n litArgs_iridescence_intensity\n #endif\n );\n #endif\n #endif\n #ifdef LIT_AO\n #ifdef LIT_OCCLUDE_DIRECT\n occludeDiffuse(litArgs_ao);\n #endif\n #if LIT_OCCLUDE_SPECULAR != NONE\n occludeSpecular(litArgs_gloss, litArgs_ao, litArgs_worldNormal, dViewDirW);\n #endif\n #endif\n #ifdef LIT_SPECULARITY_FACTOR\n dSpecularLight = dSpecularLight * litArgs_specularityFactor;\n #endif\n #if !defined(LIT_OPACITY_FADES_SPECULAR)\n #if LIT_BLEND_TYPE == NORMAL || LIT_BLEND_TYPE == PREMULTIPLIED\n var specLum: f32 = dot((dSpecularLight + dReflection.rgb * dReflection.a), vec3f( 0.2126, 0.7152, 0.0722 ));\n #ifdef LIT_CLEARCOAT\n specLum = specLum + dot(ccSpecularLight * litArgs_clearcoat_specularity + ccReflection * litArgs_clearcoat_specularity, vec3f( 0.2126, 0.7152, 0.0722 ));\n #endif\n litArgs_opacity = clamp(litArgs_opacity + gammaCorrectInput(specLum), 0.0, 1.0);\n #endif\n litArgs_opacity = litArgs_opacity * uniform.material_alphaFade;\n #endif\n #ifdef LIT_LIGHTMAP_BAKING\n #ifdef LIT_LIGHTMAP_BAKING_COLOR\n #include "bakeLmEndPS"\n #endif\n #ifdef LIT_LIGHTMAP_BAKING_DIR\n #include "bakeDirLmEndPS"\n #endif\n #else\n #include "endPS"\n #include "outputAlphaPS"\n #endif\n #ifdef LIT_MSDF\n output.color = applyMsdf(output.color);\n #endif\n #include "outputPS"\n #include "debugOutputPS"\n #ifdef LIT_SHADOW_CATCHER\n output.color = vec4f(vec3f(dShadowCatcher), output.color.a);\n #endif\n return output;\n}\n',litForwardDeclarationPS:'\nvar sReflection: vec3f;\nvar dVertexNormalW: vec3f;\nvar dTangentW: vec3f;\nvar dBinormalW: vec3f;\nvar dViewDirW: vec3f;\nvar dReflDirW: vec3f;\nvar ccReflDirW: vec3f;\nvar dLightDirNormW: vec3f;\nvar dAtten: f32;\nvar dTBN: mat3x3f;\nvar dReflection: vec4f;\nvar dDiffuseLight: vec3f;\nvar dSpecularLight: vec3f;\nvar ccFresnel: f32;\nvar ccReflection: vec3f;\nvar ccSpecularLight: vec3f;\nvar ccSpecularityNoFres: f32;\nvar sSpecularLight: vec3f;\n#ifdef LIT_DISPERSION\n uniform material_dispersion: f32;\n#endif\n#ifndef LIT_OPACITY_FADES_SPECULAR\n uniform material_alphaFade: f32;\n#endif\n#ifdef LIT_SSAO\n var ssaoTexture : texture_2d;\n var ssaoTextureSampler : sampler;\n uniform ssaoTextureSizeInv: vec2f;\n#endif\n#ifdef LIT_SHADOW_CATCHER\n var dShadowCatcher: f32 = 1.0;\n#endif\n#if LIGHT_COUNT > 0\n #include "lightDeclarationPS, LIGHT_COUNT"\n#endif\n#ifdef LIT_SPECULAR\n #if LIT_FRESNEL_MODEL == NONE && !defined(LIT_REFLECTIONS) && !defined(LIT_DIFFUSE_MAP) \n #define LIT_OLD_AMBIENT\n #endif\n#endif\n#ifdef STD_LIGHTMAP_DIR\n uniform bakeDir: f32;\n#endif\n#ifdef LIT_LIGHTMAP_BAKING_ADD_AMBIENT\n uniform ambientBakeOcclusionContrast: f32;\n uniform ambientBakeOcclusionBrightness: f32;\n#endif\n',litForwardMainPS:'\n@fragment\nfn fragmentMain(input: FragmentInput) -> FragmentOutput {\n #include "litUserMainStartPS"\n dReflection = vec4f(0.0);\n #ifdef LIT_CLEARCOAT\n ccSpecularLight = vec3f(0.0);\n ccReflection = vec3f(0.0);\n #endif\n #if LIT_NONE_SLICE_MODE == SLICED\n #include "startNineSlicedPS"\n #elif LIT_NONE_SLICE_MODE == TILED\n #include "startNineSlicedTiledPS"\n #endif\n #ifdef LIT_NEEDS_NORMAL\n dVertexNormalW = normalize(vNormalW);\n #ifdef LIT_TANGENTS\n #if defined(LIT_HEIGHTS) || defined(LIT_USE_NORMALS) || defined(LIT_USE_CLEARCOAT_NORMALS) || defined(LIT_GGX_SPECULAR)\n dTangentW = vTangentW;\n dBinormalW = vBinormalW;\n #endif\n #endif\n getViewDir();\n #ifdef LIT_TBN\n getTBN(dTangentW, dBinormalW, dVertexNormalW);\n #ifdef LIT_TWO_SIDED_LIGHTING\n handleTwoSidedLighting();\n #endif\n #endif\n #endif\n evaluateFrontend();\n #include "debugProcessFrontendPS"\n var output: FragmentOutput = evaluateBackend();\n #include "litUserMainEndPS"\n return output;\n}\n',litForwardPostCodePS:'\n#ifdef LIT_NEEDS_NORMAL\n #include "cubeMapRotatePS"\n #include "cubeMapProjectPS"\n #include "envProcPS"\n#endif\n#ifdef LIT_SPECULAR_OR_REFLECTION\n #ifdef LIT_METALNESS\n #include "metalnessModulatePS"\n #endif\n #if LIT_FRESNEL_MODEL == SCHLICK\n #include "fresnelSchlickPS"\n #endif\n #ifdef LIT_IRIDESCENCE\n #include "iridescenceDiffractionPS"\n #endif\n#endif\n#ifdef LIT_AO\n #include "aoDiffuseOccPS"\n #include "aoSpecOccPS"\n#endif\n#if LIT_REFLECTION_SOURCE == ENVATLASHQ\n #include "envAtlasPS"\n #include "reflectionEnvHQPS"\n#elif LIT_REFLECTION_SOURCE == ENVATLAS\n #include "envAtlasPS"\n #include "reflectionEnvPS"\n#elif LIT_REFLECTION_SOURCE == CUBEMAP\n #include "reflectionCubePS"\n#elif LIT_REFLECTION_SOURCE == SPHEREMAP\n #include "reflectionSpherePS"\n#endif\n#ifdef LIT_REFLECTIONS\n #ifdef LIT_CLEARCOAT\n #include "reflectionCCPS"\n #endif\n #ifdef LIT_SHEEN\n #include "reflectionSheenPS"\n #endif\n#endif\n#ifdef LIT_REFRACTION\n #if defined(LIT_DYNAMIC_REFRACTION)\n #include "refractionDynamicPS"\n #elif defined(LIT_REFLECTIONS)\n #include "refractionCubePS"\n #endif\n#endif\n#ifdef LIT_SHEEN\n #include "lightSheenPS"\n#endif\nuniform material_ambient: vec3f;\n#ifdef LIT_SPECULAR\n #ifdef LIT_LIGHTING\n #ifdef LIT_GGX_SPECULAR\n #include "lightSpecularAnisoGGXPS"\n #else\n #include "lightSpecularBlinnPS"\n #endif\n #endif\n#endif\n#include "combinePS"\n#ifdef LIT_LIGHTMAP\n #include "lightmapAddPS"\n#endif\n#ifdef LIT_ADD_AMBIENT\n #include "ambientPS"\n#endif\n#ifdef LIT_MSDF\n #include "msdfPS"\n#endif\n#ifdef LIT_NEEDS_NORMAL\n #include "viewDirPS"\n #ifdef LIT_SPECULAR\n #ifdef LIT_GGX_SPECULAR\n #include "reflDirAnisoPS"\n #else\n #include "reflDirPS"\n #endif\n #endif\n#endif\n#include "lightingPS"\n',litForwardPreCodePS:'\n#include "basePS"\n#include "sphericalPS"\n#include "decodePS"\n#include "gammaPS"\n#include "tonemappingPS"\n#include "fogPS"\n#if LIT_NONE_SLICE_MODE == SLICED\n #include "baseNineSlicedPS"\n#elif LIT_NONE_SLICE_MODE == TILED\n #include "baseNineSlicedTiledPS"\n#endif\n#ifdef LIT_TBN\n #include "TBNPS"\n #ifdef LIT_TWO_SIDED_LIGHTING\n #include "twoSidedLightingPS"\n #endif\n#endif\n',litMainPS:'\n#include "varyingsPS"\n#include "litUserDeclarationPS"\n#include "frontendDeclPS"\n#if defined(PICK_PASS) || defined(PREPASS_PASS)\n #include "frontendCodePS"\n #include "litUserCodePS"\n #include "litOtherMainPS"\n#elif defined(SHADOW_PASS)\n #include "frontendCodePS"\n #include "litUserCodePS"\n #include "litShadowMainPS"\n#else\n #include "litForwardDeclarationPS"\n #include "litForwardPreCodePS"\n #include "frontendCodePS"\n #include "litForwardPostCodePS"\n #include "litForwardBackendPS"\n #include "litUserCodePS"\n #include "litForwardMainPS"\n#endif\n',litMainVS:'\n#include "varyingsVS"\n#include "litUserDeclarationVS"\n#ifdef VERTEX_COLOR\n attribute vertex_color: vec4f;\n#endif\n#ifdef NINESLICED\n varying vMask: vec2f;\n varying vTiledUv: vec2f;\n var dMaskGlobal: vec2f;\n var dTiledUvGlobal: vec2f;\n uniform innerOffset: vec4f;\n uniform outerScale: vec2f;\n uniform atlasRect: vec4f;\n#endif\nvar dPositionW: vec3f;\nvar dModelMatrix: mat4x4f;\n#include "transformCoreVS"\n#ifdef UV0\n attribute vertex_texCoord0: vec2f;\n #include "uv0VS"\n#endif\n#ifdef UV1\n attribute vertex_texCoord1: vec2f;\n #include "uv1VS"\n#endif\n#ifdef LINEAR_DEPTH\n #ifndef VIEWMATRIX\n #define VIEWMATRIX\n uniform matrix_view: mat4x4f;\n #endif\n#endif\n#include "transformVS"\n#ifdef NORMALS\n #include "normalCoreVS"\n #include "normalVS"\n#endif\n#ifdef TANGENTS\n attribute vertex_tangent: vec4f;\n#endif\n#include "uvTransformUniformsPS, UV_TRANSFORMS_COUNT"\n#ifdef MSDF\n #include "msdfVS"\n#endif\n#include "litUserCodeVS"\n@vertex\nfn vertexMain(input : VertexInput) -> VertexOutput {\n #include "litUserMainStartVS"\n var output : VertexOutput;\n output.position = getPosition();\n output.vPositionW = getWorldPosition();\n #ifdef NORMALS\n output.vNormalW = getNormal();\n #endif\n #ifdef TANGENTS\n output.vTangentW = normalize(dNormalMatrix * vertex_tangent.xyz);\n output.vBinormalW = cross(output.vNormalW, output.vTangentW) * vertex_tangent.w;\n #elif defined(GGX_SPECULAR)\n output.vObjectSpaceUpW = normalize(dNormalMatrix * vec3f(0.0, 1.0, 0.0));\n #endif\n #ifdef UV0\n var uv0: vec2f = getUv0();\n #ifdef UV0_UNMODIFIED\n output.vUv0 = uv0;\n #endif\n #endif\n #ifdef UV1\n var uv1: vec2f = getUv1();\n #ifdef UV1_UNMODIFIED\n output.vUv1 = uv1;\n #endif\n #endif\n #include "uvTransformVS, UV_TRANSFORMS_COUNT"\n #ifdef VERTEX_COLOR\n output.vVertexColor = vertex_color;\n #endif\n #ifdef LINEAR_DEPTH\n output.vLinearDepth = -(uniform.matrix_view * vec4f(output.vPositionW, 1.0)).z;\n #endif\n #ifdef MSDF\n unpackMsdfParams();\n output.outline_color = dOutlineColor;\n output.outline_thickness = dOutlineThickness;\n output.shadow_color = dShadowColor;\n output.shadow_offset = dShadowOffset;\n #endif\n #ifdef NINESLICED\n output.vMask = dMaskGlobal;\n output.vTiledUv = dTiledUvGlobal;\n #endif\n #include "litUserMainEndVS"\n return output;\n}\n',litOtherMainPS:'\n#ifdef PICK_PASS\n #include "pickPS"\n#endif\n#ifdef PREPASS_PASS\n #include "floatAsUintPS"\n#endif\n@fragment\nfn fragmentMain(input: FragmentInput) -> FragmentOutput {\n #include "litUserMainStartPS"\n var output: FragmentOutput;\n \n evaluateFrontend();\n #ifdef PICK_PASS\n output.color = getPickOutput();\n #endif\n #ifdef PREPASS_PASS\n output.color = float2vec4(vLinearDepth);\n #endif\n #include "litUserMainEndPS"\n return output;\n}\n',litShaderArgsPS:"\nvar litArgs_albedo: vec3f;\nvar litArgs_opacity: f32;\nvar litArgs_emission: vec3f;\nvar litArgs_worldNormal: vec3f;\nvar litArgs_ao: f32;\nvar litArgs_lightmap: vec3f;\nvar litArgs_lightmapDir: vec3f;\nvar litArgs_metalness: f32;\nvar litArgs_specularity: vec3f;\nvar litArgs_specularityFactor: f32;\nvar litArgs_gloss: f32;\nvar litArgs_sheen_gloss: f32;\nvar litArgs_sheen_specularity: vec3f;\nvar litArgs_transmission: f32;\nvar litArgs_thickness: f32;\nvar litArgs_ior: f32;\nvar litArgs_dispersion: f32;\nvar litArgs_iridescence_intensity: f32;\nvar litArgs_iridescence_thickness: f32;\nvar litArgs_clearcoat_worldNormal: vec3f;\nvar litArgs_clearcoat_specularity: f32;\nvar litArgs_clearcoat_gloss: f32;\n",litShaderCorePS:'\n #if LIT_NONE_SLICE_MODE == TILED\n var textureBias: f32 = -1000.0;\n #else\n uniform textureBias: f32;\n #endif\n #include "litShaderArgsPS"\n',litShadowMainPS:'\n#if LIGHT_TYPE != DIRECTIONAL\n uniform view_position: vec3f;\n uniform light_radius: f32;\n#endif\n#if SHADOW_TYPE == PCSS_32F\n #include "linearizeDepthPS"\n#endif\n@fragment\nfn fragmentMain(input: FragmentInput) -> FragmentOutput {\n #include "litUserMainStartPS"\n var output: FragmentOutput;\n evaluateFrontend();\n #ifdef PERSPECTIVE_DEPTH\n var depth: f32 = input.position.z;\n #if SHADOW_TYPE == PCSS_32F\n #if LIGHT_TYPE != DIRECTIONAL\n depth = linearizeDepthWithParams(depth, camera_params);\n #endif\n #endif\n #else\n var depth: f32 = min(distance(uniform.view_position, input.vPositionW) / uniform.light_radius, 0.99999);\n #define MODIFIED_DEPTH\n #endif\n #if SHADOW_TYPE == VSM_16F || SHADOW_TYPE == VSM_32F\n #if SHADOW_TYPE == VSM_32F\n var exponent: f32 = 15.0;\n #else\n var exponent: f32 = 5.54;\n #endif\n var depth_vsm = 2.0 * depth - 1.0;\n depth_vsm = exp(exponent * depth_vsm);\n output.color = vec4f(depth_vsm, depth_vsm * depth_vsm, 1.0, 1.0);\n #else\n #if SHADOW_TYPE == PCSS_32F\n output.color = vec4f(depth, 0.0, 0.0, 1.0);\n #else\n #ifdef MODIFIED_DEPTH\n output.fragDepth = depth;\n #endif\n output.color = vec4f(1.0);\n #endif\n #endif\n #include "litUserMainEndPS"\n \n return output;\n}\n',litUserDeclarationPS:"",litUserDeclarationVS:"",litUserCodePS:"",litUserCodeVS:"",litUserMainStartPS:"",litUserMainStartVS:"",litUserMainEndPS:"",litUserMainEndVS:"",ltcPS:"\nfn LTC_Uv(N: vec3f, V: vec3f, roughness: f32) -> vec2f {\n const LUT_SIZE: f32 = 64.0;\n const LUT_SCALE: f32 = (LUT_SIZE - 1.0) / LUT_SIZE;\n const LUT_BIAS: f32 = 0.5 / LUT_SIZE;\n let dotNV: f32 = saturate(dot( N, V ));\n let uv: vec2f = vec2f( roughness, sqrt( 1.0 - dotNV ) );\n return uv * LUT_SCALE + LUT_BIAS;\n}\nfn LTC_ClippedSphereFormFactor( f: vec3f ) -> f32 {\n let l: f32 = length( f );\n return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nfn LTC_EdgeVectorFormFactor( v1: vec3f, v2: vec3f ) -> vec3f {\n let x: f32 = dot( v1, v2 );\n let y: f32 = abs( x );\n let a: f32 = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n let b: f32 = 3.4175940 + ( 4.1616724 + y ) * y;\n let v: f32 = a / b;\n let inv_sqrt_term = inverseSqrt( max( 1.0 - x * x, 1e-7f ) );\n let theta_sintheta: f32 = select( (0.5 * inv_sqrt_term - v), v, x > 0.0 );\n return cross( v1, v2 ) * theta_sintheta;\n}\nstruct Coords {\n coord0: vec3f,\n coord1: vec3f,\n coord2: vec3f,\n coord3: vec3f,\n}\nfn LTC_EvaluateRect( N: vec3f, V: vec3f, P: vec3f, mInv: mat3x3f, rectCoords: Coords) -> f32 {\n let v1: vec3f = rectCoords.coord1 - rectCoords.coord0;\n let v2: vec3f = rectCoords.coord3 - rectCoords.coord0;\n let lightNormal: vec3f = cross( v1, v2 );\n let factor: f32 = sign(-dot( lightNormal, P - rectCoords.coord0 ));\n let T1: vec3f = normalize( V - N * dot( V, N ) );\n let T2: vec3f = factor * cross( N, T1 );\n let mat: mat3x3f = mInv * transpose( mat3x3f( T1, T2, N ) );\n var coords: array;\n coords[0] = mat * ( rectCoords.coord0 - P );\n coords[1] = mat * ( rectCoords.coord1 - P );\n coords[2] = mat * ( rectCoords.coord2 - P );\n coords[3] = mat * ( rectCoords.coord3 - P );\n coords[0] = normalize( coords[0] );\n coords[1] = normalize( coords[1] );\n coords[2] = normalize( coords[2] );\n coords[3] = normalize( coords[3] );\n var vectorFormFactor: vec3f = vec3f( 0.0 );\n vectorFormFactor = vectorFormFactor + LTC_EdgeVectorFormFactor( coords[0], coords[1] );\n vectorFormFactor = vectorFormFactor + LTC_EdgeVectorFormFactor( coords[1], coords[2] );\n vectorFormFactor = vectorFormFactor + LTC_EdgeVectorFormFactor( coords[2], coords[3] );\n vectorFormFactor = vectorFormFactor + LTC_EdgeVectorFormFactor( coords[3], coords[0] );\n let result: f32 = LTC_ClippedSphereFormFactor( vectorFormFactor );\n return result;\n}\nvar dLTCCoords: Coords;\nfn getLTCLightCoords(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) -> Coords {\n var coords: Coords;\n coords.coord0 = lightPos + halfWidth - halfHeight;\n coords.coord1 = lightPos - halfWidth - halfHeight;\n coords.coord2 = lightPos - halfWidth + halfHeight;\n coords.coord3 = lightPos + halfWidth + halfHeight;\n return coords;\n}\nvar dSphereRadius: f32;\nfn getSphereLightCoords(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) -> Coords {\n dSphereRadius = max(length(halfWidth), length(halfHeight));\n let f: vec3f = reflect(normalize(lightPos - uniform.view_position), vNormalW);\n let w: vec3f = normalize(cross(f, halfHeight));\n let h: vec3f = normalize(cross(f, w));\n return getLTCLightCoords(lightPos, w * dSphereRadius, h * dSphereRadius);\n}\nvar dLTCUV: vec2f;\n#ifdef LIT_CLEARCOAT\n var ccLTCUV: vec2f;\n#endif\nfn getLTCLightUV(gloss: f32, worldNormal: vec3f, viewDir: vec3f) -> vec2f {\n let roughness: f32 = max((1.0 - gloss) * (1.0 - gloss), 0.001);\n return LTC_Uv( worldNormal, viewDir, roughness );\n}\nvar dLTCSpecFres: vec3f;\n#ifdef LIT_CLEARCOAT\n var ccLTCSpecFres: vec3f;\n#endif\nfn getLTCLightSpecFres(uv: vec2f, specularity: vec3f) -> vec3f {\n let t2: vec4f = textureSampleLevel(areaLightsLutTex2, areaLightsLutTex2Sampler, uv, 0.0);\n return specularity * t2.x + ( vec3f( 1.0 ) - specularity) * t2.y;\n}\nfn calcLTCLightValues(gloss: f32, worldNormal: vec3f, viewDir: vec3f, specularity: vec3f, clearcoatGloss: f32, clearcoatWorldNormal: vec3f, clearcoatSpecularity: f32) {\n dLTCUV = getLTCLightUV(gloss, worldNormal, viewDir);\n dLTCSpecFres = getLTCLightSpecFres(dLTCUV, specularity);\n #ifdef LIT_CLEARCOAT\n ccLTCUV = getLTCLightUV(clearcoatGloss, clearcoatWorldNormal, viewDir);\n ccLTCSpecFres = getLTCLightSpecFres(ccLTCUV, vec3f(clearcoatSpecularity));\n #endif\n}\nfn calcRectLightValues(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) {\n dLTCCoords = getLTCLightCoords(lightPos, halfWidth, halfHeight);\n}\nfn calcDiskLightValues(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) {\n calcRectLightValues(lightPos, halfWidth, halfHeight);\n}\nfn calcSphereLightValues(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) {\n dLTCCoords = getSphereLightCoords(lightPos, halfWidth, halfHeight);\n}\nfn SolveCubic(Coefficient_in: vec4f) -> vec3f {\n let pi: f32 = 3.14159;\n var Coefficient = Coefficient_in;\n Coefficient = vec4f(Coefficient.xyz / Coefficient.w, Coefficient.w);\n let new_yz: vec2f = Coefficient.yz / 3.0;\n Coefficient = vec4f(Coefficient.x, new_yz.x, new_yz.y, Coefficient.w);\n \n let A: f32 = Coefficient.w;\n let B: f32 = Coefficient.z;\n let C: f32 = Coefficient.y;\n let D: f32 = Coefficient.x;\n let Delta: vec3f = vec3f(\n -Coefficient.z * Coefficient.z + Coefficient.y,\n -Coefficient.y * Coefficient.z + Coefficient.x,\n dot(vec2f(Coefficient.z, -Coefficient.y), Coefficient.xy)\n );\n let Discriminant: f32 = dot(vec2f(4.0 * Delta.x, -Delta.y), Delta.zy);\n var xlc: vec2f;\n var xsc: vec2f;\n {\n let A_a: f32 = 1.0;\n let C_a: f32 = Delta.x;\n let D_a: f32 = -2.0 * B * Delta.x + Delta.y;\n let Theta: f32 = atan2(sqrt(Discriminant), -D_a) / 3.0;\n let sqrt_neg_Ca = sqrt(-C_a);\n let x_1a: f32 = 2.0 * sqrt_neg_Ca * cos(Theta);\n let x_3a: f32 = 2.0 * sqrt_neg_Ca * cos(Theta + (2.0 / 3.0) * pi);\n let xl: f32 = select(x_3a, x_1a, (x_1a + x_3a) > 2.0 * B);\n xlc = vec2f(xl - B, A);\n }\n {\n let A_d: f32 = D;\n let C_d: f32 = Delta.z;\n let D_d: f32 = -D * Delta.y + 2.0 * C * Delta.z;\n let Theta: f32 = atan2(D * sqrt(Discriminant), -D_d) / 3.0;\n let sqrt_neg_Cd = sqrt(-C_d);\n let x_1d: f32 = 2.0 * sqrt_neg_Cd * cos(Theta);\n let x_3d: f32 = 2.0 * sqrt_neg_Cd * cos(Theta + (2.0 / 3.0) * pi);\n let xs: f32 = select(x_3d, x_1d, x_1d + x_3d < 2.0 * C);\n xsc = vec2f(-D, xs + C);\n }\n let E: f32 = xlc.y * xsc.y;\n let F: f32 = -xlc.x * xsc.y - xlc.y * xsc.x;\n let G: f32 = xlc.x * xsc.x;\n let xmc: vec2f = vec2f(C * F - B * G, -B * F + C * E);\n var Root: vec3f = vec3f(xsc.x / xsc.y, xmc.x / xmc.y, xlc.x / xlc.y);\n if (Root.x < Root.y && Root.x < Root.z) {\n Root = Root.yxz;\n } else if (Root.z < Root.x && Root.z < Root.y) {\n Root = Root.xzy;\n }\n return Root;\n}\nfn LTC_EvaluateDisk(N: vec3f, V: vec3f, P: vec3f, Minv: mat3x3f, points: Coords) -> f32 {\n let T1: vec3f = normalize(V - N * dot(V, N));\n let T2: vec3f = cross(N, T1);\n let R: mat3x3f = transpose( mat3x3f( T1, T2, N ) );\n var L_: array;\n L_[0] = R * ( points.coord0 - P );\n L_[1] = R * ( points.coord1 - P );\n L_[2] = R * ( points.coord2 - P );\n let C: vec3f = 0.5 * (L_[0] + L_[2]);\n var V1: vec3f = 0.5 * (L_[1] - L_[2]);\n var V2: vec3f = 0.5 * (L_[1] - L_[0]);\n let C_Minv: vec3f = Minv * C;\n let V1_Minv: vec3f = Minv * V1;\n let V2_Minv: vec3f = Minv * V2;\n var a: f32;\n var b: f32;\n let d11: f32 = dot(V1_Minv, V1_Minv);\n let d22: f32 = dot(V2_Minv, V2_Minv);\n let d12: f32 = dot(V1_Minv, V2_Minv);\n if (abs(d12) / sqrt(d11 * d22) > 0.0001) {\n let tr: f32 = d11 + d22;\n let det_inner: f32 = -d12 * d12 + d11 * d22;\n let det: f32 = sqrt(det_inner);\n let u: f32 = 0.5 * sqrt(tr - 2.0 * det);\n let v: f32 = 0.5 * sqrt(tr + 2.0 * det);\n let e_max: f32 = (u + v) * (u + v);\n let e_min: f32 = (u - v) * (u - v);\n var V1_: vec3f;\n var V2_: vec3f;\n if (d11 > d22) {\n V1_ = d12 * V1_Minv + (e_max - d11) * V2_Minv;\n V2_ = d12 * V1_Minv + (e_min - d11) * V2_Minv;\n } else {\n V1_ = d12*V2_Minv + (e_max - d22)*V1_Minv;\n V2_ = d12*V2_Minv + (e_min - d22)*V1_Minv;\n }\n a = 1.0 / e_max;\n b = 1.0 / e_min;\n V1 = normalize(V1_);\n V2 = normalize(V2_);\n } else {\n a = 1.0 / dot(V1_Minv, V1_Minv);\n b = 1.0 / dot(V2_Minv, V2_Minv);\n V1 = V1_Minv * sqrt(a);\n V2 = V2_Minv * sqrt(b);\n }\n var V3: vec3f = normalize(cross(V1, V2));\n if (dot(C_Minv, V3) < 0.0) {\n V3 = V3 * -1.0;\n }\n let L: f32 = dot(V3, C_Minv);\n let x0: f32 = dot(V1, C_Minv) / L;\n let y0: f32 = dot(V2, C_Minv) / L;\n let E1: f32 = inverseSqrt(a);\n let E2: f32 = inverseSqrt(b);\n let a_scaled = a * L * L;\n let b_scaled = b * L * L;\n let c0: f32 = a_scaled * b_scaled;\n let c1: f32 = a_scaled * b_scaled * (1.0 + x0 * x0 + y0 * y0) - a_scaled - b_scaled;\n let c2: f32 = 1.0 - a_scaled * (1.0 + x0 * x0) - b_scaled * (1.0 + y0 * y0);\n let c3: f32 = 1.0;\n let roots: vec3f = SolveCubic(vec4f(c0, c1, c2, c3));\n let e1: f32 = roots.x;\n let e2: f32 = roots.y;\n let e3: f32 = roots.z;\n var avgDir: vec3f = vec3f(a_scaled * x0 / (a_scaled - e2), b_scaled * y0 / (b_scaled - e2), 1.0);\n let rotate: mat3x3f = mat3x3f(V1, V2, V3);\n avgDir = rotate * avgDir;\n avgDir = normalize(avgDir);\n let L1: f32 = sqrt(-e2 / e3);\n let L2: f32 = sqrt(-e2 / e1);\n let formFactor: f32 = max(0.0, L1 * L2 * inverseSqrt((1.0 + L1 * L1) * (1.0 + L2 * L2)));\n const LUT_SIZE_disk: f32 = 64.0;\n const LUT_SCALE_disk: f32 = ( LUT_SIZE_disk - 1.0 ) / LUT_SIZE_disk;\n const LUT_BIAS_disk: f32 = 0.5 / LUT_SIZE_disk;\n var uv: vec2f = vec2f(avgDir.z * 0.5 + 0.5, formFactor);\n uv = uv * LUT_SCALE_disk + LUT_BIAS_disk;\n let scale: f32 = textureSampleLevel(areaLightsLutTex2, areaLightsLutTex2Sampler, uv, 0.0).w;\n return formFactor * scale;\n}\nfn FixNan(value: f32) -> f32 {\n return select(value, 0.0, value != value);\n}\nfn getRectLightDiffuse(worldNormal: vec3f, viewDir: vec3f, lightDir: vec3f, lightDirNorm: vec3f) -> f32 {\n let identityMat = mat3x3f(vec3f(1.0, 0.0, 0.0), vec3f(0.0, 1.0, 0.0), vec3f(0.0, 0.0, 1.0));\n return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, identityMat, dLTCCoords );\n}\nfn getDiskLightDiffuse(worldNormal: vec3f, viewDir: vec3f, lightDir: vec3f, lightDirNorm: vec3f) -> f32 {\n let identityMat = mat3x3f(vec3f(1.0, 0.0, 0.0), vec3f(0.0, 1.0, 0.0), vec3f(0.0, 0.0, 1.0));\n return FixNan(LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, identityMat, dLTCCoords ));\n}\nfn getSphereLightDiffuse(worldNormal: vec3f, viewDir: vec3f, lightDir: vec3f, lightDirNorm: vec3f) -> f32 {\n let falloff: f32 = dSphereRadius / (dot(lightDir, lightDir) + dSphereRadius);\n return FixNan(getLightDiffuse(worldNormal, viewDir, lightDirNorm) * falloff);\n}\nfn getLTCLightInvMat(uv: vec2f) -> mat3x3f {\n let t1: vec4f = textureSampleLevel(areaLightsLutTex1, areaLightsLutTex1Sampler, uv, 0.0);\n return mat3x3f(\n vec3f( t1.x, 0.0, t1.y ),\n vec3f( 0.0, 1.0, 0.0 ),\n vec3f( t1.z, 0.0, t1.w )\n );\n}\nfn calcRectLightSpecular(worldNormal: vec3f, viewDir: vec3f, uv: vec2f) -> f32 {\n let mInv: mat3x3f = getLTCLightInvMat(uv);\n return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );\n}\nfn getRectLightSpecular(worldNormal: vec3f, viewDir: vec3f) -> f32 {\n return calcRectLightSpecular(worldNormal, viewDir, dLTCUV);\n}\nfn calcDiskLightSpecular(worldNormal: vec3f, viewDir: vec3f, uv: vec2f) -> f32 {\n let mInv: mat3x3f = getLTCLightInvMat(uv);\n return LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );\n}\nfn getDiskLightSpecular(worldNormal: vec3f, viewDir: vec3f) -> f32 {\n return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);\n}\nfn getSphereLightSpecular(worldNormal: vec3f, viewDir: vec3f) -> f32 {\n return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);\n}\n",metalnessPS:"\n#ifdef STD_METALNESS_CONSTANT\nuniform material_metalness: f32;\n#endif\nfn getMetalness() {\n var metalness: f32 = 1.0;\n #ifdef STD_METALNESS_CONSTANT\n metalness = metalness * uniform.material_metalness;\n #endif\n #ifdef STD_METALNESS_TEXTURE\n metalness = metalness * textureSampleBias({STD_METALNESS_TEXTURE_NAME}, {STD_METALNESS_TEXTURE_NAME}Sampler, {STD_METALNESS_TEXTURE_UV}, uniform.textureBias).{STD_METALNESS_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_METALNESS_VERTEX\n metalness = metalness * saturate(vVertexColor.{STD_METALNESS_VERTEX_CHANNEL});\n #endif\n dMetalness = metalness;\n}\n",metalnessModulatePS:"\nfn getSpecularModulate(specularity: vec3f, albedo: vec3f, metalness: f32, f0: f32) -> vec3f {\n let dielectricF0: vec3f = f0 * specularity;\n return mix(dielectricF0, albedo, metalness);\n}\nfn getAlbedoModulate(albedo: vec3f, metalness: f32) -> vec3f {\n return albedo * (1.0 - metalness);\n}\n",morphPS:"\n varying uv0: vec2f;\n var morphTexture: texture_2d_array;\n var morphTextureSampler : sampler;\n uniform morphFactor: array;\n uniform morphIndex: array;\n uniform count: u32;\n @fragment\n fn fragmentMain(input : FragmentInput) -> FragmentOutput {\n var color = vec3f(0, 0, 0);\n for (var i: u32 = 0; i < uniform.count; i = i + 1) {\n var textureIndex: u32 = uniform.morphIndex[i].element;\n var delta = textureSample(morphTexture, morphTextureSampler, input.uv0, textureIndex).xyz;\n color += uniform.morphFactor[i].element * delta;\n }\n var output: FragmentOutput;\n output.color = vec4f(color, 1.0);\n return output;\n }\n",morphVS:"\n attribute vertex_position: vec2f;\n varying uv0: vec2f;\n @vertex\n fn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n output.position = vec4f(input.vertex_position, 0.5, 1.0);\n output.uv0 = input.vertex_position * 0.5 + vec2f(0.5, 0.5);\n return output;\n }\n",msdfPS:"\nvar texture_msdfMap: texture_2d;\nvar texture_msdfMapSampler: sampler;\nfn median(r: f32, g: f32, b: f32) -> f32 {\n return max(min(r, g), min(max(r, g), b));\n}\nfn map(min: f32, max: f32, v: f32) -> f32 {\n return (v - min) / (max - min);\n}\nuniform font_sdfIntensity: f32;\nuniform font_pxrange: f32;\nuniform font_textureWidth: f32;\n#ifndef LIT_MSDF_TEXT_ATTRIBUTE\n uniform outline_color: vec4f;\n uniform outline_thickness: f32;\n uniform shadow_color: vec4f;\n uniform shadow_offset: vec2f;\n#else\n varying outline_color: vec4f;\n varying outline_thickness: f32;\n varying shadow_color: vec4f;\n varying shadow_offset: vec2f;\n#endif\nfn applyMsdf(color_in: vec4f) -> vec4f {\n #ifndef LIT_MSDF_TEXT_ATTRIBUTE\n var outline_colorValue = uniform.outline_color;\n var outline_thicknessValue = uniform.outline_thickness;\n var shadow_colorValue = uniform.shadow_color;\n var shadow_offsetValue = uniform.shadow_offset;\n #else\n var outline_colorValue = outline_color;\n var outline_thicknessValue = outline_thickness;\n var shadow_colorValue = shadow_color;\n var shadow_offsetValue = shadow_offset;\n #endif\n var color = vec4f(gammaCorrectInputVec3(color_in.rgb), color_in.a);\n let tsample: vec3f = textureSample(texture_msdfMap, texture_msdfMapSampler, vUv0).rgb;\n let uvShdw: vec2f = vUv0 - shadow_offsetValue;\n let ssample: vec3f = textureSample(texture_msdfMap, texture_msdfMapSampler, uvShdw).rgb;\n let sigDist: f32 = median(tsample.r, tsample.g, tsample.b);\n var sigDistShdw: f32 = median(ssample.r, ssample.g, ssample.b);\n let smoothingMax: f32 = 0.2;\n let w: vec2f = abs(dpdx(vUv0)) + abs(dpdy(vUv0));\n let smoothing: f32 = clamp(w.x * uniform.font_textureWidth / uniform.font_pxrange, 0.0, smoothingMax);\n let mapMin: f32 = 0.05;\n let mapMax: f32 = clamp(1.0 - uniform.font_sdfIntensity, mapMin, 1.0);\n let sigDistInner: f32 = map(mapMin, mapMax, sigDist);\n let sigDistOutline: f32 = map(mapMin, mapMax, sigDist + outline_thicknessValue);\n sigDistShdw = map(mapMin, mapMax, sigDistShdw + outline_thicknessValue);\n let center: f32 = 0.5;\n let inside: f32 = smoothstep(center - smoothing, center + smoothing, sigDistInner);\n let outline: f32 = smoothstep(center - smoothing, center + smoothing, sigDistOutline);\n let shadow: f32 = smoothstep(center - smoothing, center + smoothing, sigDistShdw);\n let tcolor_outline: vec4f = outline * vec4f(outline_colorValue.a * outline_colorValue.rgb, outline_colorValue.a);\n var tcolor: vec4f = select(vec4f(0.0), tcolor_outline, outline > inside);\n tcolor = mix(tcolor, color, inside);\n let scolor_shadow: vec4f = shadow * vec4f(shadow_colorValue.a * shadow_colorValue.rgb, shadow_colorValue.a);\n let scolor: vec4f = select(tcolor, scolor_shadow, shadow > outline);\n tcolor = mix(scolor, tcolor, outline);\n tcolor = vec4f(gammaCorrectOutput(tcolor.rgb), tcolor.a);\n return tcolor;\n}\n",msdfVS:"\nattribute vertex_outlineParameters: vec3f;\nattribute vertex_shadowParameters: vec3f;\nvarying outline_color: vec4f;\nvarying outline_thickness: f32;\nvarying shadow_color: vec4f;\nvarying shadow_offset: vec2f;\nvar dOutlineColor: vec4f;\nvar dOutlineThickness: f32;\nvar dShadowColor: vec4f;\nvar dShadowOffset: vec2f;\nfn unpackMsdfParams() {\n let little: vec3f = vertex_outlineParameters % vec3f(256.0);\n let big: vec3f = (vertex_outlineParameters - little) / 256.0;\n dOutlineColor = vec4f(little.x, big.x, little.y, big.y) / 255.0;\n dOutlineThickness = little.z / 255.0 * 0.2;\n let little_shadow = vertex_shadowParameters % vec3f(256.0);\n let big_shadow = (vertex_shadowParameters - little_shadow) / 256.0;\n dShadowColor = vec4f(little_shadow.x, big_shadow.x, little_shadow.y, big_shadow.y) / 255.0;\n dShadowOffset = (vec2f(little_shadow.z, big_shadow.z) / 127.0 - 1.0) * 0.005;\n}\n",normalVS:"\nvar dNormalMatrix: mat3x3f;\nfn getNormal() -> vec3f {\n dNormalMatrix = getNormalMatrix(dModelMatrix);\n let localNormal: vec3f = getLocalNormal(vertex_normal);\n return normalize(dNormalMatrix * localNormal);\n}",normalCoreVS:"\nattribute vertex_normal: vec3f;\nuniform matrix_normal: mat3x3f;\n#ifdef MORPHING_NORMAL\n #ifdef MORPHING_INT\n var morphNormalTex: texture_2d;\n var morphNormalTexSampler: sampler;\n #else\n var morphNormalTex: texture_2d;\n var morphNormalTexSampler: sampler;\n #endif\n#endif\nfn getLocalNormal(vertexNormal: vec3f) -> vec3f {\n var localNormal: vec3f = vertexNormal;\n #ifdef MORPHING_NORMAL\n let morphUV: vec2i = getTextureMorphCoords();\n #ifdef MORPHING_INT\n let morphNormalInt: vec4u = textureLoad(morphNormalTex, morphUV, 0);\n let morphNormalF: vec3f = vec3f(morphNormalInt.xyz) / 65535.0 * 2.0 - 1.0;\n localNormal = localNormal + morphNormalF;\n #else\n let morphNormal: vec3f = textureLoad(morphNormalTex, morphUV, 0).xyz;\n localNormal = localNormal + morphNormal;\n #endif\n #endif\n return localNormal;\n}\n#if defined(SKIN) || defined(BATCH)\n fn getNormalMatrix(modelMatrix: mat4x4f) -> mat3x3f {\n return mat3x3f(modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz);\n }\n#elif defined(INSTANCING)\n fn getNormalMatrix(modelMatrix: mat4x4f) -> mat3x3f {\n return mat3x3f(modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz);\n }\n#else\n fn getNormalMatrix(modelMatrix: mat4x4f) -> mat3x3f {\n return uniform.matrix_normal;\n }\n#endif\n",normalMapPS:"\n#ifdef STD_NORMAL_TEXTURE\n uniform material_bumpiness: f32;\n#endif\n#ifdef STD_NORMALDETAIL_TEXTURE\n uniform material_normalDetailMapBumpiness: f32;\n fn blendNormals(inN1: vec3f, inN2: vec3f) -> vec3f {\n let n1: vec3f = inN1 + vec3f(0.0, 0.0, 1.0);\n let n2: vec3f = inN2 * vec3f(-1.0, -1.0, 1.0);\n return n1 * dot(n1, n2) / n1.z - n2;\n }\n#endif\nfn getNormal() {\n#ifdef STD_NORMAL_TEXTURE\n var normalMap: vec3f = {STD_NORMAL_TEXTURE_DECODE}(textureSampleBias({STD_NORMAL_TEXTURE_NAME}, {STD_NORMAL_TEXTURE_NAME}Sampler, {STD_NORMAL_TEXTURE_UV}, uniform.textureBias));\n normalMap = mix(vec3f(0.0, 0.0, 1.0), normalMap, uniform.material_bumpiness);\n #ifdef STD_NORMALDETAIL_TEXTURE\n var normalDetailMap: vec3f = {STD_NORMALDETAIL_TEXTURE_DECODE}(textureSampleBias({STD_NORMALDETAIL_TEXTURE_NAME}, {STD_NORMALDETAIL_TEXTURE_NAME}Sampler, {STD_NORMALDETAIL_TEXTURE_UV}, uniform.textureBias));\n normalDetailMap = mix(vec3f(0.0, 0.0, 1.0), normalDetailMap, uniform.material_normalDetailMapBumpiness);\n normalMap = blendNormals(normalMap, normalDetailMap);\n #endif\n dNormalW = normalize(dTBN * normalMap);\n#else\n dNormalW = dVertexNormalW;\n#endif\n}\n",opacityPS:"\nuniform material_opacity: f32;\nfn getOpacity() {\n dAlpha = uniform.material_opacity;\n #ifdef STD_OPACITY_TEXTURE\n dAlpha = dAlpha * textureSampleBias({STD_OPACITY_TEXTURE_NAME}, {STD_OPACITY_TEXTURE_NAME}Sampler, {STD_OPACITY_TEXTURE_UV}, uniform.textureBias).{STD_OPACITY_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_OPACITY_VERTEX\n dAlpha = dAlpha * clamp(vVertexColor.{STD_OPACITY_VERTEX_CHANNEL}, 0.0, 1.0);\n #endif\n}\n",opacityDitherPS:'\n#if STD_OPACITY_DITHER == BAYER8\n #include "bayerPS"\n#endif\nuniform blueNoiseJitter: vec4f;\n#if STD_OPACITY_DITHER == BLUENOISE\n var blueNoiseTex32 : texture_2d;\n var blueNoiseTex32Sampler : sampler;\n#endif\nfn opacityDither(alpha: f32, id: f32) {\n #if STD_OPACITY_DITHER == BAYER8\n var noise: f32 = bayer8(floor((pcPosition.xy + uniform.blueNoiseJitter.xy + id) % vec2f(8.0))) / 64.0;\n #else\n #if STD_OPACITY_DITHER == BLUENOISE\n var uv = fract(pcPosition.xy / 32.0 + uniform.blueNoiseJitter.xy + id);\n var noise: f32 = textureSampleLevel(blueNoiseTex32, blueNoiseTex32Sampler, uv, 0.0).y;\n #endif\n #if STD_OPACITY_DITHER == IGNNOISE\n var magic = vec3f(0.06711056, 0.00583715, 52.9829189);\n var noise: f32 = fract(magic.z * fract(dot(pcPosition.xy + uniform.blueNoiseJitter.xy + id, magic.xy)));\n #endif\n #endif\n noise = pow(noise, 2.2);\n if (alpha < noise) {\n discard;\n }\n}\n',outputPS:"\n",outputAlphaPS:"\n#if LIT_BLEND_TYPE == NORMAL || LIT_BLEND_TYPE == ADDITIVEALPHA || defined(LIT_ALPHA_TO_COVERAGE)\n output.color = vec4f(output.color.rgb, litArgs_opacity);\n#elif LIT_BLEND_TYPE == PREMULTIPLIED\n output.color = vec4f(output.color.rgb * litArgs_opacity, litArgs_opacity);\n#else\n output.color = vec4f(output.color.rgb, 1.0);\n#endif\n",outputTex2DPS:"\nvarying vUv0: vec2f;\nvar source: texture_2d;\nvar sourceSampler: sampler;\n@fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n output.color = textureSample(source, sourceSampler, input.vUv0);\n return output;\n}\n",sheenPS:"\nuniform material_sheen: vec3f;\nfn getSheen() {\n var sheenColor = uniform.material_sheen;\n #ifdef STD_SHEEN_TEXTURE\n sheenColor = sheenColor * {STD_SHEEN_TEXTURE_DECODE}(textureSampleBias({STD_SHEEN_TEXTURE_NAME}, {STD_SHEEN_TEXTURE_NAME}Sampler, {STD_SHEEN_TEXTURE_UV}, uniform.textureBias)).{STD_SHEEN_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_SHEEN_VERTEX\n sheenColor = sheenColor * saturate3(vVertexColor.{STD_SHEEN_VERTEX_CHANNEL});\n #endif\n sSpecularity = sheenColor;\n}\n",sheenGlossPS:"\nuniform material_sheenGloss: f32;\nfn getSheenGlossiness() {\n var sheenGlossiness = uniform.material_sheenGloss;\n #ifdef STD_SHEENGLOSS_TEXTURE\n sheenGlossiness = sheenGlossiness * textureSampleBias({STD_SHEENGLOSS_TEXTURE_NAME}, {STD_SHEENGLOSS_TEXTURE_NAME}Sampler, {STD_SHEENGLOSS_TEXTURE_UV}, uniform.textureBias).{STD_SHEENGLOSS_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_SHEENGLOSS_VERTEX\n sheenGlossiness = sheenGlossiness * saturate(vVertexColor.{STD_SHEENGLOSS_VERTEX_CHANNEL});\n #endif\n #ifdef STD_SHEENGLOSS_INVERT\n sheenGlossiness = 1.0 - sheenGlossiness;\n #endif\n sGlossiness = sheenGlossiness + 0.0000001;\n}\n",parallaxPS:"\nuniform material_heightMapFactor: f32;\nfn getParallax() {\n var parallaxScale = uniform.material_heightMapFactor;\n var height: f32 = textureSampleBias({STD_HEIGHT_TEXTURE_NAME}, {STD_HEIGHT_TEXTURE_NAME}Sampler, {STD_HEIGHT_TEXTURE_UV}, uniform.textureBias).{STD_HEIGHT_TEXTURE_CHANNEL};\n height = height * parallaxScale - parallaxScale * 0.5;\n var viewDirT: vec3f = dViewDirW * dTBN;\n viewDirT.z = viewDirT.z + 0.42;\n dUvOffset = height * (viewDirT.xy / viewDirT.z);\n}\n",pickPS:"\nuniform meshInstanceId: u32;\nfn getPickOutput() -> vec4f {\n let inv: vec4f = vec4f(1.0 / 255.0);\n let shifts: vec4u = vec4u(16u, 8u, 0u, 24u);\n let col: vec4u = (vec4u(uniform.meshInstanceId) >> shifts) & vec4u(0xffu);\n return vec4f(col) * inv;\n}",reflDirPS:"\nfn getReflDir(worldNormal: vec3f, viewDir: vec3f, gloss: f32, tbn: mat3x3f) {\n dReflDirW = normalize(-reflect(viewDir, worldNormal));\n}\n",reflDirAnisoPS:"\nfn getReflDir(worldNormal: vec3f, viewDir: vec3f, gloss: f32, tbn: mat3x3f) {\n let roughness: f32 = sqrt(1.0 - min(gloss, 1.0));\n let direction: vec2f = dAnisotropyRotation;\n let anisotropicT: vec3f = normalize(tbn * vec3f(direction, 0.0));\n let anisotropicB: vec3f = normalize(cross(tbn[2], anisotropicT));\n let anisotropy: f32 = dAnisotropy;\n let anisotropicDirection: vec3f = anisotropicB;\n let anisotropicTangent: vec3f = cross(anisotropicDirection, viewDir);\n let anisotropicNormal: vec3f = cross(anisotropicTangent, anisotropicDirection);\n let bendFactor: f32 = 1.0 - anisotropy * (1.0 - roughness);\n let bendFactor4: f32 = bendFactor * bendFactor * bendFactor * bendFactor;\n let bentNormal: vec3f = normalize(mix(normalize(anisotropicNormal), normalize(worldNormal), bendFactor4));\n dReflDirW = reflect(-viewDir, bentNormal);\n}",reflectionCCPS:"\n#ifdef LIT_CLEARCOAT\nfn addReflectionCC(reflDir: vec3f, gloss: f32) {\n ccReflection = ccReflection + calcReflection(reflDir, gloss);\n}\n#endif\n",reflectionCubePS:"\nvar texture_cubeMap: texture_cube;\nvar texture_cubeMapSampler: sampler;\nuniform material_reflectivity: f32;\nfn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f {\n var lookupVec: vec3f = cubeMapProject(reflDir);\n lookupVec.x = lookupVec.x * -1.0;\n return {reflectionDecode}(textureSample(texture_cubeMap, texture_cubeMapSampler, lookupVec));\n}\nfn addReflection(reflDir: vec3f, gloss: f32) {\n dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity);\n}\n",reflectionEnvHQPS:"\n#ifndef ENV_ATLAS\n #define ENV_ATLAS\n var texture_envAtlas: texture_2d;\n var texture_envAtlasSampler: sampler;\n#endif\nvar texture_cubeMap: texture_cube;\nvar texture_cubeMapSampler: sampler;\nuniform material_reflectivity: f32;\nfn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f {\n let dir: vec3f = cubeMapProject(reflDir) * vec3f(-1.0, 1.0, 1.0);\n let uv: vec2f = toSphericalUv(dir);\n let level: f32 = saturate(1.0 - gloss) * 5.0;\n let ilevel: f32 = floor(level);\n let flevel: f32 = level - ilevel;\n let sharp: vec3f = {reflectionCubemapDecode}(textureSample(texture_cubeMap, texture_cubeMapSampler, dir));\n let roughA: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, mapRoughnessUv(uv, ilevel)));\n let roughB: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, mapRoughnessUv(uv, ilevel + 1.0)));\n return processEnvironment(mix(sharp, mix(roughA, roughB, flevel), min(level, 1.0)));\n}\nfn addReflection(reflDir: vec3f, gloss: f32) {\n dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity);\n}\n",reflectionEnvPS:"\n#ifndef ENV_ATLAS\n#define ENV_ATLAS\n var texture_envAtlas: texture_2d;\n var texture_envAtlasSampler: sampler;\n#endif\nuniform material_reflectivity: f32;\nfn shinyMipLevel(uv: vec2f) -> f32 {\n let dx: vec2f = dpdx(uv);\n let dy: vec2f = dpdy(uv);\n let uv2: vec2f = vec2f(fract(uv.x + 0.5), uv.y);\n let dx2: vec2f = dpdx(uv2);\n let dy2: vec2f = dpdy(uv2);\n let maxd: f32 = min(max(dot(dx, dx), dot(dy, dy)), max(dot(dx2, dx2), dot(dy2, dy2)));\n return clamp(0.5 * log2(maxd) - 1.0 + uniform.textureBias, 0.0, 5.0);\n}\nfn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f {\n let dir: vec3f = cubeMapProject(reflDir) * vec3f(-1.0, 1.0, 1.0);\n let uv: vec2f = toSphericalUv(dir);\n let level: f32 = saturate(1.0 - gloss) * 5.0;\n let ilevel: f32 = floor(level);\n let level2: f32 = shinyMipLevel(uv * atlasSize);\n let ilevel2: f32 = floor(level2);\n var uv0: vec2f;\n var uv1: vec2f;\n var weight: f32;\n if (ilevel == 0.0) {\n uv0 = mapShinyUv(uv, ilevel2);\n uv1 = mapShinyUv(uv, ilevel2 + 1.0);\n weight = level2 - ilevel2;\n } else {\n uv0 = mapRoughnessUv(uv, ilevel);\n uv1 = uv0;\n weight = 0.0;\n }\n let linearA: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, uv0));\n let linearB: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, uv1));\n let linear0: vec3f = mix(linearA, linearB, weight);\n let linear1: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, mapRoughnessUv(uv, ilevel + 1.0)));\n return processEnvironment(mix(linear0, linear1, level - ilevel));\n}\nfn addReflection(reflDir: vec3f, gloss: f32) {\n dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity);\n}\n",reflectionSpherePS:"\n#ifndef VIEWMATRIX\n #define VIEWMATRIX\n uniform matrix_view: mat4x4f;\n#endif\nvar texture_sphereMap: texture_2d;\nvar texture_sphereMapSampler: sampler;\nuniform material_reflectivity: f32;\nfn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f {\n let viewRotationMatrix = mat3x3f(uniform.matrix_view[0].xyz, uniform.matrix_view[1].xyz, uniform.matrix_view[2].xyz);\n let reflDirV: vec3f = viewRotationMatrix * reflDir;\n let m: f32 = 2.0 * sqrt(dot(reflDirV.xy, reflDirV.xy) + (reflDirV.z + 1.0) * (reflDirV.z + 1.0));\n let sphereMapUv: vec2f = reflDirV.xy / m + 0.5;\n return {reflectionDecode}(textureSample(texture_sphereMap, texture_sphereMapSampler, sphereMapUv));\n}\nfn addReflection(reflDir: vec3f, gloss: f32) {\n dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity);\n}\n",reflectionSheenPS:"\nfn addReflectionSheen(worldNormal: vec3f, viewDir: vec3f, gloss: f32) {\n let NoV: f32 = dot(worldNormal, viewDir);\n let alphaG: f32 = gloss * gloss;\n let a: f32 = select(\n -8.48 * alphaG + 14.3 * gloss - 9.95,\n -339.2 * alphaG + 161.4 * gloss - 25.9,\n gloss < 0.25\n );\n let b: f32 = select(\n 1.97 * alphaG - 3.27 * gloss + 0.72,\n 44.0 * alphaG - 23.7 * gloss + 3.26,\n gloss < 0.25\n );\n let dg_add: f32 = select(\n 0.1 * ( gloss - 0.25 ),\n 0.0,\n gloss < 0.25\n );\n let dg: f32 = exp( a * NoV + b ) + dg_add;\n sReflection = sReflection + (calcReflection(worldNormal, 0.0) * saturate(dg));\n}",refractionCubePS:"\nfn refract2(viewVec: vec3f, normal: vec3f, IOR: f32) -> vec3f {\n let vn: f32 = dot(viewVec, normal);\n let k: f32 = 1.0 - IOR * IOR * (1.0 - vn * vn);\n let refrVec: vec3f = IOR * viewVec - (IOR * vn + sqrt(k)) * normal;\n return refrVec;\n}\nfn addRefraction(\n worldNormal: vec3f,\n viewDir: vec3f,\n thickness: f32,\n gloss: f32,\n specularity: vec3f,\n albedo: vec3f,\n transmission: f32,\n refractionIndex: f32,\n dispersion: f32\n#if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel: vec3f,\n iridescenceIntensity: f32\n#endif\n) {\n let tmpRefl: vec4f = dReflection;\n let reflectionDir: vec3f = refract2(-viewDir, worldNormal, refractionIndex);\n dReflection = vec4f(0.0);\n addReflection(reflectionDir, gloss);\n dDiffuseLight = mix(dDiffuseLight, dReflection.rgb * albedo, transmission);\n dReflection = tmpRefl;\n}\n",refractionDynamicPS:"\nuniform material_invAttenuationDistance: f32;\nuniform material_attenuation: vec3f;\nfn evalRefractionColor(refractionVector: vec3f, gloss: f32, refractionIndex: f32) -> vec3f {\n let pointOfRefraction: vec4f = vec4f(vPositionW + refractionVector, 1.0);\n let projectionPoint: vec4f = uniform.matrix_viewProjection * pointOfRefraction;\n let uv: vec2f = getGrabScreenPos(projectionPoint);\n let iorToRoughness: f32 = (1.0 - gloss) * clamp((1.0 / refractionIndex) * 2.0 - 2.0, 0.0, 1.0);\n let refractionLod: f32 = log2(uniform.uScreenSize.x) * iorToRoughness;\n let refraction: vec3f = textureSampleLevel(uSceneColorMap, uSceneColorMapSampler, uv, refractionLod).rgb;\n return refraction;\n}\nfn addRefraction(\n worldNormal: vec3f,\n viewDir: vec3f,\n thickness: f32,\n gloss: f32,\n specularity: vec3f,\n albedo: vec3f,\n transmission: f32,\n refractionIndex: f32,\n dispersion: f32,\n#if defined(LIT_IRIDESCENCE)\n iridescenceFresnel: vec3f,\n iridescenceIntensity: f32\n#endif\n) {\n var modelScale: vec3f;\n modelScale.x = length(uniform.matrix_model[0].xyz);\n modelScale.y = length(uniform.matrix_model[1].xyz);\n modelScale.z = length(uniform.matrix_model[2].xyz);\n let scale: vec3f = thickness * modelScale;\n var refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndex)) * scale;\n var refraction = evalRefractionColor(refractionVector, gloss, refractionIndex);\n #ifdef LIT_DISPERSION\n let halfSpread: f32 = (1.0 / refractionIndex - 1.0) * 0.025 * dispersion;\n let refractionIndexR: f32 = refractionIndex - halfSpread;\n refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndexR)) * scale;\n refraction.r = evalRefractionColor(refractionVector, gloss, refractionIndexR).r;\n let refractionIndexB: f32 = refractionIndex + halfSpread;\n refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndexB)) * scale;\n refraction.b = evalRefractionColor(refractionVector, gloss, refractionIndexB).b;\n #endif\n var transmittance: vec3f;\n if (uniform.material_invAttenuationDistance != 0.0)\n {\n let attenuation: vec3f = -log(uniform.material_attenuation) * uniform.material_invAttenuationDistance;\n transmittance = exp(-attenuation * length(refractionVector));\n }\n else\n {\n transmittance = refraction;\n }\n let fresnel: vec3f = vec3f(1.0) -\n getFresnel(\n dot(viewDir, worldNormal),\n gloss,\n specularity\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n iridescenceIntensity\n #endif\n );\n dDiffuseLight = mix(dDiffuseLight, refraction * transmittance * fresnel, transmission);\n}\n",reprojectPS:'\nvarying vUv0: vec2f;\n#ifdef CUBEMAP_SOURCE\n var sourceCube: texture_cube;\n var sourceCubeSampler : sampler;\n#else\n var sourceTex: texture_2d;\n var sourceTexSampler : sampler;\n#endif\n#ifdef USE_SAMPLES_TEX\n var samplesTex: texture_2d;\n var samplesTexSampler : sampler;\n uniform samplesTexInverseSize: vec2f;\n#endif\nuniform params: vec3f;\nfn targetFace() -> f32 { return uniform.params.x; }\nfn targetTotalPixels() -> f32 { return uniform.params.y; }\nfn sourceTotalPixels() -> f32 { return uniform.params.z; }\nconst PI: f32 = 3.141592653589793;\nfn saturate(x: f32) -> f32 {\n return clamp(x, 0.0, 1.0);\n}\n#include "decodePS"\n#include "encodePS"\nfn modifySeams(dir: vec3f, scale: f32) -> vec3f {\n let adir = abs(dir);\n let M = max(max(adir.x, adir.y), adir.z);\n return dir / M * vec3f(\n select(scale, 1.0, adir.x == M),\n select(scale, 1.0, adir.y == M),\n select(scale, 1.0, adir.z == M)\n );\n}\nfn toSpherical(dir: vec3f) -> vec2f {\n let nonZeroXZ = any(dir.xz != vec2f(0.0, 0.0));\n return vec2f(select(0.0, atan2(dir.x, dir.z), nonZeroXZ), asin(dir.y));\n}\nfn fromSpherical(uv: vec2f) -> vec3f {\n return vec3f(cos(uv.y) * sin(uv.x),\n sin(uv.y),\n cos(uv.y) * cos(uv.x));\n}\nfn getDirectionEquirect(uv: vec2f) -> vec3f {\n return fromSpherical((vec2f(uv.x, 1.0 - uv.y) * 2.0 - 1.0) * vec2f(PI, PI * 0.5));\n}\nfn signNotZero(k: f32) -> f32 {\n return select(-1.0, 1.0, k >= 0.0);\n}\nfn signNotZeroVec2(v: vec2f) -> vec2f {\n return vec2f(signNotZero(v.x), signNotZero(v.y));\n}\nfn octDecode(o: vec2f) -> vec3f {\n var v = vec3f(o.x, 1.0 - abs(o.x) - abs(o.y), o.y);\n if (v.y < 0.0) {\n var temp: vec2f = (1.0 - abs(v.zx)) * signNotZeroVec2(v.xz);\n v = vec3f(temp.x, v.y, temp.y);\n }\n return normalize(v);\n}\nfn getDirectionOctahedral(uv: vec2f) -> vec3f {\n return octDecode(vec2f(uv.x, 1.0 - uv.y) * 2.0 - 1.0);\n}\nfn octEncode(v: vec3f) -> vec2f {\n let l1norm = abs(v.x) + abs(v.y) + abs(v.z);\n var result = v.xz * (1.0 / l1norm);\n if (v.y < 0.0) {\n result = (1.0 - abs(result.yx)) * signNotZeroVec2(result.xy);\n }\n return result;\n}\n#ifdef CUBEMAP_SOURCE\n fn sampleCubemapDir(dir: vec3f) -> vec4f {\n return textureSample(sourceCube, sourceCubeSampler, modifySeams(dir, 1.0));\n }\n fn sampleCubemapSph(sph: vec2f) -> vec4f {\n return sampleCubemapDir(fromSpherical(sph));\n }\n fn sampleCubemapDirLod(dir: vec3f, mipLevel: f32) -> vec4f {\n return textureSampleLevel(sourceCube, sourceCubeSampler, modifySeams(dir, 1.0), mipLevel);\n }\n fn sampleCubemapSphLod(sph: vec2f, mipLevel: f32) -> vec4f {\n return sampleCubemapDirLod(fromSpherical(sph), mipLevel);\n }\n#else\n fn sampleEquirectSph(sph: vec2f) -> vec4f {\n let uv = sph / vec2f(PI * 2.0, PI) + 0.5;\n return textureSample(sourceTex, sourceTexSampler, vec2f(uv.x, 1.0 - uv.y));\n }\n fn sampleEquirectDir(dir: vec3f) -> vec4f {\n return sampleEquirectSph(toSpherical(dir));\n }\n fn sampleEquirectSphLod(sph: vec2f, mipLevel: f32) -> vec4f {\n let uv = sph / vec2f(PI * 2.0, PI) + 0.5;\n return textureSampleLevel(sourceTex, sourceTexSampler, vec2f(uv.x, 1.0 - uv.y), mipLevel);\n }\n fn sampleEquirectDirLod(dir: vec3f, mipLevel: f32) -> vec4f {\n return sampleEquirectSphLod(toSpherical(dir), mipLevel);\n }\n fn sampleOctahedralDir(dir: vec3f) -> vec4f {\n let uv = octEncode(dir) * 0.5 + 0.5;\n return textureSample(sourceTex, sourceTexSampler, vec2f(uv.x, 1.0 - uv.y));\n }\n fn sampleOctahedralSph(sph: vec2f) -> vec4f {\n return sampleOctahedralDir(fromSpherical(sph));\n }\n fn sampleOctahedralDirLod(dir: vec3f, mipLevel: f32) -> vec4f {\n let uv = octEncode(dir) * 0.5 + 0.5;\n return textureSampleLevel(sourceTex, sourceTexSampler, vec2f(uv.x, 1.0 - uv.y), mipLevel);\n }\n fn sampleOctahedralSphLod(sph: vec2f, mipLevel: f32) -> vec4f {\n return sampleOctahedralDirLod(fromSpherical(sph), mipLevel);\n }\n#endif\nfn getDirectionCubemap(uv: vec2f) -> vec3f {\n let st = uv * 2.0 - 1.0;\n let face = targetFace();\n var vec: vec3f;\n if (face == 0.0) {\n vec = vec3f(1, -st.y, -st.x);\n } else if (face == 1.0) {\n vec = vec3f(-1, -st.y, st.x);\n } else if (face == 2.0) {\n vec = vec3f(st.x, 1, st.y);\n } else if (face == 3.0) {\n vec = vec3f(st.x, -1, -st.y);\n } else if (face == 4.0) {\n vec = vec3f(st.x, -st.y, 1);\n } else {\n vec = vec3f(-st.x, -st.y, -1);\n }\n return normalize(modifySeams(vec, 1.0));\n}\nfn matrixFromVector(n: vec3f) -> mat3x3f {\n let a = 1.0 / (1.0 + n.z);\n let b = -n.x * n.y * a;\n let b1 = vec3f(1.0 - n.x * n.x * a, b, -n.x);\n let b2 = vec3f(b, 1.0 - n.y * n.y * a, -n.y);\n return mat3x3f(b1, b2, n);\n}\nfn matrixFromVectorSlow(n: vec3f) -> mat3x3f {\n let up = select(vec3f(0.0, 0.0, select(-1.0, 1.0, n.y > 0.0)), vec3f(0.0, 1.0, 0.0), abs(n.y) > 0.0000001);\n let x = normalize(cross(up, n));\n let y = cross(n, x);\n return mat3x3f(x, y, n);\n}\nfn reproject(uv: vec2f) -> vec4f {\n if ({NUM_SAMPLES} <= 1) {\n return {ENCODE_FUNC}({DECODE_FUNC}({SOURCE_FUNC}Dir({TARGET_FUNC}(uv))));\n } else {\n let t = {TARGET_FUNC}(uv);\n let tu = dpdx(t);\n let tv = dpdy(t);\n var result = vec3f(0.0);\n for (var u = 0.0; u < {NUM_SAMPLES_SQRT}; u += 1.0) {\n for (var v = 0.0; v < {NUM_SAMPLES_SQRT}; v += 1.0) {\n result += {DECODE_FUNC}({SOURCE_FUNC}Dir(normalize(t +\n tu * (u / {NUM_SAMPLES_SQRT} - 0.5) +\n tv * (v / {NUM_SAMPLES_SQRT} - 0.5))));\n }\n }\n return {ENCODE_FUNC}(result / ({NUM_SAMPLES_SQRT} * {NUM_SAMPLES_SQRT}));\n }\n}\nconst unpackFloat: vec4f = vec4f(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0);\n#ifdef USE_SAMPLES_TEX\n fn unpackSample(i: i32, L: ptr, mipLevel: ptr) {\n var u = (f32(i * 4) + 0.5) * uniform.samplesTexInverseSize.x;\n var v = (floor(u) + 0.5) * uniform.samplesTexInverseSize.y;\n var raw: vec4f;\n raw.x = dot(textureSample(samplesTex, samplesTexSampler, vec2f(u, v)), unpackFloat); u += uniform.samplesTexInverseSize.x;\n raw.y = dot(textureSample(samplesTex, samplesTexSampler, vec2f(u, v)), unpackFloat); u += uniform.samplesTexInverseSize.x;\n raw.z = dot(textureSample(samplesTex, samplesTexSampler, vec2f(u, v)), unpackFloat); u += uniform.samplesTexInverseSize.x;\n raw.w = dot(textureSample(samplesTex, samplesTexSampler, vec2f(u, v)), unpackFloat);\n *L = raw.xyz * 2.0 - 1.0;\n *mipLevel = raw.w * 8.0;\n }\n fn prefilterSamples(uv: vec2f) -> vec4f {\n let vecSpace = matrixFromVectorSlow({TARGET_FUNC}(uv));\n var L: vec3f;\n var mipLevel: f32;\n var result = vec3f(0.0);\n var totalWeight = 0.0;\n for (var i = 0; i < {NUM_SAMPLES}; i += 1) {\n unpackSample(i, &L, &mipLevel);\n result += {DECODE_FUNC}({SOURCE_FUNC}DirLod(vecSpace * L, mipLevel)) * L.z;\n totalWeight += L.z;\n }\n return {ENCODE_FUNC}(result / totalWeight);\n }\n fn prefilterSamplesUnweighted(uv: vec2f) -> vec4f {\n let vecSpace = matrixFromVectorSlow({TARGET_FUNC}(uv));\n var L: vec3f;\n var mipLevel: f32;\n var result = vec3f(0.0);\n for (var i = 0; i < {NUM_SAMPLES}; i += 1) {\n unpackSample(i, &L, &mipLevel);\n result += {DECODE_FUNC}({SOURCE_FUNC}DirLod(vecSpace * L, mipLevel));\n }\n return {ENCODE_FUNC}(result / f32({NUM_SAMPLES}));\n }\n#endif\n@fragment\nfn fragmentMain(input : FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n output.color = {PROCESS_FUNC}(input.vUv0);\n return output;\n}\n',reprojectVS:"\nattribute vertex_position: vec2f;\nuniform uvMod: vec4f;\nvarying vUv0: vec2f;\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n output.position = vec4f(input.vertex_position, 0.5, 1.0);\n output.vUv0 = getImageEffectUV((input.vertex_position * 0.5 + vec2f(0.5, 0.5)) * uniform.uvMod.xy + uniform.uvMod.zw);\n return output;\n}\n",screenDepthPS:"\nvar uSceneDepthMap: texture_2d;\nvar uSceneDepthMapSampler: sampler;\n#ifndef SCREENSIZE\n #define SCREENSIZE\n uniform uScreenSize: vec4f;\n#endif\n#ifndef VIEWMATRIX\n #define VIEWMATRIX\n uniform matrix_view: mat4x4f;\n#endif\n#ifndef LINEARIZE_DEPTH\n #define LINEARIZE_DEPTH\n #ifndef CAMERAPLANES\n #define CAMERAPLANES\n uniform camera_params: vec4f;\n #endif\n fn linearizeDepth(z: f32) -> f32 {\n if (uniform.camera_params.w == 0.0) {\n return (uniform.camera_params.z * uniform.camera_params.y) / (uniform.camera_params.y + z * (uniform.camera_params.z - uniform.camera_params.y));\n } else {\n return uniform.camera_params.z + z * (uniform.camera_params.y - uniform.camera_params.z);\n }\n }\n#endif\nfn delinearizeDepth(linearDepth: f32) -> f32 {\n if (uniform.camera_params.w == 0.0) {\n return (uniform.camera_params.y * (uniform.camera_params.z - linearDepth)) / (linearDepth * (uniform.camera_params.z - uniform.camera_params.y));\n } else {\n return (linearDepth - uniform.camera_params.z) / (uniform.camera_params.y - uniform.camera_params.z);\n }\n}\nfn getLinearScreenDepth(uv: vec2f) -> f32 {\n #ifdef SCENE_DEPTHMAP_LINEAR\n #ifdef SCENE_DEPTHMAP_FLOAT\n return textureSample(uSceneDepthMap, uSceneDepthMapSampler, uv).r;\n #else\n let textureSize = textureDimensions(uSceneDepthMap, 0);\n let texel: vec2i = vec2i(uv * vec2f(textureSize));\n let data: vec4f = textureLoad(uSceneDepthMap, texel, 0);\n let data_u32: vec4u = vec4u(data * 255.0);\n let intBits: u32 = (data_u32.r << 24u) | (data_u32.g << 16u) | (data_u32.b << 8u) | data_u32.a;\n return bitcast(intBits);\n #endif\n #else\n return linearizeDepth(textureSample(uSceneDepthMap, uSceneDepthMapSampler, uv).r);\n #endif\n}\n#ifndef VERTEXSHADER\n fn getLinearScreenDepthFrag() -> f32 {\n let uv: vec2f = pcPosition.xy * uniform.uScreenSize.zw;\n return getLinearScreenDepth(uv);\n }\n#endif\nfn getLinearDepth(pos: vec3f) -> f32 {\n return -(uniform.matrix_view * vec4f(pos, 1.0)).z;\n}\n",shadowCascadesPS:"\nfn getShadowCascadeIndex(shadowCascadeDistances: vec4f, shadowCascadeCount: i32) -> i32 {\n let depth: f32 = 1.0 / pcPosition.w;\n let comparisons: vec4f = step(shadowCascadeDistances, vec4f(depth));\n let cascadeIndex: i32 = i32(dot(comparisons, vec4f(1.0)));\n return min(cascadeIndex, shadowCascadeCount - 1);\n}\nfn ditherShadowCascadeIndex(cascadeIndex_in: i32, shadowCascadeDistances: vec4f, shadowCascadeCount: i32, blendFactor: f32) -> i32 {\n var cascadeIndex: i32 = cascadeIndex_in;\n if (cascadeIndex < shadowCascadeCount - 1) {\n let currentRangeEnd: f32 = shadowCascadeDistances[cascadeIndex];\n let transitionStart: f32 = blendFactor * currentRangeEnd;\n let depth: f32 = 1.0 / pcPosition.w;\n if (depth > transitionStart) {\n let transitionFactor: f32 = smoothstep(transitionStart, currentRangeEnd, depth);\n let dither: f32 = fract(sin(dot(pcPosition.xy, vec2f(12.9898, 78.233))) * 43758.5453);\n if (dither < transitionFactor) {\n cascadeIndex = cascadeIndex + 1;\n }\n }\n }\n return cascadeIndex;\n}\nfn fadeShadow(shadowCoord_in: vec3f, shadowCascadeDistances: vec4f) -> vec3f {\n var shadowCoord: vec3f = shadowCoord_in;\n let depth: f32 = 1.0 / pcPosition.w;\n if (depth > shadowCascadeDistances.w) {\n shadowCoord.z = -9999999.0;\n }\n return shadowCoord;\n}\n",shadowEVSMPS:"\nfn linstep(a: f32, b: f32, v: f32) -> f32 {\n return clamp((v - a) / (b - a), 0.0, 1.0);\n}\nfn reduceLightBleeding(pMax: f32, amount: f32) -> f32 {\n return linstep(amount, 1.0, pMax);\n}\nfn chebyshevUpperBound(moments: vec2f, mean: f32, minVariance: f32, lightBleedingReduction: f32) -> f32 {\n var variance: f32 = moments.y - (moments.x * moments.x);\n variance = max(variance, minVariance);\n let d: f32 = mean - moments.x;\n var pMax: f32 = variance / (variance + (d * d));\n pMax = reduceLightBleeding(pMax, lightBleedingReduction);\n return select(pMax, 1.0, mean <= moments.x);\n}\nfn calculateEVSM(moments_in: vec3f, Z_in: f32, vsmBias: f32, exponent: f32) -> f32 {\n let Z: f32 = 2.0 * Z_in - 1.0;\n let warpedDepth: f32 = exp(exponent * Z);\n let moments: vec2f = moments_in.xy + vec2f(warpedDepth, warpedDepth*warpedDepth) * (1.0 - moments_in.z);\n let VSMBias: f32 = vsmBias;\n let depthScale: f32 = VSMBias * exponent * warpedDepth;\n let minVariance1: f32 = depthScale * depthScale;\n return chebyshevUpperBound(moments, warpedDepth, minVariance1, 0.1);\n}\nfn VSM16(tex: texture_2d, texSampler: sampler, texCoords: vec2f, resolution: f32, Z: f32, vsmBias: f32, exponent: f32) -> f32 {\n let moments: vec3f = textureSampleLevel(tex, texSampler, texCoords, 0.0).xyz;\n return calculateEVSM(moments, Z, vsmBias, exponent);\n}\nfn getShadowVSM16(shadowMap: texture_2d, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, exponent: f32) -> f32 {\n return VSM16(shadowMap, shadowMapSampler, shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);\n}\nfn getShadowSpotVSM16(shadowMap: texture_2d, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, exponent: f32, lightDir: vec3f) -> f32 {\n let Z: f32 = length(lightDir) * shadowParams.w + shadowParams.z;\n return VSM16(shadowMap, shadowMapSampler, shadowCoord.xy, shadowParams.x, Z, shadowParams.y, exponent);\n}\nfn VSM32(tex: texture_2d, texSampler: sampler, texCoords_in: vec2f, resolution: f32, Z: f32, vsmBias: f32, exponent: f32) -> f32 {\n #ifdef CAPS_TEXTURE_FLOAT_FILTERABLE\n var moments: vec3f = textureSampleLevel(tex, texSampler, texCoords_in, 0.0).xyz;\n #else\n var pixelSize : f32 = 1.0 / resolution;\n let texCoords: vec2f = texCoords_in - vec2f(pixelSize);\n let s00: vec3f = textureSampleLevel(tex, texSampler, texCoords, 0.0).xyz;\n let s10: vec3f = textureSampleLevel(tex, texSampler, texCoords + vec2f(pixelSize, 0.0), 0.0).xyz;\n let s01: vec3f = textureSampleLevel(tex, texSampler, texCoords + vec2f(0.0, pixelSize), 0.0).xyz;\n let s11: vec3f = textureSampleLevel(tex, texSampler, texCoords + vec2f(pixelSize), 0.0).xyz;\n let fr: vec2f = fract(texCoords * resolution);\n let h0: vec3f = mix(s00, s10, fr.x);\n let h1: vec3f = mix(s01, s11, fr.x);\n var moments: vec3f = mix(h0, h1, fr.y);\n #endif\n return calculateEVSM(moments, Z, vsmBias, exponent);\n}\nfn getShadowVSM32(shadowMap: texture_2d, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, exponent: f32) -> f32 {\n return VSM32(shadowMap, shadowMapSampler, shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);\n}\nfn getShadowSpotVSM32(shadowMap: texture_2d, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, exponent: f32, lightDir: vec3f) -> f32 {\n let Z: f32 = length(lightDir) * shadowParams.w + shadowParams.z;\n return VSM32(shadowMap, shadowMapSampler, shadowCoord.xy, shadowParams.x, Z, shadowParams.y, exponent);\n}\n",shadowPCF1PS:"\nfn getShadowPCF1x1(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {\n return textureSampleCompareLevel(shadowMap, shadowMapSampler, shadowCoord.xy, shadowCoord.z);\n}\nfn getShadowSpotPCF1x1(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {\n return textureSampleCompareLevel(shadowMap, shadowMapSampler, shadowCoord.xy, shadowCoord.z);\n}\n",shadowPCF3PS:"\nfn _getShadowPCF3x3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec3f) -> f32 {\n let z: f32 = shadowCoord.z;\n let uv: vec2f = shadowCoord.xy * shadowParams.x;\n let shadowMapSizeInv: f32 = 1.0 / shadowParams.x;\n let base_uv_temp: vec2f = floor(uv + 0.5);\n let s: f32 = (uv.x + 0.5 - base_uv_temp.x);\n let t: f32 = (uv.y + 0.5 - base_uv_temp.y);\n let base_uv: vec2f = (base_uv_temp - vec2f(0.5)) * shadowMapSizeInv;\n var sum: f32 = 0.0;\n let uw0: f32 = (3.0 - 2.0 * s);\n let uw1: f32 = (1.0 + 2.0 * s);\n let u0_offset: f32 = (2.0 - s) / uw0 - 1.0;\n let u1_offset: f32 = s / uw1 + 1.0;\n let vw0: f32 = (3.0 - 2.0 * t);\n let vw1: f32 = (1.0 + 2.0 * t);\n let v0_offset: f32 = (2.0 - t) / vw0 - 1.0;\n let v1_offset: f32 = t / vw1 + 1.0;\n let u0: f32 = u0_offset * shadowMapSizeInv + base_uv.x;\n let v0: f32 = v0_offset * shadowMapSizeInv + base_uv.y;\n let u1: f32 = u1_offset * shadowMapSizeInv + base_uv.x;\n let v1: f32 = v1_offset * shadowMapSizeInv + base_uv.y;\n sum = sum + uw0 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v0), z);\n sum = sum + uw1 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v0), z);\n sum = sum + uw0 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v1), z);\n sum = sum + uw1 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v1), z);\n sum = sum * (1.0 / 16.0);\n return sum;\n}\nfn getShadowPCF3x3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {\n return _getShadowPCF3x3(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz);\n}\nfn getShadowSpotPCF3x3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {\n return _getShadowPCF3x3(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz);\n}\n",shadowPCF5PS:"\nfn _getShadowPCF5x5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec3f) -> f32 {\n let z: f32 = shadowCoord.z;\n let uv: vec2f = shadowCoord.xy * shadowParams.x;\n let shadowMapSizeInv: f32 = 1.0 / shadowParams.x;\n let base_uv_temp: vec2f = floor(uv + 0.5);\n let s: f32 = (uv.x + 0.5 - base_uv_temp.x);\n let t: f32 = (uv.y + 0.5 - base_uv_temp.y);\n let base_uv: vec2f = (base_uv_temp - vec2f(0.5)) * shadowMapSizeInv;\n let uw0: f32 = (4.0 - 3.0 * s);\n let uw1: f32 = 7.0;\n let uw2: f32 = (1.0 + 3.0 * s);\n let u0_offset: f32 = (3.0 - 2.0 * s) / uw0 - 2.0;\n let u1_offset: f32 = (3.0 + s) / uw1;\n let u2_offset: f32 = s / uw2 + 2.0;\n let vw0: f32 = (4.0 - 3.0 * t);\n let vw1: f32 = 7.0;\n let vw2: f32 = (1.0 + 3.0 * t);\n let v0_offset: f32 = (3.0 - 2.0 * t) / vw0 - 2.0;\n let v1_offset: f32 = (3.0 + t) / vw1;\n let v2_offset: f32 = t / vw2 + 2.0;\n var sum: f32 = 0.0;\n let u0: f32 = u0_offset * shadowMapSizeInv + base_uv.x;\n let v0: f32 = v0_offset * shadowMapSizeInv + base_uv.y;\n let u1: f32 = u1_offset * shadowMapSizeInv + base_uv.x;\n let v1: f32 = v1_offset * shadowMapSizeInv + base_uv.y;\n let u2: f32 = u2_offset * shadowMapSizeInv + base_uv.x;\n let v2: f32 = v2_offset * shadowMapSizeInv + base_uv.y;\n sum = sum + uw0 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v0), z);\n sum = sum + uw1 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v0), z);\n sum = sum + uw2 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u2, v0), z);\n sum = sum + uw0 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v1), z);\n sum = sum + uw1 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v1), z);\n sum = sum + uw2 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u2, v1), z);\n sum = sum + uw0 * vw2 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v2), z);\n sum = sum + uw1 * vw2 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v2), z);\n sum = sum + uw2 * vw2 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u2, v2), z);\n sum = sum * (1.0 / 144.0);\n sum = saturate(sum);\n return sum;\n}\nfn getShadowPCF5x5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {\n return _getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz);\n}\nfn getShadowSpotPCF5x5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {\n return _getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz);\n}\n",shadowSoftPS:"\nfn fractSinRand(uv: vec2f) -> f32 {\n let PI: f32 = 3.141592653589793;\n let a: f32 = 12.9898; let b: f32 = 78.233; let c: f32 = 43758.5453;\n let dt: f32 = dot(uv.xy, vec2f(a, b));\n let sn: f32 = dt % PI;\n return fract(sin(sn) * c);\n}\nstruct VogelDiskData {\n invNumSamples: f32,\n initialAngle: f32,\n currentPointId: f32,\n}\nfn prepareDiskConstants(data: ptr, sampleCount: i32, randomSeed: f32) {\n let pi2: f32 = 6.28318530718;\n data.invNumSamples = 1.0 / f32(sampleCount);\n data.initialAngle = randomSeed * pi2;\n data.currentPointId = 0.0;\n}\nfn generateDiskSample(data: ptr) -> vec2f {\n let GOLDEN_ANGLE: f32 = 2.399963;\n let r: f32 = sqrt((data.currentPointId + 0.5) * data.invNumSamples);\n let theta: f32 = data.currentPointId * GOLDEN_ANGLE + data.initialAngle;\n let offset: vec2f = vec2f(cos(theta), sin(theta)) * pow(r, 1.33);\n data.currentPointId = data.currentPointId + 1.0;\n return offset;\n}\nfn PCSSFindBlocker(shadowMap: texture_2d, shadowMapSampler: sampler, avgBlockerDepth: ptr, numBlockers: ptr,\n shadowCoords: vec2f, z: f32, shadowBlockerSamples: i32, penumbraSize: f32, invShadowMapSize: f32, randomSeed: f32) {\n var diskData: VogelDiskData;\n prepareDiskConstants(&diskData, shadowBlockerSamples, randomSeed);\n let searchWidth: f32 = penumbraSize * invShadowMapSize;\n var blockerSum: f32 = 0.0;\n var numBlockers_local: i32 = 0;\n for( var i: i32 = 0; i < shadowBlockerSamples; i = i + 1 ) {\n let diskUV: vec2f = generateDiskSample(&diskData);\n let sampleUV: vec2f = shadowCoords + diskUV * searchWidth;\n let shadowMapDepth: f32 = textureSampleLevel(shadowMap, shadowMapSampler, sampleUV, 0.0).r;\n if ( shadowMapDepth < z ) {\n blockerSum = blockerSum + shadowMapDepth;\n numBlockers_local = numBlockers_local + 1;\n }\n }\n *avgBlockerDepth = blockerSum / f32(numBlockers_local);\n *numBlockers = numBlockers_local;\n}\nfn PCSSFilter(shadowMap: texture_2d, shadowMapSampler: sampler, uv: vec2f, receiverDepth: f32, shadowSamples: i32, filterRadius: f32, randomSeed: f32) -> f32 {\n var diskData: VogelDiskData;\n prepareDiskConstants(&diskData, shadowSamples, randomSeed);\n var sum: f32 = 0.0;\n for (var i: i32 = 0; i < shadowSamples; i = i + 1) {\n let offsetUV: vec2f = generateDiskSample(&diskData) * filterRadius;\n let depth: f32 = textureSampleLevel(shadowMap, shadowMapSampler, uv + offsetUV, 0.0).r;\n sum = sum + step(receiverDepth, depth);\n }\n return sum / f32(shadowSamples);\n}\nfn getPenumbra(dblocker: f32, dreceiver: f32, penumbraSize: f32, penumbraFalloff: f32) -> f32 {\n let dist: f32 = dreceiver - dblocker;\n let penumbra: f32 = 1.0 - pow(1.0 - dist, penumbraFalloff);\n return penumbra * penumbraSize;\n}\nfn PCSSDirectional(shadowMap: texture_2d, shadowMapSampler: sampler, shadowCoords: vec3f, cameraParams: vec4f, softShadowParams: vec4f) -> f32 {\n let receiverDepth: f32 = shadowCoords.z;\n let randomSeed: f32 = fractSinRand(pcPosition.xy);\n let shadowSamples: i32 = i32(softShadowParams.x);\n let shadowBlockerSamples: i32 = i32(softShadowParams.y);\n let penumbraSize: f32 = softShadowParams.z;\n let penumbraFalloff: f32 = softShadowParams.w;\n let shadowMapSize: i32 = i32(textureDimensions(shadowMap, 0).x);\n var invShadowMapSize: f32 = 1.0 / f32(shadowMapSize);\n invShadowMapSize = invShadowMapSize * (f32(shadowMapSize) / 2048.0);\n var penumbra: f32;\n if (shadowBlockerSamples > 0) {\n var avgBlockerDepth: f32 = 0.0;\n var numBlockers: i32 = 0;\n PCSSFindBlocker(shadowMap, shadowMapSampler, &avgBlockerDepth, &numBlockers, shadowCoords.xy, receiverDepth, shadowBlockerSamples, penumbraSize, invShadowMapSize, randomSeed);\n if (numBlockers < 1) {\n return 1.0;\n }\n penumbra = getPenumbra(avgBlockerDepth, shadowCoords.z, penumbraSize, penumbraFalloff);\n } else {\n penumbra = penumbraSize;\n }\n let filterRadius: f32 = penumbra * invShadowMapSize;\n return PCSSFilter(shadowMap, shadowMapSampler, shadowCoords.xy, receiverDepth, shadowSamples, filterRadius, randomSeed);\n}\nfn getShadowPCSS(shadowMap: texture_2d, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, cameraParams: vec4f, softShadowParams: vec4f, lightDir: vec3f) -> f32 {\n return PCSSDirectional(shadowMap, shadowMapSampler, shadowCoord, cameraParams, softShadowParams);\n}\n",skinBatchVS:"\nattribute vertex_boneIndices: f32;\nvar texture_poseMap: texture_2d;\nfn getBoneMatrix(indexFloat: f32) -> mat4x4f {\n let width = i32(textureDimensions(texture_poseMap).x);\n let index: i32 = i32(indexFloat + 0.5) * 3;\n let iy: i32 = index / width;\n let ix: i32 = index % width;\n let v1: vec4f = textureLoad(texture_poseMap, vec2i(ix + 0, iy), 0);\n let v2: vec4f = textureLoad(texture_poseMap, vec2i(ix + 1, iy), 0);\n let v3: vec4f = textureLoad(texture_poseMap, vec2i(ix + 2, iy), 0);\n return mat4x4f(\n v1.x, v2.x, v3.x, 0,\n v1.y, v2.y, v3.y, 0,\n v1.z, v2.z, v3.z, 0,\n v1.w, v2.w, v3.w, 1.0\n );\n}\n",skinVS:"\nattribute vertex_boneWeights: vec4f;\nattribute vertex_boneIndices: vec4f;\nvar texture_poseMap: texture_2d;\nstruct BoneMatrix {\n v1: vec4f,\n v2: vec4f,\n v3: vec4f,\n}\nfn getBoneMatrix(width: i32, index: i32) -> BoneMatrix {\n let v = index / width;\n let u = index % width;\n var result: BoneMatrix;\n result.v1 = textureLoad(texture_poseMap, vec2i(u + 0, v), 0);\n result.v2 = textureLoad(texture_poseMap, vec2i(u + 1, v), 0);\n result.v3 = textureLoad(texture_poseMap, vec2i(u + 2, v), 0);\n return result;\n}\nfn getSkinMatrix(indicesFloat: vec4f, weights: vec4f) -> mat4x4f {\n let width = i32(textureDimensions(texture_poseMap).x);\n var indices = vec4i(indicesFloat + 0.5) * 3;\n let boneA = getBoneMatrix(width, indices.x);\n let boneB = getBoneMatrix(width, indices.y);\n let boneC = getBoneMatrix(width, indices.z);\n let boneD = getBoneMatrix(width, indices.w);\n let v1 = boneA.v1 * weights.x + boneB.v1 * weights.y + boneC.v1 * weights.z + boneD.v1 * weights.w;\n let v2 = boneA.v2 * weights.x + boneB.v2 * weights.y + boneC.v2 * weights.z + boneD.v2 * weights.w;\n let v3 = boneA.v3 * weights.x + boneB.v3 * weights.y + boneC.v3 * weights.z + boneD.v3 * weights.w;\n let one = dot(weights, vec4f(1.0, 1.0, 1.0, 1.0));\n return mat4x4f(\n v1.x, v2.x, v3.x, 0,\n v1.y, v2.y, v3.y, 0,\n v1.z, v2.z, v3.z, 0,\n v1.w, v2.w, v3.w, one\n );\n}\n",skyboxPS:'\n #define LIT_SKYBOX_INTENSITY\n #include "envProcPS"\n #include "gammaPS"\n #include "tonemappingPS"\n #ifdef PREPASS_PASS\n varying vLinearDepth: f32;\n #include "floatAsUintPS"\n #endif\n varying vViewDir : vec3f;\n uniform skyboxHighlightMultiplier : f32;\n #ifdef SKY_CUBEMAP\n var texture_cubeMap : texture_cube;\n var texture_cubeMap_sampler : sampler;\n #ifdef SKYMESH\n varying vWorldPos : vec3f;\n uniform cubeMapRotationMatrix : mat3x3f;\n uniform projectedSkydomeCenter : vec3f;\n #endif\n #else\n #include "sphericalPS"\n #include "envAtlasPS"\n var texture_envAtlas : texture_2d;\n var texture_envAtlas_sampler : sampler;\n uniform mipLevel : f32;\n #endif\n @fragment\n fn fragmentMain(input : FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n #ifdef PREPASS_PASS\n output.color = float2vec4(vLinearDepth);\n #else\n var linear : vec3f;\n var dir : vec3f;\n #ifdef SKY_CUBEMAP\n #ifdef SKYMESH\n var envDir : vec3f = normalize(input.vWorldPos - uniform.projectedSkydomeCenter);\n dir = envDir * uniform.cubeMapRotationMatrix;\n #else\n dir = input.vViewDir;\n #endif\n dir.x *= -1.0;\n linear = {SKYBOX_DECODE_FNC}(textureSample(texture_cubeMap, texture_cubeMap_sampler, dir));\n #else\n dir = input.vViewDir * vec3f(-1.0, 1.0, 1.0);\n let uv : vec2f = toSphericalUv(normalize(dir));\n linear = {SKYBOX_DECODE_FNC}(textureSample(texture_envAtlas, texture_envAtlas_sampler, mapRoughnessUv(uv, uniform.mipLevel)));\n #endif\n if (any(linear >= vec3f(64.0))) {\n linear *= uniform.skyboxHighlightMultiplier;\n }\n \n output.color = vec4f(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0);\n #endif\n return output;\n }\n',skyboxVS:"\n attribute aPosition : vec4f;\n uniform matrix_view : mat4x4f;\n uniform matrix_projectionSkybox : mat4x4f;\n uniform cubeMapRotationMatrix : mat3x3f;\n varying vViewDir : vec3f;\n #ifdef PREPASS_PASS\n varying vLinearDepth: f32;\n #endif\n #ifdef SKYMESH\n uniform matrix_model : mat4x4f;\n varying vWorldPos : vec3f;\n #endif\n @vertex\n fn vertexMain(input : VertexInput) -> VertexOutput {\n var output : VertexOutput;\n var view : mat4x4f = uniform.matrix_view;\n #ifdef SKYMESH\n var worldPos : vec4f = uniform.matrix_model * input.aPosition;\n output.vWorldPos = worldPos.xyz;\n output.position = uniform.matrix_projectionSkybox * (view * worldPos);\n #ifdef PREPASS_PASS\n output.vLinearDepth = -(uniform.matrix_view * vec4f(worldPos.xyz, 1.0)).z;\n #endif\n #else\n view[3][0] = 0.0;\n view[3][1] = 0.0;\n view[3][2] = 0.0;\n output.position = uniform.matrix_projectionSkybox * (view * input.aPosition);\n output.vViewDir = input.aPosition.xyz * uniform.cubeMapRotationMatrix;\n #ifdef PREPASS_PASS\n output.vLinearDepth = -pcPosition.w;\n #endif\n #endif\n output.position.z = output.position.w - 1.0e-7;\n return output;\n }\n",specularPS:"\n#ifdef STD_SPECULAR_CONSTANT\n uniform material_specular: vec3f;\n#endif\nfn getSpecularity() {\n var specularColor = vec3f(1.0, 1.0, 1.0);\n #ifdef STD_SPECULAR_CONSTANT\n specularColor = specularColor * uniform.material_specular;\n #endif\n #ifdef STD_SPECULAR_TEXTURE\n specularColor = specularColor * {STD_SPECULAR_TEXTURE_DECODE}(textureSampleBias({STD_SPECULAR_TEXTURE_NAME}, {STD_SPECULAR_TEXTURE_NAME}Sampler, {STD_SPECULAR_TEXTURE_UV}, uniform.textureBias)).{STD_SPECULAR_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_SPECULAR_VERTEX\n specularColor = specularColor * saturate3(vVertexColor.{STD_SPECULAR_VERTEX_CHANNEL});\n #endif\n dSpecularity = specularColor;\n}\n",sphericalPS:"\nfn toSpherical(dir: vec3f) -> vec2f {\n let angle_xz = select(0.0, atan2(dir.x, dir.z), any(dir.xz != vec2f(0.0)));\n return vec2f(angle_xz, asin(dir.y));\n}\nfn toSphericalUv(dir : vec3f) -> vec2f {\n const PI : f32 = 3.141592653589793;\n let uv : vec2f = toSpherical(dir) / vec2f(PI * 2.0, PI) + vec2f(0.5, 0.5);\n return vec2f(uv.x, 1.0 - uv.y);\n}\n",specularityFactorPS:"\n#ifdef STD_SPECULARITYFACTOR_CONSTANT\n uniform material_specularityFactor: f32;\n#endif\nfn getSpecularityFactor() {\n var specularityFactor = 1.0;\n #ifdef STD_SPECULARITYFACTOR_CONSTANT\n specularityFactor = specularityFactor * uniform.material_specularityFactor;\n #endif\n #ifdef STD_SPECULARITYFACTOR_TEXTURE\n specularityFactor = specularityFactor * textureSampleBias({STD_SPECULARITYFACTOR_TEXTURE_NAME}, {STD_SPECULARITYFACTOR_TEXTURE_NAME}Sampler, {STD_SPECULARITYFACTOR_TEXTURE_UV}, uniform.textureBias).{STD_SPECULARITYFACTOR_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_SPECULARITYFACTOR_VERTEX\n specularityFactor = specularityFactor * saturate(vVertexColor.{STD_SPECULARITYFACTOR_VERTEX_CHANNEL});\n #endif\n dSpecularityFactor = specularityFactor;\n}\n",spotPS:"\nfn getSpotEffect(lightSpotDir: vec3f, lightInnerConeAngle: f32, lightOuterConeAngle: f32, lightDirNorm: vec3f) -> f32 {\n let cosAngle: f32 = dot(lightDirNorm, lightSpotDir);\n return smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle);\n}",startNineSlicedPS:"\n nineSlicedUv = vec2f(vUv0.x, 1.0 - vUv0.y);\n",startNineSlicedTiledPS:"\n let tileMask: vec2f = step(vMask, vec2f(0.99999));\n let tileSize: vec2f = 0.5 * (innerOffset.xy + innerOffset.zw);\n let tileScale: vec2f = vec2f(1.0) / (vec2f(1.0) - tileSize);\n var clampedUv: vec2f = mix(innerOffset.xy * 0.5, vec2f(1.0) - innerOffset.zw * 0.5, fract((vTiledUv - tileSize) * tileScale));\n clampedUv = clampedUv * atlasRect.zw + atlasRect.xy;\n var nineSlicedUv: vec2f = vUv0 * tileMask + clampedUv * (vec2f(1.0) - tileMask);\n nineSlicedUv.y = 1.0 - nineSlicedUv.y;\n",stdDeclarationPS:'\n var dAlpha: f32 = 1.0;\n #if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE\n #ifdef STD_OPACITY_TEXTURE_ALLOCATE\n var texture_opacityMap : texture_2d;\n var texture_opacityMapSampler : sampler;\n #endif\n #endif\n #ifdef FORWARD_PASS\n var dAlbedo: vec3f;\n var dNormalW: vec3f;\n var dSpecularity: vec3f = vec3f(0.0, 0.0, 0.0);\n var dGlossiness: f32 = 0.0;\n #ifdef LIT_REFRACTION\n var dTransmission: f32;\n var dThickness: f32;\n #endif\n #ifdef LIT_SCENE_COLOR\n var uSceneColorMap : texture_2d;\n var uSceneColorMapSampler : sampler;\n #endif\n #ifdef LIT_SCREEN_SIZE\n uniform uScreenSize: vec4f;\n #endif\n #ifdef LIT_TRANSFORMS\n var matrix_viewProjection: mat4x4f;\n var matrix_model: mat4x4f;\n #endif\n #ifdef STD_HEIGHT_MAP\n var dUvOffset: vec2f;\n #ifdef STD_DIFFUSE_TEXTURE_ALLOCATE\n var texture_heightMap : texture_2d;\n var texture_heightMapSampler : sampler;\n #endif\n #endif\n #ifdef STD_DIFFUSE_TEXTURE_ALLOCATE\n var texture_diffuseMap : texture_2d;\n var texture_diffuseMapSampler : sampler;\n #endif\n #ifdef STD_DIFFUSEDETAIL_TEXTURE_ALLOCATE\n var texture_diffuseDetailMap : texture_2d;\n var texture_diffuseDetailMapSampler : sampler;\n #endif\n #ifdef STD_NORMAL_TEXTURE_ALLOCATE\n var texture_normalMap : texture_2d;\n var texture_normalMapSampler : sampler;\n #endif\n #ifdef STD_NORMALDETAIL_TEXTURE_ALLOCATE\n var texture_normalDetailMap : texture_2d;\n var texture_normalDetailMapSampler : sampler;\n #endif\n #ifdef STD_THICKNESS_TEXTURE_ALLOCATE\n var texture_thicknessMap : texture_2d;\n var texture_thicknessMapSampler : sampler;\n #endif\n #ifdef STD_REFRACTION_TEXTURE_ALLOCATE\n var texture_refractionMap : texture_2d;\n var texture_refractionMapSampler : sampler;\n #endif\n #ifdef LIT_IRIDESCENCE\n var dIridescence: f32;\n var dIridescenceThickness: f32;\n #ifdef STD_IRIDESCENCE_THICKNESS_TEXTURE_ALLOCATE\n var texture_iridescenceThicknessMap : texture_2d;\n var texture_iridescenceThicknessMapSampler : sampler;\n #endif\n #ifdef STD_IRIDESCENCE_TEXTURE_ALLOCATE\n var texture_iridescenceMap : texture_2d;\n var texture_iridescenceMapSampler : sampler;\n #endif\n #endif\n #ifdef LIT_CLEARCOAT\n var ccSpecularity: f32;\n var ccGlossiness: f32;\n var ccNormalW: vec3f;\n #endif\n #ifdef LIT_GGX_SPECULAR\n var dAnisotropy: f32;\n var dAnisotropyRotation: vec2f;\n #endif\n #ifdef LIT_SPECULAR_OR_REFLECTION\n #ifdef LIT_SHEEN\n var sSpecularity: vec3f;\n var sGlossiness: f32;\n #ifdef STD_SHEEN_TEXTURE_ALLOCATE\n var texture_sheenMap : texture_2d;\n var texture_sheenMapSampler : sampler;\n #endif\n #ifdef STD_SHEENGLOSS_TEXTURE_ALLOCATE\n var texture_sheenGlossMap : texture_2d;\n var texture_sheenGlossMapSampler : sampler;\n #endif\n #endif\n #ifdef LIT_METALNESS\n var dMetalness: f32;\n var dIor: f32;\n #ifdef STD_METALNESS_TEXTURE_ALLOCATE\n var texture_metalnessMap : texture_2d;\n var texture_metalnessMapSampler : sampler;\n #endif\n #endif\n #ifdef LIT_SPECULARITY_FACTOR\n var dSpecularityFactor: f32;\n #ifdef STD_SPECULARITYFACTOR_TEXTURE_ALLOCATE\n var texture_specularityFactorMap : texture_2d;\n var texture_specularityFactorMapSampler : sampler;\n #endif\n #endif\n #ifdef STD_SPECULAR_COLOR\n #ifdef STD_SPECULAR_TEXTURE_ALLOCATE\n var texture_specularMap : texture_2d;\n var texture_specularMapSampler : sampler;\n #endif\n #endif\n #ifdef STD_GLOSS_TEXTURE_ALLOCATE\n var texture_glossMap : texture_2d;\n var texture_glossMapSampler : sampler;\n #endif\n #endif\n #ifdef STD_AO\n var dAo: f32;\n #ifdef STD_AO_TEXTURE_ALLOCATE\n var texture_aoMap : texture_2d;\n var texture_aoMapSampler : sampler;\n #endif\n #ifdef STD_AODETAIL_TEXTURE_ALLOCATE\n var texture_aoDetailMap : texture_2d;\n var texture_aoDetailMapSampler : sampler;\n #endif\n #endif\n var dEmission: vec3f;\n #ifdef STD_EMISSIVE_TEXTURE_ALLOCATE\n var texture_emissiveMap : texture_2d;\n var texture_emissiveMapSampler : sampler;\n #endif\n #ifdef LIT_CLEARCOAT\n #ifdef STD_CLEARCOAT_TEXTURE_ALLOCATE\n var texture_clearCoatMap : texture_2d;\n var texture_clearCoatMapSampler : sampler;\n #endif\n #ifdef STD_CLEARCOATGLOSS_TEXTURE_ALLOCATE\n var texture_clearCoatGlossMap : texture_2d;\n var texture_clearCoatGlossMapSampler : sampler;\n #endif\n #ifdef STD_CLEARCOATNORMAL_TEXTURE_ALLOCATE\n var texture_clearCoatNormalMap : texture_2d;\n var texture_clearCoatNormalMapSampler : sampler;\n #endif\n #endif\n #ifdef LIT_GGX_SPECULAR\n #ifdef STD_ANISOTROPY_TEXTURE_ALLOCATE\n var texture_anisotropyMap : texture_2d;\n var texture_anisotropyMapSampler : sampler;\n #endif\n #endif\n #if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)\n var dLightmap: vec3f;\n #ifdef STD_LIGHT_TEXTURE_ALLOCATE\n var texture_lightMap : texture_2d;\n var texture_lightMapSampler : sampler;\n #endif\n #endif\n #endif\n #include "litShaderCorePS"\n',stdFrontEndPS:'\n #if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE\n #include "opacityPS"\n #if defined(LIT_ALPHA_TEST)\n #include "alphaTestPS"\n #endif\n #if STD_OPACITY_DITHER != NONE\n #include "opacityDitherPS"\n #endif\n #endif\n #ifdef FORWARD_PASS\n #ifdef STD_HEIGHT_MAP\n #include "parallaxPS"\n #endif\n #include "diffusePS"\n #ifdef LIT_NEEDS_NORMAL\n #include "normalMapPS"\n #endif\n #ifdef LIT_REFRACTION\n #include "transmissionPS"\n #include "thicknessPS"\n #endif\n #ifdef LIT_IRIDESCENCE\n #include "iridescencePS"\n #include "iridescenceThicknessPS"\n #endif\n #ifdef LIT_SPECULAR_OR_REFLECTION\n #ifdef LIT_SHEEN\n #include "sheenPS"\n #include "sheenGlossPS"\n #endif\n #ifdef LIT_METALNESS\n #include "metalnessPS"\n #include "iorPS"\n #endif\n #ifdef LIT_SPECULARITY_FACTOR\n #include "specularityFactorPS"\n #endif\n #ifdef STD_SPECULAR_COLOR\n #include "specularPS"\n #else\n fn getSpecularity() { \n dSpecularity = vec3f(1.0, 1.0, 1.0);\n }\n #endif\n #include "glossPS"\n #endif\n #ifdef STD_AO\n #include "aoPS"\n #endif\n #include "emissivePS"\n #ifdef LIT_CLEARCOAT\n #include "clearCoatPS"\n #include "clearCoatGlossPS"\n #include "clearCoatNormalPS"\n #endif\n #if defined(LIT_SPECULAR) && defined(LIT_LIGHTING) && defined(LIT_GGX_SPECULAR)\n #include "anisotropyPS"\n #endif\n #if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)\n #include "lightmapPS"\n #endif\n #endif\n fn evaluateFrontend() {\n #if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE\n getOpacity();\n #if defined(LIT_ALPHA_TEST)\n alphaTest(dAlpha);\n #endif\n #if STD_OPACITY_DITHER != NONE\n opacityDither(dAlpha, 0.0);\n #endif\n litArgs_opacity = dAlpha;\n #endif\n #ifdef FORWARD_PASS\n #ifdef STD_HEIGHT_MAP\n getParallax();\n #endif\n getAlbedo();\n litArgs_albedo = dAlbedo;\n #ifdef LIT_NEEDS_NORMAL\n getNormal();\n litArgs_worldNormal = dNormalW;\n #endif\n #ifdef LIT_REFRACTION\n getRefraction();\n litArgs_transmission = dTransmission;\n getThickness();\n litArgs_thickness = dThickness;\n #ifdef LIT_DISPERSION\n litArgs_dispersion = uniform.material_dispersion;\n #endif\n #endif\n #ifdef LIT_IRIDESCENCE\n getIridescence();\n getIridescenceThickness();\n litArgs_iridescence_intensity = dIridescence;\n litArgs_iridescence_thickness = dIridescenceThickness;\n #endif\n #ifdef LIT_SPECULAR_OR_REFLECTION\n #ifdef LIT_SHEEN\n getSheen();\n litArgs_sheen_specularity = sSpecularity;\n getSheenGlossiness();\n litArgs_sheen_gloss = sGlossiness;\n #endif\n #ifdef LIT_METALNESS\n getMetalness();\n litArgs_metalness = dMetalness;\n getIor();\n litArgs_ior = dIor;\n #endif\n #ifdef LIT_SPECULARITY_FACTOR\n getSpecularityFactor();\n litArgs_specularityFactor = dSpecularityFactor;\n #endif\n getGlossiness();\n getSpecularity();\n litArgs_specularity = dSpecularity;\n litArgs_gloss = dGlossiness;\n #endif\n #ifdef STD_AO\n getAO();\n litArgs_ao = dAo;\n #endif\n getEmission();\n litArgs_emission = dEmission;\n #ifdef LIT_CLEARCOAT\n getClearCoat();\n getClearCoatGlossiness();\n getClearCoatNormal();\n litArgs_clearcoat_specularity = ccSpecularity;\n litArgs_clearcoat_gloss = ccGlossiness;\n litArgs_clearcoat_worldNormal = ccNormalW;\n #endif\n #if defined(LIT_SPECULAR) && defined(LIT_LIGHTING) && defined(LIT_GGX_SPECULAR)\n getAnisotropy();\n #endif\n #if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)\n getLightMap();\n litArgs_lightmap = dLightmap;\n #ifdef STD_LIGHTMAP_DIR\n litArgs_lightmapDir = dLightmapDir;\n #endif\n #endif\n #endif\n }\n',TBNPS:"\n#ifdef LIT_TANGENTS\n #define TBN_TANGENTS\n#else\n #if defined(LIT_USE_NORMALS) || defined(LIT_USE_CLEARCOAT_NORMALS)\n #define TBN_DERIVATIVES\n #endif\n#endif\n#if defined(TBN_DERIVATIVES)\n uniform tbnBasis: f32;\n#endif\nfn getTBN(tangent: vec3f, binormal: vec3f, normal: vec3f) {\n #ifdef TBN_TANGENTS\n dTBN = mat3x3f(normalize(tangent), normalize(binormal), normalize(normal));\n #elif defined(TBN_DERIVATIVES)\n let uv: vec2f = {lightingUv};\n let dp1: vec3f = dpdx( vPositionW );\n let dp2: vec3f = dpdy( vPositionW );\n let duv1: vec2f = dpdx( uv );\n let duv2: vec2f = dpdy( uv );\n let dp2perp: vec3f = cross( dp2, normal );\n let dp1perp: vec3f = cross( normal, dp1 );\n let T: vec3f = dp2perp * duv1.x + dp1perp * duv2.x;\n let B: vec3f = dp2perp * duv1.y + dp1perp * duv2.y;\n let denom: f32 = max( dot(T, T), dot(B, B) );\n let invmax: f32 = select(uniform.tbnBasis / sqrt( denom ), 0.0, denom == 0.0);\n dTBN = mat3x3f(T * invmax, -B * invmax, normal );\n #else\n var B: vec3f = cross(normal, vObjectSpaceUpW);\n var T: vec3f = cross(normal, B);\n if (dot(B,B) == 0.0)\n {\n let major: f32 = max(max(normal.x, normal.y), normal.z);\n if (normal.x == major)\n {\n B = cross(normal, vec3f(0.0, 1.0, 0.0));\n T = cross(normal, B);\n }\n else if (normal.y == major)\n {\n B = cross(normal, vec3f(0.0, 0.0, 1.0));\n T = cross(normal, B);\n }\n else\n {\n B = cross(normal, vec3f(1.0, 0.0, 0.0));\n T = cross(normal, B);\n }\n }\n dTBN = mat3x3f(normalize(T), normalize(B), normalize(normal));\n #endif\n}",thicknessPS:"\n#ifdef STD_THICKNESS_CONSTANT\nuniform material_thickness: f32;\n#endif\nfn getThickness() {\n dThickness = 1.0;\n #ifdef STD_THICKNESS_CONSTANT\n dThickness = dThickness * uniform.material_thickness;\n #endif\n #ifdef STD_THICKNESS_TEXTURE\n dThickness = dThickness * textureSampleBias({STD_THICKNESS_TEXTURE_NAME}, {STD_THICKNESS_TEXTURE_NAME}Sampler, {STD_THICKNESS_TEXTURE_UV}, uniform.textureBias).{STD_THICKNESS_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_THICKNESS_VERTEX\n dThickness = dThickness * saturate(vVertexColor.{STD_THICKNESS_VERTEX_CHANNEL});\n #endif\n}\n",tonemappingPS:'\n#if (TONEMAP == NONE)\n #include "tonemappingNonePS"\n#elif TONEMAP == FILMIC\n #include "tonemappingFilmicPS"\n#elif TONEMAP == LINEAR\n #include "tonemappingLinearPS"\n#elif TONEMAP == HEJL\n #include "tonemappingHejlPS"\n#elif TONEMAP == ACES\n #include "tonemappingAcesPS"\n#elif TONEMAP == ACES2\n #include "tonemappingAces2PS"\n#elif TONEMAP == NEUTRAL\n #include "tonemappingNeutralPS"\n#endif\n',tonemappingAcesPS:"\nuniform exposure: f32;\nfn toneMap(color: vec3f) -> vec3f {\n let tA: f32 = 2.51;\n let tB: f32 = 0.03;\n let tC: f32 = 2.43;\n let tD: f32 = 0.59;\n let tE: f32 = 0.14;\n let x: vec3f = color * uniform.exposure;\n return (x * (tA * x + tB)) / (x * (tC * x + tD) + tE);\n}\n",tonemappingAces2PS:"\nuniform exposure: f32;\nconst ACESInputMat: mat3x3f = mat3x3f(\n vec3f(0.59719, 0.35458, 0.04823),\n vec3f(0.07600, 0.90834, 0.01566),\n vec3f(0.02840, 0.13383, 0.83777)\n);\nconst ACESOutputMat: mat3x3f = mat3x3f(\n vec3f( 1.60475, -0.53108, -0.07367),\n vec3f(-0.10208, 1.10813, -0.00605),\n vec3f(-0.00327, -0.07276, 1.07602)\n);\nfn RRTAndODTFit(v: vec3f) -> vec3f {\n let a: vec3f = v * (v + vec3f(0.0245786)) - vec3f(0.000090537);\n let b: vec3f = v * (vec3f(0.983729) * v + vec3f(0.4329510)) + vec3f(0.238081);\n return a / b;\n}\nfn toneMap(color: vec3f) -> vec3f {\n var c: vec3f = color * (uniform.exposure / 0.6);\n c = c * ACESInputMat;\n c = RRTAndODTFit(c);\n c = c * ACESOutputMat;\n return clamp(c, vec3f(0.0), vec3f(1.0));\n}\n",tonemappingFilmicPS:"\nconst A: f32 = 0.15;\nconst B: f32 = 0.50;\nconst C: f32 = 0.10;\nconst D: f32 = 0.20;\nconst E: f32 = 0.02;\nconst F: f32 = 0.30;\nconst W: f32 = 11.2;\nuniform exposure: f32;\nfn uncharted2Tonemap(x: vec3f) -> vec3f {\n return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - vec3f(E / F);\n}\nfn toneMap(color: vec3f) -> vec3f {\n var c: vec3f = uncharted2Tonemap(color * uniform.exposure);\n let whiteScale: vec3f = vec3f(1.0) / uncharted2Tonemap(vec3f(W, W, W));\n c *= whiteScale;\n return c;\n}\n",tonemappingHejlPS:"\nuniform exposure: f32;\nfn toneMap(color: vec3f) -> vec3f {\n let A: f32 = 0.22;\n let B: f32 = 0.3;\n let C: f32 = 0.1;\n let D: f32 = 0.2;\n let E: f32 = 0.01;\n let F: f32 = 0.3;\n let Scl: f32 = 1.25;\n let adjusted_color = color * uniform.exposure;\n let h = max(vec3f(0.0), adjusted_color - vec3f(0.004));\n return (h * ((Scl * A) * h + Scl * vec3f(C * B)) + Scl * vec3f(D * E)) /\n (h * (A * h + vec3f(B)) + vec3f(D * F)) -\n Scl * vec3f(E / F);\n}\n",tonemappingLinearPS:"\nuniform exposure: f32;\nfn toneMap(color: vec3f) -> vec3f {\n return color * uniform.exposure;\n}\n",tonemappingNeutralPS:"\nuniform exposure: f32;\nfn toneMap(col: vec3f) -> vec3f {\n var color = col * uniform.exposure;\n let startCompression = 0.8 - 0.04;\n let desaturation = 0.15;\n let x = min(color.r, min(color.g, color.b));\n let offset = select(0.04, x - 6.25 * x * x, x < 0.08);\n color -= vec3f(offset);\n let peak = max(color.r, max(color.g, color.b));\n if (peak < startCompression) {\n return color;\n }\n let d = 1.0 - startCompression;\n let newPeak = 1.0 - d * d / (peak + d - startCompression);\n color *= newPeak / peak;\n let g = 1.0 - 1.0 / (desaturation * (peak - newPeak) + 1.0);\n return mix(color, vec3f(newPeak), vec3f(g));\n}\n",tonemappingNonePS:"\nfn toneMap(color: vec3f) -> vec3f {\n return color;\n}\n",transformVS:"\n#ifdef PIXELSNAP\n uniform uScreenSize: vec4f;\n#endif\n#ifdef SCREENSPACE\n uniform projectionFlipY: f32;\n#endif\nfn evalWorldPosition(vertexPosition: vec3f, modelMatrix: mat4x4f) -> vec4f {\n var localPos: vec3f = getLocalPosition(vertexPosition);\n #ifdef NINESLICED\n var localPosXZ: vec2f = localPos.xz;\n localPosXZ = localPosXZ * uniform.outerScale;\n let positiveUnitOffset: vec2f = clamp(vertexPosition.xz, vec2f(0.0), vec2f(1.0));\n let negativeUnitOffset: vec2f = clamp(-vertexPosition.xz, vec2f(0.0), vec2f(1.0));\n localPosXZ = localPosXZ + (-positiveUnitOffset * uniform.innerOffset.xy + negativeUnitOffset * uniform.innerOffset.zw) * vertex_texCoord0.xy;\n dTiledUvGlobal = (localPosXZ - uniform.outerScale + uniform.innerOffset.xy) * -0.5 + 1.0;\n localPosXZ = localPosXZ * -0.5;\n localPos = vec3f(localPosXZ.x, localPosXZ.y, localPos.y);\n #endif\n var posW: vec4f = modelMatrix * vec4f(localPos, 1.0);\n #ifdef SCREENSPACE\n posW = vec4f(posW.xy, 0.0, 1.0);\n #endif\n return posW;\n}\nfn getPosition() -> vec4f {\n dModelMatrix = getModelMatrix();\n let posW: vec4f = evalWorldPosition(vertex_position.xyz, dModelMatrix);\n dPositionW = posW.xyz;\n var screenPos: vec4f;\n #ifdef UV1LAYOUT\n screenPos = vec4f(vertex_texCoord1.xy * 2.0 - 1.0, 0.5, 1.0);\n screenPos.y *= -1.0;\n #else\n #ifdef SCREENSPACE\n screenPos = posW;\n screenPos.y *= uniform.projectionFlipY;\n #else\n screenPos = uniform.matrix_viewProjection * posW;\n #endif\n #ifdef PIXELSNAP\n screenPos.xy = (screenPos.xy * 0.5) + 0.5;\n screenPos.xy *= uniforms.uScreenSize.xy;\n screenPos.xy = floor(screenPos.xy);\n screenPos.xy *= uniforms.uScreenSize.zw;\n screenPos.xy = (screenPos.xy * 2.0) - 1.0;\n #endif\n #endif\n return screenPos;\n}\nfn getWorldPosition() -> vec3f {\n return dPositionW;\n}\n",transformCoreVS:'\n attribute vertex_position: vec4f;\n uniform matrix_viewProjection: mat4x4f;\n uniform matrix_model: mat4x4f;\n \n #ifdef MORPHING\n uniform morph_tex_params: vec2f;\n attribute morph_vertex_id: u32;\n fn getTextureMorphCoords() -> vec2i {\n var textureSize: vec2i = vec2i(uniform.morph_tex_params);\n var morphGridV: i32 = i32(morph_vertex_id) / textureSize.x;\n var morphGridU: i32 = i32(morph_vertex_id) - (morphGridV * textureSize.x);\n morphGridV = textureSize.y - morphGridV - 1;\n return vec2i(morphGridU, morphGridV);\n }\n #ifdef MORPHING_POSITION\n #ifdef MORPHING_INT\n uniform aabbSize: vec3f;\n uniform aabbMin: vec3f;\n var morphPositionTex: texture_2d;\n #else\n var morphPositionTex: texture_2d;\n #endif\n #endif\n #endif\n #ifdef defined(BATCH)\n #include "skinBatchVS"\n fn getModelMatrix() -> mat4x4f {\n return getBoneMatrix(vertex_boneIndices);\n }\n #elif defined(SKIN)\n #include "skinVS"\n fn getModelMatrix() -> mat4x4f {\n return uniform.matrix_model * getSkinMatrix(vertex_boneIndices, vertex_boneWeights);\n }\n #elif defined(INSTANCING)\n #include "transformInstancingVS"\n #else\n fn getModelMatrix() -> mat4x4f {\n return uniform.matrix_model;\n }\n #endif\n fn getLocalPosition(vertexPosition: vec3f) -> vec3f {\n var localPos: vec3f = vertexPosition;\n #ifdef MORPHING_POSITION\n var morphUV: vec2i = getTextureMorphCoords();\n #ifdef MORPHING_INT\n var morphPos: vec3f = vec3f(textureLoad(morphPositionTex, morphUV, 0).xyz) / 65535.0 * uniform.aabbSize + uniform.aabbMin;\n #else\n var morphPos: vec3f = textureLoad(morphPositionTex, morphUV, 0).xyz;\n #endif\n localPos += morphPos;\n #endif\n return localPos;\n }\n',transformInstancingVS:"\nattribute instance_line1: vec4f;\nattribute instance_line2: vec4f;\nattribute instance_line3: vec4f;\nattribute instance_line4: vec4f;\nfn getModelMatrix() -> mat4x4f {\n return uniform.matrix_model * mat4x4f(instance_line1, instance_line2, instance_line3, instance_line4);\n}\n",transmissionPS:"\n#ifdef STD_REFRACTION_CONSTANT\n uniform material_refraction: f32;\n#endif\nfn getRefraction() {\n var refraction: f32 = 1.0;\n #ifdef STD_REFRACTION_CONSTANT\n refraction = uniform.material_refraction;\n #endif\n #ifdef STD_REFRACTION_TEXTURE\n refraction = refraction * textureSampleBias({STD_REFRACTION_TEXTURE_NAME}, {STD_REFRACTION_TEXTURE_NAME}Sampler, {STD_REFRACTION_TEXTURE_UV}, uniform.textureBias).{STD_REFRACTION_TEXTURE_CHANNEL};\n #endif\n #ifdef STD_REFRACTION_VERTEX\n refraction = refraction * saturate(vVertexColor.{STD_REFRACTION_VERTEX_CHANNEL});\n #endif\n dTransmission = refraction;\n}\n",twoSidedLightingPS:"\nuniform twoSidedLightingNegScaleFactor: f32;\nfn handleTwoSidedLighting() {\n dTBN[2] = dTBN[2] * select(-uniform.twoSidedLightingNegScaleFactor, uniform.twoSidedLightingNegScaleFactor, pcFrontFacing);\n}\n",uv0VS:"\n#ifdef NINESLICED\n fn getUv0() -> vec2f {\n var uv = vertex_position.xz;\n let positiveUnitOffset = clamp(vertex_position.xz, vec2f(0.0, 0.0), vec2f(1.0, 1.0));\n let negativeUnitOffset = clamp(-vertex_position.xz, vec2f(0.0, 0.0), vec2f(1.0, 1.0));\n uv = uv + ((-positiveUnitOffset * uniform.innerOffset.xy) + (negativeUnitOffset * uniform.innerOffset.zw)) * vertex_texCoord0.xy;\n uv = uv * -0.5 + vec2f(0.5, 0.5);\n uv = uv * uniform.atlasRect.zw + uniform.atlasRect.xy;\n dMaskGlobal = vertex_texCoord0.xy;\n return uv;\n }\n#else\n fn getUv0() -> vec2f {\n return vertex_texCoord0;\n }\n#endif\n",uv1VS:"\nfn getUv1() -> vec2f {\n return vertex_texCoord1;\n}\n",uvTransformVS:"\noutput.vUV{TRANSFORM_UV_{i}}_{TRANSFORM_ID_{i}} = vec2f(\n dot(vec3f(uv{TRANSFORM_UV_{i}}, 1), uniform.{TRANSFORM_NAME_{i}}0),\n dot(vec3f(uv{TRANSFORM_UV_{i}}, 1), uniform.{TRANSFORM_NAME_{i}}1)\n);\n",uvTransformUniformsPS:"\n uniform {TRANSFORM_NAME_{i}}0: vec3f;\n uniform {TRANSFORM_NAME_{i}}1: vec3f;\n",viewDirPS:"\nfn getViewDir() {\n dViewDirW = normalize(uniform.view_position - vPositionW);\n}\n",webgpuPS:"\n",webgpuVS:rY};function mp(e,t){return (mp=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}e.app=null;var mm=function(t){if("function"!=typeof t&&null!==t)throw TypeError("Super expression must either be null or a function");function n(i){var r;return (r=t.call(this)||this)._batcher=null,r._destroyRequested=false,r._inFrameUpdate=false,r._librariesLoaded=false,r._fillMode=pv,r._resolutionMode=py,r._allowResize=true,r._skyboxAsset=null,r._entityIndex={},r._inTools=false,r._scriptPrefix="",r._time=0,r.enableBundles="undefined"!=typeof TextDecoder,r.timeScale=1,r.maxDeltaTime=.1,r.frame=0,r.frameGraph=new pb,r.scriptsOrder=[],r.autoRender=true,r.renderNextFrame=false,r.lightmapper=null,r.loader=new p4(r),r.scenes=new mc(r),r.scripts=new me(r),r.systems=new pZ,r.i18n=new p6(r),r.keyboard=null,r.mouse=null,r.touch=null,r.gamepads=null,r.elementInput=null,r.xr=null,n._applications[i.id]=r,A=r,e.app=r,r.root=new ml,r.root._enabledInHierarchy=true,r}n.prototype=Object.create(t&&t.prototype,{constructor:{value:n,writable:true,configurable:true}}),t&&mp(n,t);var i,r=n.prototype;return r.init=function(e){var t=this,n=e.assetPrefix,i=e.batchManager,r=e.componentSystems,s=e.elementInput,a=e.gamepads,o=e.graphicsDevice,l=e.keyboard,u=e.lightmapper,c=e.mouse,h=e.resourceHandlers,f=e.scriptsOrder,d=e.scriptPrefix,p=e.soundManager,m=e.touch,_=e.xr;this.graphicsDevice=o,o1.get(o,ns).add(mf),o1.get(o,na).add(md),this._initDefaultMaterial(),this._initProgramLibrary(),this.stats=new mh(o),this._soundManager=p,this.scene=new fB(o),this._registerSceneImmediate(this.scene),this.assets=new pj(this.loader),n&&(this.assets.prefix=n),this.bundles=new pq(this.assets),this.scriptsOrder=f||[],this.defaultLayerWorld=new cX({name:"World",id:0}),this.defaultLayerDepth=new cX({name:"Depth",id:1,enabled:false,opaqueSortMode:0}),this.defaultLayerSkybox=new cX({name:"Skybox",id:2,opaqueSortMode:0}),this.defaultLayerUi=new cX({name:"UI",id:4,transparentSortMode:1}),this.defaultLayerImmediate=new cX({name:"Immediate",id:3,opaqueSortMode:0});var v=new cZ("default");v.pushOpaque(this.defaultLayerWorld),v.pushOpaque(this.defaultLayerDepth),v.pushOpaque(this.defaultLayerSkybox),v.pushTransparent(this.defaultLayerWorld),v.pushOpaque(this.defaultLayerImmediate),v.pushTransparent(this.defaultLayerImmediate),v.pushTransparent(this.defaultLayerUi),this.scene.layers=v,pw.createPlaceholder(o),this.renderer=new cV(o),this.renderer.scene=this.scene,u&&(this.lightmapper=new u(o,this.root,this.scene,this.renderer,this.assets),this.once("prerender",this._firstBake,this)),i&&(this._batcher=new i(o,this.root,this.scene),this.once("prerender",this._firstBatch,this)),this.keyboard=l||null,this.mouse=c||null,this.touch=m||null,this.gamepads=a||null,s&&(this.elementInput=s,this.elementInput.app=this),this.xr=_?new _(this):null,this.elementInput&&this.elementInput.attachSelectEvents(),this._scriptPrefix=d||"",this.enableBundles&&this.loader.addHandler("bundle",new p3(this)),h.forEach(function(e){var n=new e(t);t.loader.addHandler(n.handlerType,n);}),r.forEach(function(e){t.systems.add(new e(t));}),this._visibilityChangeHandler=this.onVisibilityChange.bind(this),"undefined"!=typeof document&&(void 0!==document.hidden?(this._hiddenAttr="hidden",document.addEventListener("visibilitychange",this._visibilityChangeHandler,false)):void 0!==document.mozHidden?(this._hiddenAttr="mozHidden",document.addEventListener("mozvisibilitychange",this._visibilityChangeHandler,false)):void 0!==document.msHidden?(this._hiddenAttr="msHidden",document.addEventListener("msvisibilitychange",this._visibilityChangeHandler,false)):void 0!==document.webkitHidden&&(this._hiddenAttr="webkitHidden",document.addEventListener("webkitvisibilitychange",this._visibilityChangeHandler,false))),this.tick=mv(this);},r._initDefaultMaterial=function(){var e,t=new dA;t.name="Default Material",e=this.graphicsDevice,lg.get(e,function(){return t});},r._initProgramLibrary=function(){var e,t=new dK(this.graphicsDevice,new dA);e=this.graphicsDevice,oV.get(e,function(){return t});},r.configure=function(e,t){var n=this;aq.get(e,function(e,i){if(e)return void t(e);var r=i.application_properties,s=i.scenes,a=i.assets;n._parseApplicationProperties(r,function(e){n._parseScenes(s),n._parseAssets(a),e?t(e):t(null);});});},r.preload=function(e){var t=this;this.fire("preload:start");var n=this.assets.list({preload:true});if(0===n.length){this.fire("preload:end"),e();return}var i=0,r=function(){i++,t.fire("preload:progress",i/n.length),i===n.length&&(t.fire("preload:end"),e());};n.forEach(function(e){e.loaded?r():(e.once("load",r),e.once("error",r),t.assets.load(e));});},r._preloadScripts=function(e,t){t();},r._parseApplicationProperties=function(e,t){if("number"==typeof e.maxAssetRetries&&e.maxAssetRetries>0&&this.loader.enableRetry(e.maxAssetRetries),e.useDevicePixelRatio||(e.useDevicePixelRatio=e.use_device_pixel_ratio),e.resolutionMode||(e.resolutionMode=e.resolution_mode),e.fillMode||(e.fillMode=e.fill_mode),this._width=e.width,this._height=e.height,e.useDevicePixelRatio&&(this.graphicsDevice.maxPixelRatio=window.devicePixelRatio),this.setCanvasResolution(e.resolutionMode,this._width,this._height),this.setCanvasFillMode(e.fillMode,this._width,this._height),e.layers&&e.layerOrder){var n=new cZ("application"),i={};for(var r in e.layers){var s=e.layers[r];s.id=parseInt(r,10),s.enabled=1!==s.id,i[r]=new cX(s);}for(var a=0,o=e.layerOrder.length;a0,c.tags.add(u.tags),u.i18n)for(var h in u.i18n)c.addLocalizedAssetId(h,u.i18n[h]);this.assets.add(c);}},r.start=function(){this.frame=0,this.fire("start",{timestamp:eL(),target:this}),this._librariesLoaded||this.onLibrariesLoaded(),this.systems.fire("initialize",this.root),this.fire("initialize"),this.systems.fire("postInitialize",this.root),this.systems.fire("postPostInitialize",this.root),this.fire("postinitialize"),this.tick();},r.inputUpdate=function(e){this.controller&&this.controller.update(e),this.mouse&&this.mouse.update(),this.keyboard&&this.keyboard.update(),this.gamepads&&this.gamepads.update();},r.update=function(e){this.frame++,this.graphicsDevice.updateClientRect(),this.systems.fire(this._inTools?"toolsUpdate":"update",e),this.systems.fire("animationUpdate",e),this.systems.fire("postUpdate",e),this.fire("update",e),this.inputUpdate(e);},r.frameStart=function(){this.graphicsDevice.frameStart();},r.frameEnd=function(){this.graphicsDevice.frameEnd();},r.render=function(){this.fire("prerender"),this.root.syncHierarchy(),this._batcher&&this._batcher.updateAll(),this.renderComposition(this.scene.layers),this.fire("postrender");},r.renderComposition=function(e){this.renderer.update(e),this.renderer.buildFrameGraph(this.frameGraph,e),this.frameGraph.render(this.graphicsDevice);},r._fillFrameStatsBasic=function(e,t,n){var i=this.stats.frame;i.dt=t,i.ms=n,e>i._timeToCountFrames?(i.fps=i._fpsAccum,i._fpsAccum=0,i._timeToCountFrames=e+1e3):i._fpsAccum++,this.stats.drawCalls.total=this.graphicsDevice._drawCallsPerFrame,this.graphicsDevice._drawCallsPerFrame=0;},r._fillFrameStats=function(){var e=this.stats.frame;e.cameras=this.renderer._camerasRendered,e.materials=this.renderer._materialSwitches,e.shaders=this.graphicsDevice._shaderSwitchesPerFrame,e.shadowMapUpdates=this.renderer._shadowMapUpdates,e.shadowMapTime=this.renderer._shadowMapTime,e.depthMapTime=this.renderer._depthMapTime,e.forwardTime=this.renderer._forwardTime;var t=this.graphicsDevice._primsPerFrame;e.triangles=t[4]/3+Math.max(t[5]-2,0)+Math.max(t[6]-2,0),e.cullTime=this.renderer._cullTime,e.sortTime=this.renderer._sortTime,e.skinTime=this.renderer._skinTime,e.morphTime=this.renderer._morphTime,e.lightClusters=this.renderer._lightClusters,e.lightClustersTime=this.renderer._lightClustersTime,e.otherPrimitives=0;for(var n=0;nn/i?t=(e=n)/r:e=(t=i)*r;}else this._fillMode===p_&&(e=n,t=i);return this.graphicsDevice.canvas.style.width=""+e+"px",this.graphicsDevice.canvas.style.height=""+t+"px",this.updateCanvasSize(),{width:e,height:t}}},r.updateCanvasSize=function(){var e;if(this._allowResize&&(null==(e=this.xr)||!e.active)&&this._resolutionMode===pg){var t=this.graphicsDevice.canvas;this.graphicsDevice.resizeCanvas(t.clientWidth,t.clientHeight);}},r.onLibrariesLoaded=function(){this._librariesLoaded=true,this.systems.rigidbody&&this.systems.rigidbody.onLibraryLoaded();},r.applySceneSettings=function(e){var t;if(this.systems.rigidbody&&"undefined"!=typeof Ammo){var n=e.physics.gravity,i=n[0],r=n[1],s=n[2];this.systems.rigidbody.gravity.set(i,r,s);}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));},r.setAreaLightLuts=function(e,t){e&&t&&pw.set(this.graphicsDevice,e,t);},r.setSkybox=function(e){var t=this;if(e!==this._skyboxAsset){var n=function(){t.setSkybox(null);},i=function(){t.scene.setSkybox(t._skyboxAsset?t._skyboxAsset.resources:null);};this._skyboxAsset&&(this.assets.off("load:"+this._skyboxAsset.id,i,this),this.assets.off("remove:"+this._skyboxAsset.id,n,this),this._skyboxAsset.off("change",i,this)),this._skyboxAsset=e,this._skyboxAsset&&(this.assets.on("load:"+this._skyboxAsset.id,i,this),this.assets.once("remove:"+this._skyboxAsset.id,n,this),this._skyboxAsset.on("change",i,this),0!==this.scene.skyboxMip||this._skyboxAsset.loadFaces||(this._skyboxAsset.loadFaces=true),this.assets.load(this._skyboxAsset)),i();}},r._firstBake=function(){var e;null==(e=this.lightmapper)||e.bake(null,this.scene.lightmapMode);},r._firstBatch=function(){var e;null==(e=this.batcher)||e.generate();},r._processTimestamp=function(e){return e},r.drawLine=function(e,t,n,i,r){this.scene.drawLine(e,t,n,i,r);},r.drawLines=function(e,t,n,i){ void 0===n&&(n=true),void 0===i&&(i=this.scene.defaultDrawLayer),this.scene.drawLines(e,t,n,i);},r.drawLineArrays=function(e,t,n,i){ void 0===n&&(n=true),void 0===i&&(i=this.scene.defaultDrawLayer),this.scene.drawLineArrays(e,t,n,i);},r.drawWireSphere=function(e,t,n,i,r,s){ void 0===n&&(n=eN.WHITE),void 0===i&&(i=20),void 0===r&&(r=true),void 0===s&&(s=this.scene.defaultDrawLayer),this.scene.immediate.drawWireSphere(e,t,n,i,r,s);},r.drawWireAlignedBox=function(e,t,n,i,r,s){ void 0===n&&(n=eN.WHITE),void 0===i&&(i=true),void 0===r&&(r=this.scene.defaultDrawLayer),this.scene.immediate.drawWireAlignedBox(e,t,n,i,r,s);},r.drawMeshInstance=function(e,t){ void 0===t&&(t=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(null,null,null,e,t);},r.drawMesh=function(e,t,n,i){ void 0===i&&(i=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(t,n,e,null,i);},r.drawQuad=function(e,t,n){ void 0===n&&(n=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(t,e,this.scene.immediate.getQuadMesh(),null,n);},r.drawTexture=function(e,t,n,i,r,s,a,o){if(void 0===a&&(a=this.scene.defaultDrawLayer),void 0===o&&(o=true),false!==o||this.graphicsDevice.isWebGPU){var l=new e$;l.setTRS(new eW(e,t,0),e0.IDENTITY,new eW(n,-i,0)),s||((s=new h3).cull=0,s.setParameter("colorMap",r),s.shaderDesc=o?this.scene.immediate.getTextureShaderDesc(r.encoding):this.scene.immediate.getUnfilterableTextureShaderDesc(),s.update()),this.drawQuad(l,s,a);}},r.drawDepthTexture=function(e,t,n,i,r){ void 0===r&&(r=this.scene.defaultDrawLayer);var s=new h3;s.cull=0,s.shaderDesc=this.scene.immediate.getDepthTextureShaderDesc(),s.update(),this.drawTexture(e,t,n,i,null,s,r);},r.destroy=function(){if(this._inFrameUpdate){this._destroyRequested=true;return}var e,t,i,r,s=this.graphicsDevice.canvas.id;this.fire("destroy",this),this.off("librariesloaded"),"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this._visibilityChangeHandler,false),document.removeEventListener("mozvisibilitychange",this._visibilityChangeHandler,false),document.removeEventListener("msvisibilitychange",this._visibilityChangeHandler,false),document.removeEventListener("webkitvisibilitychange",this._visibilityChangeHandler,false)),this._visibilityChangeHandler=null,this.root.destroy(),this.root=null,this.mouse&&(this.mouse.off(),this.mouse.detach(),this.mouse=null),this.keyboard&&(this.keyboard.off(),this.keyboard.detach(),this.keyboard=null),this.touch&&(this.touch.off(),this.touch.detach(),this.touch=null),this.elementInput&&(this.elementInput.detach(),this.elementInput=null),this.gamepads&&(this.gamepads.destroy(),this.gamepads=null),this.controller&&(this.controller=null),this.systems.destroy(),this.scene.layers&&this.scene.layers.destroy();for(var a=this.assets.list(),o=0;o0){var i=n.bakeArea;fm.circlePointDeterministic(mb,e,t),mb.mulScalar(.5*i),n._node.rotateLocal(mb.x,0,mb.y);}n._node.getWorldTransform(),n.intensity=Math.pow(Math.pow(this.intensity,2.2)/t,.45454545454545453);},t=[{key:"numVirtualLights",get:function(){return 0===this.light.type?this.light.bakeNumSamples:1}}],function(e,t){for(var n=0;n 0.0;\n #endif\n}\nvarying vec2 vUv0;\nuniform sampler2D source;\nuniform vec2 pixelOffset;\nuniform vec2 sigmas;\nuniform float bZnorm;\nuniform float kernel[{MSIZE}];\nvoid main(void) {\n \n vec4 pixel = texture2DLod(source, vUv0, 0.0);\n if (!isUsed(pixel)) {\n gl_FragColor = pixel;\n return ;\n }\n float sigma = sigmas.x;\n float bSigma = sigmas.y;\n vec3 pixelHdr = decode(pixel);\n vec3 accumulatedHdr = vec3(0.0);\n float accumulatedFactor = 0.000001;\n const int kSize = ({MSIZE} - 1) / 2;\n for (int i = -kSize; i <= kSize; ++i) {\n for (int j = -kSize; j <= kSize; ++j) {\n \n vec2 coord = vUv0 + vec2(float(i), float(j)) * pixelOffset;\n vec4 pix = texture2DLod(source, coord, 0.0);\n if (isUsed(pix)) {\n vec3 hdr = decode(pix);\n float factor = kernel[kSize + j] * kernel[kSize + i];\n factor *= normpdf3(hdr - pixelHdr, bSigma) * bZnorm;\n accumulatedHdr += factor * hdr;\n accumulatedFactor += factor;\n }\n }\n }\n vec3 finalHDR = accumulatedHdr / accumulatedFactor;\n #if HDR\n gl_FragColor = vec4(finalHDR, 1.0);\n #else\n gl_FragColor = encodeRGBM(finalHDR);\n #endif\n}\n",glslDilatePS:"\nvarying vec2 vUv0;\nuniform sampler2D source;\nuniform vec2 pixelOffset;\nbool isUsed(vec4 pixel) {\n #if HDR\n return any(greaterThan(pixel.rgb, vec3(0.0)));\n #else\n return pixel.a > 0.0;\n #endif\n}\nvoid main(void) {\n vec4 c = texture2DLod(source, vUv0, 0.0);\n c = isUsed(c) ? c : texture2DLod(source, vUv0 - pixelOffset, 0.0);\n c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(0, -pixelOffset.y), 0.0);\n c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(pixelOffset.x, -pixelOffset.y), 0.0);\n c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(-pixelOffset.x, 0), 0.0);\n c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(pixelOffset.x, 0), 0.0);\n c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(-pixelOffset.x, pixelOffset.y), 0.0);\n c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(0, pixelOffset.y), 0.0);\n c = isUsed(c) ? c : texture2DLod(source, vUv0 + pixelOffset, 0.0);\n gl_FragColor = c;\n}\n"},mI={wgslBilateralDeNoisePS:"\nfn normpdf3(v: vec3f, sigma: f32) -> f32 {\n return 0.39894 * exp(-0.5 * dot(v, v) / (sigma * sigma)) / sigma;\n}\nfn decodeRGBM(rgbm: vec4f) -> vec3f {\n let color = (8.0 * rgbm.a) * rgbm.rgb;\n return color * color;\n}\nfn saturate(x: f32) -> f32 {\n return clamp(x, 0.0, 1.0);\n}\nfn encodeRGBM(color: vec3f) -> vec4f {\n var encoded: vec4f;\n let rgb_processed = pow(color.rgb, vec3f(0.5)) * (1.0 / 8.0);\n encoded = vec4f(rgb_processed, 0.0);\n let max_g_b = max( encoded.g, max( encoded.b, 1.0 / 255.0 ) );\n let max_rgb = max( encoded.r, max_g_b );\n encoded.a = clamp(max_rgb, 0.0, 1.0);\n encoded.a = ceil(encoded.a * 255.0) / 255.0;\n encoded = vec4f(encoded.rgb / encoded.a, encoded.a);\n return encoded;\n}\nfn decode(pixel: vec4f) -> vec3f {\n #if HDR\n return pixel.rgb;\n #else\n return decodeRGBM(pixel);\n #endif\n}\nfn isUsed(pixel: vec4f) -> bool {\n #if HDR\n return any(pixel.rgb > vec3f(0.0));\n #else\n return pixel.a > 0.0;\n #endif\n}\nvarying vUv0: vec2f;\nvar source: texture_2d;\nvar sourceSampler: sampler;\nuniform kernel: array;\nuniform pixelOffset: vec2f;\nuniform sigmas: vec2f;\nuniform bZnorm: f32;\n@fragment\nfn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n let pixel = textureSampleLevel(source, sourceSampler, input.vUv0, 0.0);\n if (!isUsed(pixel)) {\n output.color = pixel;\n return output;\n }\n let sigma = uniform.sigmas.x;\n let bSigma = uniform.sigmas.y;\n let pixelHdr = decode(pixel);\n var accumulatedHdr = vec3f(0.0);\n var accumulatedFactor = 0.000001;\n const kSize = ({MSIZE} - 1) / 2;\n for (var i: i32 = -kSize; i <= kSize; i = i + 1) {\n for (var j: i32 = -kSize; j <= kSize; j = j + 1) {\n let coord = input.vUv0 + vec2f(f32(i), f32(j)) * uniform.pixelOffset;\n let pix = textureSampleLevel(source, sourceSampler, coord, 0.0);\n if (isUsed(pix)) {\n let hdr = decode(pix);\n var factor = uniform.kernel[u32(kSize + j)].element * uniform.kernel[u32(kSize + i)].element;\n factor = factor * normpdf3(hdr - pixelHdr, bSigma) * uniform.bZnorm;\n accumulatedHdr = accumulatedHdr + factor * hdr;\n accumulatedFactor = accumulatedFactor + factor;\n }\n }\n }\n let finalHDR = accumulatedHdr / accumulatedFactor;\n #if HDR\n output.color = vec4f(finalHDR, 1.0);\n #else\n output.color = encodeRGBM(finalHDR);\n #endif\n return output;\n}\n",wgslDilatePS:"\nvarying vUv0: vec2f;\nvar source: texture_2d;\nvar sourceSampler: sampler;\nuniform pixelOffset: vec2f;\nfn isUsed(pixel: vec4f) -> bool {\n #ifdef HDR\n return any(pixel.rgb > vec3f(0.0));\n #else\n return pixel.a > 0.0;\n #endif\n}\n@fragment\nfn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var c: vec4f = textureSampleLevel(source, sourceSampler, input.vUv0, 0.0);\n c = select(textureSampleLevel(source, sourceSampler, input.vUv0 - uniform.pixelOffset, 0.0), c, isUsed(c));\n c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(0.0, -uniform.pixelOffset.y), 0.0), c, isUsed(c));\n c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(uniform.pixelOffset.x, -uniform.pixelOffset.y), 0.0), c, isUsed(c));\n c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(-uniform.pixelOffset.x, 0.0), 0.0), c, isUsed(c));\n c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(uniform.pixelOffset.x, 0.0), 0.0), c, isUsed(c));\n c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(-uniform.pixelOffset.x, uniform.pixelOffset.y), 0.0), c, isUsed(c));\n c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(0.0, uniform.pixelOffset.y), 0.0), c, isUsed(c));\n c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + uniform.pixelOffset, 0.0), c, isUsed(c));\n var output: FragmentOutput;\n output.color = c;\n return output;\n}\n"},mL=function(){function e(e){this.shaderDilate=[],this.shaderDenoise=[],this.device=e,o1.get(this.device,ns).add(mP),o1.get(this.device,na).add(mI),this.constantTexSource=e.scope.resolve("source"),this.constantPixelOffset=e.scope.resolve("pixelOffset"),this.pixelOffset=new Float32Array(2),this.sigmas=null,this.constantSigmas=null,this.kernel=null;}var t=e.prototype;return t.setSourceTexture=function(e){this.constantTexSource.setValue(e);},t.prepare=function(e,t){this.pixelOffset[0]=1/e,this.pixelOffset[1]=1/t,this.constantPixelOffset.setValue(this.pixelOffset);},t.prepareDenoise=function(e,t,n){var i=+!n;if(!this.shaderDenoise[i]){var r=new Map;r.set("{MSIZE}",15),n&&r.set("HDR",""),this.shaderDenoise[i]=o6.createShader(this.device,{uniqueName:"lmBilateralDeNoise-"+(n?"hdr":"rgbm"),attributes:{vertex_position:tA},vertexGLSL:o1.get(this.device,ns).get("fullscreenQuadVS"),vertexWGSL:o1.get(this.device,na).get("fullscreenQuadVS"),fragmentGLSL:o1.get(this.device,ns).get("glslBilateralDeNoisePS"),fragmentWGSL:o1.get(this.device,na).get("wgslBilateralDeNoisePS"),fragmentDefines:r}),this.sigmas=new Float32Array(2),this.constantSigmas=this.device.scope.resolve("sigmas"),this.constantKernel=this.device.scope.resolve("kernel[0]"),this.bZnorm=this.device.scope.resolve("bZnorm");}this.sigmas[0]=e,this.sigmas[1]=t,this.constantSigmas.setValue(this.sigmas),this.evaluateDenoiseUniforms(e,t);},t.getDenoise=function(e){return this.shaderDenoise[+!e]},t.getDilate=function(e,t){var n=+!t;if(!this.shaderDilate[n]){var i=t?"#define HDR\n":"";this.shaderDilate[n]=o6.createShader(e,{uniqueName:"lmDilate-"+(t?"hdr":"rgbm"),attributes:{vertex_position:tA},vertexGLSL:o1.get(this.device,ns).get("fullscreenQuadVS"),vertexWGSL:o1.get(this.device,na).get("fullscreenQuadVS"),fragmentGLSL:i+o1.get(this.device,ns).get("glslDilatePS"),fragmentWGSL:i+o1.get(this.device,na).get("wgslDilatePS")});}return this.shaderDilate[n]},t.evaluateDenoiseUniforms=function(e,t){function n(e,t){return .39894*Math.exp(-0.5*e*e/(t*t))/t}this.kernel=this.kernel||new Float32Array(15);for(var i=this.kernel,r=Math.floor(7),s=0;s<=r;++s){var a=n(s,e);i[r+s]=a,i[r-s]=a;}this.constantKernel.setValue(this.kernel);var o=1/n(0,t);this.bZnorm.setValue(o);},e}();function mD(e,t){return (mD=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var mR=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t,n,i,r,s,a){var o;return (o=e.call(this,t)||this).viewBindGroups=[],o.renderer=n,o.camera=i,o.worldClusters=r,o.receivers=s,o.lightArray=a,o}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&mD(t,e);var n=t.prototype;return n.destroy=function(){this.viewBindGroups.forEach(function(e){e.defaultUniformBuffer.destroy(),e.destroy();}),this.viewBindGroups.length=0;},n.execute=function(){this.device;var e=this.renderer,t=this.camera,n=this.receivers,i=this.renderTarget,r=this.worldClusters,s=this.lightArray;e.renderForwardLayer(t,i,null,void 0,0,this.viewBindGroups,{meshInstances:n,splitLights:s,lightClusters:r});},t}(s0),mM=new eW,mO=function(){function e(e,t,n,i,r){this.device=e,this.root=t,this.scene=n,this.renderer=i,this.assets=r,this.shadowMapCache=i.shadowMapCache,this._tempSet=new Set,this._initCalled=false,this.passMaterials=[],this.ambientAOMaterial=null,this.fog="",this.ambientLight=new eN,this.renderTargets=new Map,this.stats={renderPasses:0,lightmapCount:0,totalRenderTime:0,forwardTime:0,fboTime:0,shadowMapTime:0,compileTime:0,shadersLinked:0};}var t=e.prototype;return t.destroy=function(){var e;lx.decRef(this.blackTex),this.blackTex=null,lx.destroy(),this.device=null,this.root=null,this.scene=null,this.renderer=null,this.assets=null,null==(e=this.camera)||e.destroy(),this.camera=null;},t.initBake=function(e){if(this.bakeHDR=7!==this.scene.lightmapPixelFormat,!this._initCalled){this._initCalled=true,this.lightmapFilters=new mL(e),this.constantBakeDir=e.scope.resolve("bakeDir"),this.materials=[],this.blackTex=new nN(this.device,{width:4,height:4,format:7,type:t4,name:"lightmapBlack"}),lx.incRef(this.blackTex);var t=new lZ;t.clearColor.set(0,0,0,0),t.clearColorBuffer=true,t.clearDepthBuffer=false,t.clearStencilBuffer=false,t.frustumCulling=false,t.projection=1,t.aspectRatio=1,t.node=new us,this.camera=t,this.camera.shaderParams.gammaCorrection=0,this.camera.shaderParams.toneMapping=0;}if(this.scene.clusteredLightingEnabled){var n=new c9(e.supportsAreaLights,e.maxTextureSize,function(){});this.lightingParams=n;var i=this.scene.lighting;n.shadowsEnabled=i.shadowsEnabled,n.shadowAtlasResolution=i.shadowAtlasResolution,n.cookiesEnabled=i.cookiesEnabled,n.cookieAtlasResolution=i.cookieAtlasResolution,n.areaLightsEnabled=i.areaLightsEnabled,n.cells=new eW(3,3,3),n.maxLightsPerCell=4,this.worldClusters=new uT(e),this.worldClusters.name="ClusterLightmapper";}},t.finishBake=function(e){function t(e){lx.decRef(e.colorBuffer),e.destroy();}this.materials=[],this.renderTargets.forEach(function(e){t(e);}),this.renderTargets.clear(),e.forEach(function(e){e.renderTargets.forEach(function(e){t(e);}),e.renderTargets.length=0;}),this.ambientAOMaterial=null,this.worldClusters&&(this.worldClusters.destroy(),this.worldClusters=null);},t.createMaterialForPass=function(e,t,n){var i=new dA;return i.name="lmMaterial-pass:"+t+"-ambient:"+n,i.setDefine("UV1LAYOUT",""),i.setDefine("LIT_LIGHTMAP_BAKING",""),0===t?(i.setDefine("LIT_LIGHTMAP_BAKING_COLOR",""),n?i.setDefine("LIT_LIGHTMAP_BAKING_ADD_AMBIENT",""):i.ambient=new eN(0,0,0),this.bakeHDR||i.setDefine("LIGHTMAP_RGBM",""),i.lightMap=this.blackTex):(i.setDefine("LIT_LIGHTMAP_BAKING_DIR",""),i.setDefine("STD_LIGHTMAP_DIR","")),i.cull=0,i.forceUv1=true,i.update(),i},t.createMaterials=function(e,t,n){for(var i=0;i0&&t.push(new mC(e,u));}}for(var f=0;f0){this.renderer.shadowRenderer.frameUpdate();var c=1===t?2:1;this.setLightmapping(o,false,c),this.initBake(n),this.bakeInternal(c,o,l);var h=64;1===t&&(h|=128),this.scene.ambientBake&&(h|=4096),this.setLightmapping(o,true,c,h),this.finishBake(o);}var f=eL();this.stats.totalRenderTime=f-i,this.stats.shadersLinked=n._shaderStats.linked-r,this.stats.compileTime=n._shaderStats.compileTime-a,this.stats.fboTime=n._renderTargetCreationTime-s,this.stats.lightmapCount=o.length;},t.allocateTextures=function(e,t){for(var n=0;n0){t.copy(e[0].aabb);for(var n=1;n1&&T>1&&S.light.bakeDir&&(T=1);for(var E=0;E1&&S.prepareVirtualLight(E,T),S.startBake();var w=false,A=this.lightCameraPrepare(f,S);for(u=0;u0)||!(E>0))&&(!x||!(l>0));l++){var I=C.renderTargets[l],L=C.renderTargets[l].colorBuffer.width,D=this.renderTargets.get(L),R=D.colorBuffer;0===l?y=c.updateShaders:y&&(c.updateShaders=true);var M=this.passMaterials[l];for(x&&E+1===T&&0===l&&(M=this.ambientAOMaterial),s=0;s=this._right){var n=t.length;if(n)if(e=t[n-1])this._left=t[n-1],this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=n-1;else {var i=this._findKey(e,t);this._left=t[i],this._right=t[i+1],this._len=this._right-this._left;var r=1/this._len;this._recip=isFinite(r)?r:0,this._p0=i,this._p1=i+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=false;},t._findKey=function(e,t){for(var n=0;e>=t[n+1];)n++;return n},t.eval=function(e,t,n){var i=n._data,r=n._components,s=this._p0*r;if(0===t)for(var a=0;a=e)},n.nextEventBehindTime=function(e){return !!this.nextEvent&&(e===this.track.duration?this.isReverse?this.nextEvent.time>=e:this.nextEvent.time<=e:this.isReverse?this.nextEvent.time>e:this.nextEvent.time=this.track.events.length?this._eventCursor=0:this._eventCursor<0&&(this._eventCursor=this.track.events.length-1);},n.clipFrameTime=function(t){var n=e.eventFrame;n.start=0,n.end=t,n.residual=0,this.isReverse?t<0&&(n.start=this.track.duration,n.end=0,n.residual=t+this.track.duration):t>this.track.duration&&(n.start=0,n.end=this.track.duration,n.residual=t-this.track.duration);},n.alignCursorToCurrentTime=function(){for(this.resetEventCursor();this.nextEventBehindTime(this._time)&&this._eventCursor!==this.eventCursorEnd;)this.moveEventCursor();},n.fireNextEvent=function(){this._eventHandler.fire(this.nextEvent.name,mH({track:this.track},this.nextEvent)),this.moveEventCursor();},n.fireNextEventInFrame=function(e,t){return !!(this.nextEventAheadOfTime(e)&&this.nextEventBehindTime(t))&&(this.fireNextEvent(),true)},n.activeEventsForFrame=function(t,n){var i=e.eventFrame;this.clipFrameTime(n);for(var r=this.eventCursor;this.fireNextEventInFrame(t,i.end)&&r!==this.eventCursor;);this.loop&&Math.abs(i.residual)>0&&this.activeEventsForFrame(i.start,i.residual);},n.progressForTime=function(e){return e*this._speed/this._track.duration},n._update=function(e){if(this._playing){var t=this._time,n=this._track.duration,i=this._speed,r=this._loop;this._track.events.length>0&&n>0&&this.activeEventsForFrame(t,t+i*e),t+=i*e,i>=0?t>n&&(r?t=t%n||0:(t=this._track.duration,this.pause())):t<0&&(r?t=n+(t%n||0):(t=0,this.pause())),this._time=t;}this._time!==this._snapshot._time&&this._track.eval(this._time,this._snapshot);},n.play=function(){this._playing=true,this._time=0;},n.stop=function(){this._playing=false,this._time=0;},n.pause=function(){this._playing=false;},n.resume=function(){this._playing=true;},n.reset=function(){this._time=0;},t=[{key:"name",get:function(){return this._name},set:function(e){this._name=e;}},{key:"track",get:function(){return this._track},set:function(e){this._track=e,this._snapshot=new mG(e);}},{key:"snapshot",get:function(){return this._snapshot}},{key:"time",get:function(){return this._time},set:function(e){this._time=e,this.alignCursorToCurrentTime();}},{key:"speed",get:function(){return this._speed},set:function(e){var t=Math.sign(e)!==Math.sign(this._speed);this._speed=e,t&&this.alignCursorToCurrentTime();}},{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;}},{key:"eventCursorEnd",get:function(){return this.isReverse?0:this._track.events.length-1}},{key:"nextEvent",get:function(){return this._track.events[this._eventCursor]}},{key:"isReverse",get:function(){return this._speed<0}}],function(e,t){for(var n=0;n0){n=1/Math.sqrt(n);for(var i=t.length,r=0;r0&&(s=1/Math.sqrt(s));for(var a=0;ae.dot(t,n)&&(i=-i);for(var o=0;o0;)this.removeClip(0);},n.updateClipTrack=function(e,t){this._clips.forEach(function(n){n.name.includes(e)&&(n.track=t);}),this.rebind();},n.findClip=function(e){for(var t=this._clips,n=0;n0&&a._update(e),!t)break;var c=void 0,h=void 0,f=void 0;if(u>=1)for(var d=0;d0)for(var p=0;p0&&n.push(i),n},e.encode=function(e,t,n){return (Array.isArray(e)?e.join("/"):e)+"/"+t+"/"+(Array.isArray(n)?n.join("/"):n)},e}(),_u=function(){var e;function t(e,t,n,i){e.set?(this._set=e.set,this._get=e.get):this._set=e,this._type=t,this._components=n,this._targetPath=i,this._isTransform="localRotation"===this._targetPath.substring(this._targetPath.length-13)||"localPosition"===this._targetPath.substring(this._targetPath.length-13)||"localScale"===this._targetPath.substring(this._targetPath.length-10);}return e=[{key:"set",get:function(){return this._set}},{key:"get",get:function(){return this._get}},{key:"type",get:function(){return this._type}},{key:"components",get:function(){return this._components}},{key:"targetPath",get:function(){return this._targetPath}},{key:"isTransform",get:function(){return this._isTransform}}],function(e,t){for(var n=0;n0&&!!this.prevAnim,this.blending&&(this.blend=0,this.blendSpeed=1/t),this.skeleton&&(this.blending?(this.fromSkel.animation=n,this.fromSkel.addTime(this.skeleton._time),this.toSkel.animation=i):this.skeleton.animation=i),this.animEvaluator){var r=this.animEvaluator;if(this.blending)for(;r.clips.length>1;)r.removeClip(0);else this.animEvaluator.removeClips();var s=new mW(this.animations[this.currAnim],0,1,true,this.loop);s.name=this.currAnim,s.blendWeight=+!this.blending,s.reset(),this.animEvaluator.addClip(s);}}this.playing=true;}},i.getAnimation=function(e){return this.animations[e]},i.setModel=function(e){e!==this.model&&(this._resetAnimationController(),this.model=e,this.animations&&this.currAnim&&this.animations[this.currAnim]&&this.play(this.currAnim));},i.onSetAnimations=function(){var e=this.entity.model;if(e){var t=e.model;t&&t!==this.model&&this.setModel(t);}if(!this.currAnim&&this.activate&&this.enabled&&this.entity.enabled){var n=Object.keys(this._animations);n.length>0&&this.play(n[0]);}},i._resetAnimationController=function(){this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animEvaluator=null;},i._createAnimationController=function(){var e=this.model,t=this.animations,n=false,i=false;for(var r in t)t.hasOwnProperty(r)&&(t[r].constructor===_o?i=true:n=true);var s=e.getGraph();n?(this.fromSkel=new fQ(s),this.toSkel=new fQ(s),this.skeleton=new fQ(s),this.skeleton.looping=this.loop,this.skeleton.setGraph(s)):i&&(this.animEvaluator=new _s(new _c(this.entity)));},i.loadAnimationAssets=function(e){var t=this;if(e&&e.length)for(var n=this.system.app.assets,i=function(e){if(e.resources.length>1)for(var n=0;n1){if(i&&i.length>1)for(var s=0;s1)for(var o=0;o1)for(var l=0;l1)for(var t=0;t0&&this.play(a[0]);}},i.onBeforeRemove=function(){for(var e=0;e=1&&(this.blend=1)),this.playing){var t=this.skeleton;if(null!==t&&null!==this.model){if(this.blending)t.blend(this.fromSkel,this.toSkel,this.blend);else {var n=e*this.speed;t.addTime(n),this.speed>0&&t._time===t.animation.duration&&!this.loop?this.playing=false:this.speed<0&&0===t._time&&!this.loop&&(this.playing=false);}this.blending&&1===this.blend&&(t.animation=this.toSkel.animation),t.updateGraph();}}var i=this.animEvaluator;if(i){for(var r=0;r1&&(i.clips[1].blendWeight=this.blend),i.update(e);}this.blending&&1===this.blend&&(this.blending=false);},n=[{key:"animations",get:function(){return this._animations},set:function(e){this._animations=e,this.onSetAnimations();}},{key:"assets",get:function(){return this._assets},set:function(e){var t=this._assets;if(t&&t.length){for(var n=0;n0)return e[e.length-1].time}return 0},set:function(e){if(this.skeleton&&(this.skeleton.currentTime=e,this.skeleton.addTime(0),this.skeleton.updateGraph()),this.animEvaluator)for(var t=this.animEvaluator.clips,n=0;ne.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(i);!(r=s()).done;){var a=r.value;n.hasOwnProperty(a)&&(t[a]=n[a]);}e.prototype.initializeComponentData.call(this,t,n,_v);},n.cloneComponent=function(e,t){this.addComponent(t,{}),t.animation.assets=e.animation.assets.slice(),t.animation.speed=e.animation.speed,t.animation.loop=e.animation.loop,t.animation.activate=e.animation.activate,t.animation.enabled=e.animation.enabled;var n={},i=e.animation.animations;for(var r in i)i.hasOwnProperty(r)&&(n[r]=i[r]);t.animation.animations=n;var s={},a=e.animation.animationsIndex;for(var o in a)a.hasOwnProperty(o)&&(s[o]=a[o]);return t.animation.animationsIndex=s,t.animation},n.onBeforeRemove=function(e,t){t.onBeforeRemove();},n.onUpdate=function(e){var t=this.store;for(var n in t)if(t.hasOwnProperty(n)){var i=t[n];i.data.enabled&&i.entity.enabled&&i.entity.animation.update(e);}},n.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this);},t}(mV);mN._buildAccessors(_d.prototype,_v);var _y=function(){var e;function t(e,t,n,i,r){ void 0===r&&(r=1),this._state=e,this._parent=t,this._name=n,Array.isArray(i)?(this._point=new eX(i[0],i[1]),this._pointLength=this._point.length()):(this._point=i,this._pointLength=i),this._speed=r,this._weightedSpeed=1,this._weight=1,this._animTrack=null;}return e=[{key:"parent",get:function(){return this._parent}},{key:"name",get:function(){return this._name}},{key:"path",get:function(){return this._parent?this._parent.path+"."+this._name:this._name}},{key:"point",get:function(){return this._point}},{key:"pointLength",get:function(){return this._pointLength}},{key:"weight",get:function(){return this._parent?this._parent.weight*this._weight:this._weight},set:function(e){this._weight=e;}},{key:"normalizedWeight",get:function(){var e=this._state.totalWeight;return 0===e?0:this.weight/e}},{key:"speed",get:function(){return this._weightedSpeed*this._speed}},{key:"absoluteSpeed",get:function(){return Math.abs(this._speed)}},{key:"weightedSpeed",get:function(){return this._weightedSpeed},set:function(e){this._weightedSpeed=e;}},{key:"animTrack",get:function(){return this._animTrack},set:function(e){this._animTrack=e;}}],function(e,t){for(var n=0;n=0)this._animationList[i].animTrack=t;else {var r=this._getNodeFromPath(e);r.animTrack=t,this._animationList.push(r);}this._updateHasAnimations();},n._updateHasAnimations=function(){this._hasAnimations=this._animationList.length>0&&this._animationList.every(function(e){return e.animTrack&&e.animTrack!==_o.EMPTY});},t=[{key:"name",get:function(){return this._name}},{key:"animations",get:function(){return this._animationList},set:function(e){this._animationList=e,this._updateHasAnimations();}},{key:"hasAnimations",get:function(){return this._hasAnimations}},{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!==_y?this._blendTree.getNodeCount():1}},{key:"playable",get:function(){return -1!==_e.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 false}},{key:"totalWeight",get:function(){for(var e=0,t=0;te&&(e=n.animTrack.duration);}return e}}],function(e,t){for(var n=0;n"+t];return n||(cq(n=this._transitions.filter(function(n){return n.from===e&&n.to===t})),this._findTransitionsBetweenStatesCache[e+"->"+t]=n),n},n._transitionHasConditionsMet=function(e){for(var t=e.conditions,n=0;ni.value))return false;break;case mQ:if(!(r.value=i.value))return false;break;case m$:if(!(r.value<=i.value))return false;break;case m0:if(r.value!==i.value)return false;break;case m1:if(r.value===i.value)return false}}return true},n._findTransition=function(e,t){var n=this,i=[];if(e&&t)i=i.concat(this._findTransitionsBetweenStates(e,t));else if(this._isTransitioning)switch(this._transitionInterruptionSource){case mX:i=(i=i.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState("ANY"));break;case mY:i=(i=i.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState("ANY"));break;case mq:i=(i=(i=i.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState("ANY"));break;case mK:i=(i=(i=i.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState("ANY"));}else i=(i=i.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState("ANY"));if((i=i.filter(function(e){if(e.to===n.activeStateName)return false;if(e.hasExitTime){var t=n._getActiveStateProgressForTime(n._timeInStateBefore),i=n._getActiveStateProgressForTime(n._timeInState);if(e.exitTime<1&&n.activeState.loop&&(t-=Math.floor(t),i-=Math.floor(i)),i===t){if(i!==e.exitTime)return null}else if(!(e.exitTime>t&&e.exitTime<=i))return null}return n._transitionHasConditionsMet(e)})).length>0){var r=i[0];return "END"===r.to&&(r.to=this._findTransitionsFromState(m7)[0].to),r}return null},n.updateStateFromTransition=function(e){this.previousState=e.from?this.activeStateName:null,this.activeState=e.to,this._activeStateDurationDirty=true;for(var t,n,i,r=0;r0&&e.transitionOffset<1,h=0,f=0;if(c){var d=u.timelineDuration*e.transitionOffset;h=d,f=d;}this._timeInState=h,this._timeInStateBefore=f;for(var p=0;p0?i.blendWeight=0:i.blendWeight=u.animations[p].normalizedWeight,i.play(),c)i.time=u.timelineDuration*e.transitionOffset;else {var _=u.speed>=0?0:this.activeStateDuration;i.time=_;}}},n._transitionToState=function(e){if(this._findState(e)){var t=this._findTransition(this._activeStateName,e);t||(this._animEvaluator.removeClips(),t=new _D({from:null,to:e})),this.updateStateFromTransition(t);}},n.assignAnimation=function(e,t,n,i){var r=e.split("."),s=this._findState(r[0]);s||(s=new _L(this,r[0],n),this._states[r[0]]=s,this._stateNames.push(r[0])),s.addAnimation(r,t),this._animEvaluator.updateClipTrack(s.name,t),void 0!==n&&(s.speed=n),void 0!==i&&(s.loop=i),!this._playing&&this._activate&&this.playable&&this.play(),this._activeStateDurationDirty=true;},n.removeNodeAnimations=function(e){if(-1!==_e.indexOf(e))return false;var t=this._findState(e);return !!t&&(t.animations=[],true)},n.play=function(e){e&&this._transitionToState(e),this._playing=true;},n.pause=function(){this._playing=false;},n.reset=function(){this._previousStateName=null,this._activeStateName=m7,this._playing=false,this._currTransitionTime=1,this._totalTransitionTime=1,this._isTransitioning=false,this._timeInState=0,this._timeInStateBefore=0,this._animEvaluator.removeClips();},n.rebind=function(){this._animEvaluator.rebind();},n.update=function(e){if(this._playing){(this.activeState.loop||this._timeInStatethis.activeStateDuration&&(this._timeInState=this.activeStateDuration,e=this.activeStateDuration-this._timeInStateBefore));var t,n,i,r=this._findTransition(this._activeStateName);if(r&&this.updateStateFromTransition(r),this._isTransitioning)if(this._currTransitionTime+=e,this._currTransitionTime<=this._totalTransitionTime){for(var s=0!==this._totalTransitionTime?this._currTransitionTime/this._totalTransitionTime:1,a=0;a1){var u=t.length>2?this._resolvePath(e,t.slice(0,-1)):e,c=t[t.length-2];return function(e){i[r]=n(e),u[c]=i;}}return function(e){i[r]=n(e);}},n._createAnimTargetForProperty=function(e,n,i){if(this.handlers&&n[0].startsWith("weight."))return this.handlers.weight(e,n[0].replace("weight.",""));if(this.handlers&&"material"===n[0]&&2===n.length){var r,s,a,o=n[1];if(o.endsWith("Map"))return this.handlers.materialTexture(e,o)}var l=this._resolvePath(e,n,true);if(void 0===l)return null;if("number"==typeof l)r=this._setter(e,n,t._packFloat),s="vector",a=1;else if("boolean"==typeof l)r=this._setter(e,n,t._packBoolean),s="vector",a=1;else if((void 0===l?"undefined":_k(l))==="object")switch(l.constructor){case eX:r=this._setter(e,n,t._packVec2),s="vector",a=2;break;case eW:r=this._setter(e,n,t._packVec3),s="vector",a=3;break;case eY:r=this._setter(e,n,t._packVec4),s="vector",a=4;break;case eN:r=this._setter(e,n,t._packColor),s="vector",a=4;break;case e0:r=this._setter(e,n,t._packQuat),s="quaternion",a=4;break;default:return null}return -1!==n.indexOf("material")?new _u(function(t){r(t),e.material.update();},s,a,i):new _u(r,s,a,i)},n.rebind=function(){this.targetCache={},this.animComponent.rootBone?this.graph=this.animComponent.rootBone:this.graph=this.animComponent.entity;var e={},t=function(n){e[n.name]=n;for(var i=0;i0?this._layers[0]:null}}],function(e,t){for(var n=0;n1e-5){var n=this._tweenInfo.lerpColor;n.lerp(this._tweenInfo.from,this._tweenInfo.to,t),this._applyTintImmediately(new eN(n.r,n.g,n.b,n.a));}else this._applyTintImmediately(this._tweenInfo.to),this._cancelTween();},r._cancelTween=function(){delete this._tweenInfo;},r.onUpdate=function(){this._tweenInfo&&this._updateTintTween();},r.onEnable=function(){this._isHovering=false,this._hoveringCounter=0,this._isPressed=false,this._toggleHitElementListeners("on"),this._forceReapplyVisualState();},r.onDisable=function(){this._toggleHitElementListeners("off"),this._resetToDefaultVisualState(this.transitionMode);},r.onRemove=function(){this._imageEntityUnsubscribe(),this._toggleLifecycleListeners("off",this.system),this.onDisable();},r.resolveDuplicatedEntityReferenceProperties=function(e,t){e.imageEntity&&(this.imageEntity=t[e.imageEntity.getGuid()]);},n=[{key:"data",get:function(){var e=this.system.store[this.entity.getGuid()];return e?e.data:null}},{key:"enabled",get:function(){return this.data.enabled},set:function(e){this._setValue("enabled",e);}},{key:"active",get:function(){return this.data.active},set:function(e){this._setValue("active",e);}},{key:"imageEntity",get:function(){return this._imageEntity},set:function(e){if(this._imageEntity!==e){var t="string"==typeof e;(!this._imageEntity||!t||this._imageEntity.getGuid()!==e)&&((this._imageEntity&&this._imageEntityUnsubscribe(),null!=us&&"undefined"!=typeof Symbol&&us[Symbol.hasInstance]?!!us[Symbol.hasInstance](e):i(e,us))?this._imageEntity=e:t?this._imageEntity=this.system.app.getEntityFromIndex(e)||null:this._imageEntity=null,this._imageEntity&&this._imageEntitySubscribe(),this._imageEntity?this.data.imageEntity=this._imageEntity.getGuid():t&&e&&(this.data.imageEntity=e));}}},{key:"hitPadding",get:function(){return this.data.hitPadding},set:function(e){this._setValue("hitPadding",e);}},{key:"transitionMode",get:function(){return this.data.transitionMode},set:function(e){this._setValue("transitionMode",e);}},{key:"hoverTint",get:function(){return this.data.hoverTint},set:function(e){this._setValue("hoverTint",e);}},{key:"pressedTint",get:function(){return this.data.pressedTint},set:function(e){this._setValue("pressedTint",e);}},{key:"inactiveTint",get:function(){return this.data.inactiveTint},set:function(e){this._setValue("inactiveTint",e);}},{key:"fadeDuration",get:function(){return this.data.fadeDuration},set:function(e){this._setValue("fadeDuration",e);}},{key:"hoverSpriteAsset",get:function(){return this.data.hoverSpriteAsset},set:function(e){this._setValue("hoverSpriteAsset",e);}},{key:"hoverSpriteFrame",get:function(){return this.data.hoverSpriteFrame},set:function(e){this._setValue("hoverSpriteFrame",e);}},{key:"pressedSpriteAsset",get:function(){return this.data.pressedSpriteAsset},set:function(e){this._setValue("pressedSpriteAsset",e);}},{key:"pressedSpriteFrame",get:function(){return this.data.pressedSpriteFrame},set:function(e){this._setValue("pressedSpriteFrame",e);}},{key:"inactiveSpriteAsset",get:function(){return this.data.inactiveSpriteAsset},set:function(e){this._setValue("inactiveSpriteAsset",e);}},{key:"inactiveSpriteFrame",get:function(){return this.data.inactiveSpriteFrame},set:function(e){this._setValue("inactiveSpriteFrame",e);}}],function(e,t){for(var n=0;nt._triggers.indexOf(this)&&(t.addBody(e,16,65517),t._triggers.push(this)),e.forceActivationState(1),this.updateTransform();}},t.disable=function(){var e=this.body;if(e){var t=this.app.systems.rigidbody,n=t._triggers.indexOf(this);n>-1&&(t.removeBody(e),t._triggers.splice(n,1)),e.forceActivationState(5);}},e}();function vx(e,t){if("function"!=typeof t&&null!==t)throw TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:true,configurable:true}}),t&&vb(e,t);}function vb(e,t){return (vb=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var vT=new e$,vE=new eW,vw=new eW,vA=new e0,vC=new us,vP=["enabled","type","halfExtents","linearOffset","angularOffset","radius","axis","height","convexHull","asset","renderAsset","shape","model","render","checkVertexDuplicates"],vI=function(){function e(e){this.system=e;}var t=e.prototype;return t.beforeInitialize=function(e,t){t.shape=null,t.model=new he,t.model.graph=new us;},t.afterInitialize=function(e,t){this.recreatePhysicalShapes(e),e.data.initialized=true;},t.reset=function(e,t){this.beforeInitialize(e,t),this.afterInitialize(e,t);},t.recreatePhysicalShapes=function(e){var t=e.entity,n=e.data;if("undefined"!=typeof Ammo){t.trigger&&(t.trigger.destroy(),delete t.trigger),n.shape&&(e._compoundParent&&(e!==e._compoundParent&&this.system._removeCompoundChild(e._compoundParent,n.shape),e._compoundParent.entity.rigidbody&&e._compoundParent.entity.rigidbody.activate()),this.destroyShape(n)),n.shape=this.createPhysicalShape(e.entity,n);var i=!e._compoundParent;if("compound"!==n.type||e._compoundParent&&e!==e._compoundParent){if("compound"!==n.type&&!e.rigidbody){e._compoundParent=null;for(var r=t.parent;r;){if(r.collision&&"compound"===r.collision.type){e._compoundParent=r.collision;break}r=r.parent;}}}else e._compoundParent=e,t.forEach(this._addEachDescendant,e);e._compoundParent&&e!==e._compoundParent&&(i&&0===e._compoundParent.shape.getNumChildShapes()?this.system.recreatePhysicalShapes(e._compoundParent):(this.system.updateCompoundChildTransform(t,true),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(n):t.trigger=new vS(this.system.app,e,n));}},t.createPhysicalShape=function(e,t){},t.updateTransform=function(e,t,n,i){e.entity.trigger&&e.entity.trigger.updateTransform();},t.destroyShape=function(e){e.shape&&(Ammo.destroy(e.shape),e.shape=null);},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,this.destroyShape(t.data));},t.remove=function(e,t){e.rigidbody&&e.rigidbody.body&&e.rigidbody.disableSimulation(),e.trigger&&(e.trigger.destroy(),delete e.trigger);},t.clone=function(e,t){var n=this.system.store[e.getGuid()],i={enabled:n.data.enabled,type:n.data.type,halfExtents:[n.data.halfExtents.x,n.data.halfExtents.y,n.data.halfExtents.z],linearOffset:[n.data.linearOffset.x,n.data.linearOffset.y,n.data.linearOffset.z],angularOffset:[n.data.angularOffset.x,n.data.angularOffset.y,n.data.angularOffset.z,n.data.angularOffset.w],radius:n.data.radius,axis:n.data.axis,height:n.data.height,convexHull:n.data.convexHull,asset:n.data.asset,renderAsset:n.data.renderAsset,model:n.data.model,render:n.data.render,checkVertexDuplicates:n.data.checkVertexDuplicates};return this.system.addComponent(t,i)},e}(),vL=function(e){function t(){return e.apply(this,arguments)||this}return vx(t,e),t.prototype.createPhysicalShape=function(e,t){if("undefined"!=typeof Ammo){var n=t.halfExtents,i=new Ammo.btVector3(n?n.x:.5,n?n.y:.5,n?n.z:.5),r=new Ammo.btBoxShape(i);return Ammo.destroy(i),r}},t}(vI),vD=function(e){function t(){return e.apply(this,arguments)||this}return vx(t,e),t.prototype.createPhysicalShape=function(e,t){if("undefined"!=typeof Ammo)return new Ammo.btSphereShape(t.radius)},t}(vI),vR=function(e){function t(){return e.apply(this,arguments)||this}return vx(t,e),t.prototype.createPhysicalShape=function(e,t){var n,i,r,s=null!=(n=t.axis)?n:1,a=null!=(i=t.radius)?i:.5,o=Math.max((null!=(r=t.height)?r:2)-2*a,0),l=null;if("undefined"!=typeof Ammo)switch(s){case 0:l=new Ammo.btCapsuleShapeX(a,o);break;case 1:l=new Ammo.btCapsuleShape(a,o);break;case 2:l=new Ammo.btCapsuleShapeZ(a,o);}return l},t}(vI),vM=function(e){function t(){return e.apply(this,arguments)||this}return vx(t,e),t.prototype.createPhysicalShape=function(e,t){var n,i,r,s=null!=(n=t.axis)?n:1,a=null!=(i=t.radius)?i:.5,o=null!=(r=t.height)?r:1,l=null,u=null;if("undefined"!=typeof Ammo)switch(s){case 0:l=new Ammo.btVector3(.5*o,a,a),u=new Ammo.btCylinderShapeX(l);break;case 1:l=new Ammo.btVector3(a,.5*o,a),u=new Ammo.btCylinderShape(l);break;case 2:l=new Ammo.btVector3(a,a,.5*o),u=new Ammo.btCylinderShapeZ(l);}return l&&Ammo.destroy(l),u},t}(vI),vO=function(e){function t(){return e.apply(this,arguments)||this}return vx(t,e),t.prototype.createPhysicalShape=function(e,t){var n,i,r,s=null!=(n=t.axis)?n:1,a=null!=(i=t.radius)?i:.5,o=null!=(r=t.height)?r:1,l=null;if("undefined"!=typeof Ammo)switch(s){case 0:l=new Ammo.btConeShapeX(a,o);break;case 1:l=new Ammo.btConeShape(a,o);break;case 2:l=new Ammo.btConeShapeZ(a,o);}return l},t}(vI),vk=function(e){function t(){return e.apply(this,arguments)||this}vx(t,e);var n=t.prototype;return n.beforeInitialize=function(e,t){},n.createAmmoHull=function(e,t,n,i){var r=new Ammo.btConvexHullShape,s=new Ammo.btVector3,a=[];e.getPositions(a);for(var o=0;o=0&&this.model.meshInstances.splice(i,1);}this._entity.enabled&&this._element.enabled&&this._element.addModelToLayers(this.model),e||(null==(n=this.unmaskMeshInstance)||n.destroy(),this.unmaskMeshInstance=null);}},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){var e=function(t){var n,i=t.children,r=i.length;if(r){for(var s=0;s0){var r=t.calculatedWidth/t.calculatedHeight;t.fitMode===_9&&r>this._targetAspectRatio||t.fitMode===_7&&r0&&(this._targetAspectRatio=n.rect.z/n.rect.w);}this.mesh=e?t:this._defaultMesh,this.refreshMesh();},n.refreshMesh=function(){this.mesh&&(this._element._beingInitialized?this._meshDirty=true:this._updateMesh(this.mesh));},n._updateAabb=function(e){return e.center.set(0,0,0),e.halfExtents.set(.5*this._outerScale.x,.5*this._outerScale.y,.001),e.setFromTransformedAabb(e,this._renderable.node.getWorldTransform()),e},n._toggleMask=function(){this._element._dirtifyMask();var e=this._element._isScreenSpace();this._updateMaterial(e),this._renderable.setMask(!!this._mask);},n._onMaterialLoad=function(e){this.material=e.resource;},n._onMaterialAdded=function(e){this._system.app.assets.off("add:"+e.id,this._onMaterialAdded,this),this._materialAsset===e.id&&this._bindMaterialAsset(e);},n._bindMaterialAsset=function(e){this._entity.enabled&&(e.on("load",this._onMaterialLoad,this),e.on("change",this._onMaterialChange,this),e.on("remove",this._onMaterialRemove,this),e.resource?this._onMaterialLoad(e):this._system.app.assets.load(e));},n._unbindMaterialAsset=function(e){e.off("load",this._onMaterialLoad,this),e.off("change",this._onMaterialChange,this),e.off("remove",this._onMaterialRemove,this);},n._onMaterialChange=function(){},n._onMaterialRemove=function(){},n._onTextureAdded=function(e){this._system.app.assets.off("add:"+e.id,this._onTextureAdded,this),this._textureAsset===e.id&&this._bindTextureAsset(e);},n._bindTextureAsset=function(e){this._entity.enabled&&(e.on("load",this._onTextureLoad,this),e.on("change",this._onTextureChange,this),e.on("remove",this._onTextureRemove,this),e.resource?this._onTextureLoad(e):this._system.app.assets.load(e));},n._unbindTextureAsset=function(e){e.off("load",this._onTextureLoad,this),e.off("change",this._onTextureChange,this),e.off("remove",this._onTextureRemove,this);},n._onTextureLoad=function(e){this.texture=e.resource;},n._onTextureChange=function(e){},n._onTextureRemove=function(e){},n._onSpriteAssetAdded=function(e){this._system.app.assets.off("add:"+e.id,this._onSpriteAssetAdded,this),this._spriteAsset===e.id&&this._bindSpriteAsset(e);},n._bindSpriteAsset=function(e){this._entity.enabled&&(e.on("load",this._onSpriteAssetLoad,this),e.on("change",this._onSpriteAssetChange,this),e.on("remove",this._onSpriteAssetRemove,this),e.resource?this._onSpriteAssetLoad(e):this._system.app.assets.load(e));},n._unbindSpriteAsset=function(e){e.off("load",this._onSpriteAssetLoad,this),e.off("change",this._onSpriteAssetChange,this),e.off("remove",this._onSpriteAssetRemove,this),e.data.textureAtlasAsset&&this._system.app.assets.off("load:"+e.data.textureAtlasAsset,this._onTextureAtlasLoad,this);},n._onSpriteAssetLoad=function(e){if(e&&e.resource)if(e.resource.atlas)this.sprite=e.resource;else {var t=e.data.textureAtlasAsset;if(t){var n=this._system.app.assets;n.off("load:"+t,this._onTextureAtlasLoad,this),n.once("load:"+t,this._onTextureAtlasLoad,this);}}else this.sprite=null;},n._onSpriteAssetChange=function(e){this._onSpriteAssetLoad(e);},n._onSpriteAssetRemove=function(e){},n._bindSprite=function(e){this._evtSetMeshes=e.on("set:meshes",this._onSpriteMeshesChange,this),e.on("set:pixelsPerUnit",this._onSpritePpuChange,this),e.on("set:atlas",this._onAtlasTextureChange,this),e.atlas&&e.atlas.on("set:texture",this._onAtlasTextureChange,this);},n._unbindSprite=function(e){var t;null==(t=this._evtSetMeshes)||t.off(),this._evtSetMeshes=null,e.off("set:pixelsPerUnit",this._onSpritePpuChange,this),e.off("set:atlas",this._onAtlasTextureChange,this),e.atlas&&e.atlas.off("set:texture",this._onAtlasTextureChange,this);},n._onSpriteMeshesChange=function(){this._sprite&&(this._spriteFrame=ek.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite();},n._onSpritePpuChange=function(){0!==this.sprite.renderMode&&null===this._pixelsPerUnit&&this._updateSprite();},n._onAtlasTextureChange=function(){this.sprite&&this.sprite.atlas&&this.sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"));},n._onTextureAtlasLoad=function(e){var t=this._spriteAsset;vB(t,pU)?this._onSpriteAssetLoad(t):this._onSpriteAssetLoad(this._system.app.assets.get(t));},n.onEnable=function(){if(this._materialAsset){var e=this._system.app.assets.get(this._materialAsset);e&&e.resource!==this._material&&this._bindMaterialAsset(e);}if(this._textureAsset){var t=this._system.app.assets.get(this._textureAsset);t&&t.resource!==this._texture&&this._bindTextureAsset(t);}if(this._spriteAsset){var n=this._system.app.assets.get(this._spriteAsset);n&&n.resource!==this._sprite&&this._bindSpriteAsset(n);}this._element.addModelToLayers(this._renderable.model);},n.onDisable=function(){this._element.removeModelFromLayers(this._renderable.model);},n._setStencil=function(e){this._renderable.meshInstance.stencilFront=e,this._renderable.meshInstance.stencilBack=e;var t=0;if(this._element.maskedBy&&(t=this._element.maskedBy.element._image._maskRef),this._renderable.unmaskMeshInstance){var n=new it({ref:t+1,func:2,zpass:5});this._renderable.unmaskMeshInstance.stencilFront=n,this._renderable.unmaskMeshInstance.stencilBack=n;}},n._updateRenderableEmissive=function(){vU.linear(this._color),this._colorUniform[0]=vU.r,this._colorUniform[1]=vU.g,this._colorUniform[2]=vU.b,this._renderable.setParameter("material_emissive",this._colorUniform);},n._removeMaterialAssetEvents=function(){if(this._materialAsset){var e=this._system.app.assets;e.off("add:"+this._materialAsset,this._onMaterialAdded,this);var t=e.get(this._materialAsset);t&&(t.off("load",this._onMaterialLoad,this),t.off("change",this._onMaterialChange,this),t.off("remove",this._onMaterialRemove,this));}},t=[{key:"color",get:function(){return this._color},set:function(e){var t=e.r,n=e.g,i=e.b;(this._color.r!==t||this._color.g!==n||this._color.b!==i)&&(this._color.r=t,this._color.g=n,this._color.b=i,this._updateRenderableEmissive()),this._element&&this._element.fire("set:color",this._color);}},{key:"opacity",get:function(){return this._color.a},set:function(e){e!==this._color.a&&(this._color.a=e,this._renderable.setParameter("material_opacity",e)),this._element&&this._element.fire("set:opacity",e);}},{key:"rect",get:function(){return this._rect},set:function(e){var t,n,i,r;vB(e,eY)?(t=e.x,n=e.y,i=e.z,r=e.w):(t=e[0],n=e[1],i=e[2],r=e[3]),(t!==this._rect.x||n!==this._rect.y||i!==this._rect.z||r!==this._rect.w)&&(this._rect.set(t,n,i,r),this._renderable.mesh&&(this._element._beingInitialized?this._meshDirty=true:this._updateMesh(this._renderable.mesh)));}},{key:"material",get:function(){return this._material},set:function(e){if(this._material!==e){if(!e){var t=this._element._isScreenSpace();e=this.mask?t?this._system.defaultScreenSpaceImageMaskMaterial:this._system.defaultImageMaskMaterial:t?this._system.defaultScreenSpaceImageMaterial:this._system.defaultImageMaterial;}if(this._material=e,this._materialAsset){var n=this._system.app.assets.get(this._materialAsset);n&&n.resource===e||(this._removeMaterialAssetEvents(),this._materialAsset=null);}e&&(this._renderable.setMaterial(e),this._hasUserMaterial()?(this._renderable.deleteParameter("material_opacity"),this._renderable.deleteParameter("material_emissive")):(this._updateRenderableEmissive(),this._renderable.setParameter("material_opacity",this._color.a)));}}},{key:"materialAsset",get:function(){return this._materialAsset},set:function(e){var t=this._system.app.assets,n=e;if(vB(e,pU)&&(n=e.id),this._materialAsset!==n)if(this._removeMaterialAssetEvents(),this._materialAsset=n,this._materialAsset){var i=t.get(this._materialAsset);i?this._bindMaterialAsset(i):(this._materialAsset=null,this.material=null,this._materialAsset=n,t.on("add:"+this._materialAsset,this._onMaterialAdded,this));}else this._materialAsset=null,this.material=null,this._materialAsset=n;}},{key:"texture",get:function(){return this._texture},set:function(e){if(this._texture!==e){if(this._textureAsset){var t=this._system.app.assets.get(this._textureAsset);t&&t.resource!==e&&(this.textureAsset=null);}if(this._texture=e,e){this._spriteAsset&&(this.spriteAsset=null),this._renderable.setParameter("texture_emissiveMap",this._texture),this._renderable.setParameter("texture_opacityMap",this._texture),this._updateRenderableEmissive(),this._renderable.setParameter("material_opacity",this._color.a);var n=this._texture.width/this._texture.height;n!==this._targetAspectRatio&&(this._targetAspectRatio=n,this._element.fitMode!==_6&&this.refreshMesh());}else this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"),this._targetAspectRatio=-1,this._element.fitMode!==_6&&this.refreshMesh();}}},{key:"textureAsset",get:function(){return this._textureAsset},set:function(e){var t=this._system.app.assets,n=e;if(vB(e,pU)&&(n=e.id),this._textureAsset!==n){if(this._textureAsset){t.off("add:"+this._textureAsset,this._onTextureAdded,this);var i=t.get(this._textureAsset);i&&(i.off("load",this._onTextureLoad,this),i.off("change",this._onTextureChange,this),i.off("remove",this._onTextureRemove,this));}if(this._textureAsset=n,this._textureAsset){var r=t.get(this._textureAsset);r?this._bindTextureAsset(r):(this.texture=null,t.on("add:"+this._textureAsset,this._onTextureAdded,this));}else this.texture=null;}}},{key:"spriteAsset",get:function(){return this._spriteAsset},set:function(e){var t=this._system.app.assets,n=e;if(vB(e,pU)&&(n=e.id),this._spriteAsset!==n){if(this._spriteAsset){t.off("add:"+this._spriteAsset,this._onSpriteAssetAdded,this);var i=t.get(this._spriteAsset);i&&this._unbindSpriteAsset(i);}if(this._spriteAsset=n,this._spriteAsset){var r=t.get(this._spriteAsset);r?this._bindSpriteAsset(r):(this.sprite=null,t.on("add:"+this._spriteAsset,this._onSpriteAssetAdded,this));}else this.sprite=null;}this._element&&this._element.fire("set:spriteAsset",n);}},{key:"sprite",get:function(){return this._sprite},set:function(e){if(this._sprite!==e){if(this._sprite&&this._unbindSprite(this._sprite),this._spriteAsset){var t=this._system.app.assets.get(this._spriteAsset);t&&t.resource!==e&&(this.spriteAsset=null);}this._sprite=e,this._sprite&&(this._bindSprite(this._sprite),this._textureAsset&&(this.textureAsset=null)),this._sprite&&this._sprite.atlas&&this._sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap")),this._sprite&&(this._spriteFrame=ek.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite();}}},{key:"spriteFrame",get:function(){return this._spriteFrame},set:function(e){var t=this._spriteFrame;this._sprite?this._spriteFrame=ek.clamp(e,0,this._sprite.frameKeys.length-1):this._spriteFrame=e,this._spriteFrame!==t&&this._updateSprite(),this._element&&this._element.fire("set:spriteFrame",e);}},{key:"mesh",get:function(){return this._renderable.mesh},set:function(e){this._renderable.setMesh(e),this._defaultMesh===e?this._renderable.setAabbFunc(null):this._renderable.setAabbFunc(this._updateAabbFunc);}},{key:"mask",get:function(){return this._mask},set:function(e){this._mask!==e&&(this._mask=e,this._toggleMask());}},{key:"pixelsPerUnit",get:function(){return this._pixelsPerUnit},set:function(e){this._pixelsPerUnit!==e&&(this._pixelsPerUnit=e,this._sprite&&(1===this._sprite.renderMode||2===this._sprite.renderMode)&&this._updateSprite());}},{key:"aabb",get:function(){return this._renderable.meshInstance?this._renderable.meshInstance.aabb:null}}],function(e,t){for(var n=0;n0?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(),n="";n+=(n.length>0?"\n":"")+e[t]+" '"+this.buf().join("")+"'",0!==t&&1!==t;)t=this.read();return n},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 2*(this._buf.length>0);case "[":return this._mode="tag",this._buf.length>0?2:this._tag();case "\\":this._next(),"["===this._cur?this._store():this._output("\\");break;default:this._store();}},t._tag=function(){switch(this._cur){case null:return this._error="unexpected end of input reading tag",1;case "[":return this._store(),3;case "]":return this._store(),this._mode="text",4;case "=":return this._store(),5;case " ":case " ":case "\n":case "\r":case "\v":case "\f":return this._whitespace();case '"':return this._string();default:if(!this._isIdentifierSymbol(this._cur))return this._error="unrecognized character",1;return this._identifier()}},t._whitespace=function(){for(this._store();-1!==" \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(vq)},t._eof=function(){return null===this._cur},t._next=function(){return this._eof()||(this._index++,this._cur=this._index=0;--r)if(i==="/"+t[r].name&&null===t[r].end){if(t[r].end=e.length,4!==(n=this._scanner.read()))return this._error="expected close bracket",false;return true}return this._error="failed to find matching tag",false}var s={name:i,value:null,attributes:{},start:e.length,end:null};if(5===(n=this._scanner.read())){if(6!==(n=this._scanner.read()))return this._error="expected string",false;s.value=this._scanner.buf().join(""),n=this._scanner.read();}for(;;){switch(n){case 4:return t.push(s),true;case 7:var a=this._scanner.buf().join("");if(5!==(n=this._scanner.read()))return this._error="expected equals",false;if(6!==(n=this._scanner.read()))return this._error="expected string",false;var o=this._scanner.buf().join("");s.attributes[a]=o;break;default:return this._error="expected close bracket or identifier",false}n=this._scanner.read();}},e}(),vQ=function(){function e(){}return e.evaluate=function(e){var t=new vZ(e),n=[],r=[];if(!t.parse(n,r)||r.find(function(e){return null===e.end}))return {symbols:e,tags:null};var s=function(e,t){if(0===e.length)return null;for(var n={},r=0;r=1e-4,b=this._element.calculatedWidth;(!this.autoWidth||x)&&this._wrapLines||(b=Number.POSITIVE_INFINITY);var T=0,E=0;function w(e,t,n){s._lineWidths.push(Math.abs(n));var i=v>t?t+1:v,r=v>t?v+1:t,a=e.slice(i,r);if(S)for(var o=a.length;o--&&S>0;)v0.test(a[o])&&(a.splice(o,1),S--);s._lineContents.push(a.join("")),c=0,h-=s._scaledLineHeight,p++,g=0,y=0,S=0,m=0,v=t;}for(var A=true;A;){A=false,l?this._scaledLineHeight=this._lineHeight*this._fontSize/(this._maxFontSize||1e-4):this._scaledLineHeight=this._lineHeight,this.width=0,this.height=0,this._lineWidths=[],this._lineContents=[],c=0,h=0,f=0,d=0,p=1,m=0,_=0,v=0,g=0,y=0,S=0;var C=this._fontSize/32;T=this._fontMinY*C,E=this._fontMaxY*C;for(var P=0;P=u?null:this._symbols[B+1],v0.test(e)){S++,(!this._wrapLines||this._maxLines<0||p0){var Y=this._font.data.kerning;if(Y){var q=Y[ev.getCodePoint(this._symbols[B-1])||0];q&&(X=q[ev.getCodePoint(this._symbols[B])||0]||0);}}H=t.scale||1,G=C*((t.width+t.height)/2)/H,z=(t.xadvance+X)*C,U=(t.xoffset-X)*C,V=t.yoffset*C;}var K=v1.test(e),Z=t&&t.map||0,Q=-this._font.data.info.maps[Z].width/this._font.data.info.maps[Z].height,J=this._meshInfo[Z],$=c+this._spacing*z;if($>b&&y>0&&!K&&(this._maxLines<0||pthis._element.calculatedWidth&&(ef=Math.floor(this._element.fontSize*this._element.calculatedWidth/(this.width||1e-4)),(ef=ek.clamp(ef,a,o))!==this._element.fontSize)||(this.height=Math.max(this.height,E-(h+T)),this._shouldAutoFitHeight()&&this.height>this._element.calculatedHeight&&(ef=ek.clamp(this._fontSize-1,a,o))!==this._element.fontSize)){this._fontSize=ef,A=true;break}c+=this._spacing*z,K||(d=c),(this._isWordBoundary(e)||this._isValidNextChar(i)&&(this._isNextCJKBoundary(e,i)||this._isNextCJKWholeWord(i)))&&(g++,m=d,_=B+1),y++;var ed=this._getUv(e);if(J.uvs[4*n*2+0]=ed[0],J.uvs[4*n*2+1]=1-ed[1],J.uvs[4*n*2+2]=ed[2],J.uvs[4*n*2+3]=1-ed[1],J.uvs[4*n*2+4]=ed[2],J.uvs[4*n*2+5]=1-ed[3],J.uvs[4*n*2+6]=ed[0],J.uvs[4*n*2+7]=1-ed[3],this._symbolColors){var ep=3*this._symbolColors[B];I=this._colorPalette[ep],L=this._colorPalette[ep+1],D=this._colorPalette[ep+2];}if(J.colors[4*n*4+0]=I,J.colors[4*n*4+1]=L,J.colors[4*n*4+2]=D,J.colors[4*n*4+3]=255,J.colors[4*n*4+4]=I,J.colors[4*n*4+5]=L,J.colors[4*n*4+6]=D,J.colors[4*n*4+7]=255,J.colors[4*n*4+8]=I,J.colors[4*n*4+9]=L,J.colors[4*n*4+10]=D,J.colors[4*n*4+11]=255,J.colors[4*n*4+12]=I,J.colors[4*n*4+13]=L,J.colors[4*n*4+14]=D,J.colors[4*n*4+15]=255,this._symbolOutlineParams){var em=5*this._symbolOutlineParams[B];R=this._outlinePalette[em]+256*this._outlinePalette[em+1],M=this._outlinePalette[em+2]+256*this._outlinePalette[em+3],O=this._outlinePalette[em+4];}if(J.outlines[4*n*3+0]=R,J.outlines[4*n*3+1]=M,J.outlines[4*n*3+2]=O,J.outlines[4*n*3+3]=R,J.outlines[4*n*3+4]=M,J.outlines[4*n*3+5]=O,J.outlines[4*n*3+6]=R,J.outlines[4*n*3+7]=M,J.outlines[4*n*3+8]=O,J.outlines[4*n*3+9]=R,J.outlines[4*n*3+10]=M,J.outlines[4*n*3+11]=O,this._symbolShadowParams){var e_=6*this._symbolShadowParams[B];k=this._shadowPalette[e_]+256*this._shadowPalette[e_+1],N=this._shadowPalette[e_+2]+256*this._shadowPalette[e_+3],F=this._shadowPalette[e_+4]+127+256*Math.round(Q*this._shadowPalette[e_+5]+127);}J.shadows[4*n*3+0]=k,J.shadows[4*n*3+1]=N,J.shadows[4*n*3+2]=F,J.shadows[4*n*3+3]=k,J.shadows[4*n*3+4]=N,J.shadows[4*n*3+5]=F,J.shadows[4*n*3+6]=k,J.shadows[4*n*3+7]=N,J.shadows[4*n*3+8]=F,J.shadows[4*n*3+9]=k,J.shadows[4*n*3+10]=N,J.shadows[4*n*3+11]=F,J.quad++;}!A&&v=eF?(eB.element[tA].set(0,0,0),eB.element[tM].set(0,0),eB.element[tD].set(0,0,0,0),eB.element[tK].set(0,0,0,0),eB.element[tZ].set(0,0,0,0)):(eB.element[tA].set(this._meshInfo[eb].positions[3*eU+0],this._meshInfo[eb].positions[3*eU+1],this._meshInfo[eb].positions[3*eU+2]),eB.element[tM].set(this._meshInfo[eb].uvs[2*eU+0],this._meshInfo[eb].uvs[2*eU+1]),eB.element[tD].set(this._meshInfo[eb].colors[4*eU+0],this._meshInfo[eb].colors[4*eU+1],this._meshInfo[eb].colors[4*eU+2],this._meshInfo[eb].colors[4*eU+3]),eB.element[tK].set(this._meshInfo[eb].outlines[3*eU+0],this._meshInfo[eb].outlines[3*eU+1],this._meshInfo[eb].outlines[3*eU+2]),eB.element[tZ].set(this._meshInfo[eb].shadows[3*eU+0],this._meshInfo[eb].shadows[3*eU+1],this._meshInfo[eb].shadows[3*eU+2])),eB.next();eB.end(),this._meshInfo[eb].meshInstance.mesh.aabb.compute(this._meshInfo[eb].positions),this._meshInfo[eb].meshInstance._aabbVer=-1;}this._aabbDirty=true;},n._onFontRender=function(){this.font=this._font;},n._onFontLoad=function(e){this.font!==e.resource&&(this.font=e.resource);},n._onFontChange=function(e,t,n,i){if("data"===t){this._font.data=n;for(var r=this._font.data.info.maps.length,s=0;sthis._font.textures.length&&(this._meshInfo.length=this._font.textures.length),this._updateText();}}},{key:"alignment",get:function(){return this._alignment},set:function(e){vJ(e,eX)?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&&1e-4>Math.abs(this._element.anchor.x-this._element.anchor.z)&&(this._element.width=this.width),t!==e){var n=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;n!==this._fontSize&&(this._fontSize=n,this._font&&this._updateText());}}},{key:"autoHeight",get:function(){return this._autoHeight},set:function(e){var t=this._autoHeight;if(this._autoHeight=e,e&&1e-4>Math.abs(this._element.anchor.y-this._element.anchor.w)&&(this._element.height=this.height),t!==e){var n=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;n!==this._fontSize&&(this._fontSize=n,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=false,t=0;t=0&&this.system._prerender.splice(n,1),0>this.system._prerender.indexOf(e)&&this.system._prerender.push(e);}e=t;}},i._onPrerender=function(){for(var e=0;ethis.layers.indexOf(e.id))&&(this._image?e.addMeshInstances(this._image._renderable.model.meshInstances):this._text&&e.addMeshInstances(this._text._model.meshInstances));},i.onLayerRemoved=function(e){!(0>this.layers.indexOf(e.id))&&(this._image?e.removeMeshInstances(this._image._renderable.model.meshInstances):this._text&&e.removeMeshInstances(this._text._model.meshInstances));},i.onEnable=function(){var e,t=this.system.app.scene,n=t.layers;this._image&&this._image.onEnable(),this._text&&this._text.onEnable(),this._group&&this._group.onEnable(),this.useInput&&this.system.app.elementInput&&this.system.app.elementInput.addElement(this),this._evtLayersChanged=t.on("set:layers",this.onLayersChanged,this),n&&(this._evtLayerAdded=n.on("add",this.onLayerAdded,this),this._evtLayerRemoved=n.on("remove",this.onLayerRemoved,this)),this._batchGroupId>=0&&(null==(e=this.system.app.batcher)||e.insert(ll.ELEMENT,this.batchGroupId,this.entity)),this.fire("enableelement");},i.onDisable=function(){var e,t,n,i,r=this.system.app.scene.layers;null==(e=this._evtLayersChanged)||e.off(),this._evtLayersChanged=null,r&&(null==(t=this._evtLayerAdded)||t.off(),this._evtLayerAdded=null,null==(n=this._evtLayerRemoved)||n.off(),this._evtLayerRemoved=null),this._image&&this._image.onDisable(),this._text&&this._text.onDisable(),this._group&&this._group.onDisable(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this._batchGroupId>=0&&(null==(i=this.system.app.batcher)||i.remove(ll.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 n=this._absRight-this._absLeft,i=this._absTop-this._absBottom;e?this._setWidth(n):this._setCalculatedWidth(n,false),t?this._setHeight(i):this._setCalculatedHeight(i,false);var r=this.entity.getLocalPosition();r.x=this._margin.x+this._calculatedWidth*this._pivot.x,r.y=this._margin.y+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(r),this._sizeDirty=false;}},i._setWidth=function(e){this._width=e,this._setCalculatedWidth(e,false),this.fire("set:width",this._width);},i._setHeight=function(e){this._height=e,this._setCalculatedHeight(e,false),this.fire("set:height",this._height);},i._setCalculatedWidth=function(e,t){if(!(1e-4>=Math.abs(e-this._calculatedWidth))){if(this._calculatedWidth=e,this.entity._dirtifyLocal(),t){var n=this.entity.getLocalPosition(),i=this._pivot;this._margin.x=n.x-this._calculatedWidth*i.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(!(1e-4>=Math.abs(e-this._calculatedHeight))){if(this._calculatedHeight=e,this.entity._dirtifyLocal(),t){var n=this.entity.getLocalPosition(),i=this._pivot;this._margin.y=n.y-this._calculatedHeight*i.y,this._margin.w=this._localAnchor.w-this._localAnchor.y-this._calculatedHeight-this._margin.y;}this._flagChildrenAsDirty(),this.fire("set:calculatedHeight",this._calculatedHeight),this.fire("resize",this._calculatedWidth,this._calculatedHeight);}},i._flagChildrenAsDirty=function(){for(var e=this.entity._children,t=0,n=e.length;t=0&&this._addedModels.splice(t,1);for(var n=0;nn)&&!(d>i)&&!(p.001}},{key:"_hasSplitAnchorsY",get:function(){return Math.abs(this._anchor.y-this._anchor.w)>.001}},{key:"aabb",get:function(){return this._image?this._image.aabb:this._text?this._text.aabb:null}},{key:"anchor",get:function(){return this._anchor},set:function(e){if(gn(e,eY))this._anchor.copy(e);else {var t;(t=this._anchor).set.apply(t,[].concat(e));}this.entity._parent||this.screen?this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY):this._calculateLocalAnchors(),this._anchorDirty=true,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:anchor",this._anchor);}},{key:"batchGroupId",get:function(){return this._batchGroupId},set:function(e){var t,n;this._batchGroupId!==e&&(this.entity.enabled&&this._batchGroupId>=0&&(null==(t=this.system.app.batcher)||t.remove(ll.ELEMENT,this.batchGroupId,this.entity)),this.entity.enabled&&e>=0&&(null==(n=this.system.app.batcher)||n.insert(ll.ELEMENT,e,this.entity)),e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&(this._image&&this._image._renderable.model?this.addModelToLayers(this._image._renderable.model):this._text&&this._text._model&&this.addModelToLayers(this._text._model)),this._batchGroupId=e);}},{key:"bottom",get:function(){return this._margin.y},set:function(e){this._margin.y=e;var t=this.entity.getLocalPosition(),n=this._absTop,i=this._localAnchor.y+e;this._setHeight(n-i),t.y=e+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(t);}},{key:"calculatedWidth",get:function(){return this._calculatedWidth},set:function(e){this._setCalculatedWidth(e,true);}},{key:"calculatedHeight",get:function(){return this._calculatedHeight},set:function(e){this._setCalculatedHeight(e,true);}},{key:"canvasCorners",get:function(){if(!this._canvasCornersDirty||!this.screen||!this.screen.screen.screenSpace)return this._canvasCorners;for(var e=this.system.app.graphicsDevice,t=this.screenCorners,n=e.canvas.clientWidth/e.width,i=e.canvas.clientHeight/e.height,r=0;r<4;r++)this._canvasCorners[r].set(t[r].x*n,(e.height-t[r].y)*i);return this._canvasCornersDirty=false,this._canvasCorners}},{key:"drawOrder",get:function(){return this._drawOrder},set:function(e){var t=0;this.screen&&(t=this.screen.screen.priority),e>0xffffff&&(e=0xffffff),this._drawOrder=(t<<24)+e,this.fire("set:draworder",this._drawOrder);}},{key:"height",get:function(){return this._height},set:function(e){this._height=e,this._hasSplitAnchorsY||this._setCalculatedHeight(e,true),this.fire("set:height",this._height);}},{key:"layers",get:function(){return this._layers},set:function(e){if(this._addedModels.length)for(var t=0;t.001,a=Math.abs(t.anchor.y-t.anchor.w)>.001,o=false;void 0!==n.margin&&(gp(n.margin,eY)?t.margin.copy(n.margin):t._margin.set(n.margin[0],n.margin[1],n.margin[2],n.margin[3]),o=true),void 0!==n.left&&(t._margin.x=n.left,o=true),void 0!==n.bottom&&(t._margin.y=n.bottom,o=true),void 0!==n.right&&(t._margin.z=n.right,o=true),void 0!==n.top&&(t._margin.w=n.top,o=true),o&&(t.margin=t._margin);var l=false;void 0===n.width||s?s&&(l=true):t.width=n.width,void 0===n.height||a?a&&(l=true):t.height=n.height,l&&(t.anchor=t.anchor),void 0!==n.enabled&&(t.enabled=n.enabled),void 0!==n.useInput&&(t.useInput=n.useInput),void 0!==n.fitMode&&(t.fitMode=n.fitMode),t.batchGroupId=void 0===n.batchGroupId||null===n.batchGroupId?-1:n.batchGroupId,n.layers&&Array.isArray(n.layers)&&(t.layers=n.layers.slice(0)),void 0!==n.type&&(t.type=n.type),t.type===_5?(void 0!==n.rect&&(t.rect=n.rect),void 0!==n.color&&(gp(r=n.color,eN)||(r=new eN(n.color[0],n.color[1],n.color[2])),t.color=r),void 0!==n.opacity&&(t.opacity=n.opacity),void 0!==n.textureAsset&&(t.textureAsset=n.textureAsset),n.texture&&(t.texture=n.texture),void 0!==n.spriteAsset&&(t.spriteAsset=n.spriteAsset),n.sprite&&(t.sprite=n.sprite),void 0!==n.spriteFrame&&(t.spriteFrame=n.spriteFrame),void 0!==n.pixelsPerUnit&&null!==n.pixelsPerUnit&&(t.pixelsPerUnit=n.pixelsPerUnit),void 0!==n.materialAsset&&(t.materialAsset=n.materialAsset),n.material&&(t.material=n.material),void 0!==n.mask&&(t.mask=n.mask)):t.type===_8&&(void 0!==n.autoWidth&&(t.autoWidth=n.autoWidth),void 0!==n.autoHeight&&(t.autoHeight=n.autoHeight),void 0!==n.rtlReorder&&(t.rtlReorder=n.rtlReorder),void 0!==n.unicodeConverter&&(t.unicodeConverter=n.unicodeConverter),null!==n.text&&void 0!==n.text?t.text=n.text:null!==n.key&&void 0!==n.key&&(t.key=n.key),void 0!==n.color&&(gp(r=n.color,eN)||(r=new eN(r[0],r[1],r[2])),t.color=r),void 0!==n.opacity&&(t.opacity=n.opacity),void 0!==n.spacing&&(t.spacing=n.spacing),void 0!==n.fontSize&&(t.fontSize=n.fontSize,n.lineHeight||(t.lineHeight=n.fontSize)),void 0!==n.lineHeight&&(t.lineHeight=n.lineHeight),void 0!==n.maxLines&&(t.maxLines=n.maxLines),void 0!==n.wrapLines&&(t.wrapLines=n.wrapLines),void 0!==n.minFontSize&&(t.minFontSize=n.minFontSize),void 0!==n.maxFontSize&&(t.maxFontSize=n.maxFontSize),n.autoFitWidth&&(t.autoFitWidth=n.autoFitWidth),n.autoFitHeight&&(t.autoFitHeight=n.autoFitHeight),void 0!==n.fontAsset&&(t.fontAsset=n.fontAsset),void 0!==n.font&&(t.font=n.font),void 0!==n.alignment&&(t.alignment=n.alignment),void 0!==n.outlineColor&&(t.outlineColor=n.outlineColor),void 0!==n.outlineThickness&&(t.outlineThickness=n.outlineThickness),void 0!==n.shadowColor&&(t.shadowColor=n.shadowColor),void 0!==n.shadowOffset&&(t.shadowOffset=n.shadowOffset),void 0!==n.enableMarkup&&(t.enableMarkup=n.enableMarkup));var u=t._parseUpToScreen();u.screen&&t._updateScreen(u.screen),e.prototype.initializeComponentData.call(this,t,n,i),t._beingInitialized=false,t.type===_5&&t._image._meshDirty&&t._image._updateMesh(t._image.mesh);},n.onAddComponent=function(e,t){e.fire("element:add");},n.onRemoveComponent=function(e,t){t.onRemove();},n.cloneComponent=function(e,t){var n=e.element,i={enabled:n.enabled,width:n.width,height:n.height,anchor:n.anchor.clone(),pivot:n.pivot.clone(),margin:n.margin.clone(),alignment:n.alignment&&n.alignment.clone()||n.alignment,autoWidth:n.autoWidth,autoHeight:n.autoHeight,type:n.type,rect:n.rect&&n.rect.clone()||n.rect,rtlReorder:n.rtlReorder,unicodeConverter:n.unicodeConverter,materialAsset:n.materialAsset,material:n.material,color:n.color&&n.color.clone()||n.color,opacity:n.opacity,textureAsset:n.textureAsset,texture:n.texture,spriteAsset:n.spriteAsset,sprite:n.sprite,spriteFrame:n.spriteFrame,pixelsPerUnit:n.pixelsPerUnit,spacing:n.spacing,lineHeight:n.lineHeight,wrapLines:n.wrapLines,layers:n.layers,fontSize:n.fontSize,minFontSize:n.minFontSize,maxFontSize:n.maxFontSize,autoFitWidth:n.autoFitWidth,autoFitHeight:n.autoFitHeight,maxLines:n.maxLines,fontAsset:n.fontAsset,font:n.font,useInput:n.useInput,fitMode:n.fitMode,batchGroupId:n.batchGroupId,mask:n.mask,outlineColor:n.outlineColor&&n.outlineColor.clone()||n.outlineColor,outlineThickness:n.outlineThickness,shadowColor:n.shadowColor&&n.shadowColor.clone()||n.shadowColor,shadowOffset:n.shadowOffset&&n.shadowOffset.clone()||n.shadowOffset,enableMarkup:n.enableMarkup};return void 0!==n.key&&null!==n.key?i.key=n.key:i.text=n.text,this.addComponent(t,i)},n.getTextElementMaterial=function(e,t,n){var i=(e&&1)|(t&&2)|(n&&4),r=this._defaultTextMaterials[i];if(r)return r;var s="TextMaterial";return r=new dA,t?(r.msdfMap=this._defaultTexture,r.msdfTextAttribute=n,r.emissive.set(1,1,1)):(s="Bitmap"+s,r.emissive.set(1,1,1),r.emissiveMap=this._defaultTexture,r.opacityMap=this._defaultTexture,r.opacityMapChannel="a"),e&&(s="ScreenSpace"+s,r.depthTest=false),r.name="default"+s,r.useLighting=false,r.useTonemap=false,r.useFog=false,r.useSkybox=false,r.diffuse.set(0,0,0),r.opacity=.5,r.blendType=4,r.depthWrite=false,r.emissiveVertexColor=true,r.update(),this._defaultTextMaterials[i]=r,r},n._createBaseImageMaterial=function(){var e=new dA;return e.diffuse.set(0,0,0),e.emissive.set(1,1,1),e.emissiveMap=this._defaultTexture,e.opacityMap=this._defaultTexture,e.opacityMapChannel="a",e.useLighting=false,e.useTonemap=false,e.useFog=false,e.useSkybox=false,e.blendType=4,e.depthWrite=false,e},n.getImageElementMaterial=function(e,t,n,i){if(e)if(t)if(n)return this.defaultScreenSpaceImageMask9SlicedMaterial||(this.defaultScreenSpaceImageMask9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMask9SlicedMaterial.name="defaultScreenSpaceImageMask9SlicedMaterial",this.defaultScreenSpaceImageMask9SlicedMaterial.nineSlicedMode=1,this.defaultScreenSpaceImageMask9SlicedMaterial.depthTest=false,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9SlicedMaterial.redWrite=false,this.defaultScreenSpaceImageMask9SlicedMaterial.greenWrite=false,this.defaultScreenSpaceImageMask9SlicedMaterial.blueWrite=false,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaWrite=false,this.defaultScreenSpaceImageMask9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9SlicedMaterial)),this.defaultScreenSpaceImageMask9SlicedMaterial;else if(i)return this.defaultScreenSpaceImageMask9TiledMaterial||(this.defaultScreenSpaceImageMask9TiledMaterial=this.defaultScreenSpaceImage9TiledMaterial.clone(),this.defaultScreenSpaceImageMask9TiledMaterial.name="defaultScreenSpaceImageMask9TiledMaterial",this.defaultScreenSpaceImageMask9TiledMaterial.nineSlicedMode=2,this.defaultScreenSpaceImageMask9TiledMaterial.depthTest=false,this.defaultScreenSpaceImageMask9TiledMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9TiledMaterial.redWrite=false,this.defaultScreenSpaceImageMask9TiledMaterial.greenWrite=false,this.defaultScreenSpaceImageMask9TiledMaterial.blueWrite=false,this.defaultScreenSpaceImageMask9TiledMaterial.alphaWrite=false,this.defaultScreenSpaceImageMask9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9TiledMaterial)),this.defaultScreenSpaceImageMask9TiledMaterial;else return this.defaultScreenSpaceImageMaskMaterial||(this.defaultScreenSpaceImageMaskMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaskMaterial.name="defaultScreenSpaceImageMaskMaterial",this.defaultScreenSpaceImageMaskMaterial.depthTest=false,this.defaultScreenSpaceImageMaskMaterial.alphaTest=1,this.defaultScreenSpaceImageMaskMaterial.redWrite=false,this.defaultScreenSpaceImageMaskMaterial.greenWrite=false,this.defaultScreenSpaceImageMaskMaterial.blueWrite=false,this.defaultScreenSpaceImageMaskMaterial.alphaWrite=false,this.defaultScreenSpaceImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaskMaterial)),this.defaultScreenSpaceImageMaskMaterial;else if(n)return this.defaultScreenSpaceImage9SlicedMaterial||(this.defaultScreenSpaceImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9SlicedMaterial.name="defaultScreenSpaceImage9SlicedMaterial",this.defaultScreenSpaceImage9SlicedMaterial.nineSlicedMode=1,this.defaultScreenSpaceImage9SlicedMaterial.depthTest=false,this.defaultScreenSpaceImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9SlicedMaterial)),this.defaultScreenSpaceImage9SlicedMaterial;else if(i)return this.defaultScreenSpaceImage9TiledMaterial||(this.defaultScreenSpaceImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9TiledMaterial.name="defaultScreenSpaceImage9TiledMaterial",this.defaultScreenSpaceImage9TiledMaterial.nineSlicedMode=2,this.defaultScreenSpaceImage9TiledMaterial.depthTest=false,this.defaultScreenSpaceImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9TiledMaterial)),this.defaultScreenSpaceImage9TiledMaterial;else return this.defaultScreenSpaceImageMaterial||(this.defaultScreenSpaceImageMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaterial.name="defaultScreenSpaceImageMaterial",this.defaultScreenSpaceImageMaterial.depthTest=false,this.defaultScreenSpaceImageMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaterial)),this.defaultScreenSpaceImageMaterial;if(t)if(n)return this.defaultImage9SlicedMaskMaterial||(this.defaultImage9SlicedMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaskMaterial.name="defaultImage9SlicedMaskMaterial",this.defaultImage9SlicedMaskMaterial.nineSlicedMode=1,this.defaultImage9SlicedMaskMaterial.alphaTest=1,this.defaultImage9SlicedMaskMaterial.redWrite=false,this.defaultImage9SlicedMaskMaterial.greenWrite=false,this.defaultImage9SlicedMaskMaterial.blueWrite=false,this.defaultImage9SlicedMaskMaterial.alphaWrite=false,this.defaultImage9SlicedMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaskMaterial)),this.defaultImage9SlicedMaskMaterial;else if(i)return this.defaultImage9TiledMaskMaterial||(this.defaultImage9TiledMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaskMaterial.name="defaultImage9TiledMaskMaterial",this.defaultImage9TiledMaskMaterial.nineSlicedMode=2,this.defaultImage9TiledMaskMaterial.alphaTest=1,this.defaultImage9TiledMaskMaterial.redWrite=false,this.defaultImage9TiledMaskMaterial.greenWrite=false,this.defaultImage9TiledMaskMaterial.blueWrite=false,this.defaultImage9TiledMaskMaterial.alphaWrite=false,this.defaultImage9TiledMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaskMaterial)),this.defaultImage9TiledMaskMaterial;else return this.defaultImageMaskMaterial||(this.defaultImageMaskMaterial=this._createBaseImageMaterial(),this.defaultImageMaskMaterial.name="defaultImageMaskMaterial",this.defaultImageMaskMaterial.alphaTest=1,this.defaultImageMaskMaterial.redWrite=false,this.defaultImageMaskMaterial.greenWrite=false,this.defaultImageMaskMaterial.blueWrite=false,this.defaultImageMaskMaterial.alphaWrite=false,this.defaultImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaskMaterial)),this.defaultImageMaskMaterial;return n?(this.defaultImage9SlicedMaterial||(this.defaultImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaterial.name="defaultImage9SlicedMaterial",this.defaultImage9SlicedMaterial.nineSlicedMode=1,this.defaultImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaterial)),this.defaultImage9SlicedMaterial):i?(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)},n.registerUnicodeConverter=function(e){this._unicodeConverter=e;},n.registerRtlReorder=function(e){this._rtlReorder=e;},n.getUnicodeConverter=function(){return this._unicodeConverter},n.getRtlReorder=function(){return this._rtlReorder},t}(mV),gg="free",gy="limited",gS="locked";function gx(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(gT);!(t=n()).done;){var r,s=t.value;e.hasOwnProperty(s)&&((r=e[s],null!=eX&&"undefined"!=typeof Symbol&&eX[Symbol.hasInstance]?!!eX[Symbol.hasInstance](r):i(r,eX))?this["_"+s].copy(e[s]):this["_"+s]=e[s]);}this._createConstraint();},r.onEnable=function(){this._createConstraint();},r.onDisable=function(){this._destroyConstraint();},r._onSetEnabled=function(e,t,n){},r._onBeforeRemove=function(){this.fire("remove");},n=[{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());}}],function(e,t){for(var n=0;n=n)return gU.APPLY_SHRINKING;return gU.NONE;case 3:if(tMath.abs(r)&&1e-5>Math.abs(s)?t:t*r/s}function h(e){for(var t=[],n=0;n=0;--i)n[t[i]]=n[t[i+1]]+e[t[i]];return n}return function(e,c){e=e.filter(s),gV.x=(t=c).containerSize.x-t.padding.x-t.padding.z,gV.y=t.containerSize.y-t.padding.y-t.padding.w,function(e){for(var t=0;t0&&(s+=t.spacing[n.axis]);var l=r[o][n.size];s+=l,!a&&s>gV[n.axis]&&0!==i[i.length-1].length&&(s=l,i.push([])),i[i.length-1].push(e[o]),a&&s>gV[n.axis]&&o!==e.length-1&&(s=0,i.push([]));}return i}(e)),_=function(e,n){for(var r=[],s=[],c=0;ch.largestSize[i.size]&&(h.largestElement=h[f],h.largestSize=d);}r.push(h.largestElement),s.push(h.largestSize);}var p=o(s,i),m=a(t[i.fitting],p,gV[i.axis]);m===gU.APPLY_STRETCHING?l(s,p,i):m===gU.APPLY_SHRINKING&&u(s,p,i);for(var _=0;_0;){var t=this._reflowQueue.slice();this._reflowQueue.length=0,t.sort(function(e,t){return e.entity.graphDepth-t.entity.graphDepth});for(var n=0;n=100)break}},n._onRemoveComponent=function(e,t){t.onRemove();},n.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("postUpdate",this._onPostUpdate,this);},t}(mV);mN._buildAccessors(gY.prototype,gZ);var gJ=function(){function e(){this.map=new Map;}return e.prototype.destroy=function(e){this.map.forEach(function(e){return e.mesh.destroy()});},e}(),g$=new nM,g0=function(e,t){var n,i,r=g$.get(e,function(){return new gJ}),s=r.map.get(t);if(!s){switch(t){case "box":n=lv.fromGeometry(e,new ft),i={x:2,y:2,z:2,uv:2/3};break;case "capsule":n=lv.fromGeometry(e,new dV({radius:.5,height:2})),i={x:2*Math.PI,y:Math.PI,z:2*Math.PI,uv:1/3+1/3/3*2};break;case "cone":n=lv.fromGeometry(e,new dG({baseRadius:.5,peakRadius:0,height:1})),i={x:2.54,y:2.54,z:2.54,uv:1/3+1/3/3};break;case "cylinder":n=lv.fromGeometry(e,new dW({radius:.5,height:1})),i={x:Math.PI,y:1.58,z:Math.PI,uv:1/3+1/3/3*2};break;case "plane":n=lv.fromGeometry(e,new dX({halfExtents:new eX(.5,.5),widthSegments:1,lengthSegments:1})),i={x:0,y:1,z:0,uv:1};break;case "sphere":n=lv.fromGeometry(e,new fi({radius:.5})),i={x:Math.PI,y:Math.PI,z:Math.PI,uv:1};break;case "torus":n=lv.fromGeometry(e,new dq({tubeRadius:.2,ringRadius:.3})),i={x:.5*Math.PI*.5-.1*Math.PI*.1,y:.4,z:.4,uv:1};break;default:throw Error("Invalid primitive type: "+t)}n.incRefCount(),s={mesh:n,area:i},r.map.set(t,s);}return s};function g1(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?!!t[Symbol.hasInstance](e):i(e,t)}function g2(e,t){return (g2=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var g3=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t,n){var i;return (i=e.call(this,t,n)||this)._type="asset",i._asset=null,i._model=null,i._mapping={},i._castShadows=true,i._receiveShadows=true,i._materialAsset=null,i._castShadowsLightmap=true,i._lightmapped=false,i._lightmapSizeMultiplier=1,i.isStatic=false,i._layers=[0],i._batchGroupId=-1,i._customAabb=null,i._area=null,i._materialEvents=null,i._clonedModel=false,i._evtLayersChanged=null,i._evtLayerAdded=null,i._evtLayerRemoved=null,i._material=t.defaultMaterial,n.on("remove",i.onRemoveChild,i),n.on("removehierarchy",i.onRemoveChild,i),n.on("insert",i.onInsertChild,i),n.on("inserthierarchy",i.onInsertChild,i),i}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&g2(t,e);var n,i=t.prototype;return i.addModelToLayers=function(){for(var e=this.system.app.scene.layers,t=0;tthis.layers.indexOf(e.id)||e.addMeshInstances(this.meshInstances);},i.onLayerRemoved=function(e){0>this.layers.indexOf(e.id)||e.removeMeshInstances(this.meshInstances);},i._setMaterialEvent=function(e,t,n,i){var r=t+":"+n;this.system.app.assets.on(r,i,this),this._materialEvents||(this._materialEvents=[]),this._materialEvents[e]||(this._materialEvents[e]={}),this._materialEvents[e][r]={id:n,handler:i};},i._unsetMaterialEvents=function(){var e=this.system.app.assets,t=this._materialEvents;if(t){for(var n=0,i=t.length;n=0&&(null==(t=n.batcher)||t.insert(ll.MODEL,this.batchGroupId,this.entity));},i.onDisable=function(){var e,t,n,i,r=this.system.app,s=r.scene.layers;null==(e=this._evtLayersChanged)||e.off(),this._evtLayersChanged=null,s&&(null==(t=this._evtLayerAdded)||t.off(),this._evtLayerAdded=null,null==(n=this._evtLayerRemoved)||n.off(),this._evtLayerRemoved=null),this._batchGroupId>=0&&(null==(i=r.batcher)||i.remove(ll.MODEL,this.batchGroupId,this.entity)),this._model&&this.removeModelFromLayers();},i.hide=function(){if(this._model)for(var e=this._model.meshInstances,t=0,n=e.length;t=0&&(null==(t=this.system.app.batcher)||t.remove(ll.MODEL,this.batchGroupId,this.entity)),this.entity.enabled&&e>=0&&(null==(n=this.system.app.batcher)||n.insert(ll.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;g1(e,pU)&&(t=e.id);var n=this.system.app.assets;if(t!==this._materialAsset){if(this._materialAsset){n.off("add:"+this._materialAsset,this._onMaterialAssetAdd,this);var i=n.get(this._materialAsset);i&&this._unbindMaterialAsset(i);}if(this._materialAsset=t,this._materialAsset){var r=n.get(this._materialAsset);r?this._bindMaterialAsset(r):(this._setMaterial(this.system.defaultMaterial),n.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,n=this.asset?this.system.app.assets.get(this.asset):null,i=n?n.data.mapping:null,r=null,s=0,a=t.length;sthis.layers.indexOf(e.id)||e.addMeshInstances([this.emitter.meshInstance]));},i.onLayerRemoved=function(e){this.emitter&&(0>this.layers.indexOf(e.id)||e.removeMeshInstances([this.emitter.meshInstance]));},i._bindColorMapAsset=function(e){if(e.on("load",this._onColorMapAssetLoad,this),e.on("unload",this._onColorMapAssetUnload,this),e.on("remove",this._onColorMapAssetRemove,this),e.on("change",this._onColorMapAssetChange,this),e.resource)this._onColorMapAssetLoad(e);else {if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e);}},i._unbindColorMapAsset=function(e){e.off("load",this._onColorMapAssetLoad,this),e.off("unload",this._onColorMapAssetUnload,this),e.off("remove",this._onColorMapAssetRemove,this),e.off("change",this._onColorMapAssetChange,this);},i._onColorMapAssetLoad=function(e){this.colorMap=e.resource;},i._onColorMapAssetUnload=function(e){this.colorMap=null;},i._onColorMapAssetRemove=function(e){this._onColorMapAssetUnload(e);},i._onColorMapAssetChange=function(e){},i.onSetColorMapAsset=function(e,t,n){var i=this,r=this.system.app.assets;if(t){var s=r.get(t);s&&this._unbindColorMapAsset(s);}if(n){g9(n,pU)&&(this.data.colorMapAsset=n.id,n=n.id);var a=r.get(n);a?this._bindColorMapAsset(a):r.once("add:"+n,function(e){i._bindColorMapAsset(e);});}else this.colorMap=null;},i._bindNormalMapAsset=function(e){if(e.on("load",this._onNormalMapAssetLoad,this),e.on("unload",this._onNormalMapAssetUnload,this),e.on("remove",this._onNormalMapAssetRemove,this),e.on("change",this._onNormalMapAssetChange,this),e.resource)this._onNormalMapAssetLoad(e);else {if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e);}},i._unbindNormalMapAsset=function(e){e.off("load",this._onNormalMapAssetLoad,this),e.off("unload",this._onNormalMapAssetUnload,this),e.off("remove",this._onNormalMapAssetRemove,this),e.off("change",this._onNormalMapAssetChange,this);},i._onNormalMapAssetLoad=function(e){this.normalMap=e.resource;},i._onNormalMapAssetUnload=function(e){this.normalMap=null;},i._onNormalMapAssetRemove=function(e){this._onNormalMapAssetUnload(e);},i._onNormalMapAssetChange=function(e){},i.onSetNormalMapAsset=function(e,t,n){var i=this,r=this.system.app.assets;if(t){var s=r.get(t);s&&this._unbindNormalMapAsset(s);}if(n){g9(n,pU)&&(this.data.normalMapAsset=n.id,n=n.id);var a=r.get(n);a?this._bindNormalMapAsset(a):r.once("add:"+n,function(e){i._bindNormalMapAsset(e);});}else this.normalMap=null;},i._bindMeshAsset=function(e){if(e.on("load",this._onMeshAssetLoad,this),e.on("unload",this._onMeshAssetUnload,this),e.on("remove",this._onMeshAssetRemove,this),e.on("change",this._onMeshAssetChange,this),e.resource)this._onMeshAssetLoad(e);else {if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e);}},i._unbindMeshAsset=function(e){e.off("load",this._onMeshAssetLoad,this),e.off("unload",this._onMeshAssetUnload,this),e.off("remove",this._onMeshAssetRemove,this),e.off("change",this._onMeshAssetChange,this);},i._onMeshAssetLoad=function(e){this._onMeshChanged(e.resource);},i._onMeshAssetUnload=function(e){this.mesh=null;},i._onMeshAssetRemove=function(e){this._onMeshAssetUnload(e);},i._onMeshAssetChange=function(e){},i.onSetMeshAsset=function(e,t,n){var i=this.system.app.assets;if(t){var r=i.get(t);r&&this._unbindMeshAsset(r);}if(n){g9(n,pU)&&(this.data.meshAsset=n.id,n=n.id);var s=i.get(n);s&&this._bindMeshAsset(s);}else this._onMeshChanged(null);},i.onSetMesh=function(e,t,n){!n||g9(n,pU)||"number"==typeof n?this.meshAsset=n:this._onMeshChanged(n);},i._onMeshChanged=function(e){e&&!g9(e,lv)&&(e=e.meshInstances[0]?e.meshInstances[0].mesh:null),this.data.mesh=e,this.emitter&&(this.emitter.mesh=e,this.emitter.resetMaterial(),this.rebuild());},i.onSetRenderAsset=function(e,t,n){var i=this.system.app.assets;if(t){var r=i.get(t);r&&this._unbindRenderAsset(r);}if(n){g9(n,pU)&&(this.data.renderAsset=n.id,n=n.id);var s=i.get(n);s&&this._bindRenderAsset(s);}else this._onRenderChanged(null);},i._bindRenderAsset=function(e){if(e.on("load",this._onRenderAssetLoad,this),e.on("unload",this._onRenderAssetUnload,this),e.on("remove",this._onRenderAssetRemove,this),e.resource)this._onRenderAssetLoad(e);else {if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e);}},i._unbindRenderAsset=function(e){var t;e.off("load",this._onRenderAssetLoad,this),e.off("unload",this._onRenderAssetUnload,this),e.off("remove",this._onRenderAssetRemove,this),null==(t=this._evtSetMeshes)||t.off(),this._evtSetMeshes=null;},i._onRenderAssetLoad=function(e){this._onRenderChanged(e.resource);},i._onRenderAssetUnload=function(e){this._onRenderChanged(null);},i._onRenderAssetRemove=function(e){this._onRenderAssetUnload(e);},i._onRenderChanged=function(e){var t;if(!e)return void this._onMeshChanged(null);null==(t=this._evtSetMeshes)||t.off(),this._evtSetMeshes=e.on("set:meshes",this._onRenderSetMeshes,this),e.meshes&&this._onRenderSetMeshes(e.meshes);},i._onRenderSetMeshes=function(e){this._onMeshChanged(e&&e[0]);},i.onSetLoop=function(e,t,n){this.emitter&&(this.emitter[e]=n,this.emitter.resetTime());},i.onSetBlendType=function(e,t,n){this.emitter&&(this.emitter[e]=n,this.emitter.material.blendType=n,this.emitter.resetMaterial(),this.rebuild());},i._requestDepth=function(){!this._requestedDepth&&(L||(L=this.system.app.scene.layers.getLayerById(1)),L&&(L.incrementCounter(),this._requestedDepth=true));},i._releaseDepth=function(){this._requestedDepth&&L&&(L.decrementCounter(),this._requestedDepth=false);},i.onSetDepthSoftening=function(e,t,n){t!==n&&(n?this.enabled&&this.entity.enabled&&this._requestDepth():this.enabled&&this.entity.enabled&&this._releaseDepth(),this.emitter&&(this.emitter[e]=n),this.emitter&&(this.reset(),this.emitter.resetMaterial(),this.rebuild()));},i.onSetSimpleProperty=function(e,t,n){this.emitter&&(this.emitter[e]=n,this.emitter.resetMaterial());},i.onSetComplexProperty=function(e,t,n){this.emitter&&(this.emitter[e]=n,this.emitter.resetMaterial(),this.rebuild(),this.reset());},i.onSetGraphProperty=function(e,t,n){this.emitter&&(this.emitter[e]=n,this.emitter.rebuildGraphs(),this.emitter.resetMaterial());},i.onEnable=function(){for(var e=this.system.app.scene,t=e.layers,n=this.data,i=0,r=yi.length;i=0))continue;s=this.system.app.assets.get(s);}s&&!s.resource&&this.system.app.assets.load(s);}}if(!this.system.app.graphicsDevice.disableParticleSystem){if(!this.emitter){var a=n.mesh;g9(a,lv)||(a=null),this.emitter=new hJ(this.system.app.graphicsDevice,{numParticles:n.numParticles,emitterExtents:n.emitterExtents,emitterExtentsInner:n.emitterExtentsInner,emitterRadius:n.emitterRadius,emitterRadiusInner:n.emitterRadiusInner,emitterShape:n.emitterShape,initialVelocity:n.initialVelocity,wrap:n.wrap,localSpace:n.localSpace,screenSpace:n.screenSpace,wrapBounds:n.wrapBounds,lifetime:n.lifetime,rate:n.rate,rate2:n.rate2,orientation:n.orientation,particleNormal:n.particleNormal,animTilesX:n.animTilesX,animTilesY:n.animTilesY,animStartFrame:n.animStartFrame,animNumFrames:n.animNumFrames,animNumAnimations:n.animNumAnimations,animIndex:n.animIndex,randomizeAnimIndex:n.randomizeAnimIndex,animSpeed:n.animSpeed,animLoop:n.animLoop,startAngle:n.startAngle,startAngle2:n.startAngle2,scaleGraph:n.scaleGraph,scaleGraph2:n.scaleGraph2,colorGraph:n.colorGraph,colorGraph2:n.colorGraph2,alphaGraph:n.alphaGraph,alphaGraph2:n.alphaGraph2,localVelocityGraph:n.localVelocityGraph,localVelocityGraph2:n.localVelocityGraph2,velocityGraph:n.velocityGraph,velocityGraph2:n.velocityGraph2,rotationSpeedGraph:n.rotationSpeedGraph,rotationSpeedGraph2:n.rotationSpeedGraph2,radialSpeedGraph:n.radialSpeedGraph,radialSpeedGraph2:n.radialSpeedGraph2,colorMap:n.colorMap,normalMap:n.normalMap,loop:n.loop,preWarm:n.preWarm,sort:n.sort,stretch:n.stretch,alignToMotion:n.alignToMotion,lighting:n.lighting,halfLambert:n.halfLambert,intensity:n.intensity,depthSoftening:n.depthSoftening,scene:this.system.app.scene,mesh:a,depthWrite:n.depthWrite,noFog:n.noFog,node:this.entity,blendType:n.blendType}),this.emitter.meshInstance.node=this.entity,this.emitter.drawOrder=this.drawOrder,n.autoPlay||(this.pause(),this.emitter.meshInstance.visible=false);}this.emitter.colorMap&&this.addMeshInstanceToLayers(),this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),t&&(this._evtLayerAdded=t.on("add",this.onLayerAdded,this),this._evtLayerRemoved=t.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&n.depthSoftening&&this._requestDepth();}},i.onDisable=function(){var e,t,n,i=this.system.app.scene.layers;null==(e=this._evtLayersChanged)||e.off(),this._evtLayersChanged=null,i&&(null==(t=this._evtLayerAdded)||t.off(),this._evtLayerAdded=null,null==(n=this._evtLayerRemoved)||n.off(),this._evtLayerRemoved=null),this.emitter&&(this.removeMeshInstanceFromLayers(),this.data.depthSoftening&&this._releaseDepth(),this.emitter.camera=null);},i.onBeforeRemove=function(){this.enabled&&(this.enabled=false),this.emitter&&(this.emitter.destroy(),this.emitter=null);for(var e=0;e 1e-06) ? v / l : v;\n}\nvoid main(void) {\n vec3 meshLocalPos = particle_vertexData.xyz;\n float id = floor(particle_vertexData.w);\n float rndFactor = fract(sin(id + 1.0 + seed));\n vec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));\n float uv = id / numParticlesPot;\n readInput(uv);\n#ifdef LOCAL_SPACE\n inVel = mat3(matrix_model) * inVel;\n#endif\n vec2 velocityV = safeNormalize((mat3(matrix_view) * inVel).xy);\n float particleLifetime = lifetime;\n if (inLife <= 0.0 || inLife > particleLifetime || !inShow)\n meshLocalPos = vec3(0.0);\n vec2 quadXY = meshLocalPos.xy;\n float nlife = clamp(inLife / particleLifetime, 0.0, 1.0);\n vec3 paramDiv;\n vec4 params = tex1Dlod_lerp(TEXTURE_PASS(internalTex2), vec2(nlife, 0), paramDiv);\n float scale = params.y;\n float scaleDiv = paramDiv.x;\n float alphaDiv = paramDiv.z;\n scale += (scaleDiv * 2.0 - 1.0) * scaleDivMult * fract(rndFactor*10000.0);\n#ifndef USE_MESH\n texCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);\n#else\n texCoordsAlphaLife = vec4(particle_uv, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);\n#endif\n vec3 particlePos = inPos;\n vec3 particlePosMoved = vec3(0.0);\n mat2 rotMatrix;\n",particleAnimFrameClampVS:"\n float animFrame = min(floor(texCoordsAlphaLife.w * animTexParams.y) + animTexParams.x, animTexParams.z);\n",particleAnimFrameLoopVS:"\n float animFrame = floor(mod(texCoordsAlphaLife.w * animTexParams.y + animTexParams.x, animTexParams.z + 1.0));\n",particleAnimTexVS:"\n float animationIndex;\n if (animTexIndexParams.y == 1.0) {\n animationIndex = floor((animTexParams.w + 1.0) * rndFactor3.z) * (animTexParams.z + 1.0);\n } else {\n animationIndex = animTexIndexParams.x * (animTexParams.z + 1.0);\n }\n float atlasX = (animationIndex + animFrame) * animTexTilesParams.x;\n float atlasY = 1.0 - floor(atlasX + 1.0) * animTexTilesParams.y;\n atlasX = fract(atlasX);\n texCoordsAlphaLife.xy *= animTexTilesParams.xy;\n texCoordsAlphaLife.xy += vec2(atlasX, atlasY);\n",particleInputFloatPS:"\nvoid readInput(float uv) {\n vec4 tex = texture2D(particleTexIN, vec2(uv, 0.25));\n vec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.75));\n inPos = tex.xyz;\n inVel = tex2.xyz;\n inAngle = (tex.w < 0.0? -tex.w : tex.w) - 1000.0;\n inShow = tex.w >= 0.0;\n inLife = tex2.w;\n}\n",particleInputRgba8PS:"\n#define PI2 6.283185307179586\nuniform vec3 inBoundsSize;\nuniform vec3 inBoundsCenter;\nuniform float maxVel;\nfloat decodeFloatRG(vec2 rg) {\n return 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 vec4 tex0 = texture2D(particleTexIN, vec2(uv, 0.125));\n vec4 tex1 = texture2D(particleTexIN, vec2(uv, 0.375));\n vec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.625));\n vec4 tex3 = texture2D(particleTexIN, vec2(uv, 0.875));\n inPos = vec3(decodeFloatRG(tex0.rg), decodeFloatRG(tex0.ba), decodeFloatRG(tex1.rg));\n inPos = (inPos - vec3(0.5)) * inBoundsSize + inBoundsCenter;\n inVel = tex2.xyz;\n inVel = (inVel - vec3(0.5)) * maxVel;\n inAngle = decodeFloatRG(tex1.ba) * PI2;\n inShow = tex2.a > 0.5;\n inLife = decodeFloatRGBA(tex3);\n float maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));\n float maxPosLife = lifetime+1.0;\n inLife = inLife * (maxNegLife + maxPosLife) - maxNegLife;\n}\n",particleOutputFloatPS:"\nvoid writeOutput() {\n if (gl_FragCoord.y<1.0) {\n gl_FragColor = vec4(outPos, (outAngle + 1000.0) * visMode);\n } else {\n gl_FragColor = vec4(outVel, outLife);\n }\n}\n",particleOutputRgba8PS:"\nuniform vec3 outBoundsMul;\nuniform vec3 outBoundsAdd;\nvec2 encodeFloatRG( float v ) {\n vec2 enc = vec2(1.0, 255.0) * v;\n enc = fract(enc);\n enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n return enc;\n}\nvec4 encodeFloatRGBA( float v ) {\n vec4 enc = vec4(1.0, 255.0, 65025.0, 160581375.0) * v;\n enc = fract(enc);\n enc -= enc.yzww * vec4(1.0/255.0,1.0/255.0,1.0/255.0,0.0);\n return enc;\n}\nvoid writeOutput() {\n outPos = outPos * outBoundsMul + outBoundsAdd;\n outAngle = fract(outAngle / PI2);\n outVel = (outVel / maxVel) + vec3(0.5);\n float maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));\n float maxPosLife = lifetime+1.0;\n outLife = (outLife + maxNegLife) / (maxNegLife + maxPosLife);\n if (gl_FragCoord.y < 1.0) {\n gl_FragColor = vec4(encodeFloatRG(outPos.x), encodeFloatRG(outPos.y));\n } else if (gl_FragCoord.y < 2.0) {\n gl_FragColor = vec4(encodeFloatRG(outPos.z), encodeFloatRG(outAngle));\n } else if (gl_FragCoord.y < 3.0) {\n gl_FragColor = vec4(outVel, visMode*0.5+0.5);\n } else {\n gl_FragColor = encodeFloatRGBA(outLife);\n }\n}\n",particleUpdaterAABBPS:"\nuniform mat3 spawnBounds;\nuniform vec3 spawnPosInnerRatio;\nvec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {\n vec3 pos = inBounds - vec3(0.5);\n vec3 posAbs = abs(pos);\n vec3 maxPos = vec3(max(posAbs.x, max(posAbs.y, posAbs.z)));\n vec3 edge = maxPos + (vec3(0.5) - maxPos) * spawnPosInnerRatio;\n pos.x = edge.x * (maxPos.x == posAbs.x ? sign(pos.x) : 2.0 * pos.x);\n pos.y = edge.y * (maxPos.y == posAbs.y ? sign(pos.y) : 2.0 * pos.y);\n pos.z = edge.z * (maxPos.z == posAbs.z ? sign(pos.z) : 2.0 * pos.z);\n#ifndef LOCAL_SPACE\n return emitterPos + spawnBounds * pos;\n#else\n return spawnBounds * pos;\n#endif\n}\nvoid addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {\n localVelocity -= vec3(0, 0, initialVelocity);\n}\n",particleUpdaterEndPS:"\n writeOutput();\n}\n",particleUpdaterInitPS:"\nvarying vec2 vUv0;\nuniform highp sampler2D particleTexIN;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\nuniform highp sampler2D internalTex3;\nuniform mat3 emitterMatrix;\nuniform mat3 emitterMatrixInv;\nuniform vec3 emitterScale;\nuniform vec3 emitterPos;\nuniform vec3 frameRandom;\nuniform vec3 localVelocityDivMult;\nuniform vec3 velocityDivMult;\nuniform float delta;\nuniform float rate;\nuniform float rateDiv;\nuniform float lifetime;\nuniform float numParticles;\nuniform float rotSpeedDivMult;\nuniform float radialSpeedDivMult;\nuniform float seed;\nuniform float startAngle;\nuniform float startAngle2;\nuniform float initialVelocity;\nuniform float graphSampleSize;\nuniform float graphNumSamples;\nvec3 inPos;\nvec3 inVel;\nfloat inAngle;\nbool inShow;\nfloat inLife;\nfloat visMode;\nvec3 outPos;\nvec3 outVel;\nfloat outAngle;\nbool outShow;\nfloat outLife;\n",particleUpdaterNoRespawnPS:"\n if (outLife >= lifetime) {\n outLife -= max(lifetime, (numParticles - 1.0) * particleRate);\n visMode = -1.0;\n }\n",particleUpdaterOnStopPS:"\n visMode = outLife < 0.0? -1.0: visMode;\n",particleUpdaterRespawnPS:"\n if (outLife >= lifetime) {\n outLife -= max(lifetime, (numParticles - 1.0) * particleRate);\n visMode = 1.0;\n }\n visMode = outLife < 0.0? 1.0: visMode;\n",particleUpdaterSpherePS:"\nuniform float spawnBoundsSphere;\nuniform float spawnBoundsSphereInnerRatio;\nvec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {\n float rnd4 = fract(rndFactor * 1000.0);\n vec3 norm = normalize(inBounds.xyz - vec3(0.5));\n float r = rnd4 * (1.0 - spawnBoundsSphereInnerRatio) + spawnBoundsSphereInnerRatio;\n#ifndef LOCAL_SPACE\n return emitterPos + norm * r * spawnBoundsSphere;\n#else\n return norm * r * spawnBoundsSphere;\n#endif\n}\nvoid addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {\n localVelocity += normalize(inBounds - vec3(0.5)) * initialVelocity;\n}\n",particleUpdaterStartPS:"\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\nvec3 unpack3NFloats(float src) {\n float r = fract(src);\n float g = fract(src * 256.0);\n float b = fract(src * 65536.0);\n return vec3(r, g, b);\n}\nvec3 tex1Dlod_lerp(TEXTURE_ACCEPT_HIGHP(tex), vec2 tc, out vec3 w) {\n vec4 a = texture2D(tex, tc);\n vec4 b = texture2D(tex, tc + graphSampleSize);\n float c = fract(tc.x * graphNumSamples);\n vec3 unpackedA = unpack3NFloats(a.w);\n vec3 unpackedB = unpack3NFloats(b.w);\n w = mix(unpackedA, unpackedB, c);\n return mix(a.xyz, b.xyz, c);\n}\n#define HASHSCALE4 vec4(1031, .1030, .0973, .1099)\nvec4 hash41(float p) {\n vec4 p4 = fract(vec4(p) * HASHSCALE4);\n p4 += dot(p4, p4.wzxy+19.19);\n return fract(vec4((p4.x + p4.y)*p4.z, (p4.x + p4.z)*p4.y, (p4.y + p4.z)*p4.w, (p4.z + p4.w)*p4.x));\n}\nvoid main(void) {\n if (gl_FragCoord.x > numParticles) discard;\n readInput(vUv0.x);\n visMode = inShow? 1.0 : -1.0;\n vec4 rndFactor = hash41(gl_FragCoord.x + seed);\n float particleRate = rate + rateDiv * rndFactor.x;\n outLife = inLife + delta;\n float nlife = clamp(outLife / lifetime, 0.0, 1.0);\n vec3 localVelocityDiv;\n vec3 velocityDiv;\n vec3 paramDiv;\n vec3 localVelocity = tex1Dlod_lerp(TEXTURE_PASS(internalTex0), vec2(nlife, 0), localVelocityDiv);\n vec3 velocity = tex1Dlod_lerp(TEXTURE_PASS(internalTex1), vec2(nlife, 0), velocityDiv);\n vec3 params = tex1Dlod_lerp(TEXTURE_PASS(internalTex2), vec2(nlife, 0), paramDiv);\n float rotSpeed = params.x;\n float rotSpeedDiv = paramDiv.y;\n vec3 radialParams = tex1Dlod_lerp(TEXTURE_PASS(internalTex3), vec2(nlife, 0), paramDiv);\n float radialSpeed = radialParams.x;\n float radialSpeedDiv = radialParams.y;\n bool respawn = inLife <= 0.0 || outLife >= lifetime;\n inPos = respawn ? calcSpawnPosition(rndFactor.xyz, rndFactor.x) : inPos;\n inAngle = respawn ? mix(startAngle, startAngle2, rndFactor.x) : inAngle;\n#ifndef LOCAL_SPACE\n vec3 radialVel = inPos - emitterPos;\n#else\n vec3 radialVel = inPos;\n#endif\n radialVel = (dot(radialVel, radialVel) > 1.0E-8) ? radialSpeed * normalize(radialVel) : vec3(0.0);\n radialVel += (radialSpeedDiv * vec3(2.0) - vec3(1.0)) * radialSpeedDivMult * rndFactor.xyz;\n localVelocity += (localVelocityDiv * vec3(2.0) - vec3(1.0)) * localVelocityDivMult * rndFactor.xyz;\n velocity += (velocityDiv * vec3(2.0) - vec3(1.0)) * velocityDivMult * rndFactor.xyz;\n rotSpeed += (rotSpeedDiv * 2.0 - 1.0) * rotSpeedDivMult * rndFactor.y;\n addInitialVelocity(localVelocity, rndFactor.xyz);\n#ifndef LOCAL_SPACE\n outVel = emitterMatrix * localVelocity + (radialVel + velocity) * emitterScale;\n#else\n outVel = (localVelocity + radialVel) / emitterScale + emitterMatrixInv * velocity;\n#endif\n outPos = inPos + outVel * delta;\n outAngle = inAngle + rotSpeed * delta;\n",particle_billboardVS:"\n quadXY = rotate(quadXY, inAngle, rotMatrix);\n vec3 localPos = billboard(particlePos, quadXY);\n",particle_blendAddPS:"\n dBlendModeFogFactor = 0.0;\n rgb *= saturate(gammaCorrectInput(max(a, 0.0)));\n if ((rgb.r + rgb.g + rgb.b) < 0.000001) discard;\n",particle_blendMultiplyPS:"\n rgb = mix(vec3(1.0), rgb, vec3(a));\n if (rgb.r + rgb.g + rgb.b > 2.99) discard;\n",particle_blendNormalPS:"\n if (a < 0.01) discard;\n",particle_cpuVS:"\nattribute vec4 particle_vertexData;\nattribute vec4 particle_vertexData2;\nattribute vec4 particle_vertexData3;\nattribute float particle_vertexData4;\n#ifndef USE_MESH\n attribute vec2 particle_vertexData5;\n#else\n attribute vec4 particle_vertexData5;\n#endif\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\n#ifndef VIEWMATRIX\n #define VIEWMATRIX\n uniform mat4 matrix_view;\n#endif\nuniform mat3 matrix_normal;\nuniform mat4 matrix_viewInverse;\nuniform float numParticles;\nuniform float lifetime;\nuniform float stretch;\nuniform float seed;\nuniform vec3 wrapBounds;\nuniform vec3 emitterScale;\nuniform vec3 faceTangent;\nuniform vec3 faceBinorm;\n#ifdef PARTICLE_GPU\n uniform highp sampler2D internalTex0;\n uniform highp sampler2D internalTex1;\n uniform highp sampler2D internalTex2;\n#endif\nuniform vec3 emitterPos;\nvarying vec4 texCoordsAlphaLife;\nvec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix)\n{\n float c = cos(pRotation);\n float s = sin(pRotation);\n mat2 m = mat2(c, -s, s, c);\n rotMatrix = m;\n return m * quadXY;\n}\nvec3 billboard(vec3 InstanceCoords, vec2 quadXY)\n{\n vec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;\n return pos;\n}\nvec3 customFace(vec3 InstanceCoords, vec2 quadXY)\n{\n vec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;\n return pos;\n}\nvoid main(void)\n{\n vec3 particlePos = particle_vertexData.xyz;\n vec3 inPos = particlePos;\n vec3 vertPos = particle_vertexData3.xyz;\n vec3 inVel = vec3(particle_vertexData2.w, particle_vertexData3.w, particle_vertexData5.x);\n float id = floor(particle_vertexData4);\n float rndFactor = fract(sin(id + 1.0 + seed));\n vec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));\n#ifdef LOCAL_SPACE\n inVel = mat3(matrix_model) * inVel;\n#endif\n vec2 velocityV = normalize((mat3(matrix_view) * inVel).xy);\n vec2 quadXY = vertPos.xy;\n#ifdef USE_MESH\n texCoordsAlphaLife = vec4(particle_vertexData5.zw, particle_vertexData2.z, particle_vertexData.w);\n#else\n texCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, particle_vertexData2.z, particle_vertexData.w);\n#endif\n mat2 rotMatrix;\n float inAngle = particle_vertexData2.x;\n vec3 particlePosMoved = vec3(0.0);\n vec3 meshLocalPos = particle_vertexData3.xyz;\n",particle_cpu_endVS:"\n localPos *= particle_vertexData2.y * emitterScale;\n localPos += particlePos;\n gl_Position = matrix_viewProjection * vec4(localPos, 1.0);\n",particle_customFaceVS:"\n quadXY = rotate(quadXY, inAngle, rotMatrix);\n vec3 localPos = customFace(particlePos, quadXY);\n",particle_endPS:"\n rgb = addFog(rgb);\n rgb = toneMap(rgb);\n rgb = gammaCorrectOutput(rgb);\n gl_FragColor = vec4(rgb, a);\n}\n",particle_endVS:"\n localPos *= scale * emitterScale;\n localPos += particlePos;\n #ifdef SCREEN_SPACE\n gl_Position = vec4(localPos.x, localPos.y, 0.0, 1.0);\n #else\n gl_Position = matrix_viewProjection * vec4(localPos.xyz, 1.0);\n #endif\n",particle_halflambertPS:"\n vec3 negNormal = normal * 0.5 + 0.5;\n vec3 posNormal = -normal * 0.5 + 0.5;\n negNormal *= negNormal;\n posNormal *= posNormal;\n",particle_initVS:"\nattribute vec4 particle_vertexData;\n#if defined(USE_MESH)\n #if defined(USE_MESH_UV)\n attribute vec2 particle_uv;\n #else\n vec2 particle_uv = vec2(0.0, 0.0);\n #endif\n#endif\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\nuniform mat3 matrix_normal;\nuniform mat4 matrix_viewInverse;\n#ifndef VIEWMATRIX\n #define VIEWMATRIX\n uniform mat4 matrix_view;\n#endif\nuniform float numParticles;\nuniform float numParticlesPot;\nuniform float graphSampleSize;\nuniform float graphNumSamples;\nuniform float stretch;\nuniform vec3 wrapBounds;\nuniform vec3 emitterScale;\nuniform vec3 emitterPos;\nuniform vec3 faceTangent;\nuniform vec3 faceBinorm;\nuniform float rate;\nuniform float rateDiv;\nuniform float lifetime;\nuniform float deltaRandomnessStatic;\nuniform float scaleDivMult;\nuniform float alphaDivMult;\nuniform float seed;\nuniform float delta;\nuniform sampler2D particleTexOUT;\nuniform sampler2D particleTexIN;\n#ifdef PARTICLE_GPU\n uniform highp sampler2D internalTex0;\n uniform highp sampler2D internalTex1;\n uniform highp sampler2D internalTex2;\n#endif\n#ifndef CAMERAPLANES\n #define CAMERAPLANES\n uniform vec4 camera_params;\n#endif\nvarying vec4 texCoordsAlphaLife;\nvec3 inPos;\nvec3 inVel;\nfloat inAngle;\nbool inShow;\nfloat inLife;\n",particle_lambertPS:"\n vec3 negNormal = max(normal, vec3(0.0));\n vec3 posNormal = max(-normal, vec3(0.0));\n",particle_lightingPS:"\n vec3 light = negNormal.x*lightCube[0] + posNormal.x*lightCube[1] +\n negNormal.y*lightCube[2] + posNormal.y*lightCube[3] +\n negNormal.z*lightCube[4] + posNormal.z*lightCube[5];\n rgb *= light;\n",particle_localShiftVS:"\n particlePos = (matrix_model * vec4(particlePos, 1.0)).xyz;\n",particle_meshVS:"\n vec3 localPos = meshLocalPos;\n localPos.xy = rotate(localPos.xy, inAngle, rotMatrix);\n localPos.yz = rotate(localPos.yz, inAngle, rotMatrix);\n billboard(particlePos, quadXY);\n",particle_normalVS:"\n Normal = normalize(localPos + matrix_viewInverse[2].xyz);\n",particle_normalMapPS:"\n vec3 normalMap = normalize(texture2D(normalMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y)).xyz * 2.0 - 1.0);\n vec3 normal = ParticleMat * normalMap;\n",particle_pointAlongVS:"\n inAngle = atan(velocityV.x, velocityV.y);\n",particle_simulationPS:'\n #include "particleUpdaterInitPS"\n #ifdef PACK8\n #include "particleInputRgba8PS"\n #include "particleOutputRgba8PS"\n #else\n #include "particleInputFloatPS"\n #include "particleOutputFloatPS"\n #endif\n #ifdef EMITTERSHAPE_BOX\n #include "particleUpdaterAABBPS"\n #else\n #include "particleUpdaterSpherePS"\n #endif\n #include "particleUpdaterStartPS"\n #ifdef RESPAWN\n #include "particleUpdaterRespawnPS"\n #endif\n #ifdef NO_RESPAWN\n #include "particleUpdaterNoRespawnPS"\n #endif\n #ifdef ON_STOP\n #include "particleUpdaterOnStopPS"\n #endif\n #include "particleUpdaterEndPS"\n',particle_shaderPS:'\n #if NORMAL != NONE\n #if NORMAL == VERTEX\n varying vec3 Normal;\n #endif\n #if NORMAL == MAP\n varying mat3 ParticleMat;\n #endif\n uniform vec3 lightCube[6];\n #endif\n #ifdef SOFT\n varying float vDepth;\n #include "screenDepthPS"\n #endif\n #include "gammaPS"\n #include "tonemappingPS"\n #include "fogPS"\n #if NORMAL == MAP\n uniform sampler2D normalMap;\n #endif\n #include "particlePS"\n #ifdef SOFT\n #include "particle_softPS"\n #endif\n #if NORMAL == VERTEX\n vec3 normal = Normal;\n #endif\n #if NORMAL == MAP\n #include "particle_normalMapPS"\n #endif\n #if NORMAL != NONE\n #ifdef HALF_LAMBERT\n #include "particle_halflambertPS"\n #else\n #include "particle_lambertPS"\n #endif\n #include "particle_lightingPS"\n #endif\n #if BLEND == NORMAL\n #include "particle_blendNormalPS"\n #elif BLEND == ADDITIVE\n #include "particle_blendAddPS"\n #elif BLEND == MULTIPLICATIVE\n #include "particle_blendMultiplyPS"\n #endif\n #include "particle_endPS"\n',particle_shaderVS:'\n #ifdef ANIMTEX\n uniform vec2 animTexTilesParams;\n uniform vec4 animTexParams;\n uniform vec2 animTexIndexParams;\n #endif\n #if NORMAL == MAP\n varying mat3 ParticleMat;\n #endif\n #if NORMAL == VERTEX\n varying vec3 Normal;\n #endif\n #ifdef SOFT\n varying float vDepth;\n #endif\n #ifdef PARTICLE_GPU\n #include "particle_initVS"\n #ifdef PACK8\n #include "particleInputRgba8PS"\n #else\n #include "particleInputFloatPS"\n #endif\n #ifdef SOFT\n #include "screenDepthPS"\n #endif\n #include "particleVS"\n #else\n #ifdef SOFT\n #include "screenDepthPS"\n #endif\n #include "particle_cpuVS"\n #endif\n #ifdef LOCAL_SPACE\n #include "particle_localShiftVS"\n #endif\n #ifdef ANIMTEX\n #ifdef ANIMTEX_LOOP\n #include "particleAnimFrameLoopVS"\n #else\n #include "particleAnimFrameClampVS"\n #endif\n #include "particleAnimTexVS"\n #endif\n #ifdef PARTICLE_GPU\n #ifdef WRAP\n #include "particle_wrapVS"\n #endif\n #endif\n #ifdef ALIGN_TO_MOTION\n #include "particle_pointAlongVS"\n #endif\n #ifdef USE_MESH\n #include "particle_meshVS"\n #else\n #ifdef CUSTOM_FACE\n #include "particle_customFaceVS"\n #else\n #include "particle_billboardVS"\n #endif\n #endif\n #if NORMAL == VERTEX\n #include "particle_normalVS"\n #endif\n #if NORMAL == MAP\n #include "particle_TBNVS"\n #endif\n #ifdef STRETCH\n #include "particle_stretchVS"\n #endif\n #ifdef PARTICLE_GPU\n #include "particle_endVS"\n #else\n #include "particle_cpu_endVS"\n #endif\n #ifdef SOFT\n #include "particle_softVS"\n #endif\n }\n',particle_softPS:"\n float depth = getLinearScreenDepth();\n float particleDepth = vDepth;\n float depthDiff = saturate(abs(particleDepth - depth) * softening);\n a *= depthDiff;\n",particle_softVS:"\n vDepth = getLinearDepth(localPos);\n",particle_stretchVS:"\n vec3 moveDir = inVel * stretch;\n vec3 posPrev = particlePos - moveDir;\n posPrev += particlePosMoved;\n vec2 centerToVertexV = normalize((mat3(matrix_view) * localPos).xy);\n float interpolation = dot(-velocityV, centerToVertexV) * 0.5 + 0.5;\n particlePos = mix(particlePos, posPrev, interpolation);\n",particle_TBNVS:"\n mat3 rot3 = mat3(rotMatrix[0][0], rotMatrix[0][1], 0.0, rotMatrix[1][0], rotMatrix[1][1], 0.0, 0.0, 0.0, 1.0);\n ParticleMat = mat3(-matrix_viewInverse[0].xyz, -matrix_viewInverse[1].xyz, matrix_viewInverse[2].xyz) * rot3;\n",particle_wrapVS:"\n vec3 origParticlePos = particlePos;\n particlePos -= matrix_model[3].xyz;\n particlePos = mod(particlePos, wrapBounds) - wrapBounds * 0.5;\n particlePos += matrix_model[3].xyz;\n particlePosMoved = particlePos - origParticlePos;\n"},yo={particlePS:"\nvarying texCoordsAlphaLife: vec4f;\nvar colorMap: texture_2d;\nvar colorMapSampler: sampler;\nvar colorParam: texture_2d;\nvar colorParamSampler: sampler;\nuniform graphSampleSize: f32;\nuniform graphNumSamples: f32;\n#ifndef CAMERAPLANES\n #define CAMERAPLANES\n uniform camera_params: vec4f;\n#endif\nuniform softening: f32;\nuniform colorMult: f32;\nfn saturate(x: f32) -> f32 {\n return clamp(x, 0.0, 1.0);\n}\n@fragment\nfn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n let tex: vec4f = textureSample(colorMap, colorMapSampler, vec2f(input.texCoordsAlphaLife.x, 1.0 - input.texCoordsAlphaLife.y));\n var ramp: vec4f = textureSample(colorParam, colorParamSampler, vec2f(input.texCoordsAlphaLife.w, 0.0));\n ramp = vec4f(ramp.rgb * uniform.colorMult, ramp.a);\n ramp.a = ramp.a + input.texCoordsAlphaLife.z;\n var rgb: vec3f = tex.rgb * ramp.rgb;\n var a: f32 = tex.a * ramp.a;\n",particleVS:"\nfn unpack3NFloats(src: f32) -> vec3f {\n let r = fract(src);\n let g = fract(src * 256.0);\n let b = fract(src * 65536.0);\n return vec3f(r, g, b);\n}\nfn saturate(x: f32) -> f32 {\n return clamp(x, 0.0, 1.0);\n}\nstruct TexLerpUnpackResult {\n result: vec4f,\n unpacked: vec3f\n}\nfn tex1Dlod_lerp_simple(tex: texture_2d, texSampler: sampler, tc: vec2f) -> vec4f {\n let tc_next = tc + vec2f(uniform.graphSampleSize);\n return mix( textureSample(tex, texSampler, tc), textureSample(tex, texSampler, tc_next), fract(tc.x * uniform.graphNumSamples) );\n}\nfn tex1Dlod_lerp_unpack(tex: texture_2d, texSampler: sampler, tc: vec2f) -> TexLerpUnpackResult {\n let tc_next = tc + vec2f(uniform.graphSampleSize);\n let a = textureSampleLevel(tex, texSampler, tc, 0.0);\n let b = textureSampleLevel(tex, texSampler, tc_next, 0.0);\n let c = fract(tc.x * uniform.graphNumSamples);\n let unpackedA = unpack3NFloats(a.w);\n let unpackedB = unpack3NFloats(b.w);\n let w_out = mix(unpackedA, unpackedB, c);\n return TexLerpUnpackResult(mix(a, b, c), w_out);\n}\nstruct RotateResult {\n rotatedVec: vec2f,\n matrix: mat2x2f\n}\nfn rotateWithMatrix(quadXY: vec2f, pRotation: f32) -> RotateResult {\n let c = cos(pRotation);\n let s = sin(pRotation);\n let m = mat2x2f(vec2f(c, s), vec2f(-s, c));\n return RotateResult(m * quadXY, m);\n}\nfn billboard(InstanceCoords: vec3f, quadXY: vec2f) -> vec3f {\n var pos: vec3f;\n #ifdef SCREEN_SPACE\n pos = vec3f(-1.0, 0.0, 0.0) * quadXY.x + vec3f(0.0, -1.0, 0.0) * quadXY.y;\n #else\n pos = -uniform.matrix_viewInverse[0].xyz * quadXY.x + -uniform.matrix_viewInverse[1].xyz * quadXY.y;\n #endif\n return pos;\n}\nfn customFace(InstanceCoords: vec3f, quadXY: vec2f) -> vec3f {\n let pos = uniform.faceTangent * quadXY.x + uniform.faceBinorm * quadXY.y;\n return pos;\n}\nfn safeNormalize(v: vec2f) -> vec2f {\n let l = length(v);\n return select(v, v / l, l > 1e-06);\n}\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n let meshLocalPos_in = input.particle_vertexData.xyz;\n let id = floor(input.particle_vertexData.w);\n let rndFactor = fract(sin(id + 1.0 + uniform.seed));\n let rndFactor3 = vec3f(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));\n let uv = id / uniform.numParticlesPot;\n readInput(uv);\n #ifdef LOCAL_SPACE\n let modelRotation = mat3x3f(uniform.matrix_model[0].xyz, uniform.matrix_model[1].xyz, uniform.matrix_model[2].xyz);\n inVel = modelRotation * inVel;\n #endif\n let viewRotation = mat3x3f(uniform.matrix_view[0].xyz, uniform.matrix_view[1].xyz, uniform.matrix_view[2].xyz);\n let velocityV = safeNormalize((viewRotation * inVel).xy);\n let particleLifetime = uniform.lifetime;\n var meshLocalPos = meshLocalPos_in;\n if (inLife <= 0.0 || inLife > particleLifetime || !inShow) {\n meshLocalPos = vec3f(0.0);\n }\n let quadXY = meshLocalPos.xy;\n let nlife = clamp(inLife / particleLifetime, 0.0, 1.0);\n let lerp_result = tex1Dlod_lerp_unpack(internalTex2, internalTex2Sampler, vec2f(nlife, 0.0));\n let params = lerp_result.result;\n let paramDiv = lerp_result.unpacked;\n var scale = params.y;\n let scaleDiv = paramDiv.x;\n let alphaDiv = paramDiv.z;\n scale = scale + (scaleDiv * 2.0 - 1.0) * uniform.scaleDivMult * fract(rndFactor*10000.0);\n #ifndef USE_MESH\n output.texCoordsAlphaLife = vec4f(quadXY * -0.5 + 0.5, (alphaDiv * 2.0 - 1.0) * uniform.alphaDivMult * fract(rndFactor*1000.0), nlife);\n #else\n output.texCoordsAlphaLife = vec4f(particle_uv, (alphaDiv * 2.0 - 1.0) * uniform.alphaDivMult * fract(rndFactor*1000.0), nlife);\n #endif\n var particlePos = inPos;\n var particlePosMoved = vec3f(0.0);\n var rotMatrix: mat2x2f;\n",particleAnimFrameClampVS:"\n let animFrame: f32 = min(floor(input.texCoordsAlphaLife.w * uniform.animTexParams.y) + uniform.animTexParams.x, uniform.animTexParams.z);\n",particleAnimFrameLoopVS:"\n let animFrame: f32 = floor((output.texCoordsAlphaLife.w * uniform.animTexParams.y + uniform.animTexParams.x) % (uniform.animTexParams.z + 1.0)); \n",particleAnimTexVS:"\n var animationIndex: f32;\n if (uniform.animTexIndexParams.y == 1.0) {\n animationIndex = floor((uniform.animTexParams.w + 1.0) * rndFactor3.z) * (uniform.animTexParams.z + 1.0);\n } else {\n animationIndex = uniform.animTexIndexParams.x * (uniform.animTexParams.z + 1.0);\n }\n var atlasX: f32 = (animationIndex + animFrame) * uniform.animTexTilesParams.x;\n let atlasY: f32 = 1.0 - floor(atlasX + 1.0) * uniform.animTexTilesParams.y;\n atlasX = fract(atlasX);\n let current_tcal_xy = output.texCoordsAlphaLife.xy;\n let scaled_tcal_xy = current_tcal_xy * uniform.animTexTilesParams.xy;\n let final_tcal_xy = scaled_tcal_xy + vec2f(atlasX, atlasY);\n output.texCoordsAlphaLife = vec4f(final_tcal_xy, output.texCoordsAlphaLife.z, output.texCoordsAlphaLife.w);\n",particleInputFloatPS:"\nfn readInput(uv: f32) {\n let tex: vec4f = textureSampleLevel(particleTexIN, particleTexINSampler, vec2f(uv, 0.25), 0.0);\n let tex2: vec4f = textureSampleLevel(particleTexIN, particleTexINSampler, vec2f(uv, 0.75), 0.0);\n inPos = tex.xyz;\n inVel = tex2.xyz;\n inAngle = abs(tex.w) - 1000.0;\n inShow = tex.w >= 0.0;\n inLife = tex2.w;\n}\n",particleInputRgba8PS:"\nconst PI2: f32 = 6.283185307179586;\nuniform inBoundsSize: vec3f;\nuniform inBoundsCenter: vec3f;\nuniform maxVel: f32;\nfn decodeFloatRG(rg: vec2f) -> f32 {\n return rg.y * (1.0 / 255.0) + rg.x;\n}\nfn decodeFloatRGBA( rgba: vec4f ) -> f32 {\n return dot(rgba, vec4f(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));\n}\nfn readInput(uv: f32) {\n let tex0 = textureSampleLevel(particleTexIN, particleTexINSampler, vec2f(uv, 0.125), 0.0);\n let tex1 = textureSampleLevel(particleTexIN, particleTexINSampler, vec2f(uv, 0.375), 0.0);\n let tex2 = textureSampleLevel(particleTexIN, particleTexINSampler, vec2f(uv, 0.625), 0.0);\n let tex3 = textureSampleLevel(particleTexIN, particleTexINSampler, vec2f(uv, 0.875), 0.0);\n inPos = vec3f(decodeFloatRG(tex0.rg), decodeFloatRG(tex0.ba), decodeFloatRG(tex1.rg));\n inPos = (inPos - vec3f(0.5)) * uniform.inBoundsSize + uniform.inBoundsCenter;\n inVel = tex2.xyz;\n inVel = (inVel - vec3f(0.5)) * uniform.maxVel;\n inAngle = decodeFloatRG(tex1.ba) * PI2;\n inShow = tex2.a > 0.5;\n let life_decoded = decodeFloatRGBA(tex3);\n let maxNegLife = max(uniform.lifetime, (uniform.numParticles - 1.0) * (uniform.rate + uniform.rateDiv));\n let maxPosLife = uniform.lifetime + 1.0;\n inLife = life_decoded * (maxNegLife + maxPosLife) - maxNegLife;\n}",particleOutputFloatPS:"\nfn getOutput() -> vec4f {\n if (pcPosition.y < 1.0) {\n return vec4f(outPos, (outAngle + 1000.0) * visMode);\n } else {\n return vec4f(outVel, outLife);\n }\n}\n",particleOutputRgba8PS:"\nuniform outBoundsMul: vec3f;\nuniform outBoundsAdd: vec3f;\nfn encodeFloatRG( v: f32 ) -> vec2f {\n var enc: vec2f = vec2f(1.0, 255.0) * v;\n enc = fract(enc);\n enc = enc - enc.yy * (1.0 / 255.0);\n return enc;\n}\nfn encodeFloatRGBA( v: f32 ) -> vec4f {\n let factors = vec4f(1.0, 255.0, 65025.0, 160581375.0);\n var enc: vec4f = factors * v;\n enc = fract(enc);\n enc = enc - enc.yzww * vec4f(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);\n return enc;\n}\nfn getOutput() -> vec4f {\n outPos = outPos * uniform.outBoundsMul + uniform.outBoundsAdd;\n outAngle = fract(outAngle / PI2);\n outVel = (outVel / uniform.maxVel) + vec3f(0.5);\n let maxNegLife = max(uniform.lifetime, (uniform.numParticles - 1.0) * (uniform.rate + uniform.rateDiv));\n let maxPosLife = uniform.lifetime + 1.0;\n outLife = (outLife + maxNegLife) / (maxNegLife + maxPosLife);\n if (pcPosition.y < 1.0) {\n return vec4f(encodeFloatRG(outPos.x), encodeFloatRG(outPos.y));\n } else if (pcPosition.y < 2.0) {\n return vec4f(encodeFloatRG(outPos.z), encodeFloatRG(outAngle));\n } else if (pcPosition.y < 3.0) {\n return vec4f(outVel, visMode * 0.5 + 0.5);\n } else {\n return encodeFloatRGBA(outLife);\n }\n}\n",particleUpdaterAABBPS:"\nuniform spawnBounds: mat3x3f;\nuniform spawnPosInnerRatio: vec3f;\nfn calcSpawnPosition(inBounds: vec3f, rndFactor: f32) -> vec3f {\n var pos = inBounds - vec3f(0.5);\n let posAbs = abs(pos);\n let maxComp = max(posAbs.x, max(posAbs.y, posAbs.z));\n let maxPos = vec3f(maxComp);\n let edge = maxPos + (vec3f(0.5) - maxPos) * uniform.spawnPosInnerRatio;\n pos.x = edge.x * select(2.0 * pos.x, sign(pos.x), maxPos.x == posAbs.x);\n pos.y = edge.y * select(2.0 * pos.y, sign(pos.y), maxPos.y == posAbs.y);\n pos.z = edge.z * select(2.0 * pos.z, sign(pos.z), maxPos.z == posAbs.z);\n #ifndef LOCAL_SPACE\n return uniform.emitterPos + uniform.spawnBounds * pos;\n #else\n return uniform.spawnBounds * pos;\n #endif\n}\nfn addInitialVelocity(localVelocity: ptr, inBounds: vec3f) {\n *localVelocity = *localVelocity - vec3f(0.0, 0.0, uniform.initialVelocity);\n}\n",particleUpdaterEndPS:"\n output.color = getOutput();\n return output;\n}\n",particleUpdaterInitPS:"\nvarying vUv0: vec2f;\nvar particleTexIN: texture_2d;\nvar particleTexINSampler: sampler;\nvar internalTex0: texture_2d;\nvar internalTex0Sampler: sampler;\nvar internalTex1: texture_2d;\nvar internalTex1Sampler: sampler;\nvar internalTex2: texture_2d;\nvar internalTex2Sampler: sampler;\nvar internalTex3: texture_2d;\nvar internalTex3Sampler: sampler;\nuniform emitterMatrix: mat3x3f;\nuniform emitterMatrixInv: mat3x3f;\nuniform emitterScale: vec3f;\nuniform emitterPos: vec3f;\nuniform frameRandom: vec3f;\nuniform localVelocityDivMult: vec3f;\nuniform velocityDivMult: vec3f;\nuniform delta: f32;\nuniform rate: f32;\nuniform rateDiv: f32;\nuniform lifetime: f32;\nuniform numParticles: f32;\nuniform rotSpeedDivMult: f32;\nuniform radialSpeedDivMult: f32;\nuniform seed: f32;\nuniform startAngle: f32;\nuniform startAngle2: f32;\nuniform initialVelocity: f32;\nuniform graphSampleSize: f32;\nuniform graphNumSamples: f32;\nvar inPos: vec3f;\nvar inVel: vec3f;\nvar inAngle: f32;\nvar inShow: bool;\nvar inLife: f32;\nvar visMode: f32;\nvar outPos: vec3f;\nvar outVel: vec3f;\nvar outAngle: f32;\nvar outShow: bool;\nvar outLife: f32;\n",particleUpdaterNoRespawnPS:"\n if (outLife >= uniform.lifetime) {\n outLife = outLife - max(uniform.lifetime, (uniform.numParticles - 1.0) * particleRate);\n visMode = -1.0;\n }\n",particleUpdaterOnStopPS:"\n visMode = select(visMode, -1.0, outLife < 0.0);\n",particleUpdaterRespawnPS:"\n if (outLife >= uniform.lifetime) {\n let subtractAmount = max(uniform.lifetime, (uniform.numParticles - 1.0) * particleRate);\n outLife = outLife - subtractAmount;\n visMode = 1.0;\n }\n visMode = select(visMode, 1.0, outLife < 0.0);\n",particleUpdaterSpherePS:"\nuniform spawnBoundsSphere: f32;\nuniform spawnBoundsSphereInnerRatio: f32;\nfn calcSpawnPosition(inBounds: vec3f, rndFactor: f32) -> vec3f {\n let rnd4: f32 = fract(rndFactor * 1000.0);\n let norm: vec3f = normalize(inBounds.xyz - vec3f(0.5));\n let r: f32 = rnd4 * (1.0 - uniform.spawnBoundsSphereInnerRatio) + uniform.spawnBoundsSphereInnerRatio;\n #ifndef LOCAL_SPACE\n return uniform.emitterPos + norm * r * uniform.spawnBoundsSphere;\n #else\n return norm * r * uniform.spawnBoundsSphere;\n #endif\n}\nfn addInitialVelocity(localVelocity: ptr, inBounds: vec3f) {\n let initialVelOffset: vec3f = normalize(inBounds - vec3f(0.5)) * uniform.initialVelocity;\n *localVelocity = *localVelocity + initialVelOffset;\n}\n",particleUpdaterStartPS:"\nfn saturate(x: f32) -> f32 {\n return clamp(x, 0.0, 1.0);\n}\nfn unpack3NFloats(src: f32) -> vec3f {\n let r = fract(src);\n let g = fract(src * 256.0);\n let b = fract(src * 65536.0);\n return vec3f(r, g, b);\n}\nstruct TexLerpUnpackResult {\n result: vec3f,\n unpacked: vec3f\n}\nfn tex1Dlod_lerp(tex: texture_2d, texSampler: sampler, tc: vec2f) -> TexLerpUnpackResult {\n let tc_next = tc + vec2f(uniform.graphSampleSize);\n let a = textureSampleLevel(tex, texSampler, tc, 0.0);\n let b = textureSampleLevel(tex, texSampler, tc_next, 0.0);\n let c = fract(tc.x * uniform.graphNumSamples);\n let unpackedA = unpack3NFloats(a.w);\n let unpackedB = unpack3NFloats(b.w);\n let w_out = mix(unpackedA, unpackedB, c);\n return TexLerpUnpackResult(mix(a.xyz, b.xyz, c), w_out);\n}\nconst HASHSCALE4: vec4f = vec4f(1031.0, 0.1030, 0.0973, 0.1099);\nfn hash41(p: f32) -> vec4f {\n var p4 = fract(vec4f(p) * HASHSCALE4);\n p4 = p4 + dot(p4, p4.wzxy + 19.19);\n return fract(vec4f((p4.x + p4.y)*p4.z, (p4.x + p4.z)*p4.y, (p4.y + p4.z)*p4.w, (p4.z + p4.w)*p4.x));\n}\n@fragment\nfn fragmentMain(input : FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n if (pcPosition.x > uniform.numParticles) {\n discard;\n return output;\n }\n readInput(input.vUv0.x);\n visMode = select(-1.0, 1.0, inShow);\n let rndFactor = hash41(pcPosition.x + uniform.seed);\n let particleRate = uniform.rate + uniform.rateDiv * rndFactor.x;\n outLife = inLife + uniform.delta;\n let nlife = clamp(outLife / uniform.lifetime, 0.0, 1.0);\n let lerpResult0 = tex1Dlod_lerp(internalTex0, internalTex0Sampler, vec2f(nlife, 0.0));\n var localVelocity = lerpResult0.result;\n let localVelocityDiv = lerpResult0.unpacked;\n let lerpResult1 = tex1Dlod_lerp(internalTex1, internalTex1Sampler, vec2f(nlife, 0.0));\n var velocity = lerpResult1.result;\n let velocityDiv = lerpResult1.unpacked;\n let lerpResult2 = tex1Dlod_lerp(internalTex2, internalTex2Sampler, vec2f(nlife, 0.0));\n let params = lerpResult2.result;\n let paramDiv = lerpResult2.unpacked;\n var rotSpeed = params.x;\n let rotSpeedDiv = paramDiv.y;\n let lerpResult3 = tex1Dlod_lerp(internalTex3, internalTex3Sampler, vec2f(nlife, 0.0));\n let radialParams = lerpResult3.result;\n let radialParamDiv = lerpResult3.unpacked;\n let radialSpeed = radialParams.x;\n let radialSpeedDiv = radialParamDiv.y;\n let respawn = inLife <= 0.0 || outLife >= uniform.lifetime;\n inPos = select(inPos, calcSpawnPosition(rndFactor.xyz, rndFactor.x), respawn);\n inAngle = select(inAngle, mix(uniform.startAngle, uniform.startAngle2, rndFactor.x), respawn);\n #ifndef LOCAL_SPACE\n var radialVel: vec3f = inPos - uniform.emitterPos;\n #else\n var radialVel: vec3f = inPos;\n #endif\n radialVel = select(vec3f(0.0), radialSpeed * normalize(radialVel), dot(radialVel, radialVel) > 1.0E-8);\n radialVel = radialVel + (radialSpeedDiv * vec3f(2.0) - vec3f(1.0)) * uniform.radialSpeedDivMult * rndFactor.xyz;\n localVelocity = localVelocity + (localVelocityDiv * vec3f(2.0) - vec3f(1.0)) * uniform.localVelocityDivMult * rndFactor.xyz;\n velocity = velocity + (velocityDiv * vec3f(2.0) - vec3f(1.0)) * uniform.velocityDivMult * rndFactor.xyz;\n rotSpeed = rotSpeed + (rotSpeedDiv * 2.0 - 1.0) * uniform.rotSpeedDivMult * rndFactor.y;\n addInitialVelocity(&localVelocity, rndFactor.xyz);\n #ifndef LOCAL_SPACE\n outVel = uniform.emitterMatrix * localVelocity + (radialVel + velocity) * uniform.emitterScale;\n #else\n outVel = (localVelocity + radialVel) / uniform.emitterScale + uniform.emitterMatrixInv * velocity;\n #endif\n outPos = inPos + outVel * uniform.delta;\n outAngle = inAngle + rotSpeed * uniform.delta;\n",particle_billboardVS:"\n let rotationResult = rotateWithMatrix(quadXY, inAngle);\n let rotatedQuadXY = rotationResult.rotatedVec;\n rotMatrix = rotationResult.matrix;\n var localPos = billboard(particlePos, rotatedQuadXY);\n",particle_blendAddPS:"\n dBlendModeFogFactor = 0.0;\n rgb = rgb * saturate(gammaCorrectInput(max(a, 0.0)));\n if ((rgb.r + rgb.g + rgb.b) < 0.000001) {\n discard;\n } \n",particle_blendMultiplyPS:"\n rgb = mix(vec3f(1.0), rgb, a);\n if ((rgb.r + rgb.g + rgb.b) > 2.99) {\n discard;\n }\n",particle_blendNormalPS:"\n if (a < 0.01) {\n discard;\n }\n",particle_cpuVS:"\nattribute particle_vertexData: vec4f;\nattribute particle_vertexData2: vec4f;\nattribute particle_vertexData3: vec4f;\nattribute particle_vertexData4: f32;\n#ifndef USE_MESH\n attribute particle_vertexData5: vec2f;\n#else\n attribute particle_vertexData5: vec4f;\n#endif\nuniform matrix_viewProjection: mat4x4f;\nuniform matrix_model: mat4x4f;\n#ifndef VIEWMATRIX\n #define VIEWMATRIX\n uniform matrix_view: mat4x4f;\n#endif\nuniform matrix_normal: mat3x3f;\nuniform matrix_viewInverse: mat4x4f;\nuniform numParticles: f32;\nuniform lifetime: f32;\nuniform stretch: f32;\nuniform seed: f32;\nuniform wrapBounds: vec3f;\nuniform emitterScale: vec3f;\nuniform faceTangent: vec3f;\nuniform faceBinorm: vec3f;\n#ifdef PARTICLE_GPU\n var internalTex0: texture_2d;\n var internalTex0Sampler: sampler;\n var internalTex1: texture_2d;\n var internalTex1Sampler: sampler;\n var internalTex2: texture_2d;\n var internalTex2Sampler: sampler;\n#endif\nuniform emitterPos: vec3f;\nvarying texCoordsAlphaLife: vec4f;\nstruct RotateResult {\n rotatedVec: vec2f,\n matrix: mat2x2f\n}\nfn rotateWithMatrix(quadXY: vec2f, pRotation: f32) -> RotateResult {\n let c = cos(pRotation);\n let s = sin(pRotation);\n let m = mat2x2f(vec2f(c, s), vec2f(-s, c));\n return RotateResult(m * quadXY, m);\n}\nfn billboard(InstanceCoords: vec3f, quadXY: vec2f) -> vec3f {\n let pos = -uniform.matrix_viewInverse[0].xyz * quadXY.x + -uniform.matrix_viewInverse[1].xyz * quadXY.y;\n return pos;\n}\nfn customFace(InstanceCoords: vec3f, quadXY: vec2f) -> vec3f {\n let pos = uniform.faceTangent * quadXY.x + uniform.faceBinorm * quadXY.y;\n return pos;\n}\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n var particlePos = input.particle_vertexData.xyz;\n let inPos = particlePos;\n let vertPos = input.particle_vertexData3.xyz;\n var inVel = vec3f(input.particle_vertexData2.w, input.particle_vertexData3.w, input.particle_vertexData5.x);\n let id = floor(input.particle_vertexData4);\n let rndFactor = fract(sin(id + 1.0 + uniform.seed));\n let rndFactor3 = vec3f(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));\n #ifdef LOCAL_SPACE\n let modelRotation = mat3x3f(uniform.matrix_model[0].xyz, uniform.matrix_model[1].xyz, uniform.matrix_model[2].xyz);\n inVel = modelRotation * inVel;\n #endif\n let velocityV = safeNormalize((mat3x3f(uniform.matrix_view[0].xyz, uniform.matrix_view[1].xyz, uniform.matrix_view[2].xyz) * inVel).xy);\n let quadXY = vertPos.xy;\n #ifdef USE_MESH\n output.texCoordsAlphaLife = vec4f(input.particle_vertexData5.zw, input.particle_vertexData2.z, input.particle_vertexData.w);\n #else\n output.texCoordsAlphaLife = vec4f(quadXY * -0.5 + 0.5, input.particle_vertexData2.z, input.particle_vertexData.w);\n #endif\n var rotMatrix: mat2x2f;\n let inAngle = input.particle_vertexData2.x;\n var particlePosMoved = vec3f(0.0);\n let meshLocalPos = input.particle_vertexData3.xyz;\n",particle_cpu_endVS:"\n localPos = localPos * input.particle_vertexData2.y * emitterScale;\n localPos = localPos + particlePos;\n output.position = uniform.matrix_viewProjection * vec4f(localPos, 1.0);\n",particle_customFaceVS:"\n let rotationResult = rotateWithMatrix(quadXY, inAngle);\n let rotatedQuadXY = rotationResult.rotatedVec;\n rotMatrix = rotationResult.matrix;\n var localPos = customFace(particlePos, rotatedQuadXY);\n",particle_endPS:"\n rgb = addFog(rgb);\n rgb = toneMap(rgb);\n rgb = gammaCorrectOutput(rgb);\n output.color = vec4f(rgb, a);\n return output;\n}\n",particle_endVS:"\n localPos = localPos * scale * uniform.emitterScale;\n localPos = localPos + particlePos;\n #ifdef SCREEN_SPACE\n output.position = vec4f(localPos.x, localPos.y, 0.0, 1.0);\n #else\n output.position = uniform.matrix_viewProjection * vec4f(localPos.xyz, 1.0);\n #endif\n",particle_halflambertPS:"\n var negNormal: vec3f = normal * 0.5 + 0.5;\n var posNormal: vec3f = -normal * 0.5 + 0.5;\n negNormal = negNormal * negNormal;\n posNormal = posNormal * posNormal;\n",particle_initVS:"\nattribute particle_vertexData: vec4f;\n#if defined(USE_MESH)\n #if defined(USE_MESH_UV)\n attribute particle_uv: vec2f;\n #else\n var particle_uv: vec2f = vec2f(0.0, 0.0);\n #endif\n#endif\nuniform matrix_viewProjection: mat4x4f;\nuniform matrix_model: mat4x4f;\nuniform matrix_normal: mat3x3f;\nuniform matrix_viewInverse: mat4x4f;\n#ifndef VIEWMATRIX\n #define VIEWMATRIX\n uniform matrix_view: mat4x4f;\n#endif\nuniform numParticles: f32;\nuniform numParticlesPot: f32;\nuniform graphSampleSize: f32;\nuniform graphNumSamples: f32;\nuniform stretch: f32;\nuniform wrapBounds: vec3f;\nuniform emitterScale: vec3f;\nuniform emitterPos: vec3f;\nuniform faceTangent: vec3f;\nuniform faceBinorm: vec3f;\nuniform rate: f32;\nuniform rateDiv: f32;\nuniform lifetime: f32;\nuniform deltaRandomnessStatic: f32;\nuniform scaleDivMult: f32;\nuniform alphaDivMult: f32;\nuniform seed: f32;\nuniform delta: f32;\nvar particleTexOUT: texture_2d;\nvar particleTexOUTSampler: sampler;\nvar particleTexIN: texture_2d;\nvar particleTexINSampler: sampler;\n#ifdef PARTICLE_GPU\n var internalTex0: texture_2d;\n var internalTex0Sampler: sampler;\n var internalTex1: texture_2d;\n var internalTex1Sampler: sampler;\n var internalTex2: texture_2d;\n var internalTex2Sampler: sampler;\n#endif\n#ifndef CAMERAPLANES\n #define CAMERAPLANES\n uniform camera_params: vec4f;\n#endif\nvarying texCoordsAlphaLife: vec4f;\nvar inPos: vec3f;\nvar inVel: vec3f;\nvar inAngle: f32;\nvar inShow: bool;\nvar inLife: f32;\n",particle_lambertPS:"\n var negNormal: vec3f = max(normal, vec3(0.0));\n var posNormal: vec3f = max(-normal, vec3(0.0));\n",particle_lightingPS:"\n let light: vec3f = negNormal.x * uniform.lightCube[0] + posNormal.x * uniform.lightCube[1] +\n negNormal.y * uniform.lightCube[2] + posNormal.y * uniform.lightCube[3] +\n negNormal.z * uniform.lightCube[4] + posNormal.z * uniform.lightCube[5];\n rgb = rgb * light;\n",particle_localShiftVS:"\nparticlePos = (uniform.matrix_model * vec4f(particlePos, 1.0)).xyz;\n",particle_meshVS:"\nvar localPos = meshLocalPos;\nlet rotResultXY = rotateWithMatrix(localPos.xy, inAngle);\nlocalPos = vec3f(rotResultXY.rotatedVec, localPos.z);\nrotMatrix = rotResultXY.matrix;\nlet rotResultYZ = rotateWithMatrix(localPos.yz, inAngle);\nlocalPos = vec3f(localPos.x, rotResultYZ.rotatedVec);\nrotMatrix = rotResultYZ.matrix;\nbillboard(particlePos, quadXY);\n",particle_normalVS:"\noutput.Normal = normalize(localPos + uniform.matrix_viewInverse[2].xyz);\n",particle_normalMapPS:"\n let sampledNormal: vec4f = textureSample(normalMap, normalMapSampler, vec2f(input.texCoordsAlphaLife.x, 1.0 - input.texCoordsAlphaLife.y));\n let normalMap: vec3f = normalize(sampledNormal.xyz * 2.0 - 1.0);\n let ParticleMat = mat3x3(ParticleMat0, ParticleMat1, ParticleMat2);\n let normal: vec3f = ParticleMat * normalMap;\n",particle_pointAlongVS:"\n inAngle = atan2(velocityV.x, velocityV.y);\n",particle_simulationPS:'\n #include "particleUpdaterInitPS"\n #ifdef PACK8\n #include "particleInputRgba8PS"\n #include "particleOutputRgba8PS"\n #else\n #include "particleInputFloatPS"\n #include "particleOutputFloatPS"\n #endif\n #ifdef EMITTERSHAPE_BOX\n #include "particleUpdaterAABBPS"\n #else\n #include "particleUpdaterSpherePS"\n #endif\n #include "particleUpdaterStartPS"\n #ifdef RESPAWN\n #include "particleUpdaterRespawnPS"\n #endif\n #ifdef NO_RESPAWN\n #include "particleUpdaterNoRespawnPS"\n #endif\n #ifdef ON_STOP\n #include "particleUpdaterOnStopPS"\n #endif\n #include "particleUpdaterEndPS"\n',particle_shaderPS:'\n #if NORMAL != NONE\n #if NORMAL == VERTEX\n varying Normal: vec3f;\n #endif\n #if NORMAL == MAP\n varying ParticleMat0: vec3f;\n varying ParticleMat1: vec3f;\n varying ParticleMat2: vec3f;\n #endif\n uniform lightCube: array;\n #endif\n #ifdef SOFT\n varying vDepth: f32;\n #include "screenDepthPS"\n #endif\n #include "gammaPS"\n #include "tonemappingPS"\n #include "fogPS"\n #if NORMAL == MAP\n var normalMap: texture_2d;\n var normalMapSampler: sampler;\n #endif\n #include "particlePS"\n #ifdef SOFT\n #include "particle_softPS"\n #endif\n #if NORMAL == VERTEX\n var normal: vec3f = Normal;\n #endif\n #if NORMAL == MAP\n #include "particle_normalMapPS"\n #endif\n #if NORMAL != NONE\n #ifdef HALF_LAMBERT\n #include "particle_halflambertPS"\n #else\n #include "particle_lambertPS"\n #endif\n #include "particle_lightingPS"\n #endif\n #if BLEND == NORMAL\n #include "particle_blendNormalPS"\n #elif BLEND == ADDITIVE\n #include "particle_blendAddPS"\n #elif BLEND == MULTIPLICATIVE\n #include "particle_blendMultiplyPS"\n #endif\n #include "particle_endPS"\n',particle_shaderVS:'\n #ifdef ANIMTEX\n uniform animTexTilesParams: vec2f;\n uniform animTexParams: vec4f;\n uniform animTexIndexParams: vec2f;\n #endif\n #if NORMAL == MAP\n varying ParticleMat0: vec3f;\n varying ParticleMat1: vec3f;\n varying ParticleMat2: vec3f;\n #endif\n #if NORMAL == VERTEX\n varying Normal: vec3f;\n #endif\n #ifdef SOFT\n varying vDepth: f32;\n #endif\n #ifdef PARTICLE_GPU\n #include "particle_initVS"\n #ifdef PACK8\n #include "particleInputRgba8PS"\n #else\n #include "particleInputFloatPS"\n #endif\n #ifdef SOFT\n #include "screenDepthPS"\n #endif\n #include "particleVS"\n #else\n #ifdef SOFT\n #include "screenDepthPS"\n #endif\n #include "particle_cpuVS"\n #endif\n #ifdef LOCAL_SPACE\n #include "particle_localShiftVS"\n #endif\n #ifdef ANIMTEX\n #ifdef ANIMTEX_LOOP\n #include "particleAnimFrameLoopVS"\n #else\n #include "particleAnimFrameClampVS"\n #endif\n #include "particleAnimTexVS"\n #endif\n #ifdef PARTICLE_GPU\n #ifdef WRAP\n #include "particle_wrapVS"\n #endif\n #endif\n #ifdef ALIGN_TO_MOTION\n #include "particle_pointAlongVS"\n #endif\n #ifdef USE_MESH\n #include "particle_meshVS"\n #else\n #ifdef CUSTOM_FACE\n #include "particle_customFaceVS"\n #else\n #include "particle_billboardVS"\n #endif\n #endif\n #if NORMAL == VERTEX\n #include "particle_normalVS"\n #endif\n #if NORMAL == MAP\n #include "particle_TBNVS"\n #endif\n #ifdef STRETCH\n #include "particle_stretchVS"\n #endif\n #ifdef PARTICLE_GPU\n #include "particle_endVS"\n #else\n #include "particle_cpu_endVS"\n #endif\n #ifdef SOFT\n #include "particle_softVS"\n #endif\n return output;\n}\n',particle_softPS:"\n var depth: f32 = getLinearScreenDepthFrag();\n var particleDepth: f32 = vDepth;\n var depthDiff: f32 = saturate(abs(particleDepth - depth) * uniform.softening);\n a = a * depthDiff;\n",particle_softVS:"\n output.vDepth = getLinearDepth(localPos);\n",particle_stretchVS:"\n let moveDir: vec3f = inVel * uniform.stretch;\n var posPrev: vec3f = particlePos - moveDir;\n posPrev = posPrev + particlePosMoved;\n let viewRotationTemp: mat3x3f = mat3x3f(uniform.matrix_view[0].xyz, uniform.matrix_view[1].xyz, uniform.matrix_view[2].xyz);\n let centerToVertexV: vec2f = normalize((viewRotationTemp * localPos).xy);\n let interpolation: f32 = dot(-velocityV, centerToVertexV) * 0.5 + 0.5;\n particlePos = mix(particlePos, posPrev, interpolation);\n",particle_TBNVS:"\n let rot3 = mat3x3f(\n vec3f(rotMatrix[0][0], rotMatrix[1][0], 0.0),\n vec3f(rotMatrix[0][1], rotMatrix[1][1], 0.0),\n vec3f(0.0, 0.0, 1.0)\n );\n let viewBasis = mat3x3f(\n -uniform.matrix_viewInverse[0].xyz,\n -uniform.matrix_viewInverse[1].xyz,\n uniform.matrix_viewInverse[2].xyz\n );\n let tempMat = viewBasis * rot3;\n output.ParticleMat0 = tempMat[0];\n output.ParticleMat1 = tempMat[1];\n output.ParticleMat2 = tempMat[2];\n",particle_wrapVS:"\n let origParticlePos: vec3f = particlePos;\n particlePos = particlePos - uniform.matrix_model[3].xyz;\n particlePos = (particlePos % uniform.wrapBounds) - uniform.wrapBounds * 0.5;\n particlePos = particlePos + uniform.matrix_model[3].xyz;\n particlePosMoved = particlePos - origParticlePos;\n"};function yl(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?!!t[Symbol.hasInstance](e):i(e,t)}function yu(e,t){return (yu=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var yc=["enabled","autoPlay","numParticles","lifetime","rate","rate2","startAngle","startAngle2","loop","preWarm","lighting","halfLambert","intensity","depthWrite","noFog","depthSoftening","sort","blendType","stretch","alignToMotion","emitterShape","emitterExtents","emitterExtentsInner","emitterRadius","emitterRadiusInner","initialVelocity","wrap","wrapBounds","localSpace","screenSpace","colorMapAsset","normalMapAsset","mesh","meshAsset","renderAsset","orientation","particleNormal","localVelocityGraph","localVelocityGraph2","velocityGraph","velocityGraph2","rotationSpeedGraph","rotationSpeedGraph2","radialSpeedGraph","radialSpeedGraph2","scaleGraph","scaleGraph2","colorGraph","colorGraph2","alphaGraph","alphaGraph2","colorMap","normalMap","animTilesX","animTilesY","animStartFrame","animNumFrames","animNumAnimations","animIndex","randomizeAnimIndex","animSpeed","animLoop","layers"],yh=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this,t)||this).id="particlesystem",n.ComponentType=yr,n.DataType=ys,n.schema=yc,n.propertyTypes={emitterExtents:"vec3",emitterExtentsInner:"vec3",particleNormal:"vec3",wrapBounds:"vec3",localVelocityGraph:"curveset",localVelocityGraph2:"curveset",velocityGraph:"curveset",velocityGraph2:"curveset",colorGraph:"curveset",colorGraph2:"curveset",alphaGraph:"curve",alphaGraph2:"curve",rotationSpeedGraph:"curve",rotationSpeedGraph2:"curve",radialSpeedGraph:"curve",radialSpeedGraph2:"curve",scaleGraph:"curve",scaleGraph2:"curve"},n.on("beforeremove",n.onBeforeRemove,n),n.app.systems.on("update",n.onUpdate,n),o1.get(t.graphicsDevice,ns).add(ya),o1.get(t.graphicsDevice,na).add(yo),n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&yu(t,e);var n=t.prototype;return n.initializeComponentData=function(t,n,i){var r={};i=[];var s=this.propertyTypes;for(var a in (yl(n.mesh,pU)||"number"==typeof n.mesh)&&(n.meshAsset=n.mesh,delete n.mesh),n){if(n.hasOwnProperty(a)&&(i.push(a),r[a]=n[a]),"vec3"===s[a])Array.isArray(r[a])&&(r[a]=new eW(r[a][0],r[a][1],r[a][2]));else if("curve"===s[a]){if(!yl(r[a],eB)){var o=r[a].type;r[a]=new eB(r[a].keys),r[a].type=o;}}else if("curveset"===s[a]&&!yl(r[a],eU)){var l=r[a].type;r[a]=new eU(r[a].keys),r[a].type=l;}r.layers&&Array.isArray(r.layers)&&(r.layers=r.layers.slice(0));}e.prototype.initializeComponentData.call(this,t,r,i);},n.cloneComponent=function(e,t){for(var n=e.particlesystem.data,i=this.schema,r={},s=0,a=i.length;s=u.fixedTimeStep&&(d=Math.floor(u.simTime/u.fixedTimeStep),u.simTime-=d*u.fixedTimeStep),d){d=Math.min(d,u.maxSubSteps);for(var p=0;p=0){var s=i[r];s.decRefCount(),0===s.refCount&&(i.splice(r,1),i.length||e._skinInstanceCache.delete(n),t&&(t.destroy(),s.skinInstance=null));}}}}},e}();yp._skinInstanceCache=new Map;var ym=function(){function e(e,t,n,i,r){this._evtLoadById=null,this._evtUnloadById=null,this._evtAddById=null,this._evtRemoveById=null,this._evtLoadByUrl=null,this._evtAddByUrl=null,this._evtRemoveByUrl=null,this.propertyName=e,this.parent=t,this._scope=r,this._registry=n,this.id=null,this.url=null,this.asset=null,this._onAssetLoad=i.load,this._onAssetAdd=i.add,this._onAssetRemove=i.remove,this._onAssetUnload=i.unload;}var t,n=e.prototype;return n._bind=function(){this.id&&(this._onAssetLoad&&(this._evtLoadById=this._registry.on("load:"+this.id,this._onLoad,this)),this._onAssetAdd&&(this._evtAddById=this._registry.once("add:"+this.id,this._onAdd,this)),this._onAssetRemove&&(this._evtRemoveById=this._registry.on("remove:"+this.id,this._onRemove,this)),this._onAssetUnload&&(this._evtUnloadById=this._registry.on("unload:"+this.id,this._onUnload,this))),this.url&&(this._onAssetLoad&&(this._evtLoadByUrl=this._registry.on("load:url:"+this.url,this._onLoad,this)),this._onAssetAdd&&(this._evtAddByUrl=this._registry.once("add:url:"+this.url,this._onAdd,this)),this._onAssetRemove&&(this._evtRemoveByUrl=this._registry.on("remove:url:"+this.url,this._onRemove,this)));},n._unbind=function(){var e,t,n,i,r,s,a;this.id&&(null==(e=this._evtLoadById)||e.off(),this._evtLoadById=null,null==(t=this._evtAddById)||t.off(),this._evtAddById=null,null==(n=this._evtRemoveById)||n.off(),this._evtRemoveById=null,null==(i=this._evtUnloadById)||i.off(),this._evtUnloadById=null),this.url&&(null==(r=this._evtLoadByUrl)||r.off(),this._evtLoadByUrl=null,null==(s=this._evtAddByUrl)||s.off(),this._evtAddByUrl=null,null==(a=this._evtRemoveByUrl)||a.off(),this._evtRemoveByUrl=null);},n._onLoad=function(e){this._onAssetLoad.call(this._scope,this.propertyName,this.parent,e);},n._onAdd=function(e){this.asset=e,this._onAssetAdd.call(this._scope,this.propertyName,this.parent,e);},n._onRemove=function(e){this._onAssetRemove.call(this._scope,this.propertyName,this.parent,e),this.asset=null;},n._onUnload=function(e){this._onAssetUnload.call(this._scope,this.propertyName,this.parent,e);},t=[{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();}}],function(e,t){for(var n=0;nthis.layers.indexOf(e.id)||e.addMeshInstances(this._meshInstances);},i.onLayerRemoved=function(e){0>this.layers.indexOf(e.id)||e.removeMeshInstances(this._meshInstances);},i.onEnable=function(){var e,t=this.system.app,n=t.scene,i=n.layers;this._rootBone&&this._cloneSkinInstances(),this._evtLayersChanged=n.on("set:layers",this.onLayersChanged,this),i&&(this._evtLayerAdded=i.on("add",this.onLayerAdded,this),this._evtLayerRemoved=i.on("remove",this.onLayerRemoved,this));var r="asset"===this._type;this._meshInstances&&this._meshInstances.length?this.addToLayers():r&&this.asset&&this._onRenderAssetAdded();for(var s=0;s=0&&(null==(e=t.batcher)||e.insert(ll.RENDER,this.batchGroupId,this.entity));},i.onDisable=function(){var e,t,n,i,r=this.system.app,s=r.scene.layers;null==(e=this._evtLayersChanged)||e.off(),this._evtLayersChanged=null,this._rootBone&&this._clearSkinInstances(),s&&(null==(t=this._evtLayerAdded)||t.off(),this._evtLayerAdded=null,null==(n=this._evtLayerRemoved)||n.off(),this._evtLayerRemoved=null),this._batchGroupId>=0&&(null==(i=r.batcher)||i.remove(ll.RENDER,this.batchGroupId,this.entity)),this.removeFromLayers();},i.hide=function(){if(this._meshInstances)for(var e=0;e=0&&(null==(t=this.system.app.batcher)||t.remove(ll.RENDER,this.batchGroupId,this.entity)),this.entity.enabled&&e>=0&&(null==(n=this.system.app.batcher)||n.insert(ll.RENDER,e,this.entity)),e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addToLayers(),this._batchGroupId=e;}}},{key:"material",get:function(){return this._material},set:function(e){if(this._material!==e&&(this._material=e,this._meshInstances&&"asset"!==this._type))for(var t=0;te.length){for(var t=e.length;tthis._pool.length)for(var t=this._pool.length;t=this._pool.length&&this._resize(2*this._pool.length),this._pool[this._count++]},t.freeAll=function(){this._count=0;},e}();function yw(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?!!t[Symbol.hasInstance](e):i(e,t)}function yA(e,t){return (yA=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var yC=new e0,yP=new e0,yI=new eW,yL=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(){var t;return t=e.apply(this,arguments)||this,t._angularDamping=0,t._angularFactor=new eW(1,1,1),t._angularVelocity=new eW,t._body=null,t._friction=.5,t._group=2,t._linearDamping=0,t._linearFactor=new eW(1,1,1),t._linearVelocity=new eW,t._mask=65533,t._mass=1,t._restitution=0,t._rollingFriction=0,t._simulationEnabled=false,t._type=vv,t}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&yA(t,e);var n,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.removeBody(this._body),this.system.destroyBody(this._body),this._body=null);var n=this._type===vg?this._mass:0;this._getEntityTransform(D);var i=this.system.createBody(n,e,D);if(i.setRestitution(this._restitution),i.setFriction(this._friction),i.setRollingFriction(this._rollingFriction),i.setDamping(this._linearDamping,this._angularDamping),this._type===vg){var r=this._linearFactor;R.setValue(r.x,r.y,r.z),i.setLinearFactor(R);var s=this._angularFactor;R.setValue(s.x,s.y,s.z),i.setAngularFactor(R);}else this._type===vy&&(i.setCollisionFlags(2|i.getCollisionFlags()),i.setActivationState(4));i.entity=t,this.body=i,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 vg:this.system._dynamic.push(this),t.forceActivationState(1),this.syncEntityToBody();break;case vy:this.system._kinematic.push(this),t.forceActivationState(4);break;case vv:t.forceActivationState(1),this.syncEntityToBody();}"compound"===e.collision.type&&this.system._compounds.push(e.collision),t.activate(),this._simulationEnabled=true;}}},i.disableSimulation=function(){var e=this._body;if(e&&this._simulationEnabled){var t=this.system,n=t._compounds.indexOf(this.entity.collision);n>-1&&t._compounds.splice(n,1),(n=t._dynamic.indexOf(this))>-1&&t._dynamic.splice(n,1),(n=t._kinematic.indexOf(this))>-1&&t._kinematic.splice(n,1),t.removeBody(e),e.forceActivationState(5),this._simulationEnabled=false;}},i.applyForce=function(e,t,n,i,r,s){var a=this._body;a&&(a.activate(),yw(e,eW)?R.setValue(e.x,e.y,e.z):R.setValue(e,t,n),yw(t,eW)?M.setValue(t.x,t.y,t.z):void 0!==i?M.setValue(i,r,s):M.setValue(0,0,0),a.applyForce(R,M));},i.applyTorque=function(e,t,n){var i=this._body;i&&(i.activate(),yw(e,eW)?R.setValue(e.x,e.y,e.z):R.setValue(e,t,n),i.applyTorque(R));},i.applyImpulse=function(e,t,n,i,r,s){var a=this._body;a&&(a.activate(),yw(e,eW)?R.setValue(e.x,e.y,e.z):R.setValue(e,t,n),yw(t,eW)?M.setValue(t.x,t.y,t.z):void 0!==i?M.setValue(i,r,s):M.setValue(0,0,0),a.applyImpulse(R,M));},i.applyTorqueImpulse=function(e,t,n){var i=this._body;i&&(i.activate(),yw(e,eW)?R.setValue(e.x,e.y,e.z):R.setValue(e,t,n),i.applyTorqueImpulse(R));},i.isStatic=function(){return this._type===vv},i.isStaticOrKinematic=function(){return this._type===vv||this._type===vy},i.isKinematic=function(){return this._type===vy},i._getEntityTransform=function(e){var t=this.entity,n=t.collision;if(n){var i=n.getShapePosition(),r=n.getShapeRotation();R.setValue(i.x,i.y,i.z),O.setValue(r.x,r.y,r.z,r.w);}else {var s=t.getPosition(),a=t.getRotation();R.setValue(s.x,s.y,s.z),O.setValue(a.x,a.y,a.z,a.w);}e.setOrigin(R),e.setRotation(O);},i.syncEntityToBody=function(){var e=this._body;if(e){if(this._getEntityTransform(D),e.setWorldTransform(D),this._type===vy){var t=e.getMotionState();t&&t.setWorldTransform(D);}e.activate();}},i._updateDynamic=function(){var e=this._body;if(e.isActive()){var t=e.getMotionState();if(t){var n=this.entity;t.getWorldTransform(D);var i=D.getOrigin(),r=D.getRotation(),s=n.collision;if(s&&s._hasOffset){var a=s.data.linearOffset,o=s.data.angularOffset,l=yP.copy(o).invert(),u=yC.set(r.x(),r.y(),r.z(),r.w()).mul(l);u.transformVector(a,yI),n.setPosition(i.x()-yI.x,i.y()-yI.y,i.z()-yI.z),n.setRotation(u);}else n.setPosition(i.x(),i.y(),i.z()),n.setRotation(r.x(),r.y(),r.z(),r.w());}}},i._updateKinematic=function(){var e=this._body.getMotionState();e&&(this._getEntityTransform(D),e.setWorldTransform(D));},i.teleport=function(e,t,n,i,r,s){yw(e,eW)?this.entity.setPosition(e):this.entity.setPosition(e,t,n),yw(t,e0)?this.entity.setRotation(t):yw(t,eW)?this.entity.setEulerAngles(t):void 0!==i&&this.entity.setEulerAngles(i,r,s),this.syncEntityToBody();},i.onEnable=function(){this._body||this.createBody(),this.enableSimulation();},i.onDisable=function(){this.disableSimulation();},t.onLibraryLoaded=function(){"undefined"!=typeof Ammo&&(D=new Ammo.btTransform,R=new Ammo.btVector3,M=new Ammo.btVector3,O=new Ammo.btQuaternion);},t.onAppDestroy=function(){Ammo.destroy(D),Ammo.destroy(R),Ammo.destroy(M),Ammo.destroy(O),D=null,R=null,M=null,O=null;},n=[{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===vg&&(R.setValue(e.x,e.y,e.z),this._body.setAngularFactor(R)));}},{key:"angularVelocity",get:function(){if(this._body&&this._type===vg){var e=this._body.getAngularVelocity();this._angularVelocity.set(e.x(),e.y(),e.z());}return this._angularVelocity},set:function(e){this._body&&this._type===vg&&(this._body.activate(),R.setValue(e.x,e.y,e.z),this._body.setAngularVelocity(R),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===vg&&(R.setValue(e.x,e.y,e.z),this._body.setLinearFactor(R)));}},{key:"linearVelocity",get:function(){if(this._body&&this._type===vg){var e=this._body.getLinearVelocity();this._linearVelocity.set(e.x(),e.y(),e.z());}return this._linearVelocity},set:function(e){this._body&&this._type===vg&&(this._body.activate(),R.setValue(e.x,e.y,e.z),this._body.setLinearVelocity(R),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===vg)){var t=this.enabled&&this.entity.enabled;t&&this.disableSimulation(),this._body.getCollisionShape().calculateLocalInertia(e,R),this._body.setMassProps(e,R),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 vg:this._group=1,this._mask=65535;break;case vy:this._group=4,this._mask=65535;break;default:this._group=2,this._mask=65533;}this.createBody();}}}],function(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(["mass","linearDamping","angularDamping","linearFactor","angularFactor","friction","rollingFriction","restitution","type","group","mask"]);!(r=s()).done;){var a=r.value;if(n.hasOwnProperty(a)){var o=n[a];Array.isArray(o)?t[a]=new eW(o[0],o[1],o[2]):t[a]=o;}}e.prototype.initializeComponentData.call(this,t,n,["enabled"]);},n.cloneComponent=function(e,t){var n=e.rigidbody,i={enabled:n.enabled,mass:n.mass,linearDamping:n.linearDamping,angularDamping:n.angularDamping,linearFactor:[n.linearFactor.x,n.linearFactor.y,n.linearFactor.z],angularFactor:[n.angularFactor.x,n.angularFactor.y,n.angularFactor.z],friction:n.friction,rollingFriction:n.rollingFriction,restitution:n.restitution,type:n.type,group:n.group,mask:n.mask};return this.addComponent(t,i)},n.onBeforeRemove=function(e,t){t.enabled&&(t.enabled=false),t.body&&(this.destroyBody(t.body),t.body=null);},n.addBody=function(e,t,n){ void 0!==t&&void 0!==n?this.dynamicsWorld.addRigidBody(e,t,n):this.dynamicsWorld.addRigidBody(e);},n.removeBody=function(e){this.dynamicsWorld.removeRigidBody(e);},n.createBody=function(e,t,n){var i=new Ammo.btVector3(0,0,0);0!==e&&t.calculateLocalInertia(e,i);var r=new Ammo.btDefaultMotionState(n),s=new Ammo.btRigidBodyConstructionInfo(e,r,t,i),a=new Ammo.btRigidBody(s);return Ammo.destroy(s),Ammo.destroy(i),a},n.destroyBody=function(e){var t=e.getMotionState();t&&Ammo.destroy(t),Ammo.destroy(e);},n.raycastFirst=function(e,t,n){if(void 0===n&&(n={}),n.filterTags||n.filterCallback)return n.sort=true,this.raycastAll(e,t,n)[0]||null;var i=null;k.setValue(e.x,e.y,e.z),N.setValue(t.x,t.y,t.z);var r=new Ammo.ClosestRayResultCallback(k,N);if("number"==typeof n.filterCollisionGroup&&r.set_m_collisionFilterGroup(n.filterCollisionGroup),"number"==typeof n.filterCollisionMask&&r.set_m_collisionFilterMask(n.filterCollisionMask),this.dynamicsWorld.rayTest(k,N,r),r.hasHit()){var s=r.get_m_collisionObject(),a=Ammo.castObject(s,Ammo.btRigidBody);if(a){var o=r.get_m_hitPointWorld(),l=r.get_m_hitNormalWorld();i=new yO(a.entity,new eW(o.x(),o.y(),o.z()),new eW(l.x(),l.y(),l.z()),r.get_m_closestHitFraction());}}return Ammo.destroy(r),i},n.raycastAll=function(e,t,n){ void 0===n&&(n={});var i=[];k.setValue(e.x,e.y,e.z),N.setValue(t.x,t.y,t.z);var r=new Ammo.AllHitsRayResultCallback(k,N);if("number"==typeof n.filterCollisionGroup&&r.set_m_collisionFilterGroup(n.filterCollisionGroup),"number"==typeof n.filterCollisionMask&&r.set_m_collisionFilterMask(n.filterCollisionMask),this.dynamicsWorld.rayTest(k,N,r),r.hasHit()){for(var s=r.get_m_collisionObjects(),a=r.get_m_hitPointWorld(),o=r.get_m_hitNormalWorld(),l=r.get_m_hitFractions(),u=s.size(),c=0;cthis.collisions[i].others.indexOf(t)&&(this.collisions[i].others.push(t),n=true),this.frameCollisions[i]=this.frameCollisions[i]||{others:[],entity:e},this.frameCollisions[i].others.push(t),n},n._createContactPointFromAmmo=function(e){var t=e.get_m_localPointA(),n=e.get_m_localPointB(),i=e.getPositionWorldOnA(),r=e.getPositionWorldOnB(),s=e.get_m_normalWorldOnB(),a=this.contactPointPool.allocate();return a.localPoint.set(t.x(),t.y(),t.z()),a.localPointOther.set(n.x(),n.y(),n.z()),a.point.set(i.x(),i.y(),i.z()),a.pointOther.set(r.x(),r.y(),r.z()),a.normal.set(s.x(),s.y(),s.z()),a.impulse=e.getAppliedImpulse(),a},n._createReverseContactPointFromAmmo=function(e){var t=e.get_m_localPointA(),n=e.get_m_localPointB(),i=e.getPositionWorldOnA(),r=e.getPositionWorldOnB(),s=e.get_m_normalWorldOnB(),a=this.contactPointPool.allocate();return a.localPointOther.set(t.x(),t.y(),t.z()),a.localPoint.set(n.x(),n.y(),n.z()),a.pointOther.set(i.x(),i.y(),i.z()),a.point.set(r.x(),r.y(),r.z()),a.normal.set(s.x(),s.y(),s.z()),a.impulse=e.getAppliedImpulse(),a},n._createSingleContactResult=function(e,t,n){var i=this.singleContactResultPool.allocate();return i.a=e,i.b=t,i.localPointA=n.localPoint,i.localPointB=n.localPointOther,i.pointA=n.point,i.pointB=n.pointOther,i.normal=n.normal,i.impulse=n.impulse,i},n._createContactResult=function(e,t){var n=this.contactResultPool.allocate();return n.other=e,n.contacts=t,n},n._cleanOldCollisions=function(){for(var e in this.collisions)if(this.collisions.hasOwnProperty(e)){for(var t=this.frameCollisions[e],n=this.collisions[e],i=n.entity,r=i.collision,s=i.rigidbody,a=n.others,o=a.length;o--;){var l=a[o];(!t||0>t.others.indexOf(l))&&(a.splice(o,1),i.trigger?(r&&r.fire("triggerleave",l),l.rigidbody&&l.rigidbody.fire("triggerleave",i)):!l.trigger&&(s&&s.fire("collisionend",l),r&&r.fire("collisionend",l)));}0===a.length&&delete this.collisions[e];}},n._hasContactEvent=function(e){var t=e.collision;if(t&&(t.hasEvent("collisionstart")||t.hasEvent("collisionend")||t.hasEvent("contact")))return true;var n=e.rigidbody;return n&&(n.hasEvent("collisionstart")||n.hasEvent("collisionend")||n.hasEvent("contact"))},n._checkForCollisions=function(e,t){var n=Ammo.wrapPointer(e,Ammo.btDynamicsWorld).getDispatcher(),i=n.getNumManifolds();this.frameCollisions={};for(var r=0;r0)if(4&f||4&d){var g=c.collision&&(c.collision.hasEvent("triggerenter")||c.collision.hasEvent("triggerleave")),y=h.collision&&(h.collision.hasEvent("triggerenter")||h.collision.hasEvent("triggerleave")),S=c.rigidbody&&(c.rigidbody.hasEvent("triggerenter")||c.rigidbody.hasEvent("triggerleave")),x=h.rigidbody&&(h.rigidbody.hasEvent("triggerenter")||h.rigidbody.hasEvent("triggerleave"));g&&(v=this._storeCollision(c,h))&&!(4&d)&&c.collision.fire("triggerenter",h),y&&(v=this._storeCollision(h,c))&&!(4&f)&&h.collision.fire("triggerenter",c),S&&(v||(v=this._storeCollision(h,c)),v&&c.rigidbody.fire("triggerenter",h)),x&&(v||(v=this._storeCollision(c,h)),v&&h.rigidbody.fire("triggerenter",c));}else {var b=this._hasContactEvent(c),T=this._hasContactEvent(h),E=this.hasEvent("contact");if(E||b||T){for(var w=0;w=0&&r!==e.element.drawOrder&&(null==(n=this.system.app.batcher)||n.markGroupDirty(e.element._batchGroupId));}e.particlesystem&&(e.particlesystem.drawOrder=t++);for(var s=e.children,a=0;a255&&(e=255),this._priority!==e&&(this._priority=e,this.syncDrawOrder());}}],function(e,t){for(var n=0;nthis.dragThreshold||Math.abs(n)>this.dragThreshold)&&this._disableContentInput();}},i._horizontalScrollbarEntitySubscribe=function(){this._evtHorizontalScrollbarAdd=this._horizontalScrollbarEntity.on("scrollbar:add",this._onHorizontalScrollbarGain,this),this._horizontalScrollbarEntity.scrollbar&&this._onHorizontalScrollbarGain();},i._verticalScrollbarEntitySubscribe=function(){this._evtVerticalScrollbarAdd=this._verticalScrollbarEntity.on("scrollbar:add",this._onVerticalScrollbarGain,this),this._verticalScrollbarEntity.scrollbar&&this._onVerticalScrollbarGain();},i._horizontalScrollbarEntityUnsubscribe=function(){var e;null==(e=this._evtHorizontalScrollbarAdd)||e.off(),this._evtHorizontalScrollbarAdd=null,this._horizontalScrollbarEntity.scrollbar&&this._onHorizontalScrollbarLose();},i._verticalScrollbarEntityUnsubscribe=function(){var e;null==(e=this._evtVerticalScrollbarAdd)||e.off(),this._evtVerticalScrollbarAdd=null,this._verticalScrollbarEntity.scrollbar&&this._onVerticalScrollbarLose();},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._onHorizontalScrollbarGain=function(){var e,t=null==(e=this._horizontalScrollbarEntity)?void 0:e.scrollbar;this._evtHorizontalScrollbarRemove=t.on("beforeremove",this._onHorizontalScrollbarLose,this),this._evtHorizontalScrollbarValue=t.on("set:value",this._onSetHorizontalScrollbarValue,this),this._syncScrollbarEnabledState(0),this._syncScrollbarPosition(0);},i._onVerticalScrollbarGain=function(){var e,t=null==(e=this._verticalScrollbarEntity)?void 0:e.scrollbar;this._evtVerticalScrollbarRemove=t.on("beforeremove",this._onVerticalScrollbarLose,this),this._evtVerticalScrollbarValue=t.on("set:value",this._onSetVerticalScrollbarValue,this),this._syncScrollbarEnabledState(1),this._syncScrollbarPosition(1);},i._onHorizontalScrollbarLose=function(){var e,t;null==(e=this._evtHorizontalScrollbarRemove)||e.off(),this._evtHorizontalScrollbarRemove=null,null==(t=this._evtHorizontalScrollbarValue)||t.off(),this._evtHorizontalScrollbarValue=null;},i._onVerticalScrollbarLose=function(){var e,t;null==(e=this._evtVerticalScrollbarRemove)||e.off(),this._evtVerticalScrollbarRemove=null,null==(t=this._evtVerticalScrollbarValue)||t.off(),this._evtVerticalScrollbarValue=null;},i._onSetHorizontalScrollingEnabled=function(){this._syncScrollbarEnabledState(0);},i._onSetVerticalScrollingEnabled=function(){this._syncScrollbarEnabledState(1);},i._onSetScroll=function(e,t,n){ false!==n&&this._velocity.set(0,0,0);var i=this._updateAxis(e,"x",0),r=this._updateAxis(t,"y",1);(i||r)&&this.fire("set:scroll",this._scroll);},i._updateAxis=function(e,t,n){var i=null!==e&&Math.abs(e-this._scroll[t])>1e-5;return (i||this._isDragging()||0===e)&&(this._scroll[t]=this._determineNewScrollValue(e,t,n),this._syncContentPosition(n),this._syncScrollbarPosition(n)),i},i._determineNewScrollValue=function(e,t,n){if(!this._getScrollingEnabled(n))return this._scroll[t];switch(this.scrollMode){case 0:return ek.clamp(e,0,this._getMaxScrollValue(n));case 1:return this._setVelocityFromOvershoot(e,t,n),e;default:return 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){if(this._contentEntity){var t=this._getAxis(e),n=this._getSign(e),i=this._prevContentSizes[e],r=this._getContentSize(e);if(null!==i&&Math.abs(i-r)>1e-4){var s=this._getMaxOffset(e,i),a=this._getMaxOffset(e,r);0===a?this._scroll[t]=1:this._scroll[t]=ek.clamp(this._scroll[t]*s/a,0,1);}var o=this._scroll[t]*this._getMaxOffset(e),l=this._contentEntity.getLocalPosition();l[t]=o*n,this._contentEntity.setLocalPosition(l),this._prevContentSizes[e]=r;}},i._syncScrollbarPosition=function(e){var t=this._scrollbarEntities[e];if(null==t?void 0:t.scrollbar){var n=this._getAxis(e);this._scrollbarUpdateFlags[e]=true,t.scrollbar.value=this._scroll[n],t.scrollbar.handleSize=this._getScrollbarHandleSize(n,e),this._scrollbarUpdateFlags[e]=false;}},i._syncScrollbarEnabledState=function(e){var t=this._scrollbarEntities[e];if(t){var n=this._getScrollingEnabled(e);switch(this._getScrollbarVisibility(e)){case 0:t.enabled=n;return;case 1:t.enabled=n&&this._contentIsLargerThanViewport(e);return;default:t.enabled=n;}}},i._contentIsLargerThanViewport=function(e){return this._getContentSize(e)>this._getViewportSize(e)},i._contentPositionToScrollValue=function(e){var t=this._getMaxOffset(0),n=this._getMaxOffset(1);return 0===t?y9.x=0:y9.x=e.x/t,0===n?y9.y=0:y9.y=-(e.y/n),y9},i._getMaxOffset=function(e,t){t=void 0===t?this._getContentSize(e):t;var n=this._getViewportSize(e);return tMath.abs(i))return 1;var r=Math.min(n/i,1),s=this._toOvershoot(this._scroll[e],t);return 0===s?r:r/(1+Math.abs(s))},i._getViewportSize=function(e){return this._getSize(e,this._viewportEntity)},i._getContentSize=function(e){return this._getSize(e,this._contentEntity)},i._getSize=function(e,t){return (null==t?void 0:t.element)?t.element[this._getCalculatedDimension(e)]:0},i._getScrollingEnabled=function(e){return 0===e?this.horizontal:1===e?this.vertical:void 0},i._getScrollbarVisibility=function(e){return 0===e?this.horizontalScrollbarVisibility:1===e?this.verticalScrollbarVisibility:void 0},i._getSign=function(e){return 0===e?1:-1},i._getAxis=function(e){return 0===e?"x":"y"},i._getCalculatedDimension=function(e){return 0===e?"calculatedWidth":"calculatedHeight"},i._destroyDragHelper=function(){this._contentDragHelper&&this._contentDragHelper.destroy();},i.onUpdate=function(){this._contentEntity&&(this._updateVelocity(),this._syncScrollbarEnabledState(0),this._syncScrollbarEnabledState(1));},i._updateVelocity=function(){if(!this._isDragging()){if(1===this.scrollMode&&(this._hasOvershoot("x",0)&&this._setVelocityFromOvershoot(this.scroll.x,"x",0),this._hasOvershoot("y",1)&&this._setVelocityFromOvershoot(this.scroll.y,"y",1)),Math.abs(this._velocity.x)>1e-4||Math.abs(this._velocity.y)>1e-4){var e=this._contentEntity.getLocalPosition();e.x+=this._velocity.x,e.y+=this._velocity.y,this._contentEntity.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 n=this._getMaxScrollValue(t);return e<0?e:e>n?e-n:0},i._setVelocityFromOvershoot=function(e,t,n){var i=this._toOvershoot(e,n)*this._getMaxOffset(n)*this._getSign(n);Math.abs(i)>0&&(this._velocity[t]=-i/(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,false);},i._applyScrollValueTension=function(e){var t=this._getMaxScrollValue(0),n=this._toOvershoot(e.x,0);return n>0?e.x=t+ +Math.log10(1+n):n<0&&(e.x=-1*Math.log10(1-n)),t=this._getMaxScrollValue(1),(n=this._toOvershoot(e.y,1))>0?e.y=t+ +Math.log10(1+n):n<0&&(e.y=-1*Math.log10(1-n)),e},i._isDragging=function(){return this._contentDragHelper&&this._contentDragHelper.isDragging},i._setScrollbarComponentsEnabled=function(e){var t,n;(null==(t=this._horizontalScrollbarEntity)?void 0:t.scrollbar)&&(this._horizontalScrollbarEntity.scrollbar.enabled=e),(null==(n=this._verticalScrollbarEntity)?void 0:n.scrollbar)&&(this._verticalScrollbarEntity.scrollbar.enabled=e);},i._setContentDraggingEnabled=function(e){this._contentDragHelper&&(this._contentDragHelper.enabled=e);},i._onMouseWheel=function(e){if(this.useMouseWheel&&(null==(t=this._contentEntity)?void 0:t.element)){var t,n=e.event,i=n.deltaX/this._contentEntity.element.calculatedWidth*this.mouseWheelSensitivity.x,r=n.deltaY/this._contentEntity.element.calculatedHeight*this.mouseWheelSensitivity.y,s=ek.clamp(this._scroll.x+i,0,this._getMaxScrollValue(0)),a=ek.clamp(this._scroll.y+r,0,this._getMaxScrollValue(1));this.scroll=new eX(s,a);}},i._enableContentInput=function(){for(;this._disabledContentInputEntities.length;){var e=this._disabledContentInputEntities.pop();e.element&&(e.element.useInput=true);}this._disabledContentInput=false;},i._disableContentInput=function(){var e=this,t=function(n){n.element&&n.element.useInput&&(e._disabledContentInputEntities.push(n),n.element.useInput=false);for(var i=n.children,r=0,s=i.length;r1e-5&&(this.data.value=ek.clamp(n,0,1),this._updateHandlePositionAndSize(),this.fire("set:value",this.data.value));},r._onSetHandleSize=function(e,t,n){Math.abs(n-t)>1e-5&&(this.data.handleSize=ek.clamp(n,0,1),this._updateHandlePositionAndSize());},r._onSetHandleAlignment=function(){this._updateHandlePositionAndSize();},r._onSetOrientation=function(e,t,n){var i;n!==t&&(null==(i=this._handleEntity)?void 0:i.element)&&(this._handleEntity.element[this._getOppositeDimension()]=0);},r._updateHandlePositionAndSize=function(){var e=this._handleEntity,t=null==e?void 0:e.element;if(e){var n=e.getLocalPosition();n[this._getAxis()]=this._getHandlePosition(),e.setLocalPosition(n);}t&&(t[this._getDimension()]=this._getHandleLength());},r._handlePositionToScrollValue=function(e){return e*this._getSign()/this._getUsableTrackLength()},r._scrollValueToHandlePosition=function(e){return e*this._getSign()*this._getUsableTrackLength()},r._getUsableTrackLength=function(){return Math.max(this._getTrackLength()-this._getHandleLength(),.001)},r._getTrackLength=function(){return this.entity.element?0===this.orientation?this.entity.element.calculatedWidth:this.entity.element.calculatedHeight:0},r._getHandleLength=function(){return this._getTrackLength()*this.handleSize},r._getHandlePosition=function(){return this._scrollValueToHandlePosition(this.value)},r._getSign=function(){return 0===this.orientation?1:-1},r._getAxis=function(){return 0===this.orientation?"x":"y"},r._getDimension=function(){return 0===this.orientation?"width":"height"},r._getOppositeDimension=function(){return 0===this.orientation?"height":"width"},r._destroyDragHelper=function(){this._handleDragHelper&&this._handleDragHelper.destroy();},r._setHandleDraggingEnabled=function(e){this._handleDragHelper&&(this._handleDragHelper.enabled=e);},r.onEnable=function(){this._setHandleDraggingEnabled(true);},r.onDisable=function(){this._setHandleDraggingEnabled(false);},r.onRemove=function(){this._destroyDragHelper(),this._toggleLifecycleListeners("off");},r.resolveDuplicatedEntityReferenceProperties=function(e,t){e.handleEntity&&(this.handleEntity=t[e.handleEntity.getGuid()]);},n=[{key:"data",get:function(){var e=this.system.store[this.entity.getGuid()];return e?e.data:null}},{key:"enabled",get:function(){return this.data.enabled},set:function(e){this._setValue("enabled",e);}},{key:"orientation",get:function(){return this.data.orientation},set:function(e){this._setValue("orientation",e);}},{key:"value",get:function(){return this.data.value},set:function(e){this._setValue("value",e);}},{key:"handleSize",get:function(){return this.data.handleSize},set:function(e){this._setValue("handleSize",e);}},{key:"handleEntity",get:function(){return this._handleEntity},set:function(e){if(this._handleEntity!==e){var t="string"==typeof e;(!this._handleEntity||!t||this._handleEntity.getGuid()!==e)&&((this._handleEntity&&this._handleEntityUnsubscribe(),null!=us&&"undefined"!=typeof Symbol&&us[Symbol.hasInstance]?!!us[Symbol.hasInstance](e):i(e,us))?this._handleEntity=e:t?this._handleEntity=this.system.app.getEntityFromIndex(e)||null:this._handleEntity=null,this._handleEntity&&this._handleEntitySubscribe(),this._handleEntity?this.data.handleEntity=this._handleEntity.getGuid():t&&e&&(this.data.handleEntity=e));}}}],function(e,t){for(var n=0;n0?i.duration:null,r._startTime=Math.max(0,Number(i.startTime)||0),r._overlap=!!i.overlap,r._autoPlay=!!i.autoPlay,r._firstNode=null,r._lastNode=null,r._asset=i.asset,Sc(r._asset,pU)&&(r._asset=r._asset.id),r._onInstancePlayHandler=r._onInstancePlay.bind(r),r._onInstancePauseHandler=r._onInstancePause.bind(r),r._onInstanceResumeHandler=r._onInstanceResume.bind(r),r._onInstanceStopHandler=r._onInstanceStop.bind(r),r._onInstanceEndHandler=r._onInstanceEnd.bind(r),r}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&Sh(t,e);var n,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 n=e._playWhenLoaded;e.sound=t,n&&e.play();};this.off("load",t),this.once("load",t),this.load();}return e}},i.pause=function(){for(var e=false,t=this.instances,n=0,i=t.length;n=0;a--){var o=r[a].isPlaying||r[a].isSuspended,l=r[a].currentTime;o&&r[a].stop();var u=i._createInstance();o&&(u.play(),u.currentTime=l),r.push(u);}}}},{key:"slots",get:function(){return this._slots},set:function(e){var t,n=this._slots;if(n)for(var r in n)n[r].stop();var s={};for(var a in e)(t=e[a],null!=Sd&&"undefined"!=typeof Symbol&&Sd[Symbol.hasInstance]?!!Sd[Symbol.hasInstance](t):i(t,Sd))?s[e[a].name]=e[a]:e[a].name&&(s[e[a].name]=new Sd(this,e[a].name,e[a]));this._slots=s,this.enabled&&this.entity.enabled&&this.onEnable();}}],function(e,t){for(var n=0;ni||n<0;this._setTime(n);var s=this.frame;(s=this._sprite?Math.floor(this._sprite.frameKeys.length*this._time/i):0)!==this._frame&&this._setFrame(s),r&&(this.loop?(this.fire("loop"),this._component.fire("loop",this)):(this._playing=false,this._paused=false,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=ek.clamp(e,0,this._sprite.frameKeys.length-1):this._frame=e,this._component.currentClip===this&&this._component._showFrame(this._frame);},i._destroy=function(){if(this._spriteAsset){var e=this._component.system.app.assets;this._unbindSpriteAsset(e.get(this._spriteAsset));}this._sprite&&(this.sprite=null),this._spriteAsset&&(this.spriteAsset=null);},i.play=function(){this._playing||(this._playing=true,this._paused=false,this.frame=0,this.fire("play"),this._component.fire("play",this));},i.pause=function(){this._playing&&!this._paused&&(this._paused=true,this.fire("pause"),this._component.fire("pause",this));},i.resume=function(){this._paused&&(this._paused=false,this.fire("resume"),this._component.fire("resume",this));},i.stop=function(){this._playing&&(this._playing=false,this._paused=false,this._time=0,this.frame=0,this.fire("stop"),this._component.fire("stop",this));},n=[{key:"duration",get:function(){if(this._sprite){var e=this.fps||Number.MIN_VALUE;return this._sprite.frameKeys.length/Math.abs(e)}return 0}},{key:"frame",get:function(){return this._frame},set:function(e){this._setFrame(e);var t=this.fps||Number.MIN_VALUE;this._setTime(this._frame/t);}},{key:"isPaused",get:function(){return this._paused}},{key:"isPlaying",get:function(){return this._playing}},{key:"sprite",get:function(){return this._sprite},set:function(e){var t,n;this._sprite&&(null==(t=this._evtSetMeshes)||t.off(),this._evtSetMeshes=null,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._evtSetMeshes=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&&((n=this._component._meshInstance)&&(n.setParameter("texture_emissiveMap",e.atlas.texture),n.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):((n=this._component._meshInstance)&&(n.deleteParameter("texture_emissiveMap"),n.deleteParameter("texture_opacityMap")),this._component._hideModel()));}},{key:"spriteAsset",get:function(){return this._spriteAsset},set:function(e){var t=this._component.system.app.assets,n=e;if(Sb(e,pU)&&(n=e.id),this._spriteAsset!==n){if(this._spriteAsset){var i=t.get(this._spriteAsset);i&&this._unbindSpriteAsset(i);}if(this._spriteAsset=n,this._spriteAsset){var r=t.get(this._spriteAsset);r?this._bindSpriteAsset(r):(this.sprite=null,t.on("add:"+this._spriteAsset,this._onSpriteAssetAdded,this));}else this.sprite=null;}}},{key:"time",get:function(){return this._time},set:function(e){this._setTime(e),this._sprite?this.frame=Math.min(this._sprite.frameKeys.length-1,Math.floor(this._time*Math.abs(this.fps))):this.frame=0;}}],function(e,t){for(var n=0;n=0&&(null==(e=t.batcher)||e.insert(ll.SPRITE,this._batchGroupId,this.entity));},r.onDisable=function(){var e,t,n,i,r=this.system.app,s=r.scene.layers;null==(e=this._evtLayersChanged)||e.off(),this._evtLayersChanged=null,s&&(null==(t=this._evtLayerAdded)||t.off(),this._evtLayerAdded=null,null==(n=this._evtLayerRemoved)||n.off(),this._evtLayerRemoved=null),this.stop(),this._hideModel(),this._batchGroupId>=0&&(null==(i=r.batcher)||i.remove(ll.SPRITE,this._batchGroupId,this.entity));},r.onDestroy=function(){var e;for(var t in this._currentClip=null,this._defaultClip&&(this._defaultClip._destroy(),this._defaultClip=null),this._clips)this._clips[t]._destroy();this._clips=null,this._hideModel(),this._model=null,null==(e=this._node)||e.remove(),this._node=null,this._meshInstance&&(this._meshInstance.material=null,this._meshInstance.mesh=null,this._meshInstance=null);},r._showModel=function(){if(!this._addedModel&&this._meshInstance){for(var e=[this._meshInstance],t=0,n=this._layers.length;tthis.layers.indexOf(e.id))&&this._addedModel&&this.enabled&&this.entity.enabled&&this._meshInstance&&e.addMeshInstances([this._meshInstance]);},r._onLayerRemoved=function(e){this._meshInstance&&(0>this.layers.indexOf(e.id)||e.removeMeshInstances([this._meshInstance]));},r.removeModelFromLayers=function(){for(var e=0;e=0&&(null==(t=this.system.app.batcher)||t.remove(ll.SPRITE,i,this.entity)),this.entity.enabled&&e>=0?null==(n=this.system.app.batcher)||n.insert(ll.SPRITE,e,this.entity):i>=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=(null!=SE&&"undefined"!=typeof Symbol&&SE[Symbol.hasInstance]?!!SE[Symbol.hasInstance](e):i(e,SE))?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}}],function(e,t){for(var n=0;n=3&&this.size.set(e[0],e[1],e[2]);}}],function(e,t){for(var n=0;n=3&&e.size.set(t.size[0],t.size[1],t.size[2]));},n.cloneComponent=function(e,t){var n={enabled:e.zone.enabled,size:e.zone.size};return this.addComponent(t,n)},n._onBeforeRemove=function(e,t){t._onBeforeRemove();},t}(mV);mN._buildAccessors(SF.prototype,Sz);var SH=function(e,t){this.effect=e,this.inputTarget=t,this.outputTarget=null,this.name=e.constructor.name;},SW=function(){function e(e,t){this.app=e,this.camera=t,this.destinationRenderTarget=null,this.effects=[],this.enabled=false,this.depthTarget=null,t.on("set:rect",this.onCameraRectChanged,this);}var t=e.prototype;return t._allocateColorBuffer=function(e,t){var n,i,r=this.camera.rect,s=this.destinationRenderTarget,a=this.app.graphicsDevice,o=Math.floor(r.z*(null!=(n=null==s?void 0:s.width)?n:a.width)),l=Math.floor(r.w*(null!=(i=null==s?void 0:s.height)?i:a.height));return new nN(a,{name:t,format:e,width:o,height:l,mipmaps:false,minFilter:0,magFilter:0,addressU:1,addressV:1})},t._createOffscreenTarget=function(e,t){var n,i,r=this.app.graphicsDevice,s=(null!=(n=this.destinationRenderTarget)?n:r.backBuffer).isColorBufferSrgb(0),a=null!=(i=t&&r.getRenderableHdrFormat([12,14],true))?i:s?20:7,o=this.camera.entity.name+"-posteffect-"+this.effects.length;return new ic({colorBuffer:this._allocateColorBuffer(a,o),depth:e,stencil:e&&this.app.graphicsDevice.supportsStencil,samples:e?r.samples:1})},t._resizeOffscreenTarget=function(e){var t=e.colorBuffer.format,n=e.colorBuffer.name;e.destroyFrameBuffers(),e.destroyTextureBuffers(),e._colorBuffer=this._allocateColorBuffer(t,n),e._colorBuffers=[e._colorBuffer];},t._destroyOffscreenTarget=function(e){e.destroyTextureBuffers(),e.destroy();},t.addEffect=function(e){var t=this.effects,n=0===t.length,i=this._createOffscreenTarget(n,e.hdr),r=new SH(e,i);t.push(r),this._sourceTarget=r.inputTarget,t.length>1&&(t[t.length-2].outputTarget=r.inputTarget),this._newPostEffect=e,e.needsDepthBuffer&&this._requestDepthMap(),this.enable(),this._newPostEffect=void 0;},t.removeEffect=function(e){for(var t=-1,n=0,i=this.effects.length;n=0&&(t>0?this.effects[t-1].outputTarget=t+11&&(this.effects[1].inputTarget._depth||(this._destroyOffscreenTarget(this.effects[1].inputTarget),this.effects[1].inputTarget=this._createOffscreenTarget(true,this.effects[1].hdr),this._sourceTarget=this.effects[1].inputTarget),this.camera.renderTarget=this.effects[1].inputTarget),this._destroyOffscreenTarget(this.effects[t].inputTarget),this.effects.splice(t,1)),this.enabled&&e.needsDepthBuffer&&this._releaseDepthMap(),0===this.effects.length&&this.disable();},t._requestDepthMaps=function(){for(var e=0,t=this.effects.length;ethis.layers.indexOf(e.id)||e.addCamera(this);},i.onLayerRemoved=function(e){0>this.layers.indexOf(e.id)||e.removeCamera(this);},i.onEnable=function(){var e,t,n,i=this.system.app.scene,r=i.layers;this.system.addCamera(this),null==(e=this._evtLayersChanged)||e.off(),this._evtLayersChanged=i.on("set:layers",this.onLayersChanged,this),r&&(null==(t=this._evtLayerAdded)||t.off(),this._evtLayerAdded=r.on("add",this.onLayerAdded,this),null==(n=this._evtLayerRemoved)||n.off(),this._evtLayerRemoved=r.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&this.addCameraToLayers(),this.postEffects.enable();},i.onDisable=function(){var e,t,n,i=this.system.app.scene.layers;this.postEffects.disable(),this.removeCameraFromLayers(),null==(e=this._evtLayersChanged)||e.off(),this._evtLayersChanged=null,i&&(null==(t=this._evtLayerAdded)||t.off(),this._evtLayerAdded=null,null==(n=this._evtLayerRemoved)||n.off(),this._evtLayerRemoved=null),this.system.removeCamera(this);},i.onRemove=function(){this.onDisable(),this.off(),this.camera.destroy();},i.calculateAspectRatio=function(e){var t=this.system.app.graphicsDevice,n=e?e.width:t.width,i=e?e.height:t.height;return n*this.rect.z/(i*this.rect.w)},i.frameUpdate=function(e){0===this.aspectRatioMode&&(this.aspectRatio=this.calculateAspectRatio(e));},i.startXr=function(e,t,n){this.system.app.xr.start(this,e,t,n);},i.endXr=function(e){if(!this._camera.xr){e&&e(Error("Camera is not in XR"));return}this._camera.xr.end(e);},i.copy=function(e){this.aperture=e.aperture,this.aspectRatio=e.aspectRatio,this.aspectRatioMode=e.aspectRatioMode,this.calculateProjection=e.calculateProjection,this.calculateTransform=e.calculateTransform,this.clearColor=e.clearColor,this.clearColorBuffer=e.clearColorBuffer,this.clearDepthBuffer=e.clearDepthBuffer,this.clearStencilBuffer=e.clearStencilBuffer,this.cullFaces=e.cullFaces,this.disablePostEffectsLayer=e.disablePostEffectsLayer,this.farClip=e.farClip,this.flipFaces=e.flipFaces,this.fov=e.fov,this.frustumCulling=e.frustumCulling,this.horizontalFov=e.horizontalFov,this.layers=e.layers,this.nearClip=e.nearClip,this.orthoHeight=e.orthoHeight,this.priority=e.priority,this.projection=e.projection,this.rect=e.rect,this.renderTarget=e.renderTarget,this.scissorRect=e.scissorRect,this.sensitivity=e.sensitivity,this.shutter=e.shutter;},n=[{key:"renderPasses",get:function(){return this._camera.renderPasses},set:function(e){this._camera.renderPasses=e||[],this.dirtyLayerCompositionCameras(),this.system.app.scene.updateShaders=true;}},{key:"shaderParams",get:function(){return this._camera.shaderParams}},{key:"gammaCorrection",get:function(){return this.camera.shaderParams.gammaCorrection},set:function(e){this.camera.shaderParams.gammaCorrection=e;}},{key:"toneMapping",get:function(){return this.camera.shaderParams.toneMapping},set:function(e){this.camera.shaderParams.toneMapping=e;}},{key:"fog",get:function(){return this._camera.fogParams},set:function(e){this._camera.fogParams=e;}},{key:"aperture",get:function(){return this._camera.aperture},set:function(e){this._camera.aperture=e;}},{key:"aspectRatio",get:function(){return this._camera.aspectRatio},set:function(e){this._camera.aspectRatio=e;}},{key:"aspectRatioMode",get:function(){return this._camera.aspectRatioMode},set:function(e){this._camera.aspectRatioMode=e;}},{key:"calculateProjection",get:function(){return this._camera.calculateProjection},set:function(e){this._camera.calculateProjection=e;}},{key:"calculateTransform",get:function(){return this._camera.calculateTransform},set:function(e){this._camera.calculateTransform=e;}},{key:"camera",get:function(){return this._camera}},{key:"clearColor",get:function(){return this._camera.clearColor},set:function(e){this._camera.clearColor=e;}},{key:"clearColorBuffer",get:function(){return this._camera.clearColorBuffer},set:function(e){this._camera.clearColorBuffer=e,this.dirtyLayerCompositionCameras();}},{key:"clearDepthBuffer",get:function(){return this._camera.clearDepthBuffer},set:function(e){this._camera.clearDepthBuffer=e,this.dirtyLayerCompositionCameras();}},{key:"clearStencilBuffer",get:function(){return this._camera.clearStencilBuffer},set:function(e){this._camera.clearStencilBuffer=e,this.dirtyLayerCompositionCameras();}},{key:"cullFaces",get:function(){return this._camera.cullFaces},set:function(e){this._camera.cullFaces=e;}},{key:"disablePostEffectsLayer",get:function(){return this._disablePostEffectsLayer},set:function(e){this._disablePostEffectsLayer=e,this.dirtyLayerCompositionCameras();}},{key:"farClip",get:function(){return this._camera.farClip},set:function(e){this._camera.farClip=e;}},{key:"flipFaces",get:function(){return this._camera.flipFaces},set:function(e){this._camera.flipFaces=e;}},{key:"fov",get:function(){return this._camera.fov},set:function(e){this._camera.fov=e;}},{key:"frustum",get:function(){return this._camera.frustum}},{key:"frustumCulling",get:function(){return this._camera.frustumCulling},set:function(e){this._camera.frustumCulling=e;}},{key:"horizontalFov",get:function(){return this._camera.horizontalFov},set:function(e){this._camera.horizontalFov=e;}},{key:"layers",get:function(){return this._camera.layers},set:function(e){var t=this,n=this._camera.layers,i=this.system.app.scene;n.forEach(function(e){var n=i.layers.getLayerById(e);null==n||n.removeCamera(t);}),this._camera.layers=e,this.enabled&&this.entity.enabled&&e.forEach(function(e){var n=i.layers.getLayerById(e);null==n||n.addCamera(t);}),this.fire("set:layers");}},{key:"layersSet",get:function(){return this._camera.layersSet}},{key:"jitter",get:function(){return this._camera.jitter},set:function(e){this._camera.jitter=e;}},{key:"nearClip",get:function(){return this._camera.nearClip},set:function(e){this._camera.nearClip=e;}},{key:"orthoHeight",get:function(){return this._camera.orthoHeight},set:function(e){this._camera.orthoHeight=e;}},{key:"postEffects",get:function(){return this._postEffects}},{key:"postEffectsEnabled",get:function(){return this._postEffects.enabled}},{key:"priority",get:function(){return this._priority},set:function(e){this._priority=e,this.dirtyLayerCompositionCameras();}},{key:"projection",get:function(){return this._camera.projection},set:function(e){this._camera.projection=e;}},{key:"projectionMatrix",get:function(){return this._camera.projectionMatrix}},{key:"rect",get:function(){return this._camera.rect},set:function(e){this._camera.rect=e,this.fire("set:rect",this._camera.rect);}},{key:"renderSceneColorMap",get:function(){return this._renderSceneColorMap>0},set:function(e){e&&!this._sceneColorMapRequested?(this.requestSceneColorMap(true),this._sceneColorMapRequested=true):this._sceneColorMapRequested&&(this.requestSceneColorMap(false),this._sceneColorMapRequested=false);}},{key:"renderSceneDepthMap",get:function(){return this._renderSceneDepthMap>0},set:function(e){e&&!this._sceneDepthMapRequested?(this.requestSceneDepthMap(true),this._sceneDepthMapRequested=true):this._sceneDepthMapRequested&&(this.requestSceneDepthMap(false),this._sceneDepthMapRequested=false);}},{key:"renderTarget",get:function(){return this._camera.renderTarget},set:function(e){this._camera.renderTarget=e,this.dirtyLayerCompositionCameras();}},{key:"scissorRect",get:function(){return this._camera.scissorRect},set:function(e){this._camera.scissorRect=e;}},{key:"sensitivity",get:function(){return this._camera.sensitivity},set:function(e){this._camera.sensitivity=e;}},{key:"shutter",get:function(){return this._camera.shutter},set:function(e){this._camera.shutter=e;}},{key:"viewMatrix",get:function(){return this._camera.viewMatrix}}],function(e,t){for(var n=0;n=0&&(this.cameras.splice(t,1),cq(this.cameras));},n.destroy=function(){this.app.off("prerender",this.onAppPrerender,this),e.prototype.destroy.call(this);},t}(mV);mN._buildAccessors(SX.prototype,SK);var SQ=function(){this.enabled=true,this.type="directional",this.color=new eN(1,1,1),this.intensity=1,this.luminance=0,this.shape=0,this.affectSpecularity=true,this.castShadows=false,this.shadowDistance=40,this.shadowIntensity=1,this.shadowResolution=1024,this.shadowBias=.05,this.numCascades=1,this.cascadeBlend=0,this.bakeNumSamples=1,this.bakeArea=0,this.cascadeDistribution=.5,this.normalOffsetBias=0,this.range=10,this.innerConeAngle=40,this.outerConeAngle=45,this.falloffMode=0,this.shadowType=0,this.vsmBlurSize=11,this.vsmBlurMode=1,this.vsmBias=.0025,this.cookieAsset=null,this.cookie=null,this.cookieIntensity=1,this.cookieFalloff=true,this.cookieChannel="rgb",this.cookieAngle=0,this.cookieScale=null,this.cookieOffset=null,this.shadowUpdateMode=2,this.mask=1,this.affectDynamic=true,this.affectLightmapped=false,this.bake=false,this.bakeDir=true,this.isStatic=false,this.layers=[0],this.penumbraSize=1,this.penumbraFalloff=1,this.shadowSamples=16,this.shadowBlockerSamples=16;},SJ=Object.keys(new SQ);function S$(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?!!t[Symbol.hasInstance](e):i(e,t)}function S0(e,t){return (S0=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var S1=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(){var t;return t=e.apply(this,arguments)||this,t._evtLayersChanged=null,t._evtLayerAdded=null,t._evtLayerRemoved=null,t._cookieAsset=null,t._cookieAssetId=null,t._cookieAssetAdd=false,t._cookieMatrix=null,t}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&S0(t,e);var n,i=t.prototype;return i._setValue=function(e,t,n,i){var r=this.data,s=r[e];(i||s!==t)&&(r[e]=t,n&&n.call(this,t,s));},i.addLightToLayers=function(){for(var e=0;e=0&&this.enabled&&this.entity.enabled&&(e.addLight(this),this.light.addLayer(e));},i.onLayerRemoved=function(e){this.layers.indexOf(e.id)>=0&&(e.removeLight(this),this.light.removeLayer(e));},i.refreshProperties=function(){for(var e=0;e=3&&n.length<=4){for(var d=0;dt.ind&&(h=t.ind),this._insertScriptInstance(u,h,c),this._scriptsIndex[r]={instance:u,onSwap:function(){n.swap(r);}},this[r]=u,t.preloading||this.initializeAttributes(u),this.fire("create",r,u),this.fire("create:"+r,u),this.system.app.scripts.on("swap:"+r,this._scriptsIndex[r].onSwap),!t.preloading&&(u.enabled&&!u._initialized&&(u._initialized=true,u.initialize&&this._scriptMethod(u,xi)),u.enabled&&!u._postInitialized&&(u._postInitialized=true,u.postInitialize&&this._scriptMethod(u,xr))),u}}else this._scriptsIndex[r]={awaiting:true,ind:this._scripts.length};return null},i.destroy=function(e){var t=e,n=e;"string"==typeof n?n=this.system.app.scripts.get(n):n&&(t=n.__name);var i=this._scriptsIndex[t];if(delete this._scriptsIndex[t],!i)return false;this._attributeDataMap.delete(t);var r=i.instance;if(r&&!r._destroyed)if(r.enabled=false,r._destroyed=true,this._isLoopingThroughScripts)this._destroyedScripts.push(r);else {var s=this._removeScriptInstance(r);s>=0&&this._resetExecutionOrder(s,this._scripts.length);}return this.system.app.scripts.off("swap:"+t,i.onSwap),delete this[t],this.fire("destroy",t,r||null),this.fire("destroy:"+t,r||null),r&&r.fire("destroy"),true},i.swap=function(e){var t=e,n=e;"string"==typeof n?n=this.system.app.scripts.get(n):n&&(t=n.__name);var i=this._scriptsIndex[t];if(!i||!i.instance)return false;var r=i.instance,s=this._scripts.indexOf(r),a=new n({app:this.system.app,entity:this.entity,enabled:r.enabled,attributes:r.__attributes});return !!a.swap&&(this.initializeAttributes(a),this._scripts[s]=a,this._scriptsIndex[t].instance=a,this[t]=a,a.__executionOrder=s,r.update&&this._updateList.remove(r),r.postUpdate&&this._postUpdateList.remove(r),a.update&&this._updateList.insert(a),a.postUpdate&&this._postUpdateList.insert(a),this._scriptMethod(a,"swap",r),this.fire("swap",t,a),this.fire("swap:"+t,a),true)},i.resolveDuplicatedEntityReferenceProperties=function(e,t){var n=this.entity.script;for(var i in e._scriptsIndex){var r=this.system.app.scripts.get(i);if(r){var s=e._scriptsIndex[i];if(s&&s.instance){var a=n[i].__attributesRaw,o=n[i].__attributes;if(a||o){var l=!!a,u=s.instance.__attributes;for(var c in u)if(u[c]){var h=r.attributes.get(c);if(h){if("entity"===h.type)this._resolveEntityScriptAttribute(h,c,u[c],l,a||o,t);else if("json"===h.type&&Array.isArray(h.schema))for(var f=u[c],d=a?a[c]:o[c],p=0;p=n||t<0)return false;var i=e,r=e;"string"!=typeof r?r=e.__name:i=null;var s=this._scriptsIndex[r];if(!s||!s.instance)return false;var a=s.instance;if(i&&!xf(a,i))return false;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,n),this._updateList.sort(),this._postUpdateList.sort(),this.fire("move",r,a,t,o),this.fire("move:"+r,a,t,o),true)},n=[{key:"scripts",get:function(){return this._scripts},set:function(e){var t,n=this;for(var i in this._scriptsData=e,e)t=this,function(i){if(e.hasOwnProperty(i)){var r=t._scriptsIndex[i];if(r&&("boolean"==typeof e[i].enabled&&(r.once("preInitialize",function(){n.initializeAttributes(r);}),r.enabled=!!e[i].enabled),"object"===xp(e[i].attributes))){for(var s in e[i].attributes)if(!xn.reservedNames.has(s)){if(!r.__attributes.hasOwnProperty(s)){var a=t.system.app.scripts.get(i);a&&a.attributes.add(s,{});}r[s]=e[i].attributes[s];}}}}(i);}},{key:"enabled",get:function(){return this._enabled},set:function(e){var t=this._enabled;this._enabled=e,this.fire("set","enabled",t,e);}}],function(e,t){for(var n=0;nNumber.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 n=0;n=0&&t._onBeforeRemove(),this._removeComponentFromEnabled(t),this._components.remove(t);},n.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("initialize",this._onInitialize,this),this.app.systems.off("postInitialize",this._onPostInitialize,this),this.app.systems.off("update",this._onUpdate,this),this.app.systems.off("postUpdate",this._onPostUpdate,this);},t}(mV);function xS(e,t){return (xS=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var xx=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t,n){var i;return (i=e.call(this,t,n)||this)._layers=[0],i._instance=null,i._materialTmp=null,i._customAabb=null,i._evtLayersChanged=null,i._evtLayerAdded=null,i._evtLayerRemoved=null,i._castShadows=false,i._assetReference=new ym("asset",i,t.app.assets,{add:i._onGSplatAssetAdded,load:i._onGSplatAssetLoad,remove:i._onGSplatAssetRemove,unload:i._onGSplatAssetUnload},i),n.on("remove",i.onRemoveChild,i),n.on("removehierarchy",i.onRemoveChild,i),n.on("insert",i.onInsertChild,i),n.on("inserthierarchy",i.onInsertChild,i),i}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&xS(t,e);var n,r=t.prototype;return r.destroyInstance=function(){if(this._instance){var e;this.removeFromLayers(),null==(e=this._instance)||e.destroy(),this._instance=null;}},r.addToLayers=function(){var e=null==(t=this.instance)?void 0:t.meshInstance;if(e)for(var t,n,i=this.system.app.scene.layers,r=0;rthis.layers.indexOf(e.id))&&this._instance&&e.addMeshInstances(this._instance.meshInstance);},r.onLayerRemoved=function(e){!(0>this.layers.indexOf(e.id))&&this._instance&&e.removeMeshInstances(this._instance.meshInstance);},r.onEnable=function(){var e=this.system.app.scene,t=e.layers;this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),t&&(this._evtLayerAdded=t.on("add",this.onLayerAdded,this),this._evtLayerRemoved=t.on("remove",this.onLayerRemoved,this)),this._instance?this.addToLayers():this.asset&&this._onGSplatAssetAdded();},r.onDisable=function(){var e,t,n,i=this.system.app.scene.layers;null==(e=this._evtLayersChanged)||e.off(),this._evtLayersChanged=null,i&&(null==(t=this._evtLayerAdded)||t.off(),this._evtLayerAdded=null,null==(n=this._evtLayerRemoved)||n.off(),this._evtLayerRemoved=null),this.removeFromLayers();},r.hide=function(){this._instance&&(this._instance.meshInstance.visible=false);},r.show=function(){this._instance&&(this._instance.meshInstance.visible=true);},r._onGSplatAssetAdded=function(){this._assetReference.asset&&(this._assetReference.asset.resource?this._onGSplatAssetLoad():this.enabled&&this.entity.enabled&&this.system.app.assets.load(this._assetReference.asset));},r._onGSplatAssetLoad=function(){this.destroyInstance();var e=this._assetReference.asset;e&&(this.instance=new pa(e.resource,this._materialTmp),this._materialTmp=null,this.customAabb=this.instance.resource.aabb.clone());},r._onGSplatAssetUnload=function(){this.destroyInstance();},r._onGSplatAssetRemove=function(){this._onGSplatAssetUnload();},n=[{key:"customAabb",get:function(){return this._customAabb},set:function(e){var t,n;this._customAabb=e,null==(n=this._instance)||null==(t=n.meshInstance)||t.setCustomAabb(this._customAabb);}},{key:"instance",get:function(){return this._instance},set:function(e){if(this.destroyInstance(),this._instance=e,this._instance){var t=this._instance.meshInstance;t.node||(t.node=this.entity),t.castShadow=this._castShadows,t.setCustomAabb(this._customAabb),this.enabled&&this.entity.enabled&&this.addToLayers();}}},{key:"material",get:function(){var e,t,n;return null!=(n=null!=(t=null==(e=this._instance)?void 0:e.material)?t:this._materialTmp)?n:null},set:function(e){this._instance?this._instance.material=e:this._materialTmp=e;}},{key:"castShadows",get:function(){return this._castShadows},set:function(e){if(this._castShadows!==e){var t,n=null==(t=this.instance)?void 0:t.meshInstance;if(n){var i=this.layers,r=this.system.app.scene;if(this._castShadows&&!e)for(var s=0;s=u.num_points(),d=h*(f?2:4),p=n._malloc(d);f?(l.GetTrianglesUInt16Array(u,d,p),t.indices=new Uint16Array(n.HEAPU16.buffer,p,h).slice().buffer):(l.GetTrianglesUInt32Array(u,d,p),t.indices=new Uint32Array(n.HEAPU32.buffer,p,h).slice().buffer),n._free(p);for(var m=[],_=0;_0){var s=t.jobQueue.shift();t.run(e,s);}else {var a=t.workers[2].indexOf(e);if(-1!==a)t.workers[2].splice(a,1),t.workers[1].push(e);else {var o=t.workers[1].indexOf(e);-1!==o&&(t.workers[1].splice(o,1),t.workers[0].push(e));}}});}),this.workers[0]=e;this.jobQueue.length&&(this.workers[0].length||this.workers[1].length);){var n=this.jobQueue.shift();if(this.workers[0].length>0){var i=this.workers[0].shift();this.workers[1].push(i),this.run(i,n);}else {var r=this.workers[1].shift();this.workers[2].push(r),this.run(r,n);}}},t.enqueueJob=function(e,t){var n={jobId:this.jobId++,buffer:e};if(this.jobCallbacks.set(n.jobId,t),this.workers[0].length>0){var i=this.workers[0].shift();this.workers[1].push(i),this.run(i,n);}else if(this.workers[1].length>0){var r=this.workers[1].shift();this.workers[2].push(r),this.run(r,n);}else this.jobQueue.push(n);},e}(),xB=function(e){var t=function(){return fetch(e).then(function(e){return e.arrayBuffer()}).then(function(e){return WebAssembly.compile(e)})};return WebAssembly.compileStreaming?WebAssembly.compileStreaming(fetch(e)).catch(function(e){return t()}):t()},xU=function(e){if(F)return true;if(!e)if(B)e=B;else {var t,n=ew.getConfig("DracoDecoderModule");e=n?{jsUrl:n.glueUrl,wasmUrl:n.wasmUrl,numWorkers:n.numWorkers}:{jsUrl:"draco.wasm.js",wasmUrl:"draco.wasm.wasm",numWorkers:1};}return !!e.jsUrl&&!!e.wasmUrl&&(F=new xF,Promise.all([(t=e.jsUrl,new Promise(function(e,n){aq.get(t,{cache:true,responseType:"text",retry:true,maxRetries:3},function(t,i){t?n(t):e(i);});})),xB(e.wasmUrl)]).then(function(t){for(var n=t[0],i=t[1],r=new Blob([["/* draco */",n,"/* worker */","(\n"+xN.toString()+"\n)()\n\n"].join("\n")],{type:"application/javascript"}),s=URL.createObjectURL(r),a=Math.max(1,Math.min(16,e.numWorkers||1)),o=[],l=0;le.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var xW=function(){function e(){}return e.prototype.destroy=function(){this.renders&&this.renders.forEach(function(e){e.meshes=null;});},e}(),xj=function(e){return /^data:[^\n\r,\u2028\u2029]*,.*$/i.test(e)},xX=function(e){switch(e){case "SCALAR":return 1;case "VEC2":return 2;case "VEC3":default:return 3;case "VEC4":case "MAT2":return 4;case "MAT3":return 9;case "MAT4":return 16}},xY=function(e){switch(e){case 5120:default:return 0;case 5121:return 1;case 5122:return 2;case 5123:return 3;case 5124:return 4;case 5125:return 5;case 5126:return 6}},xq=function(e){switch(e){case 5120:case 5121:return 1;case 5122:case 5123:return 2;case 5124:case 5125:case 5126:return 4;default:return 0}},xK=function(e){switch(e){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5124:return Int32Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:return null}},xZ={POSITION:tA,NORMAL:tC,TANGENT:tP,COLOR_0:tD,JOINTS_0:tL,WEIGHTS_0:tI,TEXCOORD_0:tM,TEXCOORD_1:tO,TEXCOORD_2:tk,TEXCOORD_3:tN,TEXCOORD_4:tF,TEXCOORD_5:tB,TEXCOORD_6:tU,TEXCOORD_7:tV},xQ=((U={})[tA]=0,U[tC]=1,U[tP]=2,U[tD]=3,U[tL]=4,U[tI]=5,U[tM]=6,U[tO]=7,U[tk]=8,U[tN]=9,U[tF]=10,U[tB]=11,U[tU]=12,U[tV]=13,U),xJ=function(e){switch(e){case 0:return function(e){return Math.max(e/127,-1)};case 1:return function(e){return e/255};case 2:return function(e){return Math.max(e/32767,-1)};case 3:return function(e){return e/65535};default:return function(e){return e}}},x$=function(e,t,n){for(var i=xJ(n),r=t.length,s=0;s0&&"localRotation"===R.paths[0].propertyPath[0]&&2!==R.interpolation&&g.push(P[P.length-1].output));}g.sort();var M=null;for(o=0;o0?i.name=e.name:i.name="node_"+t,e.hasOwnProperty("matrix")&&(bg.data.set(e.matrix),bg.getTranslation(by),i.setLocalPosition(by),bg.getEulerAngles(by),i.setLocalEulerAngles(by),bg.getScale(by),i.setLocalScale(by)),e.hasOwnProperty("rotation")){var r=e.rotation;i.setLocalRotation(r[0],r[1],r[2],r[3]);}if(e.hasOwnProperty("translation")){var s=e.translation;i.setLocalPosition(s[0],s[1],s[2]);}if(e.hasOwnProperty("scale")){var a=e.scale;i.setLocalScale(a[0],a[1],a[2]);}return e.hasOwnProperty("extensions")&&e.extensions.EXT_mesh_gpu_instancing&&n.set(e,{ext:e.extensions.EXT_mesh_gpu_instancing}),i},bx=function(e,t){var n=+("orthographic"===e.type),i=1===n?e.orthographic:e.perspective,r={enabled:false,projection:n,nearClip:i.znear,aspectRatioMode:0};i.zfar&&(r.farClip=i.zfar),1===n?(r.orthoHeight=.5*i.ymag,i.ymag&&(r.aspectRatioMode=1,r.aspectRatio=i.xmag/i.ymag)):(r.fov=i.yfov*ek.RAD_TO_DEG,i.aspectRatio&&(r.aspectRatioMode=1,r.aspectRatio=i.aspectRatio));var s=new ml(e.name);return s.addComponent("camera",r),s},bb=function(e,t){var n={enabled:false,type:"point"===e.type?"omni":e.type,color:e.hasOwnProperty("color")?new eN(e.color):eN.WHITE,range:e.hasOwnProperty("range")?e.range:9999,falloffMode:1,intensity:e.hasOwnProperty("intensity")?ek.clamp(e.intensity,0,2):1};e.hasOwnProperty("spot")&&(n.innerConeAngle=e.spot.hasOwnProperty("innerConeAngle")?e.spot.innerConeAngle*ek.RAD_TO_DEG:0,n.outerConeAngle=e.spot.hasOwnProperty("outerConeAngle")?e.spot.outerConeAngle*ek.RAD_TO_DEG:Math.PI/4),e.hasOwnProperty("intensity")&&(n.luminance=e.intensity*c6.getLightUnitConversion(c2[n.type],n.outerConeAngle,n.innerConeAngle));var i=new ml(t.name);return i.rotateLocal(90,0,0),i.addComponent("light",n),i},bT=function(e,t,n,i){if(!t.hasOwnProperty("skins")||0===t.skins.length)return [];var r=new Map;return t.skins.map(function(s){return be(e,s,t.accessors,i,n,r)})},bE=function(e,t,n,i){var r,s,a,o={},l={},u={},c=[];return {meshes:!i.skipMeshes&&(null==t||null==(r=t.meshes)?void 0:r.length)&&(null==t||null==(s=t.accessors)?void 0:s.length)&&(null==t||null==(a=t.bufferViews)?void 0:a.length)?t.meshes.map(function(r){return bn(e,r,t.accessors,n,o,l,u,i,c)}):[],meshVariants:l,meshDefaultMaterials:u,promises:c}},bw=function(e,t,n){if(!e.hasOwnProperty("materials")||0===e.materials.length)return [];var i,r,s,a,o=null==n||null==(i=n.material)?void 0:i.preprocess,l=null!=(a=null==n||null==(r=n.material)?void 0:r.process)?a:b_,u=null==n||null==(s=n.material)?void 0:s.postprocess;return e.materials.map(function(e){o&&o(e);var n=l(e,t);return u&&u(e,n),n})},bA=function(e){if(!e.hasOwnProperty("extensions")||!e.extensions.hasOwnProperty("KHR_materials_variants"))return null;for(var t=e.extensions.KHR_materials_variants.variants,n={},i=0;i0){var r,s,a,o,l=null==n||null==(r=n.camera)?void 0:r.preprocess,u=null!=(o=null==n||null==(s=n.camera)?void 0:s.process)?o:bx,c=null==n||null==(a=n.camera)?void 0:a.postprocess;e.nodes.forEach(function(n,r){if(n.hasOwnProperty("camera")){var s=e.cameras[n.camera];if(s){l&&l(s);var a=u(s,t[r]);c&&c(s,a),a&&(i||(i=new Map),i.set(n,a));}}});}return i},bR=function(e,t,n){var i=null;if(e.hasOwnProperty("nodes")&&e.hasOwnProperty("extensions")&&e.extensions.hasOwnProperty("KHR_lights_punctual")&&e.extensions.KHR_lights_punctual.hasOwnProperty("lights")){var r=e.extensions.KHR_lights_punctual.lights;if(r.length){var s,a,o,l,u=null==n||null==(s=n.light)?void 0:s.preprocess,c=null!=(l=null==n||null==(a=n.light)?void 0:a.process)?l:bb,h=null==n||null==(o=n.light)?void 0:o.postprocess;e.nodes.forEach(function(e,n){if(e.hasOwnProperty("extensions")&&e.extensions.hasOwnProperty("KHR_lights_punctual")&&e.extensions.KHR_lights_punctual.hasOwnProperty("light")){var s=r[e.extensions.KHR_lights_punctual.light];if(s){u&&u(s);var a=c(s,t[n]);h&&h(s,a),a&&(i||(i=new Map),i.set(e,a));}}});}}return i},bM=function(e,t,n){e.nodes.forEach(function(e){e.hasOwnProperty("mesh")&&e.hasOwnProperty("skin")&&t[e.mesh].meshes.forEach(function(t){t.skin=n[e.skin];});});},bO=(a=function(e,t,n,i,r){var s,a,o,l,u,c,h,f,d,p,m,_,v,g,y,S,x,b,T,E,w,A,C;return function(e,t){var n,i,r,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(o){return function(l){var u=[o,l];if(n)throw TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(s=0)),s;)try{if(n=1,i&&(r=2&u[0]?i.return:u[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,u[1])).done)return r;switch(i=0,r&&(u=[2&u[0],r.value]),u[0]){case 0:case 1:r=u;break;case 4:return s.label++,{value:u[1],done:!1};case 5:s.label++,i=u[1],u=[0];continue;case 7:u=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===u[0]||2===u[0])){s=0;continue}if(3===u[0]&&(!r||u[1]>r[0]&&u[1]parseFloat(n.asset.version))return void t("Invalid gltf version. Expected version 2.0 or above but found version '"+n.asset.version+"'.");t(null,n);},bG=function(e,t){var n=xG(e,ArrayBuffer)?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),i=n.getUint32(0,true),r=n.getUint32(4,true),s=n.getUint32(8,true);if(0x46546c67!==i)return void t("Invalid magic number found in glb header. Expected 0x46546C67, found 0x"+i.toString(16));if(2!==r)return void t("Invalid version number found in glb header. Expected 2, found "+r);if(s<=0||s>n.byteLength)return void t("Invalid length found in glb header. Found "+s);for(var a=[],o=12;on.byteLength&&t("Invalid chunk length found in glb. Found "+l);var u=n.getUint32(o+4,true),c=new Uint8Array(n.buffer,n.byteOffset+o+8,l);a.push({length:l,type:u,data:c}),o+=l+8;}return 1!==a.length&&2!==a.length?void t("Invalid number of chunks found in glb file."):0x4e4f534a!==a[0].type?void t("Invalid chunk type found in glb file. Expected 0x4E4F534A, found 0x"+a[0].type.toString(16)):a.length>1&&5130562!==a[1].type?void t("Invalid chunk type found in glb file. Expected 0x004E4942, found 0x"+a[1].type.toString(16)):void t(null,{gltfChunk:a[0].data,binaryChunk:2===a.length?a[1].data:null})},bH=function(e,t,n){var i;e&&e.toLowerCase().endsWith(".glb")||103===(i=new Uint8Array(t))[0]&&108===i[1]&&84===i[2]&&70===i[3]?bG(t,n):n(null,{gltfChunk:t,binaryChunk:null});},bW=function(e,t,n){var i,r,s,a,o=[],l=null==n||null==(i=n.bufferView)?void 0:i.preprocess,u=null==n||null==(r=n.bufferView)?void 0:r.processAsync,c=null==n||null==(s=n.bufferView)?void 0:s.postprocess;if(!(null==(a=e.bufferViews)?void 0:a.length))return o;for(var h=0;h0,maxRetries:this.maxRetries};(e.load.startsWith("blob:")||e.load.startsWith("data:"))&&(".glb"===en.getExtension(e.original).toLowerCase()?r.responseType=aY.ResponseType.ARRAY_BUFFER:r.responseType=aY.ResponseType.JSON),aq.get(e.load,r,function(r,s){if(r)t("Error loading animation resource: "+e.original+" ["+r+"]");else if(".glb"===en.getExtension(e.original).toLowerCase()){var a;bj.parse("filename.glb","",s,i.device,i.assets,null!=(a=null==n?void 0:n.options)?a:{},function(e,i){if(e)t(e);else {var r,s=i.animations;if(null==n||null==(r=n.data)?void 0:r.events)for(var a=0;a0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(n.responseType=aY.ResponseType.JSON),aq.get(e.load,n,function(n,i){n?t("Error loading animation clip resource: "+e.original+" ["+n+"]"):t(null,i);});},n.open=function(e,t){return new _o(t.name,t.duration,t.inputs.map(function(e){return new xk(1,e)}),t.outputs.map(function(e){return new xk(e.components,e.data)}),t.curves.map(function(e){return new xO([e.path],e.inputIndex,e.outputIndex,e.interpolation)}))},t}(p1);function bZ(e,t){return (bZ=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var bQ=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){return e.call(this,t,"animstategraph")||this}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&bZ(t,e);var n=t.prototype;return n.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var n={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(n.responseType=aY.ResponseType.JSON),aq.get(e.load,n,function(n,i){n?t("Error loading animation state graph resource: "+e.original+" ["+n+"]"):t(null,i);});},n.open=function(e,t){return new _H(t)},t}(p1);function bJ(e,t){return (bJ=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var b$=function(){if("undefined"==typeof window)return false;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 n=e.indexOf("rv:");return parseInt(e.substring(n+3,e.indexOf(".",n)),10)}return false}(),b0=[".ogg",".mp3",".wav",".mp4a",".m4a",".mp4",".aac",".opus"],b1=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this,t,"audio")||this).manager=t.soundManager,n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&bJ(t,e);var n=t.prototype;return n._isSupported=function(e){var t=en.getExtension(e);return b0.indexOf(t)>-1},n.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var n=function(n){var i="Error loading audio url: "+e.original;n&&(i+=": "+(n.message||n)),t(i);};if(this._createSound){if(!this._isSupported(e.original))return void n("Audio format for "+e.original+" not supported");this._createSound(e.load,function(e){t(null,new a8(e));},n);}else n(null);},n._createSound=function(e,t,n){if(aK()){var i=this.manager;if(!i.context)return void n("Audio manager has no audio context");var r={retry:this.maxRetries>0,maxRetries:this.maxRetries};(e.startsWith("blob:")||e.startsWith("data:"))&&(r.responseType=aY.ResponseType.ARRAY_BUFFER),aq.get(e,r,function(e,r){if(e)return void n(e);i.context.decodeAudioData(r,t,n);});}else {var s=null;try{s=new Audio;}catch(e){n("No support for Audio element");return}b$&&document.body.appendChild(s);var a=function(){s.removeEventListener("canplaythrough",a),b$&&document.body.removeChild(s),t(s);};s.onerror=function(){s.onerror=null,b$&&document.body.removeChild(s),n();},s.addEventListener("canplaythrough",a),s.src=e;}},t}(p1);function b2(e,t){return (b2=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var b3=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){return e.call(this,t,"binary")||this}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&b2(t,e);var n=t.prototype;return n.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),aq.get(e.load,{responseType:aY.ResponseType.ARRAY_BUFFER,retry:this.maxRetries>0,maxRetries:this.maxRetries},function(n,i){n?t("Error loading binary resource: "+e.original+" ["+n+"]"):t(null,i);});},n.openBinary=function(e){return e.buffer},t}(p1);function b4(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var b8=function(){function e(t,n,i,r){for(var s=function(t,r,s){var a=e.createAsset(n.name,t,r,s);return i.add(a),a},a=[],o=0;o=0?e.split("?")[0]:e},t.load=function(e,t,n){var i=this;pU.fetchArrayBuffer(e.load,function(r,s){r?t(r):bj.parse(i._getUrlWithoutParams(e.original),en.extractPath(e.load),s,i._device,n.registry,n.options,function(e,r){e?t(e):t(null,new b8(r,n,i._assets,i._defaultMaterial));});},n,this.maxRetries);},t.open=function(e,t,n){return t},t.patch=function(e,t){},e}();function b9(e,t){return (b9=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var b7=function(){function e(){}var t=e.prototype;return t.instantiateModelEntity=function(e){return null},t.instantiateRenderEntity=function(e){return null},t.getMaterialVariants=function(){return null},t.applyMaterialVariant=function(e,t){},t.applyMaterialVariantInstances=function(e,t){},e}(),Te=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this,t,"container")||this).glbContainerParser=new b6(t.graphicsDevice,t.assets,0),n.parsers={},n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&b9(t,e);var n,i=t.prototype;return i._getUrlWithoutParams=function(e){return e.indexOf("?")>=0?e.split("?")[0]:e},i._getParser=function(e){var t=e?en.getExtension(this._getUrlWithoutParams(e)).toLowerCase().replace(".",""):null;return this.parsers[t]||this.glbContainerParser},i.load=function(e,t,n){"string"==typeof e&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,n);},i.open=function(e,t,n){return this._getParser(e).open(e,t,n)},n=[{key:"maxRetries",get:function(){return this.glbContainerParser.maxRetries},set:function(e){for(var t in this.glbContainerParser.maxRetries=e,this.parsers)this.parsers.hasOwnProperty(t)&&(this.parsers[t].maxRetries=e);}}],function(e,t){for(var n=0;n0,maxRetries:this.maxRetries},function(n,i){n?t("Error loading css resource: "+e.original+" ["+n+"]"):t(null,i);});},n.openBinary=function(e){return null!=this.decoder||(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)},t}(p1);function Ti(e,t){return (Ti=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var Tr=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this,t,"cubemap")||this)._device=t.graphicsDevice,n._registry=t.assets,n._loader=t.loader,n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&Ti(t,e);var n=t.prototype;return n.load=function(e,t,n){this.loadAssets(n,t);},n.open=function(e,t,n){return n?n.resource:null},n.patch=function(e,t){this.loadAssets(e,function(n,i){n&&(t.fire("error",e),t.fire("error:"+e.id,n,e),e.fire("error",e));});},n.getAssetIds=function(e){var t=[];if(t[0]=e.file,(e.loadFaces||!e.file)&&e.data&&e.data.textures)for(var n=0;n<6;++n)t[n+1]=e.data.textures[n];else t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=null;return t},n.compareAssetIds=function(e,t){return e&&t?parseInt(e,10)===e||"string"==typeof e?e===t:e.url===t.url:null!==e==(null!==t)},n.update=function(e,t,n){var i=e.data||{},r=e._handlerState.assets,s=e._resources,a=[null,null,null,null,null,null,null],o=function(){return i.hasOwnProperty("type")?i.type:i.hasOwnProperty("rgbm")?i.rgbm?t4:t3:null};if(e.loaded&&n[0]===r[0])a[1]=s[1]||null,a[2]=s[2]||null,a[3]=s[3]||null,a[4]=s[4]||null,a[5]=s[5]||null,a[6]=s[6]||null;else if(n[0])if((u=n[0].resource).cubemap)for(h=0;h<6;++h)a[h+1]=new nN(this._device,{name:e.name+"_prelitCubemap"+(u.width>>h),cubemap:true,type:o()||u.type,width:u.width>>h,height:u.height>>h,format:u.format,levels:[u._levels[h]],addressU:1,addressV:1,mipmaps:0===h});else a[1]=u;var l=n.slice(1);if(e.loaded&&this.cmpArrays(l,r.slice(1)))a[0]=s[0]||null;else if(-1===l.indexOf(null)){var u,c,h,f,d=l.map(function(e){return e.resource}),p=[];for(c=0;c0,maxRetries:this.maxRetries},function(n,r){if(n)t("Error loading font resource: "+e.original+" ["+n+"]");else {var s=Tu(r);i._loadTextures(e.load.replace(".json",".png"),s,function(e,n){e?t(e):t(null,{data:s,textures:n});});}}):(n&&n.data&&(n.data=Tu(n.data)),this._loadTextures(e.load,n&&n.data,t));},n._loadTextures=function(e,t,n){for(var i=t.info.maps.length,r=0,s=null,a=Array(i),o=this._loader,l=function(t){var l=function(e,o){if(!s){if(e){s=e,n(e);return}o.upload(),a[t]=o,++r===i&&n(null,a);}};0===t?o.load(e,"texture",l):o.load(e.replace(".png",""+t+".png"),"texture",l);},u=0;u>>21,11),e.y=a(t>>>11,10),e.z=a(t,11);},l=function(e,t){e.x=a(t>>>24,8),e.y=a(t>>>16,8),e.z=a(t>>>8,8),e.w=a(t,8);},u=function(e,t){var n=1/(.5*Math.sqrt(2)),i=(a(t>>>20,10)-.5)*n,r=(a(t>>>10,10)-.5)*n,s=(a(t,10)-.5)*n,o=Math.sqrt(1-(i*i+r*r+s*s));switch(t>>>30){case 0:e.set(i,r,s,o);break;case 1:e.set(o,r,s,i);break;case 2:e.set(r,o,s,i);break;case 3:e.set(r,s,o,i);}},c=function(e,t,n){return e*(1-n)+t*n},h=e.chunkData,f=e.chunkSize,d=e.vertexData,p=e.shData0,m=e.shData1,_=e.shData2,v=e.shBands,g=[3,8,15][v-1];this.read=function(e){var a=Math.floor(e/256)*f;if(t&&(o(t,d[4*e+0]),t.x=c(h[a+0],h[a+3],t.x),t.y=c(h[a+1],h[a+4],t.y),t.z=c(h[a+2],h[a+5],t.z)),n&&u(n,d[4*e+1]),i&&(o(i,d[4*e+2]),i.x=c(h[a+6],h[a+9],i.x),i.y=c(h[a+7],h[a+10],i.y),i.z=c(h[a+8],h[a+11],i.z)),r&&(l(r,d[4*e+3]),f>12&&(r.x=c(h[a+12],h[a+15],r.x),r.y=c(h[a+13],h[a+16],r.y),r.z=c(h[a+14],h[a+17],r.z))),s&&v>0)for(var y=[p,m,_],S=0;S<3;++S)for(var x=0;x<15;++x)s[15*S+x]=x>>21)/2047,v=(m>>>11&1023)/1023,g=(2047&m)/2047;e[3*p+0]=(1-_)*t+_*r,e[3*p+1]=(1-v)*n+v*s,e[3*p+2]=(1-g)*i+g*a;}}},n.getChunks=function(e){for(var t,n,i,r,s,a,o=this.chunkData,l=this.numChunks,u=this.chunkSize,c=0;c0){for(var i=[],r=0;r<45;++r)i.push("f_rest_"+r);t.splice.apply(t,[].concat([t.indexOf("f_dc_0")+1,0],i));}var s={};t.forEach(function(t){s[t]=new Float32Array(e.numSplats);});for(var a=new eW,o=new e0,l=new eW,u=new eY,c=n>0?new Float32Array(45):null,h=this.createIter(a,o,l,u,c),f=0;f=1?40:-Math.log(1/u.w-1),c)for(var d=0;d<45;++d)s["f_rest_"+d][f]=c[d];return new d3([{name:"vertex",count:this.numSplats,properties:t.map(function(e){return {name:e,type:"float",byteSize:4,storage:s[e]}})}],this.comments)},t=[{key:"isCompressed",get:function(){return true}},{key:"numChunks",get:function(){return Math.ceil(this.numSplats/256)}},{key:"chunkSize",get:function(){return this.chunkData.length/this.numChunks}}],function(e,t){for(var n=0;n0){var d=i.evalTextureSize(o);i.shTexture0=i.createTexture("shTexture0",49,d,new Uint32Array(n.shData0.buffer)),i.shTexture1=i.createTexture("shTexture1",49,d,new Uint32Array(n.shData1.buffer)),i.shTexture2=i.createTexture("shTexture2",49,d,new Uint32Array(n.shData2.buffer));}else i.shTexture0=null,i.shTexture1=null,i.shTexture2=null;return i}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&Td(t,e);var n=t.prototype;return n.destroy=function(){var t,n,i,r,s;null==(t=this.packedTexture)||t.destroy(),null==(n=this.chunkTexture)||n.destroy(),null==(i=this.shTexture0)||i.destroy(),null==(r=this.shTexture1)||r.destroy(),null==(s=this.shTexture2)||s.destroy(),e.prototype.destroy.call(this);},n.configureMaterial=function(e){e.setDefine("GSPLAT_COMPRESSED_DATA",true),e.setParameter("packedTexture",this.packedTexture),e.setParameter("chunkTexture",this.chunkTexture),this.shTexture0?(e.setDefine("SH_BANDS",3),e.setParameter("shTexture0",this.shTexture0),e.setParameter("shTexture1",this.shTexture1),e.setParameter("shTexture2",this.shTexture2)):e.setDefine("SH_BANDS",0);},n.evalTextureSize=function(e){var t=Math.ceil(Math.sqrt(e)),n=Math.ceil(e/t);return new eX(t,n)},t}(d5);function T_(e,t,n,i,r,s,a){try{var o=e[s](a),l=o.value;}catch(e){n(e);return}o.done?t(l):Promise.resolve(l).then(i,r);}function Tv(e){return function(){var t=this,n=arguments;return new Promise(function(i,r){var s=e.apply(t,n);function a(e){T_(s,i,r,a,o,"next",e);}function o(e){T_(s,i,r,a,o,"throw",e);}a(void 0);})}}function Tg(e,t){var n,i,r,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(o){return function(l){var u=[o,l];if(n)throw TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(s=0)),s;)try{if(n=1,i&&(r=2&u[0]?i.return:u[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,u[1])).done)return r;switch(i=0,r&&(u=[2&u[0],r.value]),u[0]){case 0:case 1:r=u;break;case 4:return s.label++,{value:u[1],done:!1};case 5:s.label++,i=u[1],u=[0];continue;case 7:u=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===u[0]||2===u[0])){s=0;continue}if(3===u[0]&&(!r||u[1]>r[0]&&u[1]=n)this.head>0?(this.data.copyWithin(0,this.head,this.tail),this.data.set(e,t),this.head=0,this.tail=n):(this.data.set(e,this.tail),this.tail+=e.length);else {var i=new Uint8Array(n);this.head>0||this.tail0&&(this.data.copyWithin(0,this.head,this.tail),this.tail-=this.head,this.head=0);},n.getInt8=function(){var e=this.view.getInt8(this.head);return this.head++,e},n.getUint8=function(){var e=this.view.getUint8(this.head);return this.head++,e},n.getInt16=function(){var e=this.view.getInt16(this.head,true);return this.head+=2,e},n.getUint16=function(){var e=this.view.getUint16(this.head,true);return this.head+=2,e},n.getInt32=function(){var e=this.view.getInt32(this.head,true);return this.head+=4,e},n.getUint32=function(){var e=this.view.getUint32(this.head,true);return this.head+=4,e},n.getFloat32=function(){var e=this.view.getFloat32(this.head,true);return this.head+=4,e},n.getFloat64=function(){var e=this.view.getFloat64(this.head,true);return this.head+=8,e},t=[{key:"remaining",get:function(){return this.tail-this.head}}],function(e,t){for(var n=0;n=Ty.length&&!r(s.data,Ty))throw Error("Invalid ply header");if(-1!==(a=i(s.data,TS)))return [3,3];return [3,1];case 3:if(l=(o=TT(new TextDecoder("ascii").decode(s.data.subarray(0,a)).split("\n"))).elements,u=o.format,c=o.comments,"binary_little_endian"!==u)throw Error("Unsupported ply format");return s.head=a+TS.length,s.compact(),[4,Tv(function(){return Tg(this,function(e){switch(e.label){case 0:if(!TE(l))return [3,2];return [4,Tw(s,l,c)];case 1:case 3:case 5:return [2,e.sent()];case 2:if(l.forEach(function(e){e.properties.forEach(function(n){var i=Tx.get(n.type);if(i){var r=!t||t(n.name)?new i(e.count):null;n.storage=r;}});}),!(1===l.length&&"vertex"===l[0].name&&l[0].properties.every(function(e){return "float"===e.type})))return [3,4];return [4,TA(s,l,c)];case 4:return [4,TC(s,l,c)]}})})()];case 4:return [2,h.sent()]}})}),TI=function(e){return true},TL=function(){function e(e,t){this.app=e,this.maxRetries=t;}var t=e.prototype;return t.load=function(e,t,n){var i=this;return Tv(function(){var r,s,a,o,l,u,c,h,f;return Tg(this,function(d){switch(d.label){case 0:return d.trys.push([0,5,,6]),[4,null!=(s=null==(r=n.file)?void 0:r.contents)?s:fetch(e.load)];case 1:if(!(!(a=d.sent())||!a.body))return [3,2];return t("Error loading resource",null),[3,4];case 2:return l=parseInt(null!=(o=a.headers.get("content-length"))?o:"0",10),u=0,[4,TP(a.body.getReader(),null!=(c=n.data.elementFilter)?c:TI,function(e){u+=e,n&&n.fire("progress",u,l);})];case 3:!(h=d.sent()).isCompressed&&(null==(f=n.data.reorder)||f)&&h.reorderData(),t(null,h.isCompressed&&!n.data.decompress?new Tm(i.app.graphicsDevice,h):new d9(i.app.graphicsDevice,h.isCompressed?h.decompress():h)),d.label=4;case 4:return [3,6];case 5:return t(d.sent(),null),[3,6];case 6:return [2]}})})()},t.open=function(e,t){return t},e}();function TD(e,t,n,i,r,s,a){try{var o=e[s](a),l=o.value;}catch(e){n(e);return}o.done?t(l):Promise.resolve(l).then(i,r);}var TR=function(){function e(e,t){this.app=e,this.maxRetries=t;}var t=e.prototype;return t.loadTextures=function(e,t,n,i){var r,s=this;return (r=function(){var r,a,o,l,u,c,h,f,d,p,m,_,v,g;return function(e,t){var n,i,r,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(o){return function(l){var u=[o,l];if(n)throw TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(s=0)),s;)try{if(n=1,i&&(r=2&u[0]?i.return:u[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,u[1])).done)return r;switch(i=0,r&&(u=[2&u[0],r.value]),u[0]){case 0:case 1:r=u;break;case 4:return s.label++,{value:u[1],done:!1};case 5:s.label++,i=u[1],u=[0];continue;case 7:u=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===u[0]||2===u[0])){s=0;continue}if(3===u[0]&&(!r||u[1]>r[0]&&u[1]0,maxRetries:this.maxRetries,responseType:aY.ResponseType.JSON};aq.get(e.load,s,function(i,s){i?t("Error loading gsplat meta: "+e.original+" ["+i+"]"):r.loadTextures(e,t,n,s);});}},e}();function TM(e,t){return (TM=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var TO=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this,t,"gsplat")||this).parsers={ply:new TL(t,3),json:new TR(t,3)},n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&TM(t,e);var n=t.prototype;return n._getUrlWithoutParams=function(e){return e.indexOf("?")>=0?e.split("?")[0]:e},n._getParser=function(e){var t=en.getExtension(this._getUrlWithoutParams(e)).toLowerCase().replace(".","");return this.parsers[t]||this.parsers.ply},n.load=function(e,t,n){"string"==typeof e&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,n);},n.open=function(e,t,n){return t},t}(p1),Tk=function(){function e(){}return e.setCompressedPRS=function(e,t,n){var i,r,s=n.singleVecs,a=t.___1;a||(i=n.tripleVecs,r=t.___2);var o=a?a[0]:i[r];e.setLocalPosition(s[o],s[o+1],s[o+2]),o=a?a[1]:i[r+1],e.setLocalEulerAngles(s[o],s[o+1],s[o+2]),o=a?a[2]:i[r+2],e.setLocalScale(s[o],s[o+1],s[o+2]);},e.oneCharToKey=function(e,t){var n=e.charCodeAt(0)-t.fieldFirstCode;return t.fieldArray[n]},e.multCharToKey=function(e,t){for(var n=0,i=0;i0,maxRetries:t},function(t,i){if(t){var r="Error while loading scene JSON "+e.original;t.message?(r+=": "+t.message,t.stack&&(r+="\n"+t.stack)):r+=": "+t,n(r);}else n(t,i);});},e}();function TU(e,t){return (TU=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var TV=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){return e.call(this,t,"hierarchy")||this}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&TU(t,e);var n=t.prototype;return n.load=function(e,t){TB.load(e,this.maxRetries,t);},n.open=function(e,t){this._app.systems.script.preloading=true;var n=new TF(this._app,false).parse(t);return this._app.systems.script.preloading=false,n},t}(p1);function Tz(e,t){return (Tz=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var TG=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this,t,"html")||this).decoder=null,n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&Tz(t,e);var n=t.prototype;return n.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),aq.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},function(n,i){n?t("Error loading html resource: "+e.original+" ["+n+"]"):t(null,i);});},n.openBinary=function(e){return null!=this.decoder||(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)},t}(p1);function TH(e,t){return (TH=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var TW=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this,t,"json")||this).decoder=null,n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&TH(t,e);var n=t.prototype;return n.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var n={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(n.responseType=aY.ResponseType.JSON),aq.get(e.load,n,function(n,i){n?t("Error loading JSON resource: "+e.original+" ["+n+"]"):t(null,i);});},n.openBinary=function(e){return null!=this.decoder||(this.decoder=new TextDecoder("utf-8")),JSON.parse(this.decoder.decode(e))},t}(p1);function Tj(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?!!t[Symbol.hasInstance](e):i(e,t)}var TX=function(){function e(){this.removeInvalid=true,this.valid=true,this.enumValidators={occludeSpecular:this._createEnumValidator([0,1,2]),cull:this._createEnumValidator([0,1,2,3]),blendType:this._createEnumValidator([0,1,2,3,4,5,6,7,8,9,10]),depthFunc:this._createEnumValidator([0,1,2,3,4,5,6,7])};}var t=e.prototype;return t.setInvalid=function(e,t){this.valid=false,this.removeInvalid&&delete t[e];},t.validate=function(e){var t="path"===e.mappingFormat;for(var n in e){var i=dm[n];if(!i){dS[n]?delete e[n]:this.valid=false;continue}if(i.startsWith("enum")){var r=i.split(":")[1];this.enumValidators[r]&&!this.enumValidators[r](e[n])&&this.setInvalid(n,e);}else if("number"===i)"number"!=typeof e[n]&&this.setInvalid(n,e);else if("boolean"===i)"boolean"!=typeof e[n]&&this.setInvalid(n,e);else if("string"===i)"string"!=typeof e[n]&&this.setInvalid(n,e);else if("vec2"===i)Tj(e[n],Array)&&2===e[n].length||this.setInvalid(n,e);else if("rgb"===i)Tj(e[n],Array)&&3===e[n].length||this.setInvalid(n,e);else if("texture"===i)t?"string"==typeof e[n]||null===e[n]||Tj(e[n],nN)||this.setInvalid(n,e):"number"==typeof e[n]||null===e[n]||Tj(e[n],nN)||this.setInvalid(n,e);else if("boundingbox"===i)e[n].center&&Tj(e[n].center,Array)&&3===e[n].center.length||this.setInvalid(n,e),e[n].halfExtents&&Tj(e[n].halfExtents,Array)&&3===e[n].halfExtents.length||this.setInvalid(n,e);else if("cubemap"===i)"number"==typeof e[n]||null===e[n]||void 0===e[n]||Tj(e[n],nN)&&e[n].cubemap||this.setInvalid(n,e);else if("chunks"===i)for(var s=Object.keys(e[n]),a=0;a=0}},e}();function TY(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?!!t[Symbol.hasInstance](e):i(e,t)}var Tq=function(){function e(){this._validator=null;}var t=e.prototype;return t.parse=function(e){var t=this.migrate(e),n=this._validate(t),i=new dA;return this.initialize(i,n),i},t.initialize=function(e,t){if(t.validated||(t=this._validate(t)),t.chunks&&t.chunks&&Object.keys(t.chunks).length>0){var n=e.shaderChunks.glsl;Object.entries(t.chunks).forEach(function(e){var t=e[0],i=e[1];return n.set(t,i)});}for(var i in t){var r=dm[i],s=t[i];if("vec2"===r)e[i]=new eX(s[0],s[1]);else if("rgb"===r)e[i]=new eN(s[0],s[1],s[2]);else if("texture"===r)TY(s,nN)?e[i]=s:TY(e[i],nN)&&"number"==typeof s&&s>0||(e[i]=null);else if("cubemap"===r)TY(s,nN)?e[i]=s:TY(e[i],nN)&&"number"==typeof s&&s>0||(e[i]=null),"cubeMap"!==i||s||(e.prefilteredCubemaps=null);else if("boundingbox"===r){var a=new eW(s.center[0],s.center[1],s.center[2]),o=new eW(s.halfExtents[0],s.halfExtents[1],s.halfExtents[2]);e[i]=new e8(a,o);}else e[i]=t[i];}e.update();},t.migrate=function(e){e.shader&&delete e.shader,e.mapping_format&&(e.mappingFormat=e.mapping_format,delete e.mapping_format);var t,n=[["bumpMapFactor","bumpiness"],["aoUvSet","aoMapUv"],["aoMapVertexColor","aoVertexColor"],["diffuseMapVertexColor","diffuseVertexColor"],["emissiveMapVertexColor","emissiveVertexColor"],["specularMapVertexColor","specularVertexColor"],["metalnessMapVertexColor","metalnessVertexColor"],["opacityMapVertexColor","opacityVertexColor"],["glossMapVertexColor","glossVertexColor"],["lightMapVertexColor","lightVertexColor"],["specularMapTint","specularTint"],["metalnessMapTint","metalnessTint"],["clearCoatGlossiness","clearCoatGloss"]];for(t=0;t0,maxRetries:this.maxRetries},function(n,i){n?t&&t("Error loading material: "+e.original+" ["+n+"]"):t&&(i._engine=true,t(null,i));});},n.open=function(e,t){var n=this._parser.parse(t);return t._engine&&(n._data=t,delete t._engine),n},n.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);},n._onAssetUnload=function(e){delete e.data.parameters,delete e.data.chunks,delete e.data.name;},n._assignTexture=function(e,t,n){t.resource[e]=n;},n._getPlaceholderTexture=function(e){var t=TZ[e];return nV(this._device,t)},n._assignPlaceholderTexture=function(e,t){t.resource[e]=this._getPlaceholderTexture(e);},n._onTextureLoad=function(e,t,n){this._assignTexture(e,t,n.resource),t.resource.update();},n._onTextureAdd=function(e,t,n){this._assets.load(n);},n._onTextureRemoveOrUnload=function(e,t,n){var i=t.resource;i&&t.resource[e]===n.resource&&(this._assignPlaceholderTexture(e,t),i.update());},n._assignCubemap=function(e,t,n){if(t.resource[e]=n[0],"cubeMap"===e){var i=n.slice(1);i.every(function(e){return e})?t.resource.prefilteredCubemaps=i:i[0]&&(t.resource.envAtlas=i[0]);}},n._onCubemapLoad=function(e,t,n){this._assignCubemap(e,t,n.resources),this._parser.initialize(t.resource,t.data);},n._onCubemapAdd=function(e,t,n){this._assets.load(n);},n._onCubemapRemoveOrUnload=function(e,t,n){var i=t.resource;t.data.prefilteredCubeMap128===n.resources[1]&&(this._assignCubemap(e,t,[null,null,null,null,null,null,null]),i.update());},n._bindAndAssignAssets=function(e,t){var n,i,r,s=this._parser.migrate(e.data),a=e.resource,o="path"===s.mappingFormat;for(n=0;n0&&(s=l>65535?new Uint32Array((r=new sQ(this._device,2,a)).lock()):new Uint16Array((r=new sQ(this._device,1,a)).lock())),{buffer:r,data:s}},t._parseMeshes=function(e,t,n,i,r,s){for(var a=e.model,o=[],l=0,u=0;u0,maxRetries:this.maxRetries};(e.load.startsWith("blob:")||e.load.startsWith("data:"))&&(".glb"===en.getExtension(e.original).toLowerCase()?r.responseType=aY.ResponseType.ARRAY_BUFFER:r.responseType=aY.ResponseType.JSON),aq.get(e.load,r,function(r,s){if(t)if(r)t("Error loading model: "+e.original+" ["+r+"]");else {for(var a=0;a0,maxRetries:this.maxRetries},function(n,i){n?t("Error loading shader resource: "+e.original+" ["+n+"]"):t(null,i);});},n.openBinary=function(e){return null!=this.decoder||(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)},t}(p1);function Es(e,t){return (Es=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function Ea(e){this.resource&&(this.resource.atlas=e.resource);}function Eo(e){this.registry.load(e);}var El=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this,t,"sprite")||this)._assets=t.assets,n._device=t.graphicsDevice,n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&Es(t,e);var n=t.prototype;return n.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),".json"===en.getExtension(e.original)&&aq.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},function(e,n){e?t(e):t(null,n);});},n.open=function(e,t){var n=new fW(this._device);return e&&(n.__data=t),n},n.patch=function(e,t){var n=e.resource;if(n.__data&&(e.data.pixelsPerUnit=n.__data.pixelsPerUnit,e.data.renderMode=n.__data.renderMode,e.data.frameKeys=n.__data.frameKeys,n.__data.textureAtlasAsset)){var i=t.getByUrl(n.__data.textureAtlasAsset);i&&(e.data.textureAtlasAsset=i.id);}n.startUpdate(),n.renderMode=e.data.renderMode,n.pixelsPerUnit=e.data.pixelsPerUnit,n.frameKeys=e.data.frameKeys,this._updateAtlas(e),n.endUpdate(),e.off("change",this._onAssetChange,this),e.on("change",this._onAssetChange,this);},n._updateAtlas=function(e){var t=e.resource;if(!e.data.textureAtlasAsset){t.atlas=null;return}this._assets.off("load:"+e.data.textureAtlasAsset,Ea,e),this._assets.on("load:"+e.data.textureAtlasAsset,Ea,e);var n=this._assets.get(e.data.textureAtlasAsset);n&&n.resource?t.atlas=n.resource:n?this._assets.load(n):(this._assets.off("add:"+e.data.textureAtlasAsset,Eo,e),this._assets.on("add:"+e.data.textureAtlasAsset,Eo,e));},n._onAssetChange=function(e,t,n,i){"data"===t&&n&&n.textureAtlasAsset&&i&&n.textureAtlasAsset!==i.textureAtlasAsset&&(this._assets.off("load:"+i.textureAtlasAsset,Ea,e),this._assets.off("add:"+i.textureAtlasAsset,Eo,e));},t}(p1),Eu=function(){function e(e,t){this._templateRoot=null,this._app=e,this._data=t;}var t=e.prototype;return t.instantiate=function(){return this._templateRoot||this._parseTemplate(),this._templateRoot.clone()},t._parseTemplate=function(){var e=new TF(this._app,true);this._templateRoot=e.parse(this._data);},e}();function Ec(e,t){return (Ec=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var Eh=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this,t,"template")||this).decoder=null,n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&Ec(t,e);var n=t.prototype;return n.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var n={retry:this.maxRetries>0,maxRetries:this.maxRetries};aq.get(e.load,n,function(n,i){n?t("Error requesting template: "+e.original):t(n,i);});},n.open=function(e,t){return new Eu(this._app,t)},n.openBinary=function(e){return null!=this.decoder||(this.decoder=new TextDecoder("utf-8")),new Eu(this._app,JSON.parse(this.decoder.decode(e)))},t}(p1);function Ef(e,t){return (Ef=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var Ed=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this,t,"text")||this).decoder=null,n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&Ef(t,e);var n=t.prototype;return n.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),aq.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},function(n,i){n?t("Error loading text resource: "+e.original+" ["+n+"]"):t(null,i);});},n.openBinary=function(e){return null!=this.decoder||(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)},t}(p1);function Ep(e,t){return (Ep=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var Em={repeat:0,clamp:1,mirror:2},E_={nearest:0,linear:1,nearest_mip_nearest:2,linear_mip_nearest:4,nearest_mip_linear:3,linear_mip_linear:5},Ev=/^data\.frames\.(\d+)$/,Eg=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this,t,"textureatlas")||this)._loader=t.loader,n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&Ep(t,e);var n=t.prototype;return n.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var n=this,i=this._loader.getHandler("texture");".json"===en.getExtension(e.original)?aq.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},function(i,r){if(i)t(i);else {var s=e.original.replace(".json",".png");n._loader.load(s,"texture",function(e,n){e?t(e):t(null,{data:r,texture:n});});}}):i.load(e,t);},n.open=function(e,t,n){var i=new fX;if(t.texture&&t.data)i.texture=t.texture,i.__data=t.data;else {var r=this._loader.getHandler("texture").open(e,t,n);if(!r)return null;i.texture=r;}return i},n.patch=function(e,t){if(e.resource){e.resource.__data&&(void 0!==e.resource.__data.minfilter&&(e.data.minfilter=e.resource.__data.minfilter),void 0!==e.resource.__data.magfilter&&(e.data.magfilter=e.resource.__data.magfilter),void 0!==e.resource.__data.addressu&&(e.data.addressu=e.resource.__data.addressu),void 0!==e.resource.__data.addressv&&(e.data.addressv=e.resource.__data.addressv),void 0!==e.resource.__data.mipmaps&&(e.data.mipmaps=e.resource.__data.mipmaps),void 0!==e.resource.__data.anisotropy&&(e.data.anisotropy=e.resource.__data.anisotropy),void 0!==e.resource.__data.rgbm&&(e.data.rgbm=!!e.resource.__data.rgbm),e.data.frames=e.resource.__data.frames,delete e.resource.__data);var n=e.resource.texture;if(n&&(n.name=e.name,e.data.hasOwnProperty("minfilter")&&n.minFilter!==E_[e.data.minfilter]&&(n.minFilter=E_[e.data.minfilter]),e.data.hasOwnProperty("magfilter")&&n.magFilter!==E_[e.data.magfilter]&&(n.magFilter=E_[e.data.magfilter]),e.data.hasOwnProperty("addressu")&&n.addressU!==Em[e.data.addressu]&&(n.addressU=Em[e.data.addressu]),e.data.hasOwnProperty("addressv")&&n.addressV!==Em[e.data.addressv]&&(n.addressV=Em[e.data.addressv]),e.data.hasOwnProperty("mipmaps")&&n.mipmaps!==e.data.mipmaps&&(n.mipmaps=e.data.mipmaps),e.data.hasOwnProperty("anisotropy")&&n.anisotropy!==e.data.anisotropy&&(n.anisotropy=e.data.anisotropy),e.data.hasOwnProperty("rgbm"))){var i=e.data.rgbm?t4:t3;n.type!==i&&(n.type=i);}e.resource.texture=n;var r={};for(var s in e.data.frames){var a=e.data.frames[s];r[s]={rect:new eY(a.rect),pivot:new eX(a.pivot),border:new eY(a.border)};}e.resource.frames=r,e.off("change",this._onAssetChange,this),e.on("change",this._onAssetChange,this);}},n._onAssetChange=function(e,t,n){var i;if("data"===t||"data.frames"===t){var r={};for(var s in n.frames)i=n.frames[s],r[s]={rect:new eY(i.rect),pivot:new eX(i.pivot),border:new eY(i.border)};e.resource.frames=r;}else {var a=t.match(Ev);if(a){var o=a[1];n?(e.resource.frames[o]?((i=e.resource.frames[o]).rect.set(n.rect[0],n.rect[1],n.rect[2],n.rect[3]),i.pivot.set(n.pivot[0],n.pivot[1]),i.border.set(n.border[0],n.border[1],n.border[2],n.border[3])):e.resource.frames[o]={rect:new eY(n.rect),pivot:new eX(n.pivot),border:new eY(n.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));}}},t}(p1);function Ey(){var e,t,n,i={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFATC_RGB:11,cTFATC_RGBA_INTERPOLATED_ALPHA:12,cTFRGBA32:13,cTFRGB565:14,cTFRGBA4444:16},r={astc:i.cTFASTC_4x4,dxt:i.cTFBC1,etc1:i.cTFETC1,etc2:i.cTFETC1,pvr:i.cTFPVRTC1_4_RGB,atc:i.cTFATC_RGB,none:i.cTFRGB565},s={astc:i.cTFASTC_4x4,dxt:i.cTFBC3,etc1:i.cTFRGBA4444,etc2:i.cTFETC2,pvr:i.cTFPVRTC1_4_RGBA,atc:i.cTFATC_RGBA_INTERPOLATED_ALPHA,none:i.cTFRGBA4444},a={ETC1:21,ETC2_RGB:22,ETC2_RGBA:23,DXT1:8,DXT5:10,PVRTC_4BPP_RGB_1:26,PVRTC_4BPP_RGBA_1:27,ASTC_4x4:28,ATC_RGB:29,ATC_RGBA:30,R8_G8_B8_A8:7,R5_G6_B5:3,R4_G4_B4_A4:5},o=function(e,t){switch(e){case i.cTFETC1:return t.formats.etc2?a.ETC2_RGB:a.ETC1;case i.cTFETC2:return a.ETC2_RGBA;case i.cTFBC1:return a.DXT1;case i.cTFBC3:return a.DXT5;case i.cTFPVRTC1_4_RGB:return a.PVRTC_4BPP_RGB_1;case i.cTFPVRTC1_4_RGBA:return a.PVRTC_4BPP_RGBA_1;case i.cTFASTC_4x4:return a.ASTC_4x4;case i.cTFATC_RGB:return a.ATC_RGB;case i.cTFATC_RGBA_INTERPOLATED_ALPHA:return a.ATC_RGBA;case i.cTFRGBA32:return a.R8_G8_B8_A8;case i.cTFRGB565:return a.R5_G6_B5;case i.cTFRGBA4444:return a.R4_G4_B4_A4}},l=function(e){for(var t=0;t>3;}return t},c=function(){return "undefined"!=typeof performance?performance.now():0},h=function(e,i,r){if(r){if(e.formats.astc)return "astc"}else if(i){if(e.formats.etc2)return "etc2"}else {if(e.formats.etc2)return "etc2";if(e.formats.etc1)return "etc1"}for(var s=i?n:t,a=0;a0,maxRetries:e.maxRetries};if(e.glueUrl&&e.wasmUrl&&function(){try{var e;if(("undefined"==typeof WebAssembly?"undefined":(e=WebAssembly)&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e)=="object"&&"function"==typeof WebAssembly.instantiate){var t=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(ES(t,WebAssembly.Module))return ES(new WebAssembly.Instance(t),WebAssembly.Instance)}}catch(e){}return false}()){var r=null,s=null;aq.get(e.glueUrl,i,function(e,i){e?t(e):s?n(i,s):r=i;});var a=fetch(e.wasmUrl),o=function(){a.then(function(e){return e.arrayBuffer()}).then(function(e){return WebAssembly.compile(e)}).then(function(e){r?n(r,e):s=e;}).catch(function(e){t(e,null);});};WebAssembly.compileStreaming?WebAssembly.compileStreaming(a).then(function(e){r?n(r,e):s=e;}).catch(function(e){o();}):o();}else aq.get(e.fallbackUrl,i,function(e,i){e?t(e,null):n(i,null);});},Eb=function(){function e(){this.callbacks={},this.queue=[],this.clients=[];}var t=e.prototype;return t.enqueueJob=function(e,t,n,i){if(this.callbacks.hasOwnProperty(e))this.callbacks[e].push(n);else {this.callbacks[e]=[n];var r={url:e,data:t,options:i};this.clients.length>0?this.clients.shift().run(r):this.queue.push(r);}},t.enqueueClient=function(e){this.queue.length>0?e.run(this.queue.shift()):this.clients.push(e);},t.handleResponse=function(e,t,n){var i=this.callbacks[e];if(t)for(var r=0;r0&&++a<=o){var n=100*Math.pow(2,a),l=e.indexOf("?")>=0?"&":"?";r=setTimeout(function(){s.src=e+l+"retry="+Date.now(),r=null;},n);}else i("Error loading Texture from: '"+t+"'");},s.src=e;},n._loadImageBitmap=function(e,t,n,i){var r=this,s={cache:true,responseType:"blob",retry:this.maxRetries>0,maxRetries:this.maxRetries};aq.get(e,s,function(e,t){e?i(e):r._loadImageBitmapFromBlob(t,i);});},n._loadImageBitmapFromBlob=function(e,t){createImageBitmap(e,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then(function(e){return t(null,e)}).catch(function(e){return t(e)});},t}(ER);function EU(){return (EU=Object.assign||function(e){for(var t=1;t1||0!==n.numberOfArrayElements)return null;var i=Ez[n.glInternalFormat];if(void 0===i)return null;for(var r=16+n.bytesOfKeyValueData/4,s=n.numberOfFaces>1,a=[],o=0;o<(n.numberOfMipmapLevels||1);o++){var l,u=t[r++];s&&a.push([]);for(var c=s?a[o]:a,h=0;h<(s?6:1);++h)c.push((l=4*r,18===i?new Uint32Array(e,l,u/4):new Uint8Array(e,l,u))),r+=u+3>>2;}return {format:i,width:n.pixelWidth,height:n.pixelHeight,levels:a,cubemap:s}},t}(ER);function EH(){return (EH=Object.assign||function(e){for(var t=1;t1},i));for(var S=128,x=d?6:1,b=0x31545844===h?8:16,T=0;T32767)return this._readPixelsFlat(e,t,n);var r,s,a,o,l,u,c=[0,0,0,0];if(e.readArray(c),2!==c[0]||2!==c[1]||(128&c[2])!=0)return e.skip(-4),this._readPixelsFlat(e,t,n);var h=new Uint8Array(new ArrayBuffer(t*n*4)),f=i?0:4*t*(n-1);for(s=0;s128){if(r+(l-=128)>t)return null;for(a=0,u=e.readU8();at)return null;for(a=0;ae.length)&&(t=e.length);for(var n=0,i=Array(t);n>1),r=Math.max(1,t>>1),s=new n.constructor(i*r*4),a=Math.floor(e/i),o=Math.floor(t/r),l=a*o,u=0;u>r-1),a=Math.max(1,e._height>>r-1);if(e._cubemap){for(var o=[],l=0;l<6;++l)o.push(i(s,a,e._levels[r-1][l]));e._levels.push(o);}else e._levels.push(i(s,a,e._levels[r-1]));}e._levelsUpdated=e._cubemap?[[true,true,true,true,true,true]]:[true];}},E8=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n=e.call(this,t,"texture")||this,i=t.assets,r=t.graphicsDevice;return n._device=r,n._assets=i,n.imgParser=new EB(i,r),n.parsers={dds:new EK(i),ktx:new EG(i),ktx2:new EX(i,r),basis:new Ek(i,r),hdr:new EJ(i)},n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&E1(t,e);var n,i=t.prototype;return i._getUrlWithoutParams=function(e){return e.indexOf("?")>=0?e.split("?")[0]:e},i._getParser=function(e){var t=en.getExtension(this._getUrlWithoutParams(e)).toLowerCase().replace(".","");return this.parsers[t]||this.imgParser},i._getTextureOptions=function(e){var t={};if(e){(null==(n=e.name)?void 0:n.length)>0&&(t.name=e.name);var n,i=e.data;i.hasOwnProperty("minfilter")&&(t.minFilter=E3[i.minfilter]),i.hasOwnProperty("magfilter")&&(t.magFilter=E3[i.magfilter]),i.hasOwnProperty("addressu")&&(t.addressU=E2[i.addressu]),i.hasOwnProperty("addressv")&&(t.addressV=E2[i.addressv]),i.hasOwnProperty("mipmaps")&&(t.mipmaps=i.mipmaps),i.hasOwnProperty("anisotropy")&&(t.anisotropy=i.anisotropy),i.hasOwnProperty("flipY")&&(t.flipY=!!i.flipY),i.hasOwnProperty("srgb")&&(t.srgb=!!i.srgb),t.type=t3,i.hasOwnProperty("type")?t.type=E4[i.type]:i.hasOwnProperty("rgbm")&&i.rgbm?t.type=t4:e.file&&(8&e.file.opt)!=0&&(t.type=t6);}return t},i.load=function(e,t,n){"string"==typeof e&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,n);},i.open=function(e,t,n){if(e){var i=this._getTextureOptions(n),r=this._getParser(e).open(e,t,this._device,i);return null===r?r=new nN(this._device,{width:4,height:4,format:6}):(E5(r),t.unswizzledGGGR&&(n.file.variants.basis.opt&=-9)),r}},i.patch=function(e,t){var n=e.resource;if(n)for(var i,r=this._getTextureOptions(e),s=function(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return (n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return E$(e,void 0);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return E$(e,void 0)}}(e))){n&&(e=n);var i=0;return function(){return i>=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(Object.keys(r));!(i=s()).done;){var a=i.value;n[a]=r[a];}},n=[{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);}}],function(e,t){for(var n=0;n=a||(a=f,o=e[c],l.copy(h.transform.position),u.copy(h.transform.orientation));}this.fire("result",l,u,t||this._inputSource,o),this.manager.hitTest.fire("result",this,l,u,t||this._inputSource,o),wu.push(s),wu.push(l),wc.push(u);}},t}(ex);function wf(e,t){return (wf=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}wh.EVENT_REMOVE="remove",wh.EVENT_RESULT="result";var wd=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this)||this)._supported=ef.browser&&!!(window.XRSession&&window.XRSession.prototype.requestHitTestSource),n._available=false,n._checkingAvailability=false,n.sources=[],n.manager=t,n._supported&&(n.manager.on("start",n._onSessionStart,n),n.manager.on("end",n._onSessionEnd,n)),n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&wf(t,e);var n,i=t.prototype;return i._onSessionStart=function(){var e=this;if(this.manager.session.enabledFeatures){var t=-1!==this.manager.session.enabledFeatures.indexOf("hit-test");if(!t)return;this._available=t,this.fire("available");}else this._checkingAvailability||(this._checkingAvailability=true,this.manager.session.requestReferenceSpace(we).then(function(t){e.manager.session.requestHitTestSource({space:t}).then(function(t){t.cancel(),e.manager.active&&(e._available=true,e.fire("available"));}).catch(function(){});}).catch(function(){}));},i._onSessionEnd=function(){if(this._available){this._available=false;for(var e=0;eww.dot(wA)},i.getJointById=function(e){return this._jointsById[e]||null},n=[{key:"fingers",get:function(){return this._fingers}},{key:"joints",get:function(){return this._joints}},{key:"tips",get:function(){return this._tips}},{key:"wrist",get:function(){return this._wrist}},{key:"tracking",get:function(){return this._tracking}}],function(e,t){for(var n=0;n0&&(wL.sub2(this._localPosition,this._localPositionLast).divScalar(r),this._linearVelocity.lerp(this._linearVelocity,wL,.15));}else this._velocitiesAvailable=false;}var s=e.getPose(this._xrInputSource.targetRaySpace,this._manager._referenceSpace);s&&(this._dirtyRay=true,this._rayLocal.origin.copy(s.transform.position),this._rayLocal.direction.set(0,0,-1),wD.copy(s.transform.orientation),wD.transformVector(this._rayLocal.direction,this._rayLocal.direction));}},i._updateTransforms=function(){this._dirtyLocal&&(this._dirtyLocal=false,this._localTransform.setTRS(this._localPosition,this._localRotation,eW.ONE));var e=this._manager.camera.parent;e?this._worldTransform.mul2(e.getWorldTransform(),this._localTransform):this._worldTransform.copy(this._localTransform);},i._updateRayTransforms=function(){var e=this._dirtyRay;if(this._dirtyRay=false,this._manager.camera.parent){var t=this._manager.camera.parent.getWorldTransform();t.getTranslation(this._position),this._rotation.setFromMat4(t),this._rotation.transformVector(this._rayLocal.origin,this._ray.origin),this._ray.origin.add(this._position),this._rotation.transformVector(this._rayLocal.direction,this._ray.direction);}else e&&(this._ray.origin.copy(this._rayLocal.origin),this._ray.direction.copy(this._rayLocal.direction));},i.getPosition=function(){return this._position?(this._updateTransforms(),this._worldTransform.getTranslation(this._position),this._position):null},i.getLocalPosition=function(){return this._localPosition},i.getRotation=function(){return this._rotation?(this._updateTransforms(),this._rotation.setFromMat4(this._worldTransform),this._rotation):null},i.getLocalRotation=function(){return this._localRotation},i.getLinearVelocity=function(){return this._velocitiesAvailable?this._linearVelocity:null},i.getOrigin=function(){return this._updateRayTransforms(),this._ray.origin},i.getDirection=function(){return this._updateRayTransforms(),this._ray.direction},i.hitTestStart=function(e){var t=this;void 0===e&&(e={}),e.inputSource=this,e.profile=this._xrInputSource.profiles[0];var n=e.callback;e.callback=function(e,i){i&&t.onHitTestSourceAdd(i),n&&n(e,i);},this._manager.hitTest.start(e);},i.onHitTestSourceAdd=function(e){var t=this;this._hitTestSources.push(e),this.fire("hittest:add",e),e.on("result",function(n,i,r,s){r===t&&t.fire("hittest:result",e,n,i,s);}),e.once("remove",function(){t.onHitTestSourceRemove(e),t.fire("hittest:remove",e);});},i.onHitTestSourceRemove=function(e){var t=this._hitTestSources.indexOf(e);-1!==t&&this._hitTestSources.splice(t,1);},n=[{key:"id",get:function(){return this._id}},{key:"inputSource",get:function(){return this._xrInputSource}},{key:"targetRayMode",get:function(){return this._xrInputSource.targetRayMode}},{key:"handedness",get:function(){return this._xrInputSource.handedness}},{key:"profiles",get:function(){return this._xrInputSource.profiles}},{key:"grip",get:function(){return this._grip}},{key:"hand",get:function(){return this._hand}},{key:"gamepad",get:function(){return this._xrInputSource.gamepad||null}},{key:"selecting",get:function(){return this._selecting}},{key:"squeezing",get:function(){return this._squeezing}},{key:"elementInput",get:function(){return this._elementInput},set:function(e){this._elementInput!==e&&(this._elementInput=e,this._elementInput||(this._elementEntity=null));}},{key:"elementEntity",get:function(){return this._elementEntity}},{key:"hitTestSources",get:function(){return this._hitTestSources}}],function(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}wW.EVENT_REMOVE="remove",wW.EVENT_CHANGE="change";var wq=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this)||this)._supported=ef.browser&&!!window.XRPlane,n._available=false,n._planesIndex=new Map,n._planes=[],n._manager=t,n._supported&&(n._manager.on("start",n._onSessionStart,n),n._manager.on("end",n._onSessionEnd,n)),n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&wX(t,e);var n,i=t.prototype;return i._onSessionStart=function(){this._manager.session.enabledFeatures&&-1!==this._manager.session.enabledFeatures.indexOf("plane-detection")&&(this._available=true,this.fire("available"));},i._onSessionEnd=function(){for(var e=0;ee.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}wq.EVENT_AVAILABLE="available",wq.EVENT_UNAVAILABLE="unavailable",wq.EVENT_ADD="add",wq.EVENT_REMOVE="remove";var wJ=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t,n,i){var r;return void 0===i&&(i=null),(r=e.call(this)||this)._position=new eW,r._rotation=new e0,r._uuid=null,r._uuidRequests=null,r._anchors=t,r._xrAnchor=n,r._uuid=i,r}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&wZ(t,e);var n,i=t.prototype;return i.destroy=function(){if(this._xrAnchor){var e=this._xrAnchor;this._xrAnchor.delete(),this._xrAnchor=null,this.fire("destroy",e,this);}},i.update=function(e){if(this._xrAnchor){var t=e.getPose(this._xrAnchor.anchorSpace,this._anchors.manager._referenceSpace);if(t){if(this._position.equals(t.transform.position)&&this._rotation.equals(t.transform.orientation))return;this._position.copy(t.transform.position),this._rotation.copy(t.transform.orientation),this.fire("change");}}},i.getPosition=function(){return this._position},i.getRotation=function(){return this._rotation},i.persist=function(e){var t=this;if(!this._anchors.persistence){null==e||e(Error("Persistent Anchors are not supported"),null);return}if(this._uuid){null==e||e(null,this._uuid);return}if(this._uuidRequests){e&&this._uuidRequests.push(e);return}this._uuidRequests=[],this._xrAnchor.requestPersistentHandle().then(function(n){t._uuid=n,t._anchors._indexByUuid.set(t._uuid,t),null==e||e(null,n);for(var i,r=wQ(t._uuidRequests);!(i=r()).done;)(0, i.value)(null,n);t._uuidRequests=null,t.fire("persist",n);}).catch(function(n){null==e||e(n,null);for(var i,r=wQ(t._uuidRequests);!(i=r()).done;)(0, i.value)(n,null);t._uuidRequests=null;});},i.forget=function(e){var t=this;if(!this._uuid){null==e||e(Error("Anchor is not persistent"));return}this._anchors.forget(this._uuid,function(n){t._uuid=null,null==e||e(n),t.fire("forget");});},n=[{key:"uuid",get:function(){return this._uuid}},{key:"persistent",get:function(){return !!this._uuid}}],function(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}wJ.EVENT_DESTROY="destroy",wJ.EVENT_CHANGE="change",wJ.EVENT_PERSIST="persist",wJ.EVENT_FORGET="forget";var w2=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n,i,r;return (n=e.call(this)||this)._supported=ef.browser&&!!window.XRAnchor,n._available=false,n._checkingAvailability=false,n._persistence=ef.browser&&!!(null==(r=window)||null==(i=r.XRSession)?void 0:i.prototype.restorePersistentAnchor),n._creationQueue=[],n._index=new Map,n._indexByUuid=new Map,n._list=[],n._callbacksAnchors=new Map,n.manager=t,n._supported&&(n.manager.on("start",n._onSessionStart,n),n.manager.on("end",n._onSessionEnd,n)),n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&w0(t,e);var n,r=t.prototype;return r._onSessionStart=function(){var e,t=(null==(e=this.manager.session.enabledFeatures)?void 0:e.indexOf("anchors"))>=0;t&&(this._available=t,this.fire("available"));},r._onSessionEnd=function(){if(this._available){this._available=false;for(var e=0;ee.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}w4.EVENT_REMOVE="remove",w4.EVENT_CHANGE="change";var w9=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n;return (n=e.call(this)||this)._supported=ef.browser&&!!window.XRMesh,n._available=false,n._index=new Map,n._list=[],n._manager=t,n._supported&&(n._manager.on("start",n._onSessionStart,n),n._manager.on("end",n._onSessionEnd,n)),n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&w8(t,e);var n,i=t.prototype;return i.update=function(e){if(!this._available)if(this._manager.session.enabledFeatures||!e.detectedMeshes.size)return;else this._available=true,this.fire("available");for(var t,n=w6(e.detectedMeshes);!(t=n()).done;){var i=t.value,r=this._index.get(i);r?r.update(e):(r=new w4(this,i),this._index.set(i,r),this._list.push(r),r.update(e),this.fire("add",r));}for(var s,a=w6(this._index.values());!(s=a()).done;){var o=s.value;e.detectedMeshes.has(o.xrMesh)||this._removeMesh(o);}},i._removeMesh=function(e){this._index.delete(e.xrMesh),this._list.splice(this._list.indexOf(e),1),e.destroy(),this.fire("remove",e);},i._onSessionStart=function(){if(this._manager.session.enabledFeatures){var e=-1!==this._manager.session.enabledFeatures.indexOf("mesh-detection");e&&(this._available=e,this.fire("available"));}},i._onSessionEnd=function(){if(this._available){this._available=false;for(var e,t=w6(this._index.values());!(e=t()).done;){var n=e.value;this._removeMesh(n);}this.fire("unavailable");}},n=[{key:"supported",get:function(){return this._supported}},{key:"available",get:function(){return this._available}},{key:"meshes",get:function(){return this._list}}],function(e,t){for(var n=0;ne.length)&&(t=e.length);for(var n=0,i=Array(t);n=e.length?{done:true}:{done:false,value:e[i++]}}}throw TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}Ae.EVENT_DEPTHRESIZE="depth:resize";var Ar=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){var n,i;return (n=e.call(this)||this)._index=new Map,n._indexTmp=new Map,n._list=[],n._supportedColor=ef.browser&&!!window.XRCamera&&!!window.XRWebGLBinding,n._supportedDepth=ef.browser&&!!window.XRDepthInformation,n._availableColor=false,n._availableDepth=false,n._depthUsage="",n._depthFormat="",(i={})[wr]=2,i[ws]=16,i[wa]=15,n._depthFormats=i,n._manager=t,n._manager.on("start",n._onSessionStart,n),n._manager.on("end",n._onSessionEnd,n),n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&An(t,e);var n,i=t.prototype;return i.update=function(e,t){for(var n=0;n0){var o=new e$,l=this.views.list[0];o.copy(l.projMat);var u=o.data,c=2*Math.atan(1/u[5])*180/Math.PI,h=u[5]/u[0],f=u[14]/(u[10]+1),d=u[14]/(u[10]-1);this._camera.camera.setXrProperties({aspectRatio:h,farClip:f,fov:c,horizontalFov:false,nearClip:d});}return this._camera.camera._node.setLocalPosition(this._localPosition),this._camera.camera._node.setLocalRotation(this._localRotation),this.input.update(e),this._type===E7&&(this.hitTest.supported&&this.hitTest.update(e),this.lightEstimation.supported&&this.lightEstimation.update(e),this.imageTracking.supported&&this.imageTracking.update(e),this.anchors.supported&&this.anchors.update(e),this.planeDetection.supported&&this.planeDetection.update(e),this.meshDetection.supported&&this.meshDetection.update(e)),this.fire("update",e),true},n=[{key:"supported",get:function(){return this._supported}},{key:"active",get:function(){return !!this._session}},{key:"type",get:function(){return this._type}},{key:"spaceType",get:function(){return this._spaceType}},{key:"session",get:function(){return this._session}},{key:"frameRate",get:function(){var e,t;return null!=(t=null==(e=this._session)?void 0:e.frameRate)?t:null}},{key:"supportedFrameRates",get:function(){return this._supportedFrameRates}},{key:"framebufferScaleFactor",get:function(){return this._framebufferScaleFactor}},{key:"fixedFoveation",get:function(){var e,t;return null!=(t=null==(e=this._baseLayer)?void 0:e.fixedFoveation)?t:null},set:function(e){var t,n;(null!=(n=null==(t=this._baseLayer)?void 0:t.fixedFoveation)?n:null)!==null&&(this.app.graphicsDevice.samples,this._baseLayer.fixedFoveation=e);}},{key:"camera",get:function(){return this._camera?this._camera.entity:null}},{key:"visibilityState",get:function(){return this._session?this._session.visibilityState:null}}],function(e,t){for(var n=0;n0&&this._renderAtlas(this.chars.concat(n));},i.destroy=function(){this.atlases.forEach(function(e){return e.destroy()}),this.chars=null,this.color=null,this.data=null,this.fontName=null,this.fontSize=null,this.glyphSize=null,this.intensity=null,this.atlases=null,this.type=null,this.fontWeight=null;},i._colorToRgbString=function(e,t){var i=Math.round(255*e.r),r=Math.round(255*e.g),s=Math.round(255*e.b);return t?"rgba("+i+", "+r+", "+s+", "+e.a+")":"rgb("+i+", "+r+", "+s+")"},i.renderCharacter=function(e,t,n,i,r){e.fillStyle=r,e.fillText(t,n,i);},i._getAtlas=function(e){return e>=this.atlases.length&&(this.atlases[e]=new Af(this.app.graphicsDevice,this.width,this.height,"font-atlas-"+this.fontName+"-"+e)),this.atlases[e]},i._renderAtlas=function(e){this.chars=e;var t=this.width,n=this.height,i=this._colorToRgbString(this.color,false),r=this.color.a;this.color.a=1/255;var s=this._colorToRgbString(this.color,true);this.color.a=r;var a=0,o=this._getAtlas(a++);o.clear(s),this.data=this._createJson(this.chars,this.fontName,t,n);for(var l=ev.getSymbols(this.chars.join("")),u=0,c=0,h={},f=0;fT&&(T=this.fontSize*this.fontSize/E,o.ctx.font=this.fontWeight+" "+T.toString()+"px "+this.fontName,E=this.fontSize),this.renderCharacter(o.ctx,x,g+_,y+v,i);var w=this.padding+(this.glyphSize-E)/2,A=-this.padding+h[x].descent-c,C=E;this._addChar(this.data,x,b,g,y,p,m,w,A,C,a-1,t,n),(g+=p)+p>t&&(g=0,(y+=m)+m>n&&((o=this._getAtlas(a++)).clear(s),y=0));}this.atlases.splice(a).forEach(function(e){return e.destroy()}),this.atlases.forEach(function(e){return e.texture.upload()}),this.fire("render");},i._createJson=function(e,t,n,i){return {version:3,intensity:this.intensity,info:{face:t,width:n,height:i,maps:[{width:n,height:i}]},chars:{}}},i._addChar=function(e,t,n,i,r,s,a,o,l,u,c,h,f){e.info.maps.lengthr.indexOf(h))&&h.enabled&&l[c]&&h.camerasSet.has(n.camera)){var f=u[c];h._clearDepthBuffer&&t.clear(n.camera,false,true,false);for(var d=h.meshInstances,p=0;p0&&(i.clusteredLightingEnabled&&t.worldClustersAllocator.empty.activate(),t.setCameraUniforms(n.camera,a),e.supportsUniformBuffers&&t.setupViewUniformBuffers(this.viewBindGroups,t.viewUniformFormat,t.viewBindGroupFormat,null),t.renderForward(n.camera,a,Am,A_,3,function(t){e.setBlendState(nY.NOBLEND);}),Am.length=0);}}},t}(s0),Ag=new Set,Ay=new eY,AS=function(){function e(e,t,n){var i=this;this.renderTarget=null,this.mapping=new Map,this.deviceValid=true,this.renderer=e.renderer,this.device=e.graphicsDevice,this.renderPass=new Av(this.device,e.renderer),this.width=0,this.height=0,this.resize(t,n),this.device.on("destroy",function(){i.deviceValid=false;});}var t=e.prototype;return t.getSelection=function(e,t,n,i){ void 0===n&&(n=1),void 0===i&&(i=1);var r=this.device;if(r.isWebGPU)return [];t=this.renderTarget.height-(t+i);var s=this.sanitizeRect(e,t,n,i);r.setRenderTarget(this.renderTarget),r.updateBegin();var a=new Uint8Array(4*s.z*s.w);return r.readPixels(s.x,s.y,s.z,s.w,a),r.updateEnd(),this.decodePixels(a,this.mapping)},t.getSelectionAsync=function(e,t,n,i){var r,s=this;void 0===n&&(n=1),void 0===i&&(i=1),(null==(r=this.device)?void 0:r.isWebGL2)&&(t=this.renderTarget.height-(t+i));var a=this.sanitizeRect(e,t,n,i);return this.renderTarget.colorBuffer.read(a.x,a.y,a.z,a.w,{renderTarget:this.renderTarget,immediate:true}).then(function(e){return s.decodePixels(e,s.mapping)})},t.sanitizeRect=function(e,t,n,i){var r=this.renderTarget.width,s=this.renderTarget.height;return e=ek.clamp(Math.floor(e),0,r-1),t=ek.clamp(Math.floor(t),0,s-1),n=Math.min(n=Math.floor(Math.max(n,1)),r-e),i=Math.min(i=Math.floor(Math.max(i,1)),s-t),Ay.set(e,t,n,i)},t.decodePixels=function(e,t){var n=[];if(this.deviceValid){for(var i=e.length,r=0;r>>0;0xffffffff!==l&&Ag.add(t.get(l));}Ag.forEach(function(e){e&&n.push(e);}),Ag.clear();}return n},t.allocateRenderTarget=function(){var e=new nN(this.device,{format:7,width:this.width,height:this.height,mipmaps:false,minFilter:0,magFilter:0,addressU:1,addressV:1,name:"pick"});this.renderTarget=new ic({colorBuffer:e,depth:true});},t.releaseRenderTarget=function(){this.renderTarget&&(this.renderTarget.destroyTextureBuffers(),this.renderTarget.destroy(),this.renderTarget=null);},t.prepare=function(e,t,n){r=n,(null!=cX&&"undefined"!=typeof Symbol&&cX[Symbol.hasInstance]?!!cX[Symbol.hasInstance](r):i(r,cX))&&(n=[n]),this.renderTarget&&this.width===this.renderTarget.width&&this.height===this.renderTarget.height||(this.releaseRenderTarget(),this.allocateRenderTarget()),this.mapping.clear();var r,s=this.renderPass;s.init(this.renderTarget),s.colorOps.clearValue=eN.WHITE,s.colorOps.clear=true,s.depthStencilOps.clearDepth=true,s.update(e,t,n,this.mapping),s.render();},t.resize=function(e,t){this.width=Math.floor(e),this.height=Math.floor(t);},e}();function Ax(e,t){return (Ax=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var Ab=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){return e.call(this,t,"scenesettings")||this}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&Ax(t,e);var n=t.prototype;return n.load=function(e,t){TB.load(e,this.maxRetries,t);},n.open=function(e,t){return t.settings},t}(p1);function AT(e,t){if("function"!=typeof t&&null!==t)throw TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:true,configurable:true}}),t&&AE(e,t);}function AE(e,t){return (AE=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var Aw=new eW,AA=new eW,AC=new tn,AP=new tn,AI=new tn;AC.end=new eW,AP.end=new eW,AI.end=new eW;var AL=new eW,AD=new eW,AR=new eW,AM=new eW,AO=new eW,Ak=new eW,AN=new eW,AF=new eW,AB=new eW,AU=new eW,AV=new eW,Az=new eW,AG=new eW,AH=new eW,AW=new eW,Aj=new eW,AX=new eW,AY=new eW,Aq=new eW,AK=new eW,AZ=new eY;function AQ(e,t,n){return AV.cross(e,t).dot(n)}var AJ=function(){function e(e,t,n){this.event=e,this.element=t,this.camera=n,this._stopPropagation=false;}return e.prototype.stopPropagation=function(){this._stopPropagation=true,this.event&&(this.event.stopImmediatePropagation(),this.event.stopPropagation());},e}(),A$=function(e){function t(t,n,i,r,s,a,o){var l;return (l=e.call(this,t,n,i)||this).x=r,l.y=s,l.ctrlKey=t.ctrlKey||false,l.altKey=t.altKey||false,l.shiftKey=t.shiftKey||false,l.metaKey=t.metaKey||false,l.button=t.button,ax.isPointerLocked()?(l.dx=t.movementX||t.webkitMovementX||t.mozMovementX||0,l.dy=t.movementY||t.webkitMovementY||t.mozMovementY||0):(l.dx=r-a,l.dy=s-o),l.wheelDelta=0,"wheel"===t.type&&(t.deltaY>0?l.wheelDelta=1:t.deltaY<0&&(l.wheelDelta=-1)),l}return AT(t,e),t}(AJ),A0=function(e){function t(t,n,i,r,s,a){var o;return (o=e.call(this,t,n,i)||this).touches=t.touches,o.changedTouches=t.changedTouches,o.x=r,o.y=s,o.touch=a,o}return AT(t,e),t}(AJ),A1=function(e){function t(t,n,i,r){var s;return (s=e.call(this,t,n,i)||this).inputSource=r,s}return AT(t,e),t}(AJ),A2=function(){function e(e,t){this._app=null,this._attached=false,this._target=null,this._enabled=true,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||false!==t.useMouse,this._useTouch=!t||false!==t.useTouch,this._useXr=!t||false!==t.useXr,this._selectEventsAttached=false,ef.touch&&(this._clickedEntities={}),this.attach(e);}var t,n=e.prototype;return n.attach=function(e){this._attached&&(this._attached=false,this.detach()),this._target=e,this._attached=true;var t=!!ef.passiveEvents&&{passive:true};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&&ef.touch&&(this._target.addEventListener("touchstart",this._touchstartHandler,t),this._target.addEventListener("touchend",this._touchendHandler,false),this._target.addEventListener("touchmove",this._touchmoveHandler,false),this._target.addEventListener("touchcancel",this._touchcancelHandler,false)),this.attachSelectEvents();},n.attachSelectEvents=function(){!this._selectEventsAttached&&this._useXr&&this.app&&this.app.xr&&this.app.xr.supported&&(this._clickedEntities||(this._clickedEntities={}),this._selectEventsAttached=true,this.app.xr.on("start",this._onXrStart,this));},n.detach=function(){if(this._attached){this._attached=false;var e=!!ef.passiveEvents&&{passive:true};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,false),this._target.removeEventListener("touchmove",this._touchmoveHandler,false),this._target.removeEventListener("touchcancel",this._touchcancelHandler,false)),this._selectEventsAttached&&(this._selectEventsAttached=false,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;}},n.addElement=function(e){ -1===this._elements.indexOf(e)&&this._elements.push(e);},n.removeElement=function(e){var t=this._elements.indexOf(e);-1!==t&&this._elements.splice(t,1);},n._handleUp=function(e){this._enabled&&(ax.isPointerLocked()||(this._calcMouseCoords(e),this._onElementMouseEvent("mouseup",e)));},n._handleDown=function(e){this._enabled&&(ax.isPointerLocked()||(this._calcMouseCoords(e),this._onElementMouseEvent("mousedown",e)));},n._handleMove=function(e){this._enabled&&(this._calcMouseCoords(e),this._onElementMouseEvent("mousemove",e),this._lastX=V,this._lastY=z);},n._handleWheel=function(e){this._enabled&&(this._calcMouseCoords(e),this._onElementMouseEvent("mousewheel",e));},n._determineTouchedElements=function(e){for(var t={},n=this.app.systems.camera.cameras,i=n.length-1;i>=0;i--){for(var r=n[i],s=0,a=e.changedTouches.length,o=0;o=0;f--)this._getTargetElementByCoords(t[f],h.x,h.y)!==o||this._clickedEntities[o.entity.getGuid()]||(this._fireEvent("click",new A0(e,o,l,u,c,s)),this._clickedEntities[o.entity.getGuid()]=Date.now());this._fireEvent(e.type,new A0(e,o,l,u,c,s));}}}},n._handleTouchMove=function(e){if(e.preventDefault(),this._enabled)for(var t=this._determineTouchedElements(e),n=0,i=e.changedTouches.length;n=0&&(n=s[a],!(i=this._getTargetElementByCoords(n,V,z)));a--);if(this._hoveredElement=i,("mousemove"===e||"mouseup"===e)&&this._pressedElement?this._fireEvent(e,new A$(t,this._pressedElement,n,V,z,this._lastX,this._lastY)):i&&(this._fireEvent(e,new A$(t,i,n,V,z,this._lastX,this._lastY)),"mousedown"===e&&(this._pressedElement=i)),r!==this._hoveredElement&&(r&&this._fireEvent("mouseleave",new A$(t,r,n,V,z,this._lastX,this._lastY)),this._hoveredElement&&this._fireEvent("mouseenter",new A$(t,this._hoveredElement,n,V,z,this._lastX,this._lastY))),"mouseup"===e&&this._pressedElement){if(this._pressedElement===this._hoveredElement){var o=this._hoveredElement.entity.getGuid(),l=!this._clickedEntities;if(this._clickedEntities){var u=this._clickedEntities[o]||0;l=Date.now()-u>300,delete this._clickedEntities[o];}l&&this._fireEvent("click",new A$(t,this._hoveredElement,n,V,z,this._lastX,this._lastY));}this._pressedElement=null;}},n._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);},n._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);},n._onXrUpdate=function(){if(this._enabled)for(var e=this.app.xr.input.inputSources,t=0;t=0&&(s=o[l],!(i=this._getTargetElementByRay(AI,s)));l--);}t._elementEntity=i||null,i?(this._selectedElements[t.id]=i,r=i):delete this._selectedElements[t.id],a!==r&&(a&&this._fireEvent("selectleave",new A1(n,a,s,t)),r&&this._fireEvent("selectenter",new A1(n,r,s,t)));var u=this._selectedPressedElements[t.id];"selectmove"===e&&u&&this._fireEvent("selectmove",new A1(n,u,s,t)),"selectstart"===e&&(this._selectedPressedElements[t.id]=r,r&&this._fireEvent("selectstart",new A1(n,r,s,t))),!t.elementInput&&u&&(delete this._selectedPressedElements[t.id],a&&this._fireEvent("selectend",new A1(n,u,s,t))),"selectend"===e&&t.elementInput&&(delete this._selectedPressedElements[t.id],u&&this._fireEvent("selectend",new A1(n,u,s,t)),u&&u===a&&this._fireEvent("click",new A1(n,u,s,t)));},n._fireEvent=function(e,t){for(var n=t.element;n.fire(e,t),!t._stopPropagation&&n.entity.parent&&(n=n.entity.parent.element););},n._calcMouseCoords=function(e){var t=this._target.getBoundingClientRect(),n=Math.floor(t.left),i=Math.floor(t.top);V=e.clientX-n,z=e.clientY-i;},n._sortElements=function(e,t){var n=this.app.scene.layers.sortTransparentLayers(e.layers,t.layers);return 0!==n?n: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},n._getTargetElementByCoords=function(e,t,n){var i=this._calculateRayScreen(t,n,e,AC)?AC:null,r=this._calculateRay3d(t,n,e,AP)?AP:null;return this._getTargetElement(e,i,r)},n._getTargetElementByRay=function(e,t){AC.origin.copy(e.origin),AC.direction.copy(e.direction),AC.end.copy(AC.direction).mulScalar(2*t.farClip).add(AC.origin);var n=t.worldToScreen(AC.origin,Aw),i=this._calculateRayScreen(n.x,n.y,t,AP)?AP:null;return this._getTargetElement(t,i,AC)},n._getTargetElement=function(e,t,n){var i=null,r=1/0;this._elements.sort(this._sortHandler);for(var s=0,a=this._elements.length;s=0){i=o;break}}else {if(!n)continue;var l=this._checkElement(n,o,false);if(l>=0&&(l=l&&h<=l+a&&f<=u&&f>=c&&(h=r*(h-l)/a,f=s*(f-c)/o,f=s-f,i.origin.set(h,f,1),i.direction.set(0,0,-1),i.end.copy(i.direction).mulScalar(2).add(i.origin),true)},n._calculateRay3d=function(e,t,n,i){var r=this._target.clientWidth,s=this._target.clientHeight,a=n.rect.z*r,o=n.rect.w*s,l=n.rect.x*r,u=(1-n.rect.y)*s,c=u-o,h=e,f=t;return e>=l&&e<=l+a&&t<=u&&f>=c&&(h=r*(h-l)/a,f=s*(f-c)/o,n.screenToWorld(h,f,n.nearClip,Aw),n.screenToWorld(h,f,n.farClip,AA),i.origin.copy(Aw),i.direction.set(0,0,-1),i.end.copy(AA),true)},n._checkElement=function(t,n,i){if(n.maskedBy&&0>this._checkElement(t,n.maskedBy.element,i))return -1;var r=i?e.calculateScaleToScreen(n):e.calculateScaleToWorld(n),s=e.buildHitCorners(n,i?n.screenCorners:n.worldCorners,r);return function(e,t,n){AL.sub2(t,e),AD.sub2(n[0],e),AR.sub2(n[1],e),AM.sub2(n[2],e),Ak.cross(AM,AL);var i,r,s=AD.dot(Ak);if(s>=0){if((i=-AR.dot(Ak))<0||(r=AQ(AL,AR,AD))<0)return -1;var a=1/(i+s+r);AN.copy(n[0]).mulScalar(i*a),AF.copy(n[1]).mulScalar(s*a),AB.copy(n[2]).mulScalar(r*a),AU.copy(AN).add(AF).add(AB);}else {if(AO.sub2(n[3],e),(i=AO.dot(Ak))<0||(r=AQ(AL,AD,AO))<0)return -1;var o=1/(i+(s=-s)+r);AN.copy(n[0]).mulScalar(i*o),AF.copy(n[3]).mulScalar(s*o),AB.copy(n[2]).mulScalar(r*o),AU.copy(AN).add(AF).add(AB);}return 1e-8>AL.sub2(n[0],n[2]).lengthSq()||1e-8>AL.sub2(n[1],n[3]).lengthSq()?-1:AU.sub(e).lengthSq()}(t.origin,t.end,s)},e.buildHitCorners=function(e,t,n){var i=t;if(e.entity&&e.entity.button){var r=e.entity.button.hitPadding||AZ;AG.copy(e.entity.up),AH.copy(AG).mulScalar(-1),Aj.copy(e.entity.right),AW.copy(Aj).mulScalar(-1),AG.mulScalar(r.w*n.y),AH.mulScalar(r.y*n.y),Aj.mulScalar(r.z*n.x),AW.mulScalar(r.x*n.x),AX.copy(i[0]).add(AH).add(AW),AY.copy(i[1]).add(AH).add(Aj),Aq.copy(i[2]).add(AG).add(Aj),AK.copy(i[3]).add(AG).add(AW),i=[AX,AY,Aq,AK];}if(n.x<0){var s=i[2].x,a=i[0].x;i[0].x=s,i[1].x=a,i[2].x=a,i[3].x=s;}if(n.y<0){var o=i[2].y,l=i[0].y;i[0].y=o,i[1].y=o,i[2].y=l,i[3].y=l;}if(n.z<0){var u=i[2].x,c=i[2].y,h=i[2].z;i[2].x=i[0].x,i[2].y=i[0].y,i[2].z=i[0].z,i[0].x=u,i[0].y=c,i[0].z=h;}return i},e.calculateScaleToScreen=function(e){var t=e.entity,n=e.screen.screen.scale;for(Az.set(n,n,n);t&&!t.screen;)Az.mul(t.getLocalScale()),t=t.parent;return Az},e.calculateScaleToWorld=function(e){var t=e.entity;for(Az.set(1,1,1);t;)Az.mul(t.getLocalScale()),t=t.parent;return Az},t=[{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e;}},{key:"app",get:function(){return this._app||A},set:function(e){this._app=e;}}],function(e,t){for(var n=0;n=0?this.anisotropyRotation=0:this.anisotropyRotation=90;}}),A7("sheenTint"),A7("diffuseTint"),A7("emissiveTint"),A7("ambientTint"),A9("specularTint","specularMapTint"),A9("aoVertexColor","aoMapVertexColor"),A9("diffuseVertexColor","diffuseMapVertexColor"),A9("specularVertexColor","specularMapVertexColor"),A9("emissiveVertexColor","emissiveMapVertexColor"),A9("metalnessVertexColor","metalnessMapVertexColor"),A9("glossVertexColor","glossMapVertexColor"),A9("opacityVertexColor","opacityMapVertexColor"),A9("lightVertexColor","lightMapVertexColor"),A9("sheenGloss","sheenGlossiess"),A9("clearCoatGloss","clearCostGlossiness"),Ce("refraction","useRefraction");var Ct=Object.getOwnPropertyNames(new f2);for(var Cn in Ct)Ce(Ct[Cn]);pj.prototype.getAssetById=function(e){return this.get(e)},Object.defineProperty(wM.prototype,"ray",{get:function(){return this._rayLocal}}),Object.defineProperty(wM.prototype,"position",{get:function(){return this._localPosition}}),Object.defineProperty(wM.prototype,"rotation",{get:function(){return this._localRotation}}),Object.defineProperty(A2.prototype,"wheel",{get:function(){return -2*this.wheelDelta}}),Object.defineProperty(ay.prototype,"wheel",{get:function(){return -2*this.wheelDelta}}),mm.prototype.isFullscreen=function(){return !!document.fullscreenElement},mm.prototype.enableFullscreen=function(e,t,n){e=e||this.graphicsDevice.canvas;var i=function(){t(),document.removeEventListener("fullscreenchange",i);},r=function(){n(),document.removeEventListener("fullscreenerror",r);};t&&document.addEventListener("fullscreenchange",i,false),n&&document.addEventListener("fullscreenerror",r,false),e.requestFullscreen?e.requestFullscreen(Element.ALLOW_KEYBOARD_INPUT):n();},mm.prototype.disableFullscreen=function(e){var t=function(){e(),document.removeEventListener("fullscreenchange",t);};e&&document.addEventListener("fullscreenchange",t,false),document.exitFullscreen();},mm.prototype.getSceneUrl=function(e){var t=this.scenes.find(e);return t?t.url:null},mm.prototype.loadScene=function(e,t){this.scenes.loadScene(e,t);},mm.prototype.loadSceneHierarchy=function(e,t){this.scenes.loadSceneHierarchy(e,t);},mm.prototype.loadSceneSettings=function(e,t){this.scenes.loadSceneSettings(e,t);},g3.prototype.setVisible=function(e){this.enabled=e;},Object.defineProperty(yL.prototype,"bodyType",{get:function(){return this.type},set:function(e){this.type=e;}}),yL.prototype.syncBodyToEntity=function(){this._updateDynamic();},yU.prototype.setGravity=function(){1==arguments.length?this.gravity.copy(arguments[0]):this.gravity.set(arguments[0],arguments[1],arguments[2]);};var Ci=function(){function e(e){this._frameIndex=0,this._frameTimings=[],this._timings=[],this._prevTimings=[],this.unitsName="ms",this.decimalPlaces=1,this.enabled=true,e.on("frameupdate",this.begin.bind(this,"update")),e.on("framerender",this.mark.bind(this,"render")),e.on("frameend",this.mark.bind(this,"other"));}var t,n=e.prototype;return n.begin=function(e){if(this.enabled){this._frameIndex0){var n=this._frameTimings[this._frameIndex-1];n[1]=t-n[1];}else if(this._timings.length>0){var i=this._timings[this._timings.length-1];i[1]=t-i[1];}if(this._frameIndex>=this._frameTimings.length)this._frameTimings.push([e,t]);else {var r=this._frameTimings[this._frameIndex];r[0]=e,r[1]=t;}this._frameIndex++;}},t=[{key:"timings",get:function(){return this._timings.slice(0,-1).map(function(e){return e[1]})}}],function(e,t){for(var n=0;n3&&(this.statNames.length=3),this.unitsName=i,this.decimalPlaces=n,this.multiplier=r||1,e.on("frameupdate",function(e){for(var t,n,i=0;ithis.textRefreshRate&&(this.timingText=(this.avgTotal/this.avgCount).toFixed(this.timer.decimalPlaces),this.avgTimer=0,this.avgTotal=0,this.avgCount=0),this.enabled){for(var i=0,r=1.5*this.watermark,s=0;s=512&&(a=5,o+=16),s.set(e,{l:n,r:i,a:l,d:u,w:c,h:l+u,x:a,y:o}),a+=c+5;}),i.width=512,i.height=ek.nextPowerOfTwo(o+16+5),n(r),r.fillStyle="rgb(0, 0, 0)",r.fillRect(0,0,i.width,i.height),s.forEach(function(e,t){r.fillStyle="."===t||1===t.length&&t.charCodeAt(0)>=48&&57>=t.charCodeAt(0)?"rgb(255, 255, 255)":"rgb(170, 170, 170)",r.fillText(t,e.x-e.l,e.y+e.a);}),this.placements=s;for(var l=r.getImageData(0,0,i.width,i.height).data,u=0;u VertexOutput {\n var output : VertexOutput;\n output.position = vec4(input.vertex_position.xy * 2.0 - 1.0, 0.5, 1.0);\n output.uv0 = input.vertex_texCoord0;\n output.wordFlag = input.vertex_position.z;\n return output;\n }\n",fragmentWGSL:"\n varying uv0: vec4f;\n varying wordFlag: f32;\n uniform clr: vec4f;\n var graphTex : texture_2d;\n var graphTex_sampler : sampler;\n var wordsTex : texture_2d;\n var wordsTex_sampler : sampler;\n @fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput {\n var uv0: vec4f = input.uv0;\n var graphSample: vec4f = textureSample(graphTex, graphTex_sampler, uv0.xy);\n var graph: vec4f;\n if (uv0.w < graphSample.r) {\n graph = vec4f(0.7, 0.2, 0.2, 1.0);\n } else if (uv0.w < graphSample.g) {\n graph = vec4f(0.2, 0.7, 0.2, 1.0);\n } else if (uv0.w < graphSample.b) {\n graph = vec4f(0.2, 0.2, 0.7, 1.0);\n } else {\n graph = vec4f(0.0, 0.0, 0.0, 1.0 - 0.25 * sin(uv0.w * 3.14159));\n }\n var words: vec4f = textureSample(wordsTex, wordsTex_sampler, vec2f(uv0.x, 1.0 - uv0.y));\n var output: FragmentOutput;\n output.color = mix(graph, words, input.wordFlag) * uniform.clr;\n return output;\n }\n",attributes:{vertex_position:tA,vertex_texCoord0:tM}});this.material=s,s.cull=0,s.depthState=nZ.NODEPTH,s.blendState=new nY(true,0,6,8,0,1,1),s.update(),this.meshInstance=new lL(this.mesh,s,new us("MiniStatsMesh")),this.uniforms={clr:new Float32Array(4)},this.targetSize={width:e.width,height:e.height};}var t=e.prototype;return t.quad=function(e,t,n,i,r,s,a,o,l,u){ void 0===u&&(u=0);var c=this.targetSize.width,h=this.targetSize.height,f=e/c,d=t/h,p=(e+n)/c,m=(t+i)/h,_=l.width,v=l.height,g=r/_,y=s/v,S=(r+(null!=a?a:n))/_,x=(s+(null!=o?o:i))/v;this.data.set([f,d,u,g,y,0,0,p,d,u,S,y,1,0,p,m,u,S,x,1,1,f,m,u,g,x,0,1],28*this.quads),this.quads++,this.prim.count+=6;},t.startFrame=function(){this.quads=0,this.prim.count=0,this.targetSize.width=this.device.canvas.scrollWidth,this.targetSize.height=this.device.canvas.scrollHeight;},t.render=function(e,t,n,i,r,s){this.buffer.setData(this.data.buffer),this.uniforms.clr.set(r,0),this.material.setParameter("clr",this.uniforms.clr),this.material.setParameter("graphTex",n),this.material.setParameter("wordsTex",i),e.drawMeshInstance(this.meshInstance,t);},e}(),Cu=function(){function e(t,n){var i=this,r=t.graphicsDevice;n=n||e.getDefaultOptions(),this.initGraphs(t,r,n);var s=new Set(["","ms","0","1","2","3","4","5","6","7","8","9","."].concat(this.graphs.map(function(e){return e.name})).concat(n.stats?n.stats.map(function(e){return e.unitsName}):[]).filter(function(e){return !!e}));this.wordAtlas=new Co(r,s),this.sizes=n.sizes,this._activeSizeIndex=n.startSizeIndex;var a=document.createElement("div");a.setAttribute("id","mini-stats"),a.style.cssText="position:fixed;bottom:0;left:0;background:transparent;",document.body.appendChild(a),a.addEventListener("mouseenter",function(e){i.opacity=1;}),a.addEventListener("mouseleave",function(e){i.opacity=.7;}),a.addEventListener("click",function(e){e.preventDefault(),i._enabled&&(i.activeSizeIndex=(i.activeSizeIndex+1)%i.sizes.length,i.resize(i.sizes[i.activeSizeIndex].width,i.sizes[i.activeSizeIndex].height,i.sizes[i.activeSizeIndex].graphs));}),r.on("resizecanvas",this.updateDiv,this),r.on("losecontext",this.loseContext,this),t.on("postrender",this.postRender,this),this.app=t,this.drawLayer=t.scene.layers.getLayerById(4),this.device=r,this.render2d=new Cl(r),this.div=a,this.width=0,this.height=0,this.gspacing=2,this.clr=[1,1,1,.5],this._enabled=true,this.activeSizeIndex=this._activeSizeIndex;}var t,n=e.prototype;return n.destroy=function(){this.device.off("resizecanvas",this.updateDiv,this),this.device.off("losecontext",this.loseContext,this),this.app.off("postrender",this.postRender,this),this.graphs.forEach(function(e){return e.destroy()}),this.wordAtlas.destroy(),this.texture.destroy();},n.initGraphs=function(e,t,n){var i=this;if(this.graphs=[],n.cpu.enabled){var r=new Ci(e),s=new Ca("CPU",e,n.cpu.watermark,n.textRefreshRate,r);this.graphs.push(s);}if(n.gpu.enabled){var a=new Cr(t),o=new Ca("GPU",e,n.gpu.watermark,n.textRefreshRate,a);this.graphs.push(o);}n.stats&&n.stats.forEach(function(t){var r=new Cs(e,t.stats,t.decimalPlaces,t.unitsName,t.multiplier),s=new Ca(t.name,e,t.watermark,n.textRefreshRate,r);i.graphs.push(s);});var l=n.sizes.reduce(function(e,t){return t.width>e?t.width:e},0);this.texture=new nN(t,{name:"mini-stats-graph-texture",width:ek.nextPowerOfTwo(l),height:ek.nextPowerOfTwo(this.graphs.length),mipmaps:false,minFilter:0,magFilter:0,addressU:0,addressV:0}),this.graphs.forEach(function(e,t){e.texture=i.texture,e.yOffset=t;});},n.render=function(){var e=this.graphs,t=this.wordAtlas,n=this.render2d,i=this.width,r=this.height,s=this.gspacing;n.startFrame();for(var a=0;a>1|(21845&CP)<<1;CI=(61680&(CI=(52428&CI)>>2|(13107&CI)<<2))>>4|(3855&CI)<<4,CC[CP]=((65280&CI)>>8|(255&CI)<<8)>>1;}for(var CL=function(e,t,n){for(var i,r=e.length,s=0,a=new Cv(t);s>l]=u;}else for(s=0,i=new Cv(r);s>15-e[s]);return i},CD=new C_(288),CP=0;CP<144;++CP)CD[CP]=8;for(var CP=144;CP<256;++CP)CD[CP]=9;for(var CP=256;CP<280;++CP)CD[CP]=7;for(var CP=280;CP<288;++CP)CD[CP]=8;for(var CR=new C_(32),CP=0;CP<32;++CP)CR[CP]=5;var CM=CL(CD,9,0);CL(CD,9,1);var CO=CL(CR,5,0);CL(CR,5,1);var Ck=function(e){return (e+7)/8|0},CN=function(e,t,n){return (null==n||n>e.length)&&(n=e.length),new C_(e.subarray(t,n))},CF=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],CB=function(e,t,n){var i=Error(t||CF[e]);if(i.code=e,Error.captureStackTrace&&Error.captureStackTrace(i,CB),!n)throw i;return i},CU=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>8;},CV=function(e,t,n){n<<=7&t;var i=t/8|0;e[i]|=n,e[i+1]|=n>>8,e[i+2]|=n>>16;},Cz=function(e,t){for(var n=[],i=0;if&&(f=s[i].s);var d=new Cv(f+1),p=CG(n[c-1],d,0);if(p>t){var i=0,m=0,_=p-t,v=1<<_;for(s.sort(function(e,t){return d[t.s]-d[e.s]||e.f-t.f});it)m+=v-(1<>=_;m>0;){var y=s[i].s;d[y]=0&&m;--i){var S=s[i].s;d[S]==t&&(--d[S],++m);}p=t;}return {t:new C_(d),l:p}},CG=function(e,t,n){return -1==e.s?Math.max(CG(e.l,t,n+1),CG(e.r,t,n+1)):t[e.s]=n},CH=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new Cv(++t),i=0,r=e[0],s=1,a=function(e){n[i++]=e;},o=1;o<=t;++o)if(e[o]==r&&o!=t)++s;else {if(!r&&s>2){for(;s>138;s-=138)a(32754);s>2&&(a(s>10?s-11<<5|28690:s-3<<5|12305),s=0);}else if(s>3){for(a(r),--s;s>6;s-=6)a(8304);s>2&&(a(s-3<<5|8208),s=0);}for(;s--;)a(r);s=1,r=e[o];}return {c:n.subarray(0,i),n:t}},CW=function(e,t){for(var n=0,i=0;i>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var s=0;s4&&!L[Cx[R-1]];--R);var M=u+5<<3,O=CW(r,CD)+CW(s,CR)+a,k=CW(r,_)+CW(s,y)+a+14+3*R+CW(C,L)+2*C[16]+3*C[17]+7*C[18];if(l>=0&&M<=O&&M<=k)return Cj(t,c,e.subarray(l,l+u));if(CU(t,c,1+(k15&&(CU(t,c,U[P]>>5&127),c+=U[P]>>12);}}else h=CM,f=CD,d=CO,p=CR;for(var P=0;P255){var V=z>>18&31;CV(t,c,h[V+257]),c+=f[V+257],V>7&&(CU(t,c,z>>23&31),c+=Cy[V]);var G=31&z;CV(t,c,d[G]),c+=p[G],G>3&&(CV(t,c,z>>5&8191),c+=CS[G]);}else CV(t,c,h[z]),c+=f[z];}return CV(t,c,h[256]),c+f[256]},CY=new Cg([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Cq=new C_(0),CK=function(e,t,n,i,r,s){var a=s.z||e.length,o=new C_(i+a+5*(1+Math.ceil(a/7e3))+r),l=o.subarray(i,o.length-r),u=s.l,c=7&(s.r||0);if(t){c&&(l[0]=s.r>>3);for(var h=CY[t-1],f=h>>13,d=8191&h,p=(1<7e3||A>24576)&&(R>423||!u)){c=CX(e,l,0,S,x,b,E,A,P,w-P,c),A=T=E=0,P=w;for(var M=0;M<286;++M)x[M]=0;for(var M=0;M<30;++M)b[M]=0;}var O=2,k=0,N=d,F=L-D&32767;if(R>2&&I==y(w-F))for(var B=Math.min(f,R)-1,U=Math.min(32767,w),V=Math.min(258,R);F<=U&&--N&&L!=D;){if(e[w+O]==e[w+O-F]){for(var z=0;zO){if(O=z,k=F,z>B)break;for(var G=Math.min(F,z-2),H=0,M=0;MH&&(H=X,D=W);}}}D=m[L=D],F+=L-D&32767;}if(k){S[A++]=0x10000000|Cw[O]<<18|CA[k];var Y=31&Cw[O],q=31&CA[k];E+=Cy[Y]+CS[q],++x[257+Y],++b[q],C=w+O,++T;}else S[A++]=e[w],++x[e[w]];}}for(w=Math.max(w,C);w=a&&(l[c/8|0]=u,K=a),c=Cj(l,c+1,e.subarray(w,K));}s.i=a;}return CN(o,0,i+Ck(c)+r)},CZ=function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var n=t,i=9;--i;)n=(1&n&&-306674912)^n>>>1;e[t]=n;}return e}(),CQ=function(){var e=-1;return {p:function(t){for(var n=e,i=0;i>>8;e=n;},d:function(){return ~e}}},CJ=function(e,t,n,i,r){if(!r&&(r={l:1},t.dictionary)){var s=t.dictionary.subarray(-32768),a=new C_(s.length+e.length);a.set(s),a.set(e,s.length),e=a,r.w=s.length;}return CK(e,null==t.level?6:t.level,null==t.mem?r.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):20:12+t.mem,n,i,r)},C$=function(e,t){var n={};for(var i in e)n[i]=e[i];for(var i in t)n[i]=t[i];return n},C0=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8;},C1=function(e,t,n,r){for(var s in e){var a,o=e[s],l=t+s,u=r;(Array.isArray(o)&&(u=C$(r,o[1]),o=o[0]),a=o,null!=C_&&"undefined"!=typeof Symbol&&C_[Symbol.hasInstance]?!!C_[Symbol.hasInstance](a):i(a,C_))?n[l]=[o,u]:(n[l+="/"]=[new C_(0),u],C1(o,l,n,r));}},C2="undefined"!=typeof TextEncoder&&new TextEncoder,C3="undefined"!=typeof TextDecoder&&new TextDecoder;try{C3.decode(Cq,{stream:!0});}catch(e){}function C4(e,t){if(C2)return C2.encode(e);for(var n,i=e.length,r=new C_(e.length+(e.length>>1)),s=0,a=function(e){r[s++]=e;},n=0;nr.length){var o=new C_(s+8+(i-n<<1));o.set(r),r=o;}var l=e.charCodeAt(n);l<128||t?a(l):(l<2048?a(192|l>>6):(l>55295&&l<57344?(a(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++n))>>18),a(128|l>>12&63)):a(224|l>>12),a(128|l>>6&63)),a(128|63&l));}return CN(r,0,s)}var C5=function(e){var t=0;if(e)for(var n in e){var i=e[n].length;i>65535&&CB(9),t+=i+4;}return t},C8=function(e,t,n,i,r,s,a,o){var l=i.length,u=n.extra,c=o&&o.length,h=C5(u);C0(e,t,null!=a?0x2014b50:0x4034b50),t+=4,null!=a&&(e[t++]=20,e[t++]=n.os),e[t]=20,t+=2,e[t++]=n.flag<<1|(s<0&&8),e[t++]=r&&8,e[t++]=255&n.compression,e[t++]=n.compression>>8;var f=new Date(null==n.mtime?Date.now():n.mtime),d=f.getFullYear()-1980;if((d<0||d>119)&&CB(10),C0(e,t,d<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),t+=4,-1!=s&&(C0(e,t,n.crc),C0(e,t+4,s<0?-s-2:s),C0(e,t+8,n.size)),C0(e,t+12,l),C0(e,t+14,h),t+=16,null!=a&&(C0(e,t,c),C0(e,t+6,n.attrs),C0(e,t+10,a),t+=14),e.set(i,t),t+=l,h)for(var p in u){var m=u[p],_=m.length;C0(e,t,+p),C0(e,t+2,_),e.set(m,t+4),t+=4+_;}return c&&(e.set(o,t),t+=c),t},C6=function(e,t,n,i,r){C0(e,t,0x6054b50),C0(e,t+8,n),C0(e,t+10,n),C0(e,t+12,i),C0(e,t+16,r);};function C9(e,t){return (C9=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var C7="root",Pe=function(e,t,n){return " "+e+" inputs:"+t+" = "+n},Pt=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(){return e.apply(this,arguments)||this}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&C9(t,e);var n=t.prototype;return n.init=function(){this.meshMap=new Map,this.textureMap=new Map,this.materialMap=new Map,this.materials=[],this.files={},this.nodeNames=new Set;},n.done=function(){this.meshMap=null,this.textureMap=null,this.materialMap=null,this.materials=null,this.files=null,this.nodeNames=null;},n.build=function(e,t){var n,i=this;void 0===t&&(t={}),this.init(),this.addFile(null,C7);var r=[];e&&e.findComponents("render").forEach(function(e){r.push.apply(r,[].concat(e.meshInstances));});var s="";r.forEach(function(e){s+=i.buildMeshInstance(e);}),s+='\ndef "Materials"\n{\n '+this.materials.join("\n")+"\n}\n",this.addFile(null,C7,"",s);for(var a={maxTextureSize:t.maxTextureSize},o=Array.from(this.textureMap.keys()),l=[],u=0;u65535&&CB(11);var v=c?CJ(l,u||{},0,0):l,g=v.length,y=CQ();y.p(l),i.push(C$(u,{size:l.length,crc:y.d(),c:v,f:h,m:p,u:f!=a.length||p&&d.length!=m,o:r,compression:c})),r+=30+f+_+g,s+=76+2*(f+_)+(m||0)+g;}for(var S=new C_(s+22),x=r,b=s-r,T=0;T"}},n.getTextureFileIds=function(e){return this.getFileIds("texture","Texture_"+e.id,"Texture","png")},n.addFile=function(e,t,n,i){ void 0===n&&(n=""),void 0===i&&(i="");var r=null;i&&(r=C4(i='#usda 1.0\n(\n customLayerData = {\n string creator = "PlayCanvas UsdzExporter"\n }\n metersPerUnit = 1\n upAxis = "Y"\n)\n\n'+i));var s=this.getFileIds(e,t,n);return this.files[s.fileName]=r,s.refName},n.getMaterialRef=function(e){var t=this.materialMap.get(e);return t||(t=this.buildMaterial(e),this.materialMap.set(e,t)),t},n.getMeshRef=function(e){var t=this.meshMap.get(e);return t||(t=this.buildMesh(e),this.meshMap.set(e,t)),t},n.buildArray2=function(e){for(var t=[],n=e.length,i=0;i"},s=[],a=[],o=function(n,i,o,l,u,c,h){ void 0===c&&(c=false),void 0===h&&(h=false);var f=e[n];if(f){var d=t.getTextureFileIds(f);t.textureMap.set(f,d.refName);var p=e[""+n+"Channel"]||"rgb",m=r("/"+d.name+"_"+u+".outputs:"+p);s.push(Pe(o,""+l+".connect",m)),c&&e.alphaTest;var _=e[""+n+"Tiling"],v=e[""+n+"Offset"],g=e[""+n+"Rotation"],y=1===e[""+n+"Uv"]?"st1":"st",S=h&&i?i:eN.WHITE;a.push('\n def Shader "Transform2d_'+u+'" (\n sdrMetadata = {\n string role = "math"\n }\n )\n {\n uniform token info:id = "UsdTransform2d"\n float2 inputs:in.connect = '+r("/uvReader_"+y+".outputs:result")+"\n float inputs:rotation = "+g+"\n float2 inputs:scale = ("+_.x+", "+_.y+")\n float2 inputs:translation = ("+v.x+", "+v.y+')\n float2 outputs:result\n }\n\n def Shader "Texture_'+f.id+"_"+u+'"\n {\n uniform token info:id = "UsdUVTexture"\n asset inputs:file = @'+d.fileName+"@\n float2 inputs:st.connect = "+r("/Transform2d_"+u+".outputs:result")+'\n token inputs:wrapS = "repeat"\n token inputs:wrapT = "repeat"\n float4 inputs:scale = ('+S.r+", "+S.g+", "+S.b+", "+S.a+")\n float outputs:r\n float outputs:g\n float outputs:b\n float3 outputs:rgb\n float outputs:a\n }\n ");}else if(i){var x="float"===o?""+i:"("+i.r+", "+i.g+", "+i.b+")";s.push(Pe(o,l,x));}};o("diffuseMap",e.diffuse,"color3f","diffuseColor","diffuse",false,true),(e.transparent||e.alphaTest>0)&&o("opacityMap",e.opacity,"float","opacity","opacity",true),o("normalMap",null,"normal3f","normal","normal"),o("emissiveMap",e.emissive,"color3f","emissiveColor","emissive",false,true),o("aoMap",null,"float","occlusion","occlusion"),o("metalnessMap",e.metalness,"float","metallic","metallic"),o("glossMap",e.gloss,"float","roughness","roughness");var l='\n def Material "'+n+'"\n {\n def Shader "PreviewSurface"\n {\n uniform token info:id = "UsdPreviewSurface"\n'+s.join("\n")+"\n int inputs:useSpecularWorkflow = 0\n token outputs:surface\n }\n\n token outputs:surface.connect = "+r("/PreviewSurface.outputs:surface")+'\n\n def Shader "uvReader_st"\n {\n uniform token info:id = "UsdPrimvarReader_float2"\n token inputs:varname = "st"\n float2 inputs:fallback = (0.0, 0.0)\n float2 outputs:result\n }\n\n def Shader "uvReader_st1"\n {\n uniform token info:id = "UsdPrimvarReader_float2"\n token inputs:varname = "st1"\n float2 inputs:fallback = (0.0, 0.0)\n float2 outputs:result\n }\n\n '+a.join("\n")+"\n }\n ";return this.materials.push(l),r("")},n.buildMesh=function(e){var t=[],n=[],i=[],r=[],s=[];e.getVertexStream(tA,t),e.getVertexStream(tC,i),e.getVertexStream(tM,r),e.getVertexStream(tO,s),e.getIndices(n);var a=n.length||t.length,o=Array(a/3).fill(3).join(", ");if(!n.length)for(var l=0;l 0.0) {\n bilinearBlur /= totalWeight;\n }\n dBlur = bilinearBlur;\n return bilinearBlur;\n #else\n dBlur = texture2DLod(blurTexture, uv, 0.0).rgb;\n return dBlur;\n #endif\n }\n vec3 applyDof(vec3 color, vec2 uv) {\n vec3 blur = getDofBlur(uv);\n return mix(color, blur, dCoc.r + dCoc.g);\n }\n #endif\n",composeSsaoPS:"\n #ifdef SSAO\n #define SSAO_TEXTURE\n #endif\n #if DEBUG_COMPOSE == ssao\n #define SSAO_TEXTURE\n #endif\n #ifdef SSAO_TEXTURE\n uniform sampler2D ssaoTexture;\n \n float dSsao;\n \n vec3 applySsao(vec3 color, vec2 uv) {\n dSsao = texture2DLod(ssaoTexture, uv, 0.0).r;\n \n #ifdef SSAO\n return color * dSsao;\n #else\n return color;\n #endif\n }\n #endif\n",composeGradingPS:"\n #ifdef GRADING\n uniform vec3 brightnessContrastSaturation;\n uniform vec3 tint;\n vec3 colorGradingHDR(vec3 color, float brt, float sat, float con) {\n color *= tint;\n color = color * brt;\n float grey = dot(color, vec3(0.3, 0.59, 0.11));\n grey = grey / max(1.0, max(color.r, max(color.g, color.b)));\n color = mix(vec3(grey), color, sat);\n return mix(vec3(0.5), color, con);\n }\n vec3 applyGrading(vec3 color) {\n return colorGradingHDR(color, \n brightnessContrastSaturation.x, \n brightnessContrastSaturation.z, \n brightnessContrastSaturation.y);\n }\n #endif\n",composeVignettePS:"\n #ifdef VIGNETTE\n uniform vec4 vignetterParams;\n \n float dVignette;\n \n float calcVignette(vec2 uv) {\n float inner = vignetterParams.x;\n float outer = vignetterParams.y;\n float curvature = vignetterParams.z;\n float intensity = vignetterParams.w;\n vec2 curve = pow(abs(uv * 2.0 -1.0), vec2(1.0 / curvature));\n float edge = pow(length(curve), curvature);\n dVignette = 1.0 - intensity * smoothstep(inner, outer, edge);\n return dVignette;\n }\n vec3 applyVignette(vec3 color, vec2 uv) {\n return color * calcVignette(uv);\n }\n #endif\n",composeFringingPS:"\n #ifdef FRINGING\n uniform float fringingIntensity;\n vec3 applyFringing(vec3 color, vec2 uv) {\n vec2 centerDistance = uv - 0.5;\n vec2 offset = fringingIntensity * pow(centerDistance, vec2(2.0, 2.0));\n color.r = texture2D(sceneTexture, uv - offset).r;\n color.b = texture2D(sceneTexture, uv + offset).b;\n return color;\n }\n #endif\n",composeCasPS:"\n #ifdef CAS\n uniform float sharpness;\n float maxComponent(float x, float y, float z) { return max(x, max(y, z)); }\n vec3 toSDR(vec3 c) { return c / (1.0 + maxComponent(c.r, c.g, c.b)); }\n vec3 toHDR(vec3 c) { return c / (1.0 - maxComponent(c.r, c.g, c.b)); }\n vec3 applyCas(vec3 color, vec2 uv, float sharpness) {\n float x = sceneTextureInvRes.x;\n float y = sceneTextureInvRes.y;\n vec3 a = toSDR(texture2DLod(sceneTexture, uv + vec2(0.0, -y), 0.0).rgb);\n vec3 b = toSDR(texture2DLod(sceneTexture, uv + vec2(-x, 0.0), 0.0).rgb);\n vec3 c = toSDR(color.rgb);\n vec3 d = toSDR(texture2DLod(sceneTexture, uv + vec2(x, 0.0), 0.0).rgb);\n vec3 e = toSDR(texture2DLod(sceneTexture, uv + vec2(0.0, y), 0.0).rgb);\n float min_g = min(a.g, min(b.g, min(c.g, min(d.g, e.g))));\n float max_g = max(a.g, max(b.g, max(c.g, max(d.g, e.g))));\n float sharpening_amount = sqrt(min(1.0 - max_g, min_g) / max_g);\n float w = sharpening_amount * sharpness;\n vec3 res = (w * (a + b + d + e) + c) / (4.0 * w + 1.0);\n res = max(res, 0.0);\n return toHDR(res);\n }\n #endif\n",composeColorLutPS:"\n #ifdef COLOR_LUT\n uniform sampler2D colorLUT;\n uniform vec4 colorLUTParams;\n vec3 applyColorLUT(vec3 color) {\n vec3 c = clamp(color, 0.0, 1.0);\n float width = colorLUTParams.x;\n float height = colorLUTParams.y;\n float maxColor = colorLUTParams.z;\n float cell = c.b * maxColor;\n float cell_l = floor(cell);\n float cell_h = ceil(cell);\n float half_px_x = 0.5 / width;\n float half_px_y = 0.5 / height;\n float r_offset = half_px_x + c.r / height * (maxColor / height);\n float g_offset = half_px_y + c.g * (maxColor / height);\n vec2 uv_l = vec2(cell_l / height + r_offset, g_offset);\n vec2 uv_h = vec2(cell_h / height + r_offset, g_offset);\n vec3 color_l = texture2DLod(colorLUT, uv_l, 0.0).rgb;\n vec3 color_h = texture2DLod(colorLUT, uv_h, 0.0).rgb;\n vec3 lutColor = mix(color_l, color_h, fract(cell));\n return mix(color, lutColor, colorLUTParams.w);\n }\n #endif\n"},Pw={composePS:'\n #include "tonemappingPS"\n #include "gammaPS"\n varying uv0: vec2f;\n var sceneTexture: texture_2d;\n var sceneTextureSampler: sampler;\n uniform sceneTextureInvRes: vec2f;\n #include "composeBloomPS"\n #include "composeDofPS"\n #include "composeSsaoPS"\n #include "composeGradingPS"\n #include "composeVignettePS"\n #include "composeFringingPS"\n #include "composeCasPS"\n #include "composeColorLutPS"\n @fragment\n fn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n var uv = uv0;\n #ifdef TAA\n uv.y = 1.0 - uv.y;\n #endif\n let scene = textureSampleLevel(sceneTexture, sceneTextureSampler, uv, 0.0);\n var result = scene.rgb;\n #ifdef CAS\n result = applyCas(result, uv, uniform.sharpness);\n #endif\n #ifdef DOF\n result = applyDof(result, uv0);\n #endif\n #ifdef SSAO_TEXTURE\n result = applySsao(result, uv0);\n #endif\n #ifdef FRINGING\n result = applyFringing(result, uv);\n #endif\n #ifdef BLOOM\n result = applyBloom(result, uv0);\n #endif\n #ifdef GRADING\n result = applyGrading(result);\n #endif\n result = toneMap(result);\n #ifdef COLOR_LUT\n result = applyColorLUT(result);\n #endif\n #ifdef VIGNETTE\n result = applyVignette(result, uv);\n #endif\n #ifdef DEBUG_COMPOSE\n #if DEBUG_COMPOSE == scene\n result = scene.rgb;\n #elif defined(BLOOM) && DEBUG_COMPOSE == bloom\n result = dBloom * uniform.bloomIntensity;\n #elif defined(DOF) && DEBUG_COMPOSE == dofcoc\n result = vec3f(dCoc, 0.0);\n #elif defined(DOF) && DEBUG_COMPOSE == dofblur\n result = dBlur;\n #elif defined(SSAO_TEXTURE) && DEBUG_COMPOSE == ssao\n result = vec3f(dSsao);\n #elif defined(VIGNETTE) && DEBUG_COMPOSE == vignette\n result = vec3f(dVignette);\n #endif\n #endif\n result = gammaCorrectOutput(result);\n output.color = vec4f(result, scene.a);\n return output;\n }\n',composeBloomPS:"\n #ifdef BLOOM\n var bloomTexture: texture_2d;\n var bloomTextureSampler: sampler;\n uniform bloomIntensity: f32;\n \n var dBloom: vec3f;\n \n fn applyBloom(color: vec3f, uv: vec2f) -> vec3f {\n dBloom = textureSampleLevel(bloomTexture, bloomTextureSampler, uv, 0.0).rgb;\n return color + dBloom * uniform.bloomIntensity;\n }\n #endif\n",composeDofPS:"\n #ifdef DOF\n var cocTexture: texture_2d;\n var cocTextureSampler: sampler;\n var blurTexture: texture_2d;\n var blurTextureSampler: sampler;\n \n var dCoc: vec2f;\n var dBlur: vec3f;\n fn getDofBlur(uv: vec2f) -> vec3f {\n dCoc = textureSampleLevel(cocTexture, cocTextureSampler, uv, 0.0).rg;\n #if DOF_UPSCALE\n let blurTexelSize = 1.0 / vec2f(textureDimensions(blurTexture, 0));\n var bilinearBlur = vec3f(0.0);\n var totalWeight = 0.0;\n for (var i = -1; i <= 1; i++) {\n for (var j = -1; j <= 1; j++) {\n let offset = vec2f(f32(i), f32(j)) * blurTexelSize;\n let cocSample = textureSampleLevel(cocTexture, cocTextureSampler, uv + offset, 0.0).rg;\n let blurSample = textureSampleLevel(blurTexture, blurTextureSampler, uv + offset, 0.0).rgb;\n let cocWeight = clamp(cocSample.r + cocSample.g, 0.0, 1.0);\n bilinearBlur += blurSample * cocWeight;\n totalWeight += cocWeight;\n }\n }\n if (totalWeight > 0.0) {\n bilinearBlur /= totalWeight;\n }\n dBlur = bilinearBlur;\n return bilinearBlur;\n #else\n dBlur = textureSampleLevel(blurTexture, blurTextureSampler, uv, 0.0).rgb;\n return dBlur;\n #endif\n }\n fn applyDof(color: vec3f, uv: vec2f) -> vec3f {\n let blur = getDofBlur(uv);\n return mix(color, blur, dCoc.r + dCoc.g);\n }\n #endif\n",composeSsaoPS:"\n #ifdef SSAO\n #define SSAO_TEXTURE\n #endif\n #if DEBUG_COMPOSE == ssao\n #define SSAO_TEXTURE\n #endif\n #ifdef SSAO_TEXTURE\n var ssaoTexture: texture_2d;\n var ssaoTextureSampler: sampler;\n \n var dSsao: f32;\n \n fn applySsao(color: vec3f, uv: vec2f) -> vec3f {\n dSsao = textureSampleLevel(ssaoTexture, ssaoTextureSampler, uv, 0.0).r;\n \n #ifdef SSAO\n return color * dSsao;\n #else\n return color;\n #endif\n }\n #endif\n",composeGradingPS:"\n #ifdef GRADING\n uniform brightnessContrastSaturation: vec3f;\n uniform tint: vec3f;\n fn colorGradingHDR(color: vec3f, brt: f32, sat: f32, con: f32) -> vec3f {\n var colorOut = color * uniform.tint;\n colorOut = colorOut * brt;\n let grey = dot(colorOut, vec3f(0.3, 0.59, 0.11));\n let normalizedGrey = grey / max(1.0, max(colorOut.r, max(colorOut.g, colorOut.b)));\n colorOut = mix(vec3f(normalizedGrey), colorOut, sat);\n return mix(vec3f(0.5), colorOut, con);\n }\n fn applyGrading(color: vec3f) -> vec3f {\n return colorGradingHDR(color, \n uniform.brightnessContrastSaturation.x, \n uniform.brightnessContrastSaturation.z, \n uniform.brightnessContrastSaturation.y);\n }\n #endif\n",composeVignettePS:"\n #ifdef VIGNETTE\n uniform vignetterParams: vec4f;\n \n var dVignette: f32;\n \n fn calcVignette(uv: vec2f) -> f32 {\n let inner = uniform.vignetterParams.x;\n let outer = uniform.vignetterParams.y;\n let curvature = uniform.vignetterParams.z;\n let intensity = uniform.vignetterParams.w;\n let curve = pow(abs(uv * 2.0 - 1.0), vec2f(1.0 / curvature));\n let edge = pow(length(curve), curvature);\n dVignette = 1.0 - intensity * smoothstep(inner, outer, edge);\n return dVignette;\n }\n fn applyVignette(color: vec3f, uv: vec2f) -> vec3f {\n return color * calcVignette(uv);\n }\n #endif\n",composeFringingPS:"\n #ifdef FRINGING\n uniform fringingIntensity: f32;\n fn applyFringing(color: vec3f, uv: vec2f) -> vec3f {\n let centerDistance = uv - 0.5;\n let offset = uniform.fringingIntensity * pow(centerDistance, vec2f(2.0));\n var colorOut = color;\n colorOut.r = textureSample(sceneTexture, sceneTextureSampler, uv - offset).r;\n colorOut.b = textureSample(sceneTexture, sceneTextureSampler, uv + offset).b;\n return colorOut;\n }\n #endif\n",composeCasPS:"\n #ifdef CAS\n uniform sharpness: f32;\n fn maxComponent(x: f32, y: f32, z: f32) -> f32 { return max(x, max(y, z)); }\n fn toSDR(c: vec3f) -> vec3f { return c / (1.0 + maxComponent(c.r, c.g, c.b)); }\n fn toHDR(c: vec3f) -> vec3f { return c / (1.0 - maxComponent(c.r, c.g, c.b)); }\n fn applyCas(color: vec3f, uv: vec2f, sharpness: f32) -> vec3f {\n let x = uniform.sceneTextureInvRes.x;\n let y = uniform.sceneTextureInvRes.y;\n let a = toSDR(textureSampleLevel(sceneTexture, sceneTextureSampler, uv + vec2f(0.0, -y), 0.0).rgb);\n let b = toSDR(textureSampleLevel(sceneTexture, sceneTextureSampler, uv + vec2f(-x, 0.0), 0.0).rgb);\n let c = toSDR(color.rgb);\n let d = toSDR(textureSampleLevel(sceneTexture, sceneTextureSampler, uv + vec2f(x, 0.0), 0.0).rgb);\n let e = toSDR(textureSampleLevel(sceneTexture, sceneTextureSampler, uv + vec2f(0.0, y), 0.0).rgb);\n let min_g = min(a.g, min(b.g, min(c.g, min(d.g, e.g))));\n let max_g = max(a.g, max(b.g, max(c.g, max(d.g, e.g))));\n let sharpening_amount = sqrt(min(1.0 - max_g, min_g) / max_g);\n let w = sharpening_amount * uniform.sharpness;\n var res = (w * (a + b + d + e) + c) / (4.0 * w + 1.0);\n res = max(res, vec3f(0.0));\n return toHDR(res);\n }\n #endif\n",composeColorLutPS:"\n #ifdef COLOR_LUT\n var colorLUT: texture_2d;\n var colorLUTSampler: sampler;\n uniform colorLUTParams: vec4f;\n fn applyColorLUT(color: vec3f) -> vec3f {\n var c: vec3f = clamp(color, vec3f(0.0), vec3f(1.0));\n let width: f32 = uniform.colorLUTParams.x;\n let height: f32 = uniform.colorLUTParams.y;\n let maxColor: f32 = uniform.colorLUTParams.z;\n let cell: f32 = c.b * maxColor;\n let cell_l: f32 = floor(cell);\n let cell_h: f32 = ceil(cell);\n let half_px_x: f32 = 0.5 / width;\n let half_px_y: f32 = 0.5 / height;\n let r_offset: f32 = half_px_x + c.r / height * (maxColor / height);\n let g_offset: f32 = half_px_y + c.g * (maxColor / height);\n let uv_l: vec2f = vec2f(cell_l / height + r_offset, g_offset);\n let uv_h: vec2f = vec2f(cell_h / height + r_offset, g_offset);\n let color_l: vec3f = textureSampleLevel(colorLUT, colorLUTSampler, uv_l, 0.0).rgb;\n let color_h: vec3f = textureSampleLevel(colorLUT, colorLUTSampler, uv_h, 0.0).rgb;\n let lutColor: vec3f = mix(color_l, color_h, fract(cell));\n return mix(color, lutColor, uniform.colorLUTParams.w);\n }\n #endif\n"};function PA(e,t){return (PA=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var PC=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t){(n=e.call(this,t)||this).sceneTexture=null,n.bloomIntensity=.01,n._bloomTexture=null,n._cocTexture=null,n.blurTexture=null,n.blurTextureUpscale=false,n._ssaoTexture=null,n._toneMapping=0,n._gradingEnabled=false,n.gradingSaturation=1,n.gradingContrast=1,n.gradingBrightness=1,n.gradingTint=new eN(1,1,1,1),n._shaderDirty=true,n._vignetteEnabled=false,n.vignetteInner=.5,n.vignetteOuter=1,n.vignetteCurvature=.5,n.vignetteIntensity=.3,n._fringingEnabled=false,n.fringingIntensity=10,n._taaEnabled=false,n._sharpness=.5,n._gammaCorrection=1,n._colorLUT=null,n.colorLUTIntensity=1,n._key="",n._debug=null,o1.get(t,ns).add(PE),o1.get(t,na).add(Pw);var n,i=t.scope;return n.sceneTextureId=i.resolve("sceneTexture"),n.bloomTextureId=i.resolve("bloomTexture"),n.cocTextureId=i.resolve("cocTexture"),n.ssaoTextureId=i.resolve("ssaoTexture"),n.blurTextureId=i.resolve("blurTexture"),n.bloomIntensityId=i.resolve("bloomIntensity"),n.bcsId=i.resolve("brightnessContrastSaturation"),n.tintId=i.resolve("tint"),n.vignetterParamsId=i.resolve("vignetterParams"),n.fringingIntensityId=i.resolve("fringingIntensity"),n.sceneTextureInvResId=i.resolve("sceneTextureInvRes"),n.sceneTextureInvResValue=new Float32Array(2),n.sharpnessId=i.resolve("sharpness"),n.colorLUTId=i.resolve("colorLUT"),n.colorLUTParams=new Float32Array(4),n.colorLUTParamsId=i.resolve("colorLUTParams"),n}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&PA(t,e);var n,i=t.prototype;return i.postInit=function(){this.setClearColor(eN.BLACK),this.setClearDepth(1),this.setClearStencil(0);},i.frameUpdate=function(){var e=+!(null!=(t=this.renderTarget)?t:this.device.backBuffer).isColorBufferSrgb(0);if(this._gammaCorrection!==e&&(this._gammaCorrection=e,this._shaderDirty=true),this._shaderDirty){this._shaderDirty=false;var t,n,i=of[this._gammaCorrection],r=""+this.toneMapping+"-"+i+"-"+(this.bloomTexture?"bloom":"nobloom")+"-"+(this.cocTexture?"dof":"nodof")+"-"+(this.blurTextureUpscale?"dofupscale":"")+"-"+(this.ssaoTexture?"ssao":"nossao")+"-"+(this.gradingEnabled?"grading":"nograding")+"-"+(this.colorLUT?"colorlut":"nocolorlut")+"-"+(this.vignetteEnabled?"vignette":"novignette")+"-"+(this.fringingEnabled?"fringing":"nofringing")+"-"+(this.taaEnabled?"taa":"notaa")+"-"+(this.isSharpnessEnabled?"cas":"nocas")+"-"+(null!=(n=this._debug)?n:"");if(this._key!==r){this._key=r;var s=new Map;s.set("TONEMAP",od[this.toneMapping]),s.set("GAMMA",i),this.bloomTexture&&s.set("BLOOM",true),this.cocTexture&&s.set("DOF",true),this.blurTextureUpscale&&s.set("DOF_UPSCALE",true),this.ssaoTexture&&s.set("SSAO",true),this.gradingEnabled&&s.set("GRADING",true),this.colorLUT&&s.set("COLOR_LUT",true),this.vignetteEnabled&&s.set("VIGNETTE",true),this.fringingEnabled&&s.set("FRINGING",true),this.taaEnabled&&s.set("TAA",true),this.isSharpnessEnabled&&s.set("CAS",true),this._debug&&s.set("DEBUG_COMPOSE",this._debug);var a=new Map(o1.get(this.device,this.device.isWebGPU?na:ns));this.shader=o6.createShader(this.device,{uniqueName:"ComposeShader-"+r,attributes:{aPosition:tA},vertexChunk:"quadVS",fragmentChunk:"composePS",fragmentDefines:s,fragmentIncludes:a});}}},i.execute=function(){this.sceneTextureId.setValue(this.sceneTexture),this.sceneTextureInvResValue[0]=1/this.sceneTexture.width,this.sceneTextureInvResValue[1]=1/this.sceneTexture.height,this.sceneTextureInvResId.setValue(this.sceneTextureInvResValue),this._bloomTexture&&(this.bloomTextureId.setValue(this._bloomTexture),this.bloomIntensityId.setValue(this.bloomIntensity)),this._cocTexture&&(this.cocTextureId.setValue(this._cocTexture),this.blurTextureId.setValue(this.blurTexture)),this._ssaoTexture&&this.ssaoTextureId.setValue(this._ssaoTexture),this._gradingEnabled&&(this.bcsId.setValue([this.gradingBrightness,this.gradingContrast,this.gradingSaturation]),this.tintId.setValue([this.gradingTint.r,this.gradingTint.g,this.gradingTint.b]));var t=this._colorLUT;t&&(this.colorLUTParams[0]=t.width,this.colorLUTParams[1]=t.height,this.colorLUTParams[2]=t.height-1,this.colorLUTParams[3]=this.colorLUTIntensity,this.colorLUTParamsId.setValue(this.colorLUTParams),this.colorLUTId.setValue(t)),this._vignetteEnabled&&this.vignetterParamsId.setValue([this.vignetteInner,this.vignetteOuter,this.vignetteCurvature,this.vignetteIntensity]),this._fringingEnabled&&this.fringingIntensityId.setValue(this.fringingIntensity/1024),this.isSharpnessEnabled&&this.sharpnessId.setValue(ek.lerp(-0.125,-0.2,this.sharpness)),e.prototype.execute.call(this);},n=[{key:"debug",get:function(){return this._debug},set:function(e){this._debug!==e&&(this._debug=e,this._shaderDirty=true);}},{key:"colorLUT",get:function(){return this._colorLUT},set:function(e){this._colorLUT!==e&&(this._colorLUT=e,this._shaderDirty=true);}},{key:"bloomTexture",get:function(){return this._bloomTexture},set:function(e){this._bloomTexture!==e&&(this._bloomTexture=e,this._shaderDirty=true);}},{key:"cocTexture",get:function(){return this._cocTexture},set:function(e){this._cocTexture!==e&&(this._cocTexture=e,this._shaderDirty=true);}},{key:"ssaoTexture",get:function(){return this._ssaoTexture},set:function(e){this._ssaoTexture!==e&&(this._ssaoTexture=e,this._shaderDirty=true);}},{key:"taaEnabled",get:function(){return this._taaEnabled},set:function(e){this._taaEnabled!==e&&(this._taaEnabled=e,this._shaderDirty=true);}},{key:"gradingEnabled",get:function(){return this._gradingEnabled},set:function(e){this._gradingEnabled!==e&&(this._gradingEnabled=e,this._shaderDirty=true);}},{key:"vignetteEnabled",get:function(){return this._vignetteEnabled},set:function(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._shaderDirty=true);}},{key:"fringingEnabled",get:function(){return this._fringingEnabled},set:function(e){this._fringingEnabled!==e&&(this._fringingEnabled=e,this._shaderDirty=true);}},{key:"toneMapping",get:function(){return this._toneMapping},set:function(e){this._toneMapping!==e&&(this._toneMapping=e,this._shaderDirty=true);}},{key:"sharpness",get:function(){return this._sharpness},set:function(e){this._sharpness!==e&&(this._sharpness=e,this._shaderDirty=true);}},{key:"isSharpnessEnabled",get:function(){return this._sharpness>0}}],function(e,t){for(var n=0;n, texSampler: sampler, uv: vec2f, texSize: vec2f) -> vec4f {\n let samplePos: vec2f = uv * texSize;\n let texPos1: vec2f = floor(samplePos - 0.5) + 0.5;\n let f: vec2f = samplePos - texPos1;\n let w0: vec2f = f * (-0.5 + f * (1.0 - 0.5 * f));\n let w1: vec2f = 1.0 + f * f * (-2.5 + 1.5 * f);\n let w2: vec2f = f * (0.5 + f * (2.0 - 1.5 * f));\n let w3: vec2f = f * f * (-0.5 + 0.5 * f);\n let w12: vec2f = w1 + w2;\n let offset12: vec2f = w2 / w12;\n let texPos0: vec2f = (texPos1 - 1.0) / texSize;\n let texPos3: vec2f = (texPos1 + 2.0) / texSize;\n let texPos12: vec2f = (texPos1 + offset12) / texSize;\n var result: vec4f = vec4f(0.0);\n result = result + textureSampleLevel(tex, texSampler, vec2f(texPos0.x, texPos0.y), 0.0) * w0.x * w0.y;\n result = result + textureSampleLevel(tex, texSampler, vec2f(texPos12.x, texPos0.y), 0.0) * w12.x * w0.y;\n result = result + textureSampleLevel(tex, texSampler, vec2f(texPos3.x, texPos0.y), 0.0) * w3.x * w0.y;\n result = result + textureSampleLevel(tex, texSampler, vec2f(texPos0.x, texPos12.y), 0.0) * w0.x * w12.y;\n result = result + textureSampleLevel(tex, texSampler, vec2f(texPos12.x, texPos12.y), 0.0) * w12.x * w12.y;\n result = result + textureSampleLevel(tex, texSampler, vec2f(texPos3.x, texPos12.y), 0.0) * w3.x * w12.y;\n result = result + textureSampleLevel(tex, texSampler, vec2f(texPos0.x, texPos3.y), 0.0) * w0.x * w3.y;\n result = result + textureSampleLevel(tex, texSampler, vec2f(texPos12.x, texPos3.y), 0.0) * w12.x * w3.y;\n result = result + textureSampleLevel(tex, texSampler, vec2f(texPos3.x, texPos3.y), 0.0) * w3.x * w3.y;\n return result;\n}\n"),o1.get(t,ns).set("taaResolvePS",'\n #include "sampleCatmullRomPS"\n #include "screenDepthPS"\n uniform sampler2D sourceTexture;\n uniform sampler2D historyTexture;\n uniform mat4 matrix_viewProjectionPrevious;\n uniform mat4 matrix_viewProjectionInverse;\n uniform vec4 jitters;\n uniform vec2 textureSize;\n varying vec2 uv0;\n vec2 reproject(vec2 uv, float depth) {\n #ifndef WEBGPU\n depth = depth * 2.0 - 1.0;\n #endif\n vec4 ndc = vec4(uv * 2.0 - 1.0, depth, 1.0);\n ndc.xy -= jitters.xy;\n vec4 worldPosition = matrix_viewProjectionInverse * ndc;\n worldPosition /= worldPosition.w;\n vec4 screenPrevious = matrix_viewProjectionPrevious * worldPosition;\n return (screenPrevious.xy / screenPrevious.w) * 0.5 + 0.5;\n }\n vec4 colorClamp(vec2 uv, vec4 historyColor) {\n vec3 minColor = vec3(9999.0);\n vec3 maxColor = vec3(-9999.0);\n for(float x = -1.0; x <= 1.0; ++x) {\n for(float y = -1.0; y <= 1.0; ++y) {\n vec3 color = texture2D(sourceTexture, uv + vec2(x, y) / textureSize).rgb;\n minColor = min(minColor, color);\n maxColor = max(maxColor, color);\n }\n }\n vec3 clamped = clamp(historyColor.rgb, minColor, maxColor);\n return vec4(clamped, historyColor.a);\n }\n void main()\n {\n vec2 uv = uv0;\n #ifdef WEBGPU\n uv.y = 1.0 - uv.y;\n #endif\n vec4 srcColor = texture2D(sourceTexture, uv);\n float linearDepth = getLinearScreenDepth(uv0);\n float depth = delinearizeDepth(linearDepth);\n vec2 historyUv = reproject(uv0, depth);\n #ifdef QUALITY_HIGH\n vec4 historyColor = SampleTextureCatmullRom(TEXTURE_PASS(historyTexture), historyUv, textureSize);\n #else\n vec4 historyColor = texture2D(historyTexture, historyUv);\n #endif\n vec4 historyColorClamped = colorClamp(uv, historyColor);\n float mixFactor = (historyUv.x < 0.0 || historyUv.x > 1.0 || historyUv.y < 0.0 || historyUv.y > 1.0) ?\n 1.0 : 0.05;\n gl_FragColor = mix(historyColorClamped, srcColor, mixFactor);\n }\n'),o1.get(t,na).set("taaResolvePS",'\n #include "sampleCatmullRomPS"\n #include "screenDepthPS"\n var sourceTexture: texture_2d;\n var sourceTextureSampler: sampler;\n var historyTexture: texture_2d;\n var historyTextureSampler: sampler;\n uniform matrix_viewProjectionPrevious: mat4x4f;\n uniform matrix_viewProjectionInverse: mat4x4f;\n uniform jitters: vec4f;\n uniform textureSize: vec2f;\n varying uv0: vec2f;\n fn reproject(uv: vec2f, depth: f32) -> vec2f {\n var ndc = vec4f(uv * 2.0 - 1.0, depth, 1.0);\n ndc = vec4f(ndc.xy - uniform.jitters.xy, ndc.zw);\n var worldPosition = uniform.matrix_viewProjectionInverse * ndc;\n worldPosition = worldPosition / worldPosition.w;\n let screenPrevious = uniform.matrix_viewProjectionPrevious * worldPosition;\n return (screenPrevious.xy / screenPrevious.w) * 0.5 + 0.5;\n }\n fn colorClamp(uv: vec2f, historyColor: vec4f) -> vec4f {\n var minColor = vec3f(9999.0);\n var maxColor = vec3f(-9999.0);\n for (var ix: i32 = -1; ix <= 1; ix = ix + 1) {\n for (var iy: i32 = -1; iy <= 1; iy = iy + 1) {\n let color_sample = textureSample(sourceTexture, sourceTextureSampler, uv + vec2f(f32(ix), f32(iy)) / uniform.textureSize).rgb;\n minColor = min(minColor, color_sample);\n maxColor = max(maxColor, color_sample);\n }\n }\n let clamped = clamp(historyColor.rgb, minColor, maxColor);\n return vec4f(clamped, historyColor.a);\n }\n @fragment\n fn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n var uv = input.uv0;\n uv.y = 1.0 - uv.y;\n let srcColor = textureSample(sourceTexture, sourceTextureSampler, uv);\n let linearDepth = getLinearScreenDepth(uv0);\n let depth = delinearizeDepth(linearDepth);\n let historyUv = reproject(uv0, depth);\n #ifdef QUALITY_HIGH\n var historyColor: vec4f = SampleTextureCatmullRom(historyTexture, historyTextureSampler, historyUv, uniform.textureSize);\n #else\n var historyColor: vec4f = textureSample(historyTexture, historyTextureSampler, historyUv);\n #endif\n let historyColorClamped = colorClamp(uv, historyColor);\n let mixFactor_condition = historyUv.x < 0.0 || historyUv.x > 1.0 || historyUv.y < 0.0 || historyUv.y > 1.0;\n let mixFactor = select(0.05, 1.0, mixFactor_condition);\n output.color = mix(historyColorClamped, srcColor, mixFactor);\n return output;\n }\n');var r,s=new Map;s.set("QUALITY_HIGH",true),o6.addScreenDepthChunkDefines(t,i.shaderParams,s),r.shader=o6.createShader(t,{uniqueName:"TaaResolveShader",attributes:{aPosition:tA},vertexChunk:"quadVS",fragmentChunk:"taaResolvePS",fragmentDefines:s});var a=t.scope;return r.sourceTextureId=a.resolve("sourceTexture"),r.textureSizeId=a.resolve("textureSize"),r.textureSize=new Float32Array(2),r.historyTextureId=a.resolve("historyTexture"),r.viewProjPrevId=a.resolve("matrix_viewProjectionPrevious"),r.viewProjInvId=a.resolve("matrix_viewProjectionInverse"),r.jittersId=a.resolve("jitters"),r.cameraParams=new Float32Array(4),r.cameraParamsId=a.resolve("camera_params"),r.setup(),r}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&PP(t,e);var n=t.prototype;return n.destroy=function(){this.renderTarget&&(this.renderTarget.destroyTextureBuffers(),this.renderTarget.destroy(),this.renderTarget=null);},n.setup=function(){for(var e=0;e<2;++e)this.historyTextures[e]=new nN(this.device,{name:"TAA-History-"+e,width:4,height:4,format:this.sourceTexture.format,mipmaps:false,minFilter:1,magFilter:1,addressU:1,addressV:1}),this.historyRenderTargets[e]=new ic({colorBuffer:this.historyTextures[e],depth:false});this.historyTexture=this.historyTextures[0],this.init(this.historyRenderTargets[0],{resizeSource:this.sourceTexture});},n.before=function(){this.sourceTextureId.setValue(this.sourceTexture),this.historyTextureId.setValue(this.historyTextures[1-this.historyIndex]),this.textureSize[0]=this.sourceTexture.width,this.textureSize[1]=this.sourceTexture.height,this.textureSizeId.setValue(this.textureSize);var e=this.cameraComponent.camera;this.viewProjPrevId.setValue(e._viewProjPrevious.data),this.viewProjInvId.setValue(e._viewProjInverse.data),this.jittersId.setValue(e._jitters);var t=e._farClip;this.cameraParams[0]=1/t,this.cameraParams[1]=t,this.cameraParams[2]=e._nearClip,this.cameraParams[3]=+(1===e.projection),this.cameraParamsId.setValue(this.cameraParams);},n.update=function(){return this.historyIndex=1-this.historyIndex,this.historyTexture=this.historyTextures[this.historyIndex],this.renderTarget=this.historyRenderTargets[this.historyIndex],this.historyTexture},t}(f1);function PL(e,t){return (PL=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var PD=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t,n,i){(r=e.call(this,t)||this).cameraComponent=n,o1.get(t,ns).set("cocPS",'\n #include "screenDepthPS"\n varying vec2 uv0;\n uniform vec3 params;\n void main()\n {\n float depth = getLinearScreenDepth(uv0);\n float focusDistance = params.x;\n float focusRange = params.y;\n float invRange = params.z;\n float farRange = focusDistance + focusRange * 0.5;\n \n float cocFar = min((depth - farRange) * invRange, 1.0);\n #ifdef NEAR_BLUR\n float nearRange = focusDistance - focusRange * 0.5;\n float cocNear = min((nearRange - depth) * invRange, 1.0);\n #else\n float cocNear = 0.0;\n #endif\n gl_FragColor = vec4(cocFar, cocNear, 0.0, 0.0);\n }\n'),o1.get(t,na).set("cocPS",'\n#include "screenDepthPS"\nvarying uv0: vec2f;\nuniform params: vec3f;\n@fragment\nfn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n let depth: f32 = getLinearScreenDepth(uv0);\n let focusDistance: f32 = uniform.params.x;\n let focusRange: f32 = uniform.params.y;\n let invRange: f32 = uniform.params.z;\n let farRange: f32 = focusDistance + focusRange * 0.5;\n let cocFar: f32 = min((depth - farRange) * invRange, 1.0);\n #ifdef NEAR_BLUR\n let nearRange: f32 = focusDistance - focusRange * 0.5;\n var cocNear: f32 = min((nearRange - depth) * invRange, 1.0);\n #else\n var cocNear: f32 = 0.0;\n #endif\n output.color = vec4f(cocFar, cocNear, 0.0, 0.0);\n return output;\n}\n');var r,s=new Map;return i&&s.set("NEAR_BLUR",""),o6.addScreenDepthChunkDefines(t,n.shaderParams,s),r.shader=o6.createShader(t,{uniqueName:"CocShader-"+i,attributes:{aPosition:tA},vertexChunk:"quadVS",fragmentChunk:"cocPS",fragmentDefines:s}),r.paramsId=t.scope.resolve("params"),r.paramsValue=new Float32Array(3),r.cameraParams=new Float32Array(4),r.cameraParamsId=t.scope.resolve("camera_params"),r}return t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&PL(t,e),t.prototype.execute=function(){var t=this.paramsValue,n=this.focusRange;t[0]=this.focusDistance+.001,t[1]=n,t[2]=1/n,this.paramsId.setValue(t);var i=this.cameraComponent.camera,r=i._farClip;this.cameraParams[0]=1/r,this.cameraParams[1]=r,this.cameraParams[2]=i._nearClip,this.cameraParams[3]=+(1===i.projection),this.cameraParamsId.setValue(this.cameraParams),e.prototype.execute.call(this);},t}(f1);function PR(e,t){return (PR=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var PM=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t,n,i,r){(s=e.call(this,t)||this).blurRadiusNear=1,s.blurRadiusFar=1,s._blurRings=3,s._blurRingPoints=3,s.nearTexture=n,s.farTexture=i,s.cocTexture=r,o1.get(t,ns).set("dofBlurPS","\n #if defined(NEAR_BLUR)\n uniform sampler2D nearTexture;\n #endif\n uniform sampler2D farTexture;\n uniform sampler2D cocTexture;\n uniform vec2 kernel[{KERNEL_COUNT}];\n uniform float blurRadiusNear;\n uniform float blurRadiusFar;\n varying vec2 uv0;\n void main()\n {\n vec2 coc = texture2D(cocTexture, uv0).rg;\n float cocFar = coc.r;\n vec3 sum = vec3(0.0, 0.0, 0.0);\n #if defined(NEAR_BLUR)\n float cocNear = coc.g;\n if (cocNear > 0.0001) {\n ivec2 nearTextureSize = textureSize(nearTexture, 0);\n vec2 step = cocNear * blurRadiusNear / vec2(nearTextureSize);\n for (int i = 0; i < {KERNEL_COUNT}; i++) {\n vec2 uv = uv0 + step * kernel[i];\n vec3 tap = texture2DLod(nearTexture, uv, 0.0).rgb;\n sum += tap.rgb;\n }\n sum *= float({INV_KERNEL_COUNT});\n } else\n #endif\n \n if (cocFar > 0.0001) {\n ivec2 farTextureSize = textureSize(farTexture, 0);\n vec2 step = cocFar * blurRadiusFar / vec2(farTextureSize);\n float sumCoC = 0.0; \n for (int i = 0; i < {KERNEL_COUNT}; i++) {\n vec2 uv = uv0 + step * kernel[i];\n vec3 tap = texture2DLod(farTexture, uv, 0.0).rgb;\n float cocThis = texture2DLod(cocTexture, uv, 0.0).r;\n tap *= cocThis;\n sumCoC += cocThis;\n sum += tap;\n }\n if (sumCoC > 0.0)\n sum /= sumCoC;\n sum /= cocFar;\n }\n pcFragColor0 = vec4(sum, 1.0);\n }\n"),o1.get(t,na).set("dofBlurPS","\n#if defined(NEAR_BLUR)\n var nearTexture: texture_2d;\n var nearTextureSampler: sampler;\n#endif\nvar farTexture: texture_2d;\nvar farTextureSampler: sampler;\nvar cocTexture: texture_2d;\nvar cocTextureSampler: sampler;\nuniform kernel: array;\nuniform blurRadiusNear: f32;\nuniform blurRadiusFar: f32;\nvarying uv0: vec2f;\n@fragment\nfn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n let coc: vec2f = textureSample(cocTexture, cocTextureSampler, input.uv0).rg;\n let cocFar: f32 = coc.r;\n var sum: vec3f = vec3f(0.0, 0.0, 0.0);\n #if defined(NEAR_BLUR)\n let cocNear: f32 = coc.g;\n if (cocNear > 0.0001) {\n let nearTextureSize: vec2f = vec2f(textureDimensions(nearTexture, 0));\n let step: vec2f = cocNear * uniform.blurRadiusNear / nearTextureSize;\n for (var i: i32 = 0; i < {KERNEL_COUNT}; i = i + 1) {\n let uv: vec2f = uv0 + step * uniform.kernel[i].element;\n let tap: vec3f = textureSampleLevel(nearTexture, nearTextureSampler, uv, 0.0).rgb;\n sum = sum + tap;\n }\n sum = sum * f32({INV_KERNEL_COUNT});\n } else\n #endif\n if (cocFar > 0.0001) {\n let farTextureSize: vec2f = vec2f(textureDimensions(farTexture, 0));\n let step: vec2f = cocFar * uniform.blurRadiusFar / farTextureSize;\n var sumCoC: f32 = 0.0;\n for (var i: i32 = 0; i < {KERNEL_COUNT}; i = i + 1) {\n let uv: vec2f = uv0 + step * uniform.kernel[i].element;\n var tap: vec3f = textureSampleLevel(farTexture, farTextureSampler, uv, 0.0).rgb;\n let cocThis: f32 = textureSampleLevel(cocTexture, cocTextureSampler, uv, 0.0).r;\n tap = tap * cocThis;\n sumCoC = sumCoC + cocThis;\n sum = sum + tap;\n }\n if (sumCoC > 0.0) {\n sum = sum / sumCoC;\n }\n sum = sum / cocFar;\n }\n output.color = vec4f(sum, 1.0);\n return output;\n}\n");var s,a=t.scope;return s.kernelId=a.resolve("kernel[0]"),s.kernelCountId=a.resolve("kernelCount"),s.blurRadiusNearId=a.resolve("blurRadiusNear"),s.blurRadiusFarId=a.resolve("blurRadiusFar"),s.nearTextureId=a.resolve("nearTexture"),s.farTextureId=a.resolve("farTexture"),s.cocTextureId=a.resolve("cocTexture"),s}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&PR(t,e);var n,i=t.prototype;return i.createShader=function(){this.kernel=new Float32Array(eH.concentric(this.blurRings,this.blurRingPoints));var e=this.kernel.length>>1,t=null!==this.nearTexture,n=new Map;n.set("{KERNEL_COUNT}",e),n.set("{INV_KERNEL_COUNT}",1/e),t&&n.set("NEAR_BLUR",""),this.shader=o6.createShader(this.device,{uniqueName:"DofBlurShader-"+e+"-"+(t?"nearBlur":"noNearBlur"),attributes:{aPosition:tA},vertexChunk:"quadVS",fragmentChunk:"dofBlurPS",fragmentDefines:n});},i.execute=function(){this.shader||this.createShader(),this.nearTextureId.setValue(this.nearTexture),this.farTextureId.setValue(this.farTexture),this.cocTextureId.setValue(this.cocTexture),this.kernelId.setValue(this.kernel),this.kernelCountId.setValue(this.kernel.length>>1),this.blurRadiusNearId.setValue(this.blurRadiusNear),this.blurRadiusFarId.setValue(this.blurRadiusFar),e.prototype.execute.call(this);},n=[{key:"blurRings",get:function(){return this._blurRings},set:function(e){this._blurRings!==e&&(this._blurRings=e,this.shader=null);}},{key:"blurRingPoints",get:function(){return this._blurRingPoints},set:function(e){this._blurRingPoints!==e&&(this._blurRingPoints=e,this.shader=null);}}],function(e,t){for(var n=0;n;\nvar sourceTextureSampler: sampler;\nuniform sourceInvResolution: vec2f;\nuniform filterSize: i32;\nfn random(w: vec2f) -> f32 {\n const m: vec3f = vec3f(0.06711056, 0.00583715, 52.9829189);\n return fract(m.z * fract(dot(w, m.xy)));\n}\nfn bilateralWeight(depth: f32, sampleDepth: f32) -> f32 {\n let diff: f32 = (sampleDepth - depth);\n return max(0.0, 1.0 - diff * diff);\n}\nfn tap(sum_ptr: ptr, totalWeight_ptr: ptr, weight: f32, depth: f32, position: vec2f) {\n let color: f32 = textureSample(sourceTexture, sourceTextureSampler, position).r;\n let textureDepth: f32 = -getLinearScreenDepth(position);\n let bilateral: f32 = bilateralWeight(depth, textureDepth) * weight;\n *sum_ptr = *sum_ptr + color * bilateral;\n *totalWeight_ptr = *totalWeight_ptr + bilateral;\n}\n@fragment\nfn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n let depth: f32 = -getLinearScreenDepth(input.uv0);\n var totalWeight: f32 = 1.0;\n let color: f32 = textureSample(sourceTexture, sourceTextureSampler, input.uv0 ).r;\n var sum: f32 = color * totalWeight;\n for (var i: i32 = -uniform.filterSize; i <= uniform.filterSize; i = i + 1) {\n let weight: f32 = 1.0;\n #ifdef HORIZONTAL\n var offset: vec2f = vec2f(f32(i), 0.0) * uniform.sourceInvResolution;\n #else\n var offset: vec2f = vec2f(0.0, f32(i)) * uniform.sourceInvResolution;\n #endif\n tap(&sum, &totalWeight, weight, depth, input.uv0 + offset);\n }\n let ao: f32 = sum / totalWeight;\n output.color = vec4f(ao, ao, ao, 1.0);\n return output;\n}\n');var s,a=new Map;r&&a.set("HORIZONTAL",""),o6.addScreenDepthChunkDefines(t,i.shaderParams,a),s.shader=o6.createShader(t,{uniqueName:"DepthAware"+(r?"Horizontal":"Vertical")+"BlurShader",attributes:{aPosition:tA},vertexChunk:"quadVS",fragmentChunk:"depthAwareBlurPS",fragmentDefines:a});var o=s.device.scope;return s.sourceTextureId=o.resolve("sourceTexture"),s.sourceInvResolutionId=o.resolve("sourceInvResolution"),s.sourceInvResolutionValue=new Float32Array(2),s.filterSizeId=o.resolve("filterSize"),s}return t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&PU(t,e),t.prototype.execute=function(){this.filterSizeId.setValue(4),this.sourceTextureId.setValue(this.sourceTexture);var t=this.sourceTexture,n=t.width,i=t.height;this.sourceInvResolutionValue[0]=1/n,this.sourceInvResolutionValue[1]=1/i,this.sourceInvResolutionId.setValue(this.sourceInvResolutionValue),e.prototype.execute.call(this);},t}(f1);function Pz(e,t){return (Pz=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var PG=function(e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function t(t,n,i,r){(s=e.call(this,t)||this).radius=5,s.intensity=1,s.power=1,s.sampleCount=10,s.minAngle=5,s.randomize=false,s._scale=1,s._blueNoise=new uA(19),s.sourceTexture=n,s.cameraComponent=i,o1.get(t,ns).set("ssaoPS",'\n #include "screenDepthPS"\n \n varying vec2 uv0;\n uniform vec2 uInvResolution;\n uniform float uAspect;\n #define saturate(x) clamp(x,0.0,1.0)\n highp float getWFromProjectionMatrix(const mat4 p, const vec3 v) {\n return -v.z;\n }\n highp float getViewSpaceZFromW(const mat4 p, const float w) {\n return -w;\n }\n const float kLog2LodRate = 3.0;\n float random(const highp vec2 w) {\n const vec3 m = vec3(0.06711056, 0.00583715, 52.9829189);\n return fract(m.z * fract(dot(w, m.xy)));\n }\n highp vec2 getFragCoord() {\n return gl_FragCoord.xy;\n }\n highp vec3 computeViewSpacePositionFromDepth(highp vec2 uv, highp float linearDepth) {\n return vec3((0.5 - uv) * vec2(uAspect, 1.0) * linearDepth, linearDepth);\n }\n highp vec3 faceNormal(highp vec3 dpdx, highp vec3 dpdy) {\n return normalize(cross(dpdx, dpdy));\n }\n highp vec3 computeViewSpaceNormal(const highp vec3 position) {\n return faceNormal(dFdx(position), dFdy(position));\n }\n highp vec3 computeViewSpaceNormal(const highp vec3 position, const highp vec2 uv) {\n highp vec2 uvdx = uv + vec2(uInvResolution.x, 0.0);\n highp vec2 uvdy = uv + vec2(0.0, uInvResolution.y);\n highp vec3 px = computeViewSpacePositionFromDepth(uvdx, -getLinearScreenDepth(uvdx));\n highp vec3 py = computeViewSpacePositionFromDepth(uvdy, -getLinearScreenDepth(uvdy));\n highp vec3 dpdx = px - position;\n highp vec3 dpdy = py - position;\n return faceNormal(dpdx, dpdy);\n }\n uniform vec2 uSampleCount;\n uniform float uSpiralTurns;\n #define PI (3.14159)\n mediump vec3 tapLocation(mediump float i, const mediump float noise) {\n mediump float offset = ((2.0 * PI) * 2.4) * noise;\n mediump float angle = ((i * uSampleCount.y) * uSpiralTurns) * (2.0 * PI) + offset;\n mediump float radius = (i + noise + 0.5) * uSampleCount.y;\n return vec3(cos(angle), sin(angle), radius * radius);\n }\n highp vec2 startPosition(const float noise) {\n float angle = ((2.0 * PI) * 2.4) * noise;\n return vec2(cos(angle), sin(angle));\n }\n uniform vec2 uAngleIncCosSin;\n highp mat2 tapAngleStep() {\n highp vec2 t = uAngleIncCosSin;\n return mat2(t.x, t.y, -t.y, t.x);\n }\n mediump vec3 tapLocationFast(mediump float i, mediump vec2 p, const mediump float noise) {\n mediump float radius = (i + noise + 0.5) * uSampleCount.y;\n return vec3(p, radius * radius);\n }\n uniform float uMaxLevel;\n uniform float uInvRadiusSquared;\n uniform float uMinHorizonAngleSineSquared;\n uniform float uBias;\n uniform float uPeak2;\n void computeAmbientOcclusionSAO(inout mediump float occlusion, mediump float i, mediump float ssDiskRadius,\n const highp vec2 uv, const highp vec3 origin, const mediump vec3 normal,\n const mediump vec2 tapPosition, const float noise) {\n mediump vec3 tap = tapLocationFast(i, tapPosition, noise);\n mediump float ssRadius = max(1.0, tap.z * ssDiskRadius);\n mediump vec2 uvSamplePos = uv + vec2(ssRadius * tap.xy) * uInvResolution;\n mediump float level = clamp(floor(log2(ssRadius)) - kLog2LodRate, 0.0, float(uMaxLevel));\n highp float occlusionDepth = -getLinearScreenDepth(uvSamplePos);\n highp vec3 p = computeViewSpacePositionFromDepth(uvSamplePos, occlusionDepth);\n vec3 v = p - origin;\n float vv = dot(v, v);\n float vn = dot(v, normal);\n mediump float w = max(0.0, 1.0 - vv * uInvRadiusSquared);\n w = w * w;\n w *= step(vv * uMinHorizonAngleSineSquared, vn * vn);\n occlusion += w * max(0.0, vn + origin.z * uBias) / (vv + uPeak2);\n }\n uniform float uProjectionScaleRadius;\n uniform float uIntensity;\n uniform float uRandomize;\n float scalableAmbientObscurance(highp vec2 uv, highp vec3 origin, vec3 normal) {\n float noise = random(getFragCoord()) + uRandomize;\n highp vec2 tapPosition = startPosition(noise);\n highp mat2 angleStep = tapAngleStep();\n float ssDiskRadius = -(uProjectionScaleRadius / origin.z);\n float occlusion = 0.0;\n for (float i = 0.0; i < uSampleCount.x; i += 1.0) {\n computeAmbientOcclusionSAO(occlusion, i, ssDiskRadius, uv, origin, normal, tapPosition, noise);\n tapPosition = angleStep * tapPosition;\n }\n return occlusion;\n }\n uniform float uPower;\n void main() {\n highp vec2 uv = uv0;\n highp float depth = -getLinearScreenDepth(uv0);\n highp vec3 origin = computeViewSpacePositionFromDepth(uv, depth);\n vec3 normal = computeViewSpaceNormal(origin, uv);\n float occlusion = 0.0;\n if (uIntensity > 0.0) {\n occlusion = scalableAmbientObscurance(uv, origin, normal);\n }\n float ao = max(0.0, 1.0 - occlusion * uIntensity);\n ao = pow(ao, uPower);\n gl_FragColor = vec4(ao, ao, ao, 1.0);\n }\n'),o1.get(t,na).set("ssaoPS",'\n #include "screenDepthPS"\n varying uv0: vec2f;\n uniform uInvResolution: vec2f;\n uniform uAspect: f32;\n fn getWFromProjectionMatrix(p: mat4x4f, v: vec3f) -> f32 {\n return -v.z;\n }\n fn getViewSpaceZFromW(p: mat4x4f, w: f32) -> f32 {\n return -w;\n }\n const kLog2LodRate: f32 = 3.0;\n fn random(w: vec2f) -> f32 {\n const m: vec3f = vec3f(0.06711056, 0.00583715, 52.9829189);\n return fract(m.z * fract(dot(w, m.xy)));\n }\n fn getFragCoord() -> vec2f {\n return pcPosition.xy;\n }\n fn computeViewSpacePositionFromDepth(uv: vec2f, linearDepth: f32) -> vec3f {\n return vec3f((0.5 - uv) * vec2f(uniform.uAspect, 1.0) * linearDepth, linearDepth);\n }\n fn faceNormal(dpdx: vec3f, dpdy: vec3f) -> vec3f {\n return normalize(cross(dpdx, dpdy));\n }\n fn computeViewSpaceNormalDeriv(position: vec3f) -> vec3f {\n return faceNormal(dpdx(position), dpdy(position));\n }\n fn computeViewSpaceNormalDepth(position: vec3f, uv: vec2f) -> vec3f {\n let uvdx: vec2f = uv + vec2f(uniform.uInvResolution.x, 0.0);\n let uvdy: vec2f = uv + vec2f(0.0, uniform.uInvResolution.y);\n let px: vec3f = computeViewSpacePositionFromDepth(uvdx, -getLinearScreenDepth(uvdx));\n let py: vec3f = computeViewSpacePositionFromDepth(uvdy, -getLinearScreenDepth(uvdy));\n let dpdx: vec3f = px - position;\n let dpdy: vec3f = py - position;\n return faceNormal(dpdx, dpdy);\n }\n uniform uSampleCount: vec2f;\n uniform uSpiralTurns: f32;\n const PI: f32 = 3.14159;\n fn tapLocation(i: f32, noise: f32) -> vec3f {\n let offset: f32 = ((2.0 * PI) * 2.4) * noise;\n let angle: f32 = ((i * uniform.uSampleCount.y) * uniform.uSpiralTurns) * (2.0 * PI) + offset;\n let radius: f32 = (i + noise + 0.5) * uniform.uSampleCount.y;\n return vec3f(cos(angle), sin(angle), radius * radius);\n }\n fn startPosition(noise: f32) -> vec2f {\n let angle: f32 = ((2.0 * PI) * 2.4) * noise;\n return vec2f(cos(angle), sin(angle));\n }\n uniform uAngleIncCosSin: vec2f;\n fn tapAngleStep() -> mat2x2f {\n let t: vec2f = uniform.uAngleIncCosSin;\n return mat2x2f(vec2f(t.x, t.y), vec2f(-t.y, t.x));\n }\n fn tapLocationFast(i: f32, p: vec2f, noise_in: f32) -> vec3f {\n let radius: f32 = (i + noise_in + 0.5) * uniform.uSampleCount.y;\n return vec3f(p.x, p.y, radius * radius);\n }\n uniform uMaxLevel: f32;\n uniform uInvRadiusSquared: f32;\n uniform uMinHorizonAngleSineSquared: f32;\n uniform uBias: f32;\n uniform uPeak2: f32;\n fn computeAmbientOcclusionSAO(occlusion_ptr: ptr, i: f32, ssDiskRadius: f32,\n uv: vec2f, origin: vec3f, normal: vec3f,\n tapPosition: vec2f, noise: f32) {\n let tap: vec3f = tapLocationFast(i, tapPosition, noise);\n let ssRadius: f32 = max(1.0, tap.z * ssDiskRadius);\n let uvSamplePos: vec2f = uv + (ssRadius * tap.xy) * uniform.uInvResolution;\n let level: f32 = clamp(floor(log2(ssRadius)) - kLog2LodRate, 0.0, uniform.uMaxLevel);\n let occlusionDepth: f32 = -getLinearScreenDepth(uvSamplePos);\n let p: vec3f = computeViewSpacePositionFromDepth(uvSamplePos, occlusionDepth);\n let v: vec3f = p - origin;\n let vv: f32 = dot(v, v);\n let vn: f32 = dot(v, normal);\n var w_val: f32 = max(0.0, 1.0 - vv * uniform.uInvRadiusSquared);\n w_val = w_val * w_val;\n w_val = w_val * step(vv * uniform.uMinHorizonAngleSineSquared, vn * vn);\n *occlusion_ptr = *occlusion_ptr + w_val * max(0.0, vn + origin.z * uniform.uBias) / (vv + uniform.uPeak2);\n }\n uniform uProjectionScaleRadius: f32;\n uniform uIntensity: f32;\n uniform uRandomize: f32;\n fn scalableAmbientObscurance(uv: vec2f, origin: vec3f, normal: vec3f) -> f32 {\n let noise: f32 = random(getFragCoord()) + uniform.uRandomize;\n var tapPosition: vec2f = startPosition(noise);\n let angleStep: mat2x2f = tapAngleStep();\n let ssDiskRadius: f32 = -(uniform.uProjectionScaleRadius / origin.z);\n var occlusion: f32 = 0.0;\n for (var i: i32 = 0; i < i32(uniform.uSampleCount.x); i = i + 1) {\n computeAmbientOcclusionSAO(&occlusion, f32(i), ssDiskRadius, uv, origin, normal, tapPosition, noise);\n tapPosition = angleStep * tapPosition;\n }\n return occlusion;\n }\n uniform uPower: f32;\n @fragment\n fn fragmentMain(input: FragmentInput) -> FragmentOutput {\n var output: FragmentOutput;\n let uv: vec2f = input.uv0;\n let depth: f32 = -getLinearScreenDepth(input.uv0);\n let origin: vec3f = computeViewSpacePositionFromDepth(uv, depth);\n let normal: vec3f = computeViewSpaceNormalDepth(origin, uv);\n var occlusion: f32 = 0.0;\n if (uniform.uIntensity > 0.0) {\n occlusion = scalableAmbientObscurance(uv, origin, normal);\n }\n var ao: f32 = max(0.0, 1.0 - occlusion * uniform.uIntensity);\n ao = pow(ao, uniform.uPower);\n output.color = vec4f(ao, ao, ao, 1.0);\n return output;\n }\n');var s,a=new Map;o6.addScreenDepthChunkDefines(t,i.shaderParams,a),s.shader=o6.createShader(t,{uniqueName:"SsaoShader",attributes:{aPosition:tA},vertexChunk:"quadVS",fragmentChunk:"ssaoPS",fragmentDefines:a});var o=s.createRenderTarget("SsaoFinalTexture");s.ssaoTexture=o.colorBuffer,s.init(o,{resizeSource:s.sourceTexture});var l=new eN(0,0,0,0);if(s.setClearColor(l),r){var u=s.createRenderTarget("SsaoTempTexture"),c=new PV(t,o.colorBuffer,i,true);c.init(u,{resizeSource:o.colorBuffer}),c.setClearColor(l);var h=new PV(t,u.colorBuffer,i,false);h.init(o,{resizeSource:o.colorBuffer}),h.setClearColor(l),s.afterPasses.push(c),s.afterPasses.push(h);}return s.ssaoTextureId=t.scope.resolve("ssaoTexture"),s.ssaoTextureSizeInvId=t.scope.resolve("ssaoTextureSizeInv"),s}t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:true,configurable:true}}),e&&Pz(t,e);var n,i=t.prototype;return i.destroy=function(){var t,n;if(null==(t=this.renderTarget)||t.destroyTextureBuffers(),null==(n=this.renderTarget)||n.destroy(),this.renderTarget=null,this.afterPasses.length>0){var i=this.afterPasses[0].renderTarget;null==i||i.destroyTextureBuffers(),null==i||i.destroy();}this.afterPasses.forEach(function(e){return e.destroy()}),this.afterPasses.length=0,e.prototype.destroy.call(this);},i.createRenderTarget=function(e){return new ic({depth:false,colorBuffer:new nN(this.device,{name:e,width:1,height:1,format:52,mipmaps:false,minFilter:0,magFilter:0,addressU:1,addressV:1})})},i.execute=function(){var t=this.device,n=this.sourceTexture,i=this.sampleCount,r=this.minAngle,s=this.scale,a=this.renderTarget.colorBuffer,o=a.width,l=a.height,u=t.scope;u.resolve("uAspect").setValue(o/l),u.resolve("uInvResolution").setValue([1/o,1/l]),u.resolve("uSampleCount").setValue([i,1/i]);var c=Math.sin(r*Math.PI/180);u.resolve("uMinHorizonAngleSineSquared").setValue(c*c);var h=1/(i-.5)*62.82,f=this.radius/s,d=.1*f,p=2*d*6.282*this.intensity/i,m=.5*n.height;u.resolve("uSpiralTurns").setValue(10),u.resolve("uAngleIncCosSin").setValue([Math.cos(h),Math.sin(h)]),u.resolve("uMaxLevel").setValue(0),u.resolve("uInvRadiusSquared").setValue(1/(f*f)),u.resolve("uBias").setValue(.001),u.resolve("uPeak2").setValue(d*d),u.resolve("uIntensity").setValue(p),u.resolve("uPower").setValue(this.power),u.resolve("uProjectionScaleRadius").setValue(m*f),u.resolve("uRandomize").setValue(this.randomize?this._blueNoise.value():0),e.prototype.execute.call(this);},i.after=function(){this.ssaoTextureId.setValue(this.ssaoTexture);var e=this.sourceTexture;this.ssaoTextureSizeInvId.setValue([1/e.width,1/e.height]);},n=[{key:"scale",get:function(){return this._scale},set:function(e){this._scale=e,this.scaleX=e,this.scaleY=e;}}],function(e,t){for(var n=0;n0,e.taaEnabled=i.enabled,e.ssaoType=r.type,e.ssaoBlurEnabled=r.blurEnabled,e.formats=t.renderFormats.slice(),e.dofEnabled=this.dof.enabled,e.dofNearBlur=this.dof.nearBlur,e.dofHighQuality=this.dof.highQuality;},n.update=function(){if(this._enabled){var e=this.cameraComponent,t=this.options,n=this.renderPassCamera,i=this.rendering,r=this.bloom,s=this.grading,a=this.vignette,o=this.fringing,l=this.taa,u=this.ssao;this.updateOptions(),n.update(t);var c=n.composePass,h=n.bloomPass,f=n.ssaoPass,d=n.dofPass;n.renderTargetScale=ek.clamp(i.renderTargetScale,.1,1),c.toneMapping=i.toneMapping,c.sharpness=i.sharpness,t.bloomEnabled&&h&&(c.bloomIntensity=r.intensity,h.blurLevel=r.blurLevel),t.dofEnabled&&(d.focusDistance=this.dof.focusDistance,d.focusRange=this.dof.focusRange,d.blurRadius=this.dof.blurRadius,d.blurRings=this.dof.blurRings,d.blurRingPoints=this.dof.blurRingPoints),t.ssaoType!==Pm&&(f.intensity=u.intensity,f.power=u.power,f.radius=u.radius,f.sampleCount=u.samples,f.minAngle=u.minAngle,f.scale=u.scale,f.randomize=u.randomize),c.gradingEnabled=s.enabled,s.enabled&&(c.gradingSaturation=s.saturation,c.gradingBrightness=s.brightness,c.gradingContrast=s.contrast,c.gradingTint=s.tint),c.colorLUT=this.colorLUT.texture,c.colorLUTIntensity=this.colorLUT.intensity,c.vignetteEnabled=a.intensity>0,c.vignetteEnabled&&(c.vignetteInner=a.inner,c.vignetteOuter=a.outer,c.vignetteCurvature=a.curvature,c.vignetteIntensity=a.intensity),c.fringingEnabled=o.intensity>0,c.fringingEnabled&&(c.fringingIntensity=o.intensity),e.jitter=l.enabled?l.jitter:0,c.debug=this.debug,"ssao"===c.debug&&t.ssaoType===Pm&&(c.debug=null),"vignette"!==c.debug||c.vignetteEnabled||(c.debug=null);}},t=[{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled!==e&&(e?this.enable():this.disable(),this._enabled=e);}}],function(e,t){for(var n=0;nPJ.distance(this.root.getPosition())||(this.root.setPosition(PJ),this.fire(t.EVENT_POSITIONUPDATE,PJ));},i._updateRotation=function(){PJ.set(0,0,0),this._coordSpace===Pq&&0!==this.nodes.length&&PJ.copy(this.nodes[this.nodes.length-1].getEulerAngles()),1e-6>PJ.distance(this.root.getEulerAngles())||(this.root.setEulerAngles(PJ),this.fire(t.EVENT_ROTATIONUPDATE,PJ));},i._updateScale=function(){if(0===this._camera.projection){var e=this.root.getPosition(),n=this._camera.entity.getPosition(),i=e.distance(n);this._scale=Math.tan(.5*this._camera.fov*ek.DEG_TO_RAD)*i*.3;}else this._scale=.32*this._camera.orthoHeight;this._scale=Math.max(this._scale*this._size,1e-4),1e-6>Math.abs(this._scale-this.root.getLocalScale().x)||(this.root.setLocalScale(this._scale,this._scale,this._scale),this.fire(t.EVENT_SCALEUPDATE,this._scale));},i._getSelection=function(e,t){for(var n=this._camera.screenToWorld(e,t,0),i=this._camera.screenToWorld(e,t,this._camera.farClip-this._camera.nearClip),r=PJ.copy(i).sub(n).normalize(),s=[],a=0;athis._flipped.distance(e)||(this._flipped.copy(e),this.entity.setLocalPosition(this._getPosition()));}}],function(e,t){for(var n=0;nMath.abs(t),this.flipShapes&&(this._shapes.x.flipped=t<0),t=e.dot(this.root.up),this._shapes.y.entity.enabled=.98>Math.abs(t),this.flipShapes&&(this._shapes.y.flipped=t<0),t=e.dot(this.root.forward),this._shapes.z.entity.enabled=.98>Math.abs(t),this.flipShapes&&(this._shapes.z.flipped=t>0),IM.cross(e,this.root.right),this._shapes.yz.entity.enabled=.98>IM.length(),this.flipShapes&&(this._shapes.yz.flipped=IO.set(0,+(0>IM.dot(this.root.forward)),+(0>IM.dot(this.root.up)))),IM.cross(e,this.root.forward),this._shapes.xy.entity.enabled=.98>IM.length(),this.flipShapes&&(this._shapes.xy.flipped=IO.set(+(0>IM.dot(this.root.up)),+(IM.dot(this.root.right)>0),0)),IM.cross(e,this.root.up),this._shapes.xz.entity.enabled=.98>IM.length(),this.flipShapes&&(this._shapes.xz.flipped=IO.set(+(IM.dot(this.root.forward)>0),0,+(IM.dot(this.root.right)>0)));},i._storeNodePositions=function(){for(var e=0;e.9?(Iz.sub2(e,i),IX.copy(this._camera.entity.getRotation()).invert().transformVector(Iz,Iz),a=Math.sign(l)*Math.atan2(Iz.y,Iz.x)*ek.RAD_TO_DEG):(Iz.copy(i),IG.cross(s.normal,o).normalize().add(i),this._camera.worldToScreen(Iz,IH),this._camera.worldToScreen(IG,IW),Iz.sub2(IW,IH).normalize(),IG.set(t,n,0),a=Iz.dot(IG)),a},n=[{key:"xyzTubeRadius",get:function(){return this._shapes.x.tubeRadius},set:function(e){this._setDiskProp("tubeRadius",e);}},{key:"xyzRingRadius",get:function(){return this._shapes.x.ringRadius},set:function(e){this._setDiskProp("ringRadius",e);}},{key:"faceTubeRadius",get:function(){return this._shapes.face.tubeRadius},set:function(e){this._shapes.face.tubeRadius=e;}},{key:"faceRingRadius",get:function(){return this._shapes.face.ringRadius},set:function(e){this._shapes.face.ringRadius=e;}},{key:"ringTolerance",get:function(){return this._shapes.x.tolerance},set:function(e){this._setDiskProp("tolerance",e),this._shapes.face.tolerance=e;}}],function(e,t){for(var n=0;nMath.abs(t),this.flipShapes&&(this._shapes.x.flipped=t<0),t=e.dot(this.root.up),this._shapes.y.entity.enabled=.98>Math.abs(t),this.flipShapes&&(this._shapes.y.flipped=t<0),t=e.dot(this.root.forward),this._shapes.z.entity.enabled=.98>Math.abs(t),this.flipShapes&&(this._shapes.z.flipped=t>0),I4.cross(e,this.root.right),this._shapes.yz.entity.enabled=.98>I4.length(),this.flipShapes&&(this._shapes.yz.flipped=I5.set(0,+(0>I4.dot(this.root.forward)),+(0>I4.dot(this.root.up)))),I4.cross(e,this.root.forward),this._shapes.xy.entity.enabled=.98>I4.length(),this.flipShapes&&(this._shapes.xy.flipped=I5.set(+(0>I4.dot(this.root.up)),+(I4.dot(this.root.right)>0),0)),I4.cross(e,this.root.up),this._shapes.xz.entity.enabled=.98>I4.length(),this.flipShapes&&(this._shapes.xz.flipped=I5.set(+(I4.dot(this.root.forward)>0),0,+(I4.dot(this.root.right)>0)));},i._storeNodeScales=function(){for(var e=0;e=i.length?t(Error("Failed to create a graphics device")):Promise.resolve(i[n++]()).then(function(t){t?e(t):r();}).catch(function(e){r();});};r();})},e.createMesh=function(e,t,n){ void 0===n&&(n={});var i=new h7;return i.positions=t,i.normals=n.normals,i.tangents=n.tangents,i.colors=n.colors,i.uvs=n.uvs,i.uvs1=n.uvs1,i.blendIndices=n.blendIndices,i.blendWeights=n.blendWeights,i.indices=n.indices,lv.fromGeometry(e,i,n)},e.createPlane=function(e,t){return lv.fromGeometry(e,new dX(t))},e.createScript=T9,e.createShader=function(e,t,n,i,r){},e.createShaderFromCode=function(e,t,n,i,r,s,a){if(void 0===s&&(s=false),void 0===a&&(a={}),"boolean"==typeof s)a.useTransformFeedback=s;else {var o;(void 0===s?"undefined":(o=s)&&"undefined"!=typeof Symbol&&o.constructor===Symbol?"symbol":typeof o)=="object"&&(a=o4({},a,s));}var l=oz(e),u=l.getCachedShader(i);return u||(u=new r$(e,rQ.createDefinition(e,o4({},a,{name:i,vertexCode:t,fragmentCode:n,attributes:r}))),l.setCachedShader(i,u)),u},e.createSphere=function(e,t){return lv.fromGeometry(e,new fi(t))},e.createTorus=function(e,t){return lv.fromGeometry(e,new dq(t))},e.createURI=function(e){var t="";if((e.authority||e.scheme)&&(e.host||e.hostpath))throw Error("Can't have 'scheme' or 'authority' and 'host' or 'hostpath' option");if(e.host&&e.hostpath)throw Error("Can't have 'host' and 'hostpath' option");if(e.path&&e.hostpath)throw Error("Can't have 'path' and 'hostpath' option");return e.scheme&&(t+=""+e.scheme+":"),e.authority&&(t+="//"+e.authority),e.host&&(t+=e.host),e.path&&(t+=e.path),e.hostpath&&(t+=e.hostpath),e.query&&(t+="?"+e.query),e.fragment&&(t+="#"+e.fragment),t},e.cubemaProjectionNames=oh,e.ditherNames=oR,e.dracoInitialize=function(e){(null==e?void 0:e.lazyInit)?B=e:xU(e);},e.drawFullscreenQuad=function(e,t,n,i,r){var s;if(r){var a=t?t.width:e.width,o=t?t.height:e.height;s=A3.set(r.x*a,r.y*o,r.z*a,r.w*o);}la(e,t,i,s);},e.drawQuadWithShader=la,e.extend=ee,e.fresnelNames=oa,e.gammaNames=of,e.getPixelFormatArrayType=tw,e.getReservedScriptNames=function(){return T6},e.getTouchTargetCoords=az,e.guid=et,e.http=aq,e.isCompressedPixelFormat=ty,e.isIntegerPixelFormat=tx,e.isSrgbPixelFormat=tS,e.lightFalloffNames=ou,e.lightShapeNames=ol,e.lightTypeNames=oo,e.math=ek,e.now=eL,e.path=en,e.pixelFormatGammaToLinear=tT,e.pixelFormatInfo=tg,e.pixelFormatLinearToGamma=tb,e.platform=ef,e.reflectionSrcNames=oS,e.registerScript=Ee,e.reprojectTexture=fM,e.requiresManualGamma=tE,e.revision=$,e.script=px,e.semanticToLocation=nb,e.shaderChunks=A8,e.shadowTypeInfo=oc,e.specularOcclusionNames=op,e.spriteRenderModeNames=ow,e.string=ev,e.tonemapNames=od,e.typedArrayIndexFormats=nS,e.typedArrayIndexFormatsByteSize=nx,e.typedArrayToType={Int8Array:0,Uint8Array:1,Int16Array:2,Uint16Array:3,Int32Array:4,Uint32Array:5,Float32Array:6},e.typedArrayTypes=ng,e.typedArrayTypesByteSize=ny,e.uniformTypeToName=no,e.uniformTypeToNameMapWGSL=nu,e.uniformTypeToNameWGSL=nl,e.uniformTypeToStorage=nc,e.version=J,e.vertexTypesNames=["INT8","UINT8","INT16","UINT16","INT32","UINT32","FLOAT32","FLOAT16"];},("undefined"==typeof exports?"undefined":(n=exports)&&"undefined"!=typeof Symbol&&n.constructor===Symbol?"symbol":typeof n)=="object"&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).pc={});