Файловый менеджер - Редактировать - /home/jogoso94/public_html/jogos/cannonballs3d/playcanvas-stable.min.js
�азад
/** * @license * PlayCanvas Engine v1.64.4 revision 7fc5c5c22 (RELEASE) * Copyright 2011-2023 PlayCanvas Ltd. All rights reserved. */ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).pc={})}(this,(function(e){"use strict";function t(e,t,i){e.prototype[t]||Object.defineProperty(e.prototype,t,{value:i,configurable:!0,enumerable:!1,writable:!0})}t(Array,"fill",(function(e){if(null==this)throw new TypeError("this is null or not defined");for(var t=Object(this),i=t.length>>>0,n=arguments[1],s=n>>0,r=s<0?Math.max(i+s,0):Math.min(s,i),a=arguments[2],o=void 0===a?i:a>>0,h=o<0?Math.max(i+o,0):Math.min(o,i);r<h;)t[r]=e,r++;return t})),t(Array,"find",(function(e){if(null==this)throw TypeError('"this" is null or not defined');var t=Object(this),i=t.length>>>0;if("function"!=typeof e)throw TypeError("predicate must be a function");for(var n=arguments[1],s=0;s<i;){var r=t[s];if(e.call(n,r,s,t))return r;s++}})),t(Array,"findIndex",(function(e){if(null==this)throw new TypeError('"this" is null or not defined');var t=Object(this),i=t.length>>>0;if("function"!=typeof e)throw new TypeError("predicate must be a function");for(var n=arguments[1],s=0;s<i;){var r=t[s];if(e.call(n,r,s,t))return s;s++}return-1})),Math.log2=Math.log2||function(e){return Math.log(e)*Math.LOG2E},Math.sign||(Math.sign=function(e){return(e>0)-(e<0)||+e}),void 0===Number.isFinite&&(Number.isFinite=function(e){return"number"==typeof e&&isFinite(e)}),"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,t){if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var i=Object(e),n=1;n<arguments.length;n++){var s=arguments[n];if(null!=s)for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&(i[r]=s[r])}return i},writable:!0,configurable:!0}),Object.values=Object.values||function(e){return Object.keys(e).map((function(t){return e[t]}))},function(){if("undefined"!=typeof navigator&&"undefined"!=typeof document){navigator.pointer=navigator.pointer||navigator.webkitPointer||navigator.mozPointer;var e=function(){var e=document.createEvent("CustomEvent");e.initCustomEvent("pointerlockchange",!0,!1,null),document.dispatchEvent(e)},t=function(){var e=document.createEvent("CustomEvent");e.initCustomEvent("pointerlockerror",!0,!1,null),document.dispatchEvent(e)};document.addEventListener("webkitpointerlockchange",e,!1),document.addEventListener("webkitpointerlocklost",e,!1),document.addEventListener("mozpointerlockchange",e,!1),document.addEventListener("mozpointerlocklost",e,!1),document.addEventListener("webkitpointerlockerror",t,!1),document.addEventListener("mozpointerlockerror",t,!1),Element.prototype.mozRequestPointerLock?Element.prototype.requestPointerLock=function(){this.mozRequestPointerLock()}:Element.prototype.requestPointerLock=Element.prototype.requestPointerLock||Element.prototype.webkitRequestPointerLock||Element.prototype.mozRequestPointerLock,!Element.prototype.requestPointerLock&&navigator.pointer&&(Element.prototype.requestPointerLock=function(){document.pointerLockElement=this,navigator.pointer.lock(this,e,t)}),document.exitPointerLock=document.exitPointerLock||document.webkitExitPointerLock||document.mozExitPointerLock,document.exitPointerLock||(document.exitPointerLock=function(){navigator.pointer&&(document.pointerLockElement=null,navigator.pointer.unlock())})}}(),t(String,"endsWith",(function(e,t){return(void 0===t||t>this.length)&&(t=this.length),this.substring(t-e.length,t)===e})),t(String,"includes",(function(e,t){return"number"!=typeof t&&(t=0),!(t+e.length>this.length)&&-1!==this.indexOf(e,t)})),t(String,"startsWith",(function(e,t){var i=t>0?0|t:0;return this.substring(i,i+e.length)===e})),t(String,"trimEnd",(function(){return this.replace(new RegExp(/[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/.source+"$","g"),"")}));for(var i=0,n=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array];i<n.length;i++){var s=n[i];t(s,"fill",Array.prototype.fill),t(s,"join",Array.prototype.join)}var r={};function a(e,t){var i;r[e]=!0,void 0!==t&&(i=t,window.console&&window.console.error&&window.console.error(i))}var o=function e(t){var i=t.gl;this.ext=t,this.isAlive=!0,this.hasBeenBound=!1,this.elementArrayBuffer=null,this.attribs=new Array(t.maxVertexAttribs);for(var n=0;n<this.attribs.length;n++){var s=new e.VertexAttrib(i);this.attribs[n]=s}this.maxAttrib=0};(o.VertexAttrib=function(e){this.enabled=!1,this.buffer=null,this.size=4,this.type=e.FLOAT,this.normalized=!1,this.stride=16,this.offset=0,this.cached="",this.recache()}).prototype.recache=function(){this.cached=[this.size,this.type,this.normalized,this.stride,this.offset].join(":")};var h=function(e){var t=this;this.gl=e,function(e){var t=e.getError;e.getError=function(){do{(i=t.apply(e))!=e.NO_ERROR&&(r[i]=!0)}while(i!=e.NO_ERROR);for(var i in r)if(r[i])return delete r[i],parseInt(i);return e.NO_ERROR}}(e);var i=this.original={getParameter:e.getParameter,enableVertexAttribArray:e.enableVertexAttribArray,disableVertexAttribArray:e.disableVertexAttribArray,bindBuffer:e.bindBuffer,getVertexAttrib:e.getVertexAttrib,vertexAttribPointer:e.vertexAttribPointer};e.getParameter=function(e){return e==t.VERTEX_ARRAY_BINDING_OES?t.currentVertexArrayObject==t.defaultVertexArrayObject?null:t.currentVertexArrayObject:i.getParameter.apply(this,arguments)},e.enableVertexAttribArray=function(e){var n=t.currentVertexArrayObject;n.maxAttrib=Math.max(n.maxAttrib,e);var s=n.attribs[e];return s.enabled=!0,i.enableVertexAttribArray.apply(this,arguments)},e.disableVertexAttribArray=function(e){var n=t.currentVertexArrayObject;n.maxAttrib=Math.max(n.maxAttrib,e);var s=n.attribs[e];return s.enabled=!1,i.disableVertexAttribArray.apply(this,arguments)},e.bindBuffer=function(n,s){switch(n){case e.ARRAY_BUFFER:t.currentArrayBuffer=s;break;case e.ELEMENT_ARRAY_BUFFER:t.currentVertexArrayObject.elementArrayBuffer=s}return i.bindBuffer.apply(this,arguments)},e.getVertexAttrib=function(n,s){var r=t.currentVertexArrayObject,a=r.attribs[n];switch(s){case e.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING:return a.buffer;case e.VERTEX_ATTRIB_ARRAY_ENABLED:return a.enabled;case e.VERTEX_ATTRIB_ARRAY_SIZE:return a.size;case e.VERTEX_ATTRIB_ARRAY_STRIDE:return a.stride;case e.VERTEX_ATTRIB_ARRAY_TYPE:return a.type;case e.VERTEX_ATTRIB_ARRAY_NORMALIZED:return a.normalized;default:return i.getVertexAttrib.apply(this,arguments)}},e.vertexAttribPointer=function(e,n,s,r,a,o){var h=t.currentVertexArrayObject;h.maxAttrib=Math.max(h.maxAttrib,e);var l=h.attribs[e];return l.buffer=t.currentArrayBuffer,l.size=n,l.type=s,l.normalized=r,l.stride=a,l.offset=o,l.recache(),i.vertexAttribPointer.apply(this,arguments)},e.instrumentExtension&&e.instrumentExtension(this,"OES_vertex_array_object"),e.canvas.addEventListener("webglcontextrestored",(function(){var e;e="OESVertexArrayObject emulation library context restored",window.console&&window.console.log&&window.console.log(e),t.reset_()}),!0),this.reset_()};h.prototype.VERTEX_ARRAY_BINDING_OES=34229,h.prototype.reset_=function(){if(void 0!==this.vertexArrayObjects)for(var e=0;e<this.vertexArrayObjects.length;++e)this.vertexArrayObjects.isAlive=!1;var t=this.gl;this.maxVertexAttribs=t.getParameter(t.MAX_VERTEX_ATTRIBS),this.defaultVertexArrayObject=new o(this),this.currentVertexArrayObject=null,this.currentArrayBuffer=null,this.vertexArrayObjects=[this.defaultVertexArrayObject],this.bindVertexArrayOES(null)},h.prototype.createVertexArrayOES=function(){var e=new o(this);return this.vertexArrayObjects.push(e),e},h.prototype.deleteVertexArrayOES=function(e){e.isAlive=!1,this.vertexArrayObjects.splice(this.vertexArrayObjects.indexOf(e),1),this.currentVertexArrayObject==e&&this.bindVertexArrayOES(null)},h.prototype.isVertexArrayOES=function(e){return!!(e&&e instanceof o&&e.hasBeenBound&&e.ext==this)},h.prototype.bindVertexArrayOES=function(e){var t=this.gl;if(!e||e.isAlive){var i=this.original,n=this.currentVertexArrayObject;this.currentVertexArrayObject=e||this.defaultVertexArrayObject,this.currentVertexArrayObject.hasBeenBound=!0;var s=this.currentVertexArrayObject;if(n!=s){n&&s.elementArrayBuffer==n.elementArrayBuffer||i.bindBuffer.call(t,t.ELEMENT_ARRAY_BUFFER,s.elementArrayBuffer);for(var r=this.currentArrayBuffer,o=Math.max(n?n.maxAttrib:0,s.maxAttrib),h=0;h<=o;h++){var l=s.attribs[h],c=n?n.attribs[h]:null;if(n&&l.enabled==c.enabled||(l.enabled?i.enableVertexAttribArray.call(t,h):i.disableVertexAttribArray.call(t,h)),l.enabled){var u=!1;n&&l.buffer==c.buffer||(r!=l.buffer&&(i.bindBuffer.call(t,t.ARRAY_BUFFER,l.buffer),r=l.buffer),u=!0),(u||l.cached!=c.cached)&&i.vertexAttribPointer.call(t,h,l.size,l.type,l.normalized,l.stride,l.offset)}}this.currentArrayBuffer!=r&&i.bindBuffer.call(t,t.ARRAY_BUFFER,this.currentArrayBuffer)}}else a(t.INVALID_OPERATION,"bindVertexArrayOES: attempt to bind deleted arrayObject")};var l="1.64.4",c="7fc5c5c22",u=function(){for(var e={},t=["Array","Object","Function","Date","RegExp","Float32Array"],i=0;i<t.length;i++)e["[object "+t[i]+"]"]=t[i].toLowerCase();return e}();function d(e){if(null===e)return"null";var t=typeof e;return"undefined"===t||"number"===t||"string"===t||"boolean"===t?t:u[Object.prototype.toString.call(e)]}function f(e,t){for(var i in t){var n=t[i];"object"===d(n)?e[i]=f({},n):"array"===d(n)?e[i]=f([],n):e[i]=n}return e}var p=function(){function e(){this._callbacks={},this._callbackActive={}}var t=e.prototype;return t.initEventHandler=function(){this._callbacks={},this._callbackActive={}},t._addCallback=function(e,t,i,n){void 0===n&&(n=!1),e&&"string"==typeof e&&t&&(this._callbacks[e]||(this._callbacks[e]=[]),this._callbackActive[e]&&this._callbackActive[e]===this._callbacks[e]&&(this._callbackActive[e]=this._callbackActive[e].slice()),this._callbacks[e].push({callback:t,scope:i||this,once:n}))},t.on=function(e,t,i){return this._addCallback(e,t,i,!1),this},t.off=function(e,t,i){if(e)this._callbackActive[e]&&this._callbackActive[e]===this._callbacks[e]&&(this._callbackActive[e]=this._callbackActive[e].slice());else for(var n in this._callbackActive)this._callbacks[n]&&this._callbacks[n]===this._callbackActive[n]&&(this._callbackActive[n]=this._callbackActive[n].slice());if(e)if(t){var s=this._callbacks[e];if(!s)return this;for(var r=s.length,a=0;a<r;a++)s[a].callback===t&&(i&&s[a].scope!==i||(s[a--]=s[--r]));s.length=r}else this._callbacks[e]&&(this._callbacks[e]=[]);else this._callbacks={};return this},t.fire=function(e,t,i,n,s,r,a,o,h){if(!e||!this._callbacks[e])return this;var l;this._callbackActive[e]?(this._callbackActive[e]===this._callbacks[e]&&(this._callbackActive[e]=this._callbackActive[e].slice()),l=this._callbacks[e].slice()):this._callbackActive[e]=this._callbacks[e];for(var c=0;(l||this._callbackActive[e])&&c<(l||this._callbackActive[e]).length;c++){var u=(l||this._callbackActive[e])[c];if(u.callback.call(u.scope,t,i,n,s,r,a,o,h),u.once){var d=this._callbacks[e],f=d?d.indexOf(u):-1;-1!==f&&(this._callbackActive[e]===d&&(this._callbackActive[e]=this._callbackActive[e].slice()),this._callbacks[e].splice(f,1))}}return l||(this._callbackActive[e]=null),this},t.once=function(e,t,i){return this._addCallback(e,t,i,!0),this},t.hasEvent=function(e){return this._callbacks[e]&&0!==this._callbacks[e].length||!1},e}(),m={attach:function(e){var t=m;return e._addCallback=t._addCallback,e.on=t.on,e.off=t.off,e.fire=t.fire,e.once=t.once,e.hasEvent=t.hasEvent,e._callbacks={},e._callbackActive={},e},_addCallback:p.prototype._addCallback,on:p.prototype.on,off:p.prototype.off,fire:p.prototype.fire,once:p.prototype.once,hasEvent:p.prototype.hasEvent},_={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)}))}},g=function(){function e(){}return e.set=function(e,t){},e.get=function(t){return e._traceChannels.has(t)},e}();g._traceChannels=new Set,g.stack=!1,new Set;var v={delimiter:"/",join:function(){for(var e=arguments.length,t=arguments[0],i=0;i<e-1;++i){var n=arguments[i],s=arguments[i+1];s[0]!==v.delimiter?n&&s&&n[n.length-1]!==v.delimiter&&s[0]!==v.delimiter?t+=v.delimiter+s:t+=s:t=s}return t},normalize:function(e){for(var t=e.startsWith(v.delimiter),i=e.endsWith(v.delimiter),n=e.split("/"),s="",r=[],a=0;a<n.length;a++)""!==n[a]&&"."!==n[a]&&(".."===n[a]&&r.length>0?r=r.slice(0,r.length-2):(a>0&&r.push(v.delimiter),r.push(n[a])));return s=r.join(""),t||s[0]!==v.delimiter||(s=s.slice(1)),i&&s[s.length-1]!==v.delimiter&&(s+=v.delimiter),s},split:function(e){var t=e.lastIndexOf(v.delimiter);return-1!==t?[e.substring(0,t),e.substring(t+1)]:["",e]},getBasename:function(e){return v.split(e)[1]},getDirectory:function(e){return v.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="",i=e.split("/"),n=0;if(i.length>1)if(v.isRelativePath(e))if("."===i[0])for(n=0;n<i.length-1;++n)t+=0===n?i[n]:"/"+i[n];else if(".."===i[0])for(n=0;n<i.length-1;++n)t+=0===n?i[n]:"/"+i[n];else for(t=".",n=0;n<i.length-1;++n)t+="/"+i[n];else for(n=0;n<i.length-1;++n)t+=0===n?i[n]:"/"+i[n];return t}},y="undefined"!=typeof navigator?navigator.userAgent:"",x="undefined"!=typeof window?"browser":"node",S=/android/i.test(y)?"android":/ip([ao]d|hone)/i.test(y)?"ios":/windows/i.test(y)?"windows":/mac os/i.test(y)?"osx":/linux/i.test(y)?"linux":/cros/i.test(y)?"cros":null,b="browser"!==x?null:/(Chrome\/|Chromium\/|Edg.*\/)/.test(y)?"chrome":/Safari\//.test(y)?"safari":/Firefox\//.test(y)?"firefox":"other",w=/xbox/i.test(y),T="browser"===x&&("ontouchstart"in window||"maxTouchPoints"in navigator&&navigator.maxTouchPoints>0),A=!("browser"!==x||!navigator.getGamepads&&!navigator.webkitGetGamepads),C="undefined"!=typeof Worker,E=function(){var e=!1;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}(),M={environment:x,global:"browser"===x?window:global,browser:"browser"===x,desktop:["windows","osx","linux","cros"].includes(S),mobile:["android","ios"].includes(S),ios:"ios"===S,android:"android"===S,xbox:w,gamepads:A,touch:T,workers:C,passiveEvents:E,browserName:b},P="abcdefghijklmnopqrstuvwxyz",R="ABCDEFGHIJKLMNOPQRSTUVWXYZ",I=55296,L=127462,D=127487,O=65024,k=65039;function F(e,t){void 0===t&&(t=0);var i=e.length;if(t<0||t>=i)return null;var n=e.charCodeAt(t);if(i>1&&n>=I&&n<=56319){var s=e.charCodeAt(t+1);if(s>=56320&&s<=57343)return{code:1024*(n-I)+s-56320+65536,long:!0}}return{code:n,long:!1}}function B(e,t,i){if(!e)return!1;var n=F(e);if(n){var s=n.code;return s>=t&&s<=i}return!1}function N(e,t){if(t===e.length-1)return 1;if(B(e[t],I,56319)){var i=e.substring(t,t+2),n=e.substring(t+2,t+4);return B(n,127995,127999)||B(i,L,D)&&B(n,L,D)?4:B(n,O,k)?3:2}return B(e[t+1],O,k)?2:1}var U,z,V,G={ASCII_LOWERCASE:P,ASCII_UPPERCASE:R,ASCII_LETTERS:P+R,format:function(e){for(var t=1;t<arguments.length;t++)e=e.replace("{"+(t-1)+"}",arguments[t]);return e},toBool:function(e,t){if(void 0===t&&(t=!1),"true"===e)return!0;if(t){if("false"===e)return!1;throw new TypeError("Not a boolean string")}return!1},getCodePoint:function(e,t){var i=F(e,t);return i&&i.code},getCodePoints:function(e){if("string"!=typeof e)throw new TypeError("Not a string");for(var t,i=0,n=[];t=F(e,i);)n.push(t.code),i+=t.long?2:1;return n},getSymbols:function(e){if("string"!=typeof e)throw new TypeError("Not a string");for(var t,i=0,n=e.length,s=[],r=0;i<n;)if(B(t=e[i+(r+=N(e,i+r))],8400,8447)&&(t=e[i+r++]),B(t,O,k)&&(t=e[i+r++]),t&&8205===t.charCodeAt(0))t=e[i+r++];else{var a=e.substring(i,i+r);s.push(a),i+=r,r=0}return s},fromCodePoint:function(){for(var e,t,i,n=[],s=0;s<arguments.length;++s)t=(e=Number(arguments[s]))-65536,i=e>65535?[55296+(t>>10),t%1024+56320]:[e],n.push(String.fromCharCode.apply(null,i));return n.join("")}},H=function(){function e(){this._list=[],this._index={}}var t=e.prototype;return t.push=function(e,t){if(this._index[e])throw Error("Key already in index "+e);var i=this._list.push(t)-1;this._index[e]=i},t.has=function(e){return void 0!==this._index[e]},t.get=function(e){var t=this._index[e];return void 0!==t?this._list[t]:null},t.remove=function(e){var t=this._index[e];if(void 0!==t){for(e in this._list.splice(t,1),delete this._index[e],this._index){var i=this._index[e];i>t&&(this._index[e]=i-1)}return!0}return!1},t.list=function(){return this._list},t.clear=function(){for(var e in this._list.length=0,this._index)delete this._index[e]},e}(),W=function(){function e(){}return e.loadScript=function(e,t){var i=document.createElement("script");i.setAttribute("src",e),i.onload=function(){t(null)},i.onerror=function(){t("Failed to load script='"+e+"'")},document.body.appendChild(i)},e.loadWasm=function(t,i,n){var s=e.wasmSupported()&&i.glueUrl&&i.wasmUrl?i.glueUrl:i.fallbackUrl;s?e.loadScript(s,(function(e){if(e)n(e,null);else{var s=window[t];window[t]=void 0,s({locateFile:function(){return i.wasmUrl},onAbort:function(){n("wasm module aborted.")}}).then((function(e){n(null,e)}))}})):n("No supported wasm modules found.",null)},e.getModule=function(t){return e.modules.hasOwnProperty(t)||(e.modules[t]={config:null,initializing:!1,instance:null,callbacks:[]}),e.modules[t]},e.initialize=function(t,i){if(!i.initializing){var n=i.config;(n.glueUrl||n.wasmUrl||n.fallbackUrl)&&(i.initializing=!0,e.loadWasm(t,n,(function(e,s){e?n.errorHandler?n.errorHandler(e):console.error("failed to initialize module="+t+" error="+e):(i.instance=s,i.callbacks.forEach((function(e){e(s)})))})))}},e}();W.modules={},W.wasmSupported=(U=function(){try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){var e=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(e instanceof WebAssembly.Module)return new WebAssembly.Instance(e)instanceof WebAssembly.Instance}}catch(e){}return!1},V=z={},function(){return V===z&&(V=U()),V});var X=function(){function e(){}return e.setConfig=function(e,t){var i=W.getModule(e);i.config=t,i.callbacks.length>0&&W.initialize(e,i)},e.getConfig=function(e){var t,i;return null==(t=W.modules)||null==(i=t[e])?void 0:i.config},e.getInstance=function(e,t){var i=W.getModule(e);i.instance?t(i.instance):(i.callbacks.push(t),i.config&&W.initialize(e,i))},e}();function j(){j=function(){return e};var e={},t=Object.prototype,i=t.hasOwnProperty,n=Object.defineProperty||function(e,t,i){e[t]=i.value},s="function"==typeof Symbol?Symbol:{},r=s.iterator||"@@iterator",a=s.asyncIterator||"@@asyncIterator",o=s.toStringTag||"@@toStringTag";function h(e,t,i){return Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{h({},"")}catch(e){h=function(e,t,i){return e[t]=i}}function l(e,t,i,s){var r=t&&t.prototype instanceof d?t:d,a=Object.create(r.prototype),o=new A(s||[]);return n(a,"_invoke",{value:S(e,i,o)}),a}function c(e,t,i){try{return{type:"normal",arg:e.call(t,i)}}catch(e){return{type:"throw",arg:e}}}e.wrap=l;var u={};function d(){}function f(){}function p(){}var m={};h(m,r,(function(){return this}));var _=Object.getPrototypeOf,g=_&&_(_(C([])));g&&g!==t&&i.call(g,r)&&(m=g);var v=p.prototype=d.prototype=Object.create(m);function y(e){["next","throw","return"].forEach((function(t){h(e,t,(function(e){return this._invoke(t,e)}))}))}function x(e,t){function s(n,r,a,o){var h=c(e[n],e,r);if("throw"!==h.type){var l=h.arg,u=l.value;return u&&"object"==typeof u&&i.call(u,"__await")?t.resolve(u.__await).then((function(e){s("next",e,a,o)}),(function(e){s("throw",e,a,o)})):t.resolve(u).then((function(e){l.value=e,a(l)}),(function(e){return s("throw",e,a,o)}))}o(h.arg)}var r;n(this,"_invoke",{value:function(e,i){function n(){return new t((function(t,n){s(e,i,t,n)}))}return r=r?r.then(n,n):n()}})}function S(e,t,i){var n="suspendedStart";return function(s,r){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===s)throw r;return E()}for(i.method=s,i.arg=r;;){var a=i.delegate;if(a){var o=b(a,i);if(o){if(o===u)continue;return o}}if("next"===i.method)i.sent=i._sent=i.arg;else if("throw"===i.method){if("suspendedStart"===n)throw n="completed",i.arg;i.dispatchException(i.arg)}else"return"===i.method&&i.abrupt("return",i.arg);n="executing";var h=c(e,t,i);if("normal"===h.type){if(n=i.done?"completed":"suspendedYield",h.arg===u)continue;return{value:h.arg,done:i.done}}"throw"===h.type&&(n="completed",i.method="throw",i.arg=h.arg)}}}function b(e,t){var i=t.method,n=e.iterator[i];if(void 0===n)return t.delegate=null,"throw"===i&&e.iterator.return&&(t.method="return",t.arg=void 0,b(e,t),"throw"===t.method)||"return"!==i&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+i+"' method")),u;var s=c(n,e.iterator,t.arg);if("throw"===s.type)return t.method="throw",t.arg=s.arg,t.delegate=null,u;var r=s.arg;return r?r.done?(t[e.resultName]=r.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,u):r:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,u)}function w(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function T(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function A(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(w,this),this.reset(!0)}function C(e){if(e){var t=e[r];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,s=function t(){for(;++n<e.length;)if(i.call(e,n))return t.value=e[n],t.done=!1,t;return t.value=void 0,t.done=!0,t};return s.next=s}}return{next:E}}function E(){return{value:void 0,done:!0}}return f.prototype=p,n(v,"constructor",{value:p,configurable:!0}),n(p,"constructor",{value:f,configurable:!0}),f.displayName=h(p,o,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===f||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,h(e,o,"GeneratorFunction")),e.prototype=Object.create(v),e},e.awrap=function(e){return{__await:e}},y(x.prototype),h(x.prototype,a,(function(){return this})),e.AsyncIterator=x,e.async=function(t,i,n,s,r){void 0===r&&(r=Promise);var a=new x(l(t,i,n,s),r);return e.isGeneratorFunction(i)?a:a.next().then((function(e){return e.done?e.value:a.next()}))},y(v),h(v,o,"Generator"),h(v,r,(function(){return this})),h(v,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=Object(e),i=[];for(var n in t)i.push(n);return i.reverse(),function e(){for(;i.length;){var n=i.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},e.values=C,A.prototype={constructor:A,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(T),!e)for(var t in this)"t"===t.charAt(0)&&i.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function n(i,n){return a.type="throw",a.arg=e,t.next=i,n&&(t.method="next",t.arg=void 0),!!n}for(var s=this.tryEntries.length-1;s>=0;--s){var r=this.tryEntries[s],a=r.completion;if("root"===r.tryLoc)return n("end");if(r.tryLoc<=this.prev){var o=i.call(r,"catchLoc"),h=i.call(r,"finallyLoc");if(o&&h){if(this.prev<r.catchLoc)return n(r.catchLoc,!0);if(this.prev<r.finallyLoc)return n(r.finallyLoc)}else if(o){if(this.prev<r.catchLoc)return n(r.catchLoc,!0)}else{if(!h)throw new Error("try statement without catch or finally");if(this.prev<r.finallyLoc)return n(r.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var s=this.tryEntries[n];if(s.tryLoc<=this.prev&&i.call(s,"finallyLoc")&&this.prev<s.finallyLoc){var r=s;break}}r&&("break"===e||"continue"===e)&&r.tryLoc<=t&&t<=r.finallyLoc&&(r=null);var a=r?r.completion:{};return a.type=e,a.arg=t,r?(this.method="next",this.next=r.finallyLoc,u):this.complete(a)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),u},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),T(i),u}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var n=i.completion;if("throw"===n.type){var s=n.arg;T(i)}return s}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,i){return this.delegate={iterator:C(e),resultName:t,nextLoc:i},"next"===this.method&&(this.arg=void 0),u}},e}function q(e,t,i,n,s,r,a){try{var o=e[r](a),h=o.value}catch(e){return void i(e)}o.done?t(h):Promise.resolve(h).then(n,s)}function Y(e){return function(){var t=this,i=arguments;return new Promise((function(n,s){var r=e.apply(t,i);function a(e){q(r,n,s,a,o,"next",e)}function o(e){q(r,n,s,a,o,"throw",e)}a(void 0)}))}}function K(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,ne(n.key),n)}}function Z(e,t,i){return t&&K(e.prototype,t),i&&K(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}function $(){return $=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n])}return e},$.apply(this,arguments)}function Q(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,J(e,t)}function J(e,t){return J=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},J(e,t)}function ee(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function te(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i<t;i++)n[i]=e[i];return n}function ie(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(i)return(i=i.call(e)).next.bind(i);if(Array.isArray(e)||(i=function(e,t){if(e){if("string"==typeof e)return te(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?te(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function ne(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}var se=function(){function e(e){this.arraybuffer=e,this.dataView=new DataView(e),this.offset=0,this.stack=[]}var t=e.prototype;return t.reset=function(e){void 0===e&&(e=0),this.offset=e},t.skip=function(e){this.offset+=e},t.align=function(e){this.offset=this.offset+e-1&~(e-1)},t._inc=function(e){return this.offset+=e,this.offset-e},t.readChar=function(){return String.fromCharCode(this.dataView.getUint8(this.offset++))},t.readChars=function(e){for(var t="",i=0;i<e;++i)t+=this.readChar();return t},t.readU8=function(){return this.dataView.getUint8(this.offset++)},t.readU16=function(){return this.dataView.getUint16(this._inc(2),!0)},t.readU32=function(){return this.dataView.getUint32(this._inc(4),!0)},t.readU64=function(){return this.readU32()+Math.pow(2,32)*this.readU32()},t.readU32be=function(){return this.dataView.getUint32(this._inc(4),!1)},t.readArray=function(e){for(var t=0;t<e.length;++t)e[t]=this.readU8()},t.readLine=function(){for(var e=this.dataView,t="";!(this.offset>=e.byteLength);){var i=String.fromCharCode(this.readU8());if("\n"===i)break;t+=i}return t},Z(e,[{key:"remainingBytes",get:function(){return this.dataView.byteLength-this.offset}}]),e}(),re=function(){function e(e){this.items=[],this.length=0,this.loopIndex=-1,this._sortBy=void 0,this._sortHandler=void 0,this._sortBy=e.sortBy,this._sortHandler=this._doSort.bind(this)}var t=e.prototype;return t._binarySearch=function(e){for(var t,i,n=0,s=this.items.length-1,r=e[this._sortBy];n<=s;)t=Math.floor((n+s)/2),(i=this.items[t][this._sortBy])<=r?n=t+1:i>r&&(s=t-1);return n},t._doSort=function(e,t){var i=this._sortBy;return e[i]-t[i]},t.insert=function(e){var t=this._binarySearch(e);this.items.splice(t,0,e),this.length++,this.loopIndex>=t&&this.loopIndex++},t.append=function(e){this.items.push(e),this.length++},t.remove=function(e){var t=this.items.indexOf(e);t<0||(this.items.splice(t,1),this.length--,this.loopIndex>=t&&this.loopIndex--)},t.sort=function(){var e=this.loopIndex>=0?this.items[this.loopIndex]:null;this.items.sort(this._sortHandler),null!==e&&(this.loopIndex=this.items.indexOf(e))},e}(),ae=function(e){function t(t){var i;return(i=e.call(this)||this)._index={},i._list=[],i._parent=t,i}Q(t,e);var i=t.prototype;return i.add=function(){var e=!1,t=this._processArguments(arguments,!0);if(!t.length)return e;for(var i=0;i<t.length;i++)this._index[t[i]]||(e=!0,this._index[t[i]]=!0,this._list.push(t[i]),this.fire("add",t[i],this._parent));return e&&this.fire("change",this._parent),e},i.remove=function(){var e=!1;if(!this._list.length)return e;var t=this._processArguments(arguments,!0);if(!t.length)return e;for(var i=0;i<t.length;i++)this._index[t[i]]&&(e=!0,delete this._index[t[i]],this._list.splice(this._list.indexOf(t[i]),1),this.fire("remove",t[i],this._parent));return e&&this.fire("change",this._parent),e},i.clear=function(){if(this._list.length){var e=this._list.slice(0);this._list=[],this._index={};for(var t=0;t<e.length;t++)this.fire("remove",e[t],this._parent);this.fire("change",this._parent)}},i.has=function(){return!!this._list.length&&this._has(this._processArguments(arguments))},i._has=function(e){if(!this._list.length||!e.length)return!1;for(var t=0;t<e.length;t++)if(1===e[t].length){if(this._index[e[t][0]])return!0}else{for(var i=!0,n=0;n<e[t].length;n++)if(!this._index[e[t][n]]){i=!1;break}if(i)return!0}return!1},i.list=function(){return this._list.slice(0)},i._processArguments=function(e,t){var i=[],n=[];if(!e||!e.length)return i;for(var s=0;s<e.length;s++)if(e[s]instanceof Array){t||(n=[]);for(var r=0;r<e[s].length;r++)"string"==typeof e[s][r]&&(t?i.push(e[s][r]):n.push(e[s][r]));!t&&n.length&&i.push(n)}else"string"==typeof e[s]&&(t?i.push(e[s]):i.push([e[s]]));return i},Z(t,[{key:"size",get:function(){return this._list.length}}]),t}(p),oe="undefined"!=typeof window&&window.performance&&window.performance.now&&window.performance.timing?performance.now.bind(performance):Date.now;var he=/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,le=function(){function e(e){this.scheme=void 0,this.authority=void 0,this.path=void 0,this.query=void 0,this.fragment=void 0;var t=e.match(he);this.scheme=t[2],this.authority=t[4],this.path=t[5],this.query=t[7],this.fragment=t[9]}var t=e.prototype;return t.toString=function(){var e="";return this.scheme&&(e+=this.scheme+":"),this.authority&&(e+="//"+this.authority),e+=this.path,this.query&&(e+="?"+this.query),this.fragment&&(e+="#"+this.fragment),e},t.getQuery=function(){var e={};if(this.query)for(var t,i=ie(decodeURIComponent(this.query).split("&"));!(t=i()).done;){var n=t.value.split("=");e[n[0]]=n[1]}return e},t.setQuery=function(e){var t="";for(var i in e)e.hasOwnProperty(i)&&(""!==t&&(t+="&"),t+=encodeURIComponent(i)+"="+encodeURIComponent(e[i]));this.query=t},e}(),ce={DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,clamp:function(e,t,i){return e>=i?i:e<=t?t:e},intToBytes24:function(e){return[e>>16&255,e>>8&255,255&e]},intToBytes32:function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]},bytesToInt24:function(e,t,i){return e.length&&(i=e[2],t=e[1],e=e[0]),e<<16|t<<8|i},bytesToInt32:function(e,t,i,n){return e.length&&(n=e[3],i=e[2],t=e[1],e=e[0]),(e<<24|t<<16|i<<8|n)>>>0},lerp:function(e,t,i){return e+(t-e)*ce.clamp(i,0,1)},lerpAngle:function(e,t,i){return t-e>180&&(t-=360),t-e<-180&&(t+=360),ce.lerp(e,t,ce.clamp(i,0,1))},powerOfTwo:function(e){return 0!==e&&!(e&e-1)},nextPowerOfTwo:function(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e},nearestPowerOfTwo:function(e){return Math.pow(2,Math.round(Math.log(e)/Math.log(2)))},random:function(e,t){var i=t-e;return Math.random()*i+e},smoothstep:function(e,t,i){return i<=e?0:i>=t?1:(i=(i-e)/(t-e))*i*(3-2*i)},smootherstep:function(e,t,i){return i<=e?0:i>=t?1:(i=(i-e)/(t-e))*i*i*(i*(6*i-15)+10)},roundUp:function(e,t){return 0===t?e:Math.ceil(e/t)*t},between:function(e,t,i,n){var s=Math.min(t,i),r=Math.max(t,i);return n?e>=s&&e<=r:e>s&&e<r}},ue=function(){function e(e,t,i,n){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=1),this.r=void 0,this.g=void 0,this.b=void 0,this.a=void 0;var s=e.length;3===s||4===s?(this.r=e[0],this.g=e[1],this.b=e[2],this.a=void 0!==e[3]?e[3]:1):(this.r=e,this.g=t,this.b=i,this.a=n)}var t=e.prototype;return t.clone=function(){return new(0,this.constructor)(this.r,this.g,this.b,this.a)},t.copy=function(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this},t.equals=function(e){return this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a},t.set=function(e,t,i,n){return void 0===n&&(n=1),this.r=e,this.g=t,this.b=i,this.a=n,this},t.lerp=function(e,t,i){return this.r=e.r+i*(t.r-e.r),this.g=e.g+i*(t.g-e.g),this.b=e.b+i*(t.b-e.b),this.a=e.a+i*(t.a-e.a),this},t.fromString=function(e){var t,i=parseInt(e.replace("#","0x"),16);return e.length>7?t=ce.intToBytes32(i):(t=ce.intToBytes24(i))[3]=255,this.set(t[0]/255,t[1]/255,t[2]/255,t[3]/255),this},t.toString=function(e){var t="#"+((1<<24)+(Math.round(255*this.r)<<16)+(Math.round(255*this.g)<<8)+Math.round(255*this.b)).toString(16).slice(1);if(!0===e){var i=Math.round(255*this.a).toString(16);this.a<16/255?t+="0"+i:t+=i}return t},e}();ue.BLACK=Object.freeze(new ue(0,0,0,1)),ue.BLUE=Object.freeze(new ue(0,0,1,1)),ue.CYAN=Object.freeze(new ue(0,1,1,1)),ue.GRAY=Object.freeze(new ue(.5,.5,.5,1)),ue.GREEN=Object.freeze(new ue(0,1,0,1)),ue.MAGENTA=Object.freeze(new ue(1,0,1,1)),ue.RED=Object.freeze(new ue(1,0,0,1)),ue.WHITE=Object.freeze(new ue(1,1,1,1)),ue.YELLOW=Object.freeze(new ue(1,1,0,1));var de=function(){function e(e,t){void 0===t&&(t=0),this._curve=void 0,this._left=-1/0,this._right=1/0,this._recip=0,this._p0=0,this._p1=0,this._m0=0,this._m1=0,this._curve=e,this._reset(t)}var t=e.prototype;return t.evaluate=function(e,t){var i;void 0===t&&(t=!1),(t||e<this._left||e>=this._right)&&this._reset(e);var n=this._curve.type;if(5===n)i=this._p0;else{var s=0===this._recip?0:(e-this._left)*this._recip;i=0===n?ce.lerp(this._p0,this._p1,s):1===n?ce.lerp(this._p0,this._p1,s*s*(3-2*s)):this._evaluateHermite(this._p0,this._p1,this._m0,this._m1,s)}return i},t._reset=function(e){var t=this._curve.keys,i=t.length;if(i)if(e<t[0][0])this._left=-1/0,this._right=t[0][0],this._recip=0,this._p0=this._p1=t[0][1],this._m0=this._m1=0;else if(e>=t[i-1][0])this._left=t[i-1][0],this._right=1/0,this._recip=0,this._p0=this._p1=t[i-1][1],this._m0=this._m1=0;else{for(var n=0;e>=t[n+1][0];)n++;this._left=t[n][0],this._right=t[n+1][0];var s=1/(this._right-this._left);this._recip=isFinite(s)?s:0,this._p0=t[n][1],this._p1=t[n+1][1],this._isHermite()&&this._calcTangents(t,n)}else this._left=-1/0,this._right=1/0,this._recip=0,this._p0=this._p1=this._m0=this._m1=0},t._isHermite=function(){return 2===this._curve.type||3===this._curve.type||4===this._curve.type},t._calcTangents=function(e,t){var i,n,s=e[t],r=e[t+1];if(i=0===t?[e[0][0]+(e[0][0]-e[1][0]),e[0][1]+(e[0][1]-e[1][1])]:e[t-1],n=t===e.length-2?[e[t+1][0]+(e[t+1][0]-e[t][0]),e[t+1][1]+(e[t+1][1]-e[t][1])]:e[t+2],4===this._curve.type){var a=2*(r[0]-s[0])/(r[0]-i[0]),o=2*(r[0]-s[0])/(n[0]-s[0]);this._m0=this._curve.tension*(isFinite(a)?a:0)*(r[1]-i[1]),this._m1=this._curve.tension*(isFinite(o)?o:0)*(n[1]-s[1])}else{var h=(r[0]-s[0])/(s[0]-i[0]),l=(r[0]-s[0])/(n[0]-r[0]),c=s[1]+(i[1]-s[1])*(isFinite(h)?h:0),u=r[1]+(n[1]-r[1])*(isFinite(l)?l:0),d=2===this._curve.type?.5:this._curve.tension;this._m0=d*(r[1]-c),this._m1=d*(u-s[1])}},t._evaluateHermite=function(e,t,i,n,s){var r=s*s,a=s+s,o=1-s,h=o*o;return e*((1+a)*h)+i*(s*h)+t*(r*(3-a))+n*(r*(s-1))},e}(),fe=function(){function e(e){if(this.keys=[],this.type=1,this.tension=.5,this._eval=new de(this),e)for(var t=0;t<e.length-1;t+=2)this.keys.push([e[t],e[t+1]]);this.sort()}var t=e.prototype;return t.add=function(e,t){for(var i=this.keys,n=i.length,s=0;s<n&&!(i[s][0]>e);s++);var r=[e,t];return this.keys.splice(s,0,r),r},t.get=function(e){return this.keys[e]},t.sort=function(){this.keys.sort((function(e,t){return e[0]-t[0]}))},t.value=function(e){return this._eval.evaluate(e,!0)},t.closest=function(e){for(var t=this.keys,i=t.length,n=2,s=null,r=0;r<i;r++){var a=Math.abs(e-t[r][0]);if(!(n>=a))break;n=a,s=t[r]}return s},t.clone=function(){var e=new this.constructor;return e.keys=f(e.keys,this.keys),e.type=this.type,e.tension=this.tension,e},t.quantize=function(e){e=Math.max(e,2);var t=new Float32Array(e),i=1/(e-1);t[0]=this._eval.evaluate(0,!0);for(var n=1;n<e;n++)t[n]=this._eval.evaluate(i*n);return t},t.quantizeClamped=function(e,t,i){for(var n=this.quantize(e),s=0;s<n.length;++s)n[s]=Math.min(i,Math.max(t,n[s]));return n},Z(e,[{key:"length",get:function(){return this.keys.length}}]),e}(),pe=function(){function e(){if(this.curves=[],this._type=1,arguments.length>1)for(var e=0;e<arguments.length;e++)this.curves.push(new fe(arguments[e]));else if(0===arguments.length)this.curves.push(new fe);else{var t=arguments[0];if("number"==typeof t)for(var i=0;i<t;i++)this.curves.push(new fe);else for(var n=0;n<t.length;n++)this.curves.push(new fe(t[n]))}}var t=e.prototype;return t.get=function(e){return this.curves[e]},t.value=function(e,t){void 0===t&&(t=[]);var i=this.curves.length;t.length=i;for(var n=0;n<i;n++)t[n]=this.curves[n].value(e);return t},t.clone=function(){var e=new this.constructor;e.curves=[];for(var t=0;t<this.curves.length;t++)e.curves.push(this.curves[t].clone());return e._type=this._type,e},t.quantize=function(e){e=Math.max(e,2);for(var t=this.curves.length,i=new Float32Array(e*t),n=1/(e-1),s=0;s<t;s++)for(var r=new de(this.curves[s]),a=0;a<e;a++)i[a*t+s]=r.evaluate(n*a);return i},t.quantizeClamped=function(e,t,i){for(var n=this.quantize(e),s=0;s<n.length;++s)n[s]=Math.min(i,Math.max(t,n[s]));return n},Z(e,[{key:"length",get:function(){return this.curves.length}},{key:"type",get:function(){return this._type},set:function(e){this._type=e;for(var t=0;t<this.curves.length;t++)this.curves[t].type=e}}]),e}(),me=function(){function e(e,t,i){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),this.x=void 0,this.y=void 0,this.z=void 0,3===e.length?(this.x=e[0],this.y=e[1],this.z=e[2]):(this.x=e,this.y=t,this.z=i)}var t=e.prototype;return t.add=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this},t.add2=function(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this},t.addScalar=function(e){return this.x+=e,this.y+=e,this.z+=e,this},t.clone=function(){return new(0,this.constructor)(this.x,this.y,this.z)},t.copy=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this},t.cross=function(e,t){var i=e.x,n=e.y,s=e.z,r=t.x,a=t.y,o=t.z;return this.x=n*o-a*s,this.y=s*r-o*i,this.z=i*a-r*n,this},t.distance=function(e){var t=this.x-e.x,i=this.y-e.y,n=this.z-e.z;return Math.sqrt(t*t+i*i+n*n)},t.div=function(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this},t.div2=function(e,t){return this.x=e.x/t.x,this.y=e.y/t.y,this.z=e.z/t.z,this},t.divScalar=function(e){return this.x/=e,this.y/=e,this.z/=e,this},t.dot=function(e){return this.x*e.x+this.y*e.y+this.z*e.z},t.equals=function(e){return this.x===e.x&&this.y===e.y&&this.z===e.z},t.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},t.lengthSq=function(){return this.x*this.x+this.y*this.y+this.z*this.z},t.lerp=function(e,t,i){return this.x=e.x+i*(t.x-e.x),this.y=e.y+i*(t.y-e.y),this.z=e.z+i*(t.z-e.z),this},t.mul=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this},t.mul2=function(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this},t.mulScalar=function(e){return this.x*=e,this.y*=e,this.z*=e,this},t.normalize=function(){var e=this.x*this.x+this.y*this.y+this.z*this.z;if(e>0){var t=1/Math.sqrt(e);this.x*=t,this.y*=t,this.z*=t}return this},t.floor=function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this},t.ceil=function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this},t.round=function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this},t.min=function(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),this},t.max=function(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),this},t.project=function(e){var t=(this.x*e.x+this.y*e.y+this.z*e.z)/(e.x*e.x+e.y*e.y+e.z*e.z);return this.x=e.x*t,this.y=e.y*t,this.z=e.z*t,this},t.set=function(e,t,i){return this.x=e,this.y=t,this.z=i,this},t.sub=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this},t.sub2=function(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this},t.subScalar=function(e){return this.x-=e,this.y-=e,this.z-=e,this},t.toString=function(){return"["+this.x+", "+this.y+", "+this.z+"]"},e}();me.ZERO=Object.freeze(new me(0,0,0)),me.ONE=Object.freeze(new me(1,1,1)),me.UP=Object.freeze(new me(0,1,0)),me.DOWN=Object.freeze(new me(0,-1,0)),me.RIGHT=Object.freeze(new me(1,0,0)),me.LEFT=Object.freeze(new me(-1,0,0)),me.FORWARD=Object.freeze(new me(0,0,-1)),me.BACK=Object.freeze(new me(0,0,1));var _e=function(){function e(){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(0,this.constructor)).copy(this)},t.copy=function(e){var t=e.data,i=this.data;return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[3],i[4]=t[4],i[5]=t[5],i[6]=t[6],i[7]=t[7],i[8]=t[8],this},t.set=function(e){var t=this.data;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],this},t.equals=function(e){var t=this.data,i=e.data;return t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]&&t[4]===i[4]&&t[5]===i[5]&&t[6]===i[6]&&t[7]===i[7]&&t[8]===i[8]},t.isIdentity=function(){var e=this.data;return 1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&1===e[4]&&0===e[5]&&0===e[6]&&0===e[7]&&1===e[8]},t.setIdentity=function(){var e=this.data;return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,this},t.toString=function(){return"["+this.data.join(", ")+"]"},t.transpose=function(){var e,t=this.data;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this},t.setFromMat4=function(e){var t=e.data,i=this.data;return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[4],i[4]=t[5],i[5]=t[6],i[6]=t[8],i[7]=t[9],i[8]=t[10],this},t.transformVector=function(e,t){void 0===t&&(t=new me);var i=this.data,n=e.x,s=e.y,r=e.z;return t.x=n*i[0]+s*i[3]+r*i[6],t.y=n*i[1]+s*i[4]+r*i[7],t.z=n*i[2]+s*i[5]+r*i[8],t},e}();_e.IDENTITY=Object.freeze(new _e),_e.ZERO=Object.freeze((new _e).set([0,0,0,0,0,0,0,0,0]));var ge=function(){function e(e,t){void 0===e&&(e=0),void 0===t&&(t=0),this.x=void 0,this.y=void 0,2===e.length?(this.x=e[0],this.y=e[1]):(this.x=e,this.y=t)}var t=e.prototype;return t.add=function(e){return this.x+=e.x,this.y+=e.y,this},t.add2=function(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this},t.addScalar=function(e){return this.x+=e,this.y+=e,this},t.clone=function(){return new(0,this.constructor)(this.x,this.y)},t.copy=function(e){return this.x=e.x,this.y=e.y,this},t.cross=function(e){return this.x*e.y-this.y*e.x},t.distance=function(e){var t=this.x-e.x,i=this.y-e.y;return Math.sqrt(t*t+i*i)},t.div=function(e){return this.x/=e.x,this.y/=e.y,this},t.div2=function(e,t){return this.x=e.x/t.x,this.y=e.y/t.y,this},t.divScalar=function(e){return this.x/=e,this.y/=e,this},t.dot=function(e){return this.x*e.x+this.y*e.y},t.equals=function(e){return this.x===e.x&&this.y===e.y},t.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},t.lengthSq=function(){return this.x*this.x+this.y*this.y},t.lerp=function(e,t,i){return this.x=e.x+i*(t.x-e.x),this.y=e.y+i*(t.y-e.y),this},t.mul=function(e){return this.x*=e.x,this.y*=e.y,this},t.mul2=function(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this},t.mulScalar=function(e){return this.x*=e,this.y*=e,this},t.normalize=function(){var e=this.x*this.x+this.y*this.y;if(e>0){var t=1/Math.sqrt(e);this.x*=t,this.y*=t}return this},t.floor=function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},t.ceil=function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},t.round=function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},t.min=function(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),this},t.max=function(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),this},t.set=function(e,t){return this.x=e,this.y=t,this},t.sub=function(e){return this.x-=e.x,this.y-=e.y,this},t.sub2=function(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this},t.subScalar=function(e){return this.x-=e,this.y-=e,this},t.toString=function(){return"["+this.x+", "+this.y+"]"},e.angleRad=function(e,t){return Math.atan2(e.x*t.y-e.y*t.x,e.x*t.x+e.y*t.y)},e}();ge.ZERO=Object.freeze(new ge(0,0)),ge.ONE=Object.freeze(new ge(1,1)),ge.UP=Object.freeze(new ge(0,1)),ge.DOWN=Object.freeze(new ge(0,-1)),ge.RIGHT=Object.freeze(new ge(1,0)),ge.LEFT=Object.freeze(new ge(-1,0));var ve=function(){function e(e,t,i,n){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.x=void 0,this.y=void 0,this.z=void 0,this.w=void 0,4===e.length?(this.x=e[0],this.y=e[1],this.z=e[2],this.w=e[3]):(this.x=e,this.y=t,this.z=i,this.w=n)}var t=e.prototype;return t.add=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this},t.add2=function(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this},t.addScalar=function(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this},t.clone=function(){return new(0,this.constructor)(this.x,this.y,this.z,this.w)},t.copy=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},t.div=function(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this},t.div2=function(e,t){return this.x=e.x/t.x,this.y=e.y/t.y,this.z=e.z/t.z,this.w=e.w/t.w,this},t.divScalar=function(e){return this.x/=e,this.y/=e,this.z/=e,this.w/=e,this},t.dot=function(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w},t.equals=function(e){return this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},t.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.lengthSq=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},t.lerp=function(e,t,i){return this.x=e.x+i*(t.x-e.x),this.y=e.y+i*(t.y-e.y),this.z=e.z+i*(t.z-e.z),this.w=e.w+i*(t.w-e.w),this},t.mul=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this},t.mul2=function(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this.w=e.w*t.w,this},t.mulScalar=function(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},t.normalize=function(){var e=this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w;if(e>0){var t=1/Math.sqrt(e);this.x*=t,this.y*=t,this.z*=t,this.w*=t}return this},t.floor=function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this},t.ceil=function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this},t.round=function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this},t.min=function(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),e.w<this.w&&(this.w=e.w),this},t.max=function(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this},t.set=function(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this},t.sub=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this},t.sub2=function(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this},t.subScalar=function(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this},t.toString=function(){return"["+this.x+", "+this.y+", "+this.z+", "+this.w+"]"},e}();ve.ZERO=Object.freeze(new ve(0,0,0,0)),ve.ONE=Object.freeze(new ve(1,1,1,1));var ye=new ge,xe=new me,Se=new me,be=new me,we=new me,Te=function(){function e(){this.data=new Float32Array(16),this.data[0]=this.data[5]=this.data[10]=this.data[15]=1}e._getPerspectiveHalfSize=function(e,t,i,n,s){s?(e.x=n*Math.tan(t*Math.PI/360),e.y=e.x/i):(e.y=n*Math.tan(t*Math.PI/360),e.x=e.y*i)};var t=e.prototype;return t.add2=function(e,t){var i=e.data,n=t.data,s=this.data;return s[0]=i[0]+n[0],s[1]=i[1]+n[1],s[2]=i[2]+n[2],s[3]=i[3]+n[3],s[4]=i[4]+n[4],s[5]=i[5]+n[5],s[6]=i[6]+n[6],s[7]=i[7]+n[7],s[8]=i[8]+n[8],s[9]=i[9]+n[9],s[10]=i[10]+n[10],s[11]=i[11]+n[11],s[12]=i[12]+n[12],s[13]=i[13]+n[13],s[14]=i[14]+n[14],s[15]=i[15]+n[15],this},t.add=function(e){return this.add2(this,e)},t.clone=function(){return(new(0,this.constructor)).copy(this)},t.copy=function(e){var t=e.data,i=this.data;return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[3],i[4]=t[4],i[5]=t[5],i[6]=t[6],i[7]=t[7],i[8]=t[8],i[9]=t[9],i[10]=t[10],i[11]=t[11],i[12]=t[12],i[13]=t[13],i[14]=t[14],i[15]=t[15],this},t.equals=function(e){var t=this.data,i=e.data;return t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]&&t[4]===i[4]&&t[5]===i[5]&&t[6]===i[6]&&t[7]===i[7]&&t[8]===i[8]&&t[9]===i[9]&&t[10]===i[10]&&t[11]===i[11]&&t[12]===i[12]&&t[13]===i[13]&&t[14]===i[14]&&t[15]===i[15]},t.isIdentity=function(){var e=this.data;return 1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]},t.mul2=function(e,t){var i,n,s,r,a=e.data,o=t.data,h=this.data,l=a[0],c=a[1],u=a[2],d=a[3],f=a[4],p=a[5],m=a[6],_=a[7],g=a[8],v=a[9],y=a[10],x=a[11],S=a[12],b=a[13],w=a[14],T=a[15];return i=o[0],n=o[1],s=o[2],r=o[3],h[0]=l*i+f*n+g*s+S*r,h[1]=c*i+p*n+v*s+b*r,h[2]=u*i+m*n+y*s+w*r,h[3]=d*i+_*n+x*s+T*r,i=o[4],n=o[5],s=o[6],r=o[7],h[4]=l*i+f*n+g*s+S*r,h[5]=c*i+p*n+v*s+b*r,h[6]=u*i+m*n+y*s+w*r,h[7]=d*i+_*n+x*s+T*r,i=o[8],n=o[9],s=o[10],r=o[11],h[8]=l*i+f*n+g*s+S*r,h[9]=c*i+p*n+v*s+b*r,h[10]=u*i+m*n+y*s+w*r,h[11]=d*i+_*n+x*s+T*r,i=o[12],n=o[13],s=o[14],r=o[15],h[12]=l*i+f*n+g*s+S*r,h[13]=c*i+p*n+v*s+b*r,h[14]=u*i+m*n+y*s+w*r,h[15]=d*i+_*n+x*s+T*r,this},t.mulAffine2=function(e,t){var i,n,s,r=e.data,a=t.data,o=this.data,h=r[0],l=r[1],c=r[2],u=r[4],d=r[5],f=r[6],p=r[8],m=r[9],_=r[10],g=r[12],v=r[13],y=r[14];return i=a[0],n=a[1],s=a[2],o[0]=h*i+u*n+p*s,o[1]=l*i+d*n+m*s,o[2]=c*i+f*n+_*s,o[3]=0,i=a[4],n=a[5],s=a[6],o[4]=h*i+u*n+p*s,o[5]=l*i+d*n+m*s,o[6]=c*i+f*n+_*s,o[7]=0,i=a[8],n=a[9],s=a[10],o[8]=h*i+u*n+p*s,o[9]=l*i+d*n+m*s,o[10]=c*i+f*n+_*s,o[11]=0,i=a[12],n=a[13],s=a[14],o[12]=h*i+u*n+p*s+g,o[13]=l*i+d*n+m*s+v,o[14]=c*i+f*n+_*s+y,o[15]=1,this},t.mul=function(e){return this.mul2(this,e)},t.transformPoint=function(e,t){void 0===t&&(t=new me);var i=this.data,n=e.x,s=e.y,r=e.z;return t.x=n*i[0]+s*i[4]+r*i[8]+i[12],t.y=n*i[1]+s*i[5]+r*i[9]+i[13],t.z=n*i[2]+s*i[6]+r*i[10]+i[14],t},t.transformVector=function(e,t){void 0===t&&(t=new me);var i=this.data,n=e.x,s=e.y,r=e.z;return t.x=n*i[0]+s*i[4]+r*i[8],t.y=n*i[1]+s*i[5]+r*i[9],t.z=n*i[2]+s*i[6]+r*i[10],t},t.transformVec4=function(e,t){void 0===t&&(t=new ve);var i=this.data,n=e.x,s=e.y,r=e.z,a=e.w;return t.x=n*i[0]+s*i[4]+r*i[8]+a*i[12],t.y=n*i[1]+s*i[5]+r*i[9]+a*i[13],t.z=n*i[2]+s*i[6]+r*i[10]+a*i[14],t.w=n*i[3]+s*i[7]+r*i[11]+a*i[15],t},t.setLookAt=function(e,t,i){be.sub2(e,t).normalize(),Se.copy(i).normalize(),xe.cross(Se,be).normalize(),Se.cross(be,xe);var n=this.data;return n[0]=xe.x,n[1]=xe.y,n[2]=xe.z,n[3]=0,n[4]=Se.x,n[5]=Se.y,n[6]=Se.z,n[7]=0,n[8]=be.x,n[9]=be.y,n[10]=be.z,n[11]=0,n[12]=e.x,n[13]=e.y,n[14]=e.z,n[15]=1,this},t.setFrustum=function(e,t,i,n,s,r){var a=2*s,o=t-e,h=n-i,l=r-s,c=this.data;return c[0]=a/o,c[1]=0,c[2]=0,c[3]=0,c[4]=0,c[5]=a/h,c[6]=0,c[7]=0,c[8]=(t+e)/o,c[9]=(n+i)/h,c[10]=(-r-s)/l,c[11]=-1,c[12]=0,c[13]=0,c[14]=-a*r/l,c[15]=0,this},t.setPerspective=function(t,i,n,s,r){return e._getPerspectiveHalfSize(ye,t,i,n,r),this.setFrustum(-ye.x,ye.x,-ye.y,ye.y,n,s)},t.setOrtho=function(e,t,i,n,s,r){var a=this.data;return a[0]=2/(t-e),a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=2/(n-i),a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=-2/(r-s),a[11]=0,a[12]=-(t+e)/(t-e),a[13]=-(n+i)/(n-i),a[14]=-(r+s)/(r-s),a[15]=1,this},t.setFromAxisAngle=function(e,t){t*=ce.DEG_TO_RAD;var i=e.x,n=e.y,s=e.z,r=Math.cos(t),a=Math.sin(t),o=1-r,h=o*i,l=o*n,c=this.data;return c[0]=h*i+r,c[1]=h*n+a*s,c[2]=h*s-a*n,c[3]=0,c[4]=h*n-a*s,c[5]=l*n+r,c[6]=l*s+a*i,c[7]=0,c[8]=h*s+a*n,c[9]=l*s-i*a,c[10]=o*s*s+r,c[11]=0,c[12]=0,c[13]=0,c[14]=0,c[15]=1,this},t.setTranslate=function(e,t,i){var n=this.data;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=e,n[13]=t,n[14]=i,n[15]=1,this},t.setScale=function(e,t,i){var n=this.data;return n[0]=e,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=t,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=i,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,this},t.setViewport=function(e,t,i,n){var s=this.data;return s[0]=.5*i,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=.5*n,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=.5,s[11]=0,s[12]=e+.5*i,s[13]=t+.5*n,s[14]=.5,s[15]=1,this},t.setReflection=function(e,t){var i=e.x,n=e.y,s=e.z,r=this.data;return r[0]=1-2*i*i,r[1]=-2*i*n,r[2]=-2*i*s,r[3]=0,r[4]=-2*i*n,r[5]=1-2*n*n,r[6]=-2*n*s,r[7]=0,r[8]=-2*i*s,r[9]=-2*n*s,r[10]=1-2*s*s,r[11]=0,r[12]=-2*i*t,r[13]=-2*n*t,r[14]=-2*s*t,r[15]=1,this},t.invert=function(){var e=this.data,t=e[0],i=e[1],n=e[2],s=e[3],r=e[4],a=e[5],o=e[6],h=e[7],l=e[8],c=e[9],u=e[10],d=e[11],f=e[12],p=e[13],m=e[14],_=e[15],g=t*a-i*r,v=t*o-n*r,y=t*h-s*r,x=i*o-n*a,S=i*h-s*a,b=n*h-s*o,w=l*p-c*f,T=l*m-u*f,A=l*_-d*f,C=c*m-u*p,E=c*_-d*p,M=u*_-d*m,P=g*M-v*E+y*C+x*A-S*T+b*w;if(0===P)this.setIdentity();else{var R=1/P;e[0]=(a*M-o*E+h*C)*R,e[1]=(-i*M+n*E-s*C)*R,e[2]=(p*b-m*S+_*x)*R,e[3]=(-c*b+u*S-d*x)*R,e[4]=(-r*M+o*A-h*T)*R,e[5]=(t*M-n*A+s*T)*R,e[6]=(-f*b+m*y-_*v)*R,e[7]=(l*b-u*y+d*v)*R,e[8]=(r*E-a*A+h*w)*R,e[9]=(-t*E+i*A-s*w)*R,e[10]=(f*S-p*y+_*g)*R,e[11]=(-l*S+c*y-d*g)*R,e[12]=(-r*C+a*T-o*w)*R,e[13]=(t*C-i*T+n*w)*R,e[14]=(-f*x+p*v-m*g)*R,e[15]=(l*x-c*v+u*g)*R}return this},t.set=function(e){var t=this.data;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],this},t.setIdentity=function(){var e=this.data;return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this},t.setTRS=function(e,t,i){var n=t.x,s=t.y,r=t.z,a=t.w,o=i.x,h=i.y,l=i.z,c=n+n,u=s+s,d=r+r,f=n*c,p=n*u,m=n*d,_=s*u,g=s*d,v=r*d,y=a*c,x=a*u,S=a*d,b=this.data;return b[0]=(1-(_+v))*o,b[1]=(p+S)*o,b[2]=(m-x)*o,b[3]=0,b[4]=(p-S)*h,b[5]=(1-(f+v))*h,b[6]=(g+y)*h,b[7]=0,b[8]=(m+x)*l,b[9]=(g-y)*l,b[10]=(1-(f+_))*l,b[11]=0,b[12]=e.x,b[13]=e.y,b[14]=e.z,b[15]=1,this},t.transpose=function(){var e,t=this.data;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this},t.invertTo3x3=function(e){var t=this.data,i=e.data,n=t[0],s=t[1],r=t[2],a=t[4],o=t[5],h=t[6],l=t[8],c=t[9],u=t[10],d=u*o-h*c,f=-u*s+r*c,p=h*s-r*o,m=-u*a+h*l,_=u*n-r*l,g=-h*n+r*a,v=c*a-o*l,y=-c*n+s*l,x=o*n-s*a,S=n*d+s*m+r*v;if(0===S)return this;var b=1/S;return i[0]=b*d,i[1]=b*f,i[2]=b*p,i[3]=b*m,i[4]=b*_,i[5]=b*g,i[6]=b*v,i[7]=b*y,i[8]=b*x,this},t.getTranslation=function(e){return void 0===e&&(e=new me),e.set(this.data[12],this.data[13],this.data[14])},t.getX=function(e){return void 0===e&&(e=new me),e.set(this.data[0],this.data[1],this.data[2])},t.getY=function(e){return void 0===e&&(e=new me),e.set(this.data[4],this.data[5],this.data[6])},t.getZ=function(e){return void 0===e&&(e=new me),e.set(this.data[8],this.data[9],this.data[10])},t.getScale=function(e){return void 0===e&&(e=new me),this.getX(xe),this.getY(Se),this.getZ(be),e.set(xe.length(),Se.length(),be.length()),e},t.setFromEulerAngles=function(e,t,i){e*=ce.DEG_TO_RAD,t*=ce.DEG_TO_RAD,i*=ce.DEG_TO_RAD;var n=Math.sin(-e),s=Math.cos(-e),r=Math.sin(-t),a=Math.cos(-t),o=Math.sin(-i),h=Math.cos(-i),l=this.data;return l[0]=a*h,l[1]=-a*o,l[2]=r,l[3]=0,l[4]=s*o+h*n*r,l[5]=s*h-n*r*o,l[6]=-a*n,l[7]=0,l[8]=n*o-s*h*r,l[9]=h*n+s*r*o,l[10]=s*a,l[11]=0,l[12]=0,l[13]=0,l[14]=0,l[15]=1,this},t.getEulerAngles=function(e){void 0===e&&(e=new me),this.getScale(we);var t=we.x,i=we.y,n=we.z;if(0===t||0===i||0===n)return e.set(0,0,0);var s,r,a=this.data,o=Math.asin(-a[2]/t),h=.5*Math.PI;return o<h?o>-h?(s=Math.atan2(a[6]/i,a[10]/n),r=Math.atan2(a[1]/t,a[0]/t)):(r=0,s=-Math.atan2(a[4]/i,a[5]/i)):(r=0,s=Math.atan2(a[4]/i,a[5]/i)),e.set(s,o,r).mulScalar(ce.RAD_TO_DEG)},t.toString=function(){return"["+this.data.join(", ")+"]"},Z(e,[{key:"scaleSign",get:function(){return this.getX(xe),this.getY(Se),this.getZ(be),xe.cross(xe,Se),xe.dot(be)<0?-1:1}}]),e}();Te.IDENTITY=Object.freeze(new Te),Te.ZERO=Object.freeze((new Te).set([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]));var Ae=function(){function e(e,t,i,n){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=1),this.x=void 0,this.y=void 0,this.z=void 0,this.w=void 0,4===e.length?(this.x=e[0],this.y=e[1],this.z=e[2],this.w=e[3]):(this.x=e,this.y=t,this.z=i,this.w=n)}var t=e.prototype;return t.clone=function(){return new(0,this.constructor)(this.x,this.y,this.z,this.w)},t.conjugate=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.copy=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},t.equals=function(e){return this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},t.equalsApprox=function(e,t){return void 0===t&&(t=1e-6),Math.abs(this.x-e.x)<t&&Math.abs(this.y-e.y)<t&&Math.abs(this.z-e.z)<t&&Math.abs(this.w-e.w)<t},t.getAxisAngle=function(e){var t=2*Math.acos(this.w),i=Math.sin(t/2);return 0!==i?(e.x=this.x/i,e.y=this.y/i,e.z=this.z/i,(e.x<0||e.y<0||e.z<0)&&(e.x*=-1,e.y*=-1,e.z*=-1,t*=-1)):(e.x=1,e.y=0,e.z=0),t*ce.RAD_TO_DEG},t.getEulerAngles=function(e){var t,i,n;void 0===e&&(e=new me);var s=this.x,r=this.y,a=this.z,o=this.w,h=2*(o*r-s*a);return h<=-.99999?(t=2*Math.atan2(s,o),i=-Math.PI/2,n=0):h>=.99999?(t=2*Math.atan2(s,o),i=Math.PI/2,n=0):(t=Math.atan2(2*(o*s+r*a),1-2*(s*s+r*r)),i=Math.asin(h),n=Math.atan2(2*(o*a+s*r),1-2*(r*r+a*a))),e.set(t,i,n).mulScalar(ce.RAD_TO_DEG)},t.invert=function(){return this.conjugate().normalize()},t.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.lengthSq=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},t.mul=function(e){var t=this.x,i=this.y,n=this.z,s=this.w,r=e.x,a=e.y,o=e.z,h=e.w;return this.x=s*r+t*h+i*o-n*a,this.y=s*a+i*h+n*r-t*o,this.z=s*o+n*h+t*a-i*r,this.w=s*h-t*r-i*a-n*o,this},t.mul2=function(e,t){var i=e.x,n=e.y,s=e.z,r=e.w,a=t.x,o=t.y,h=t.z,l=t.w;return this.x=r*a+i*l+n*h-s*o,this.y=r*o+n*l+s*a-i*h,this.z=r*h+s*l+i*o-n*a,this.w=r*l-i*a-n*o-s*h,this},t.normalize=function(){var e=this.length();return 0===e?(this.x=this.y=this.z=0,this.w=1):(e=1/e,this.x*=e,this.y*=e,this.z*=e,this.w*=e),this},t.set=function(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this},t.setFromAxisAngle=function(e,t){t*=.5*ce.DEG_TO_RAD;var i=Math.sin(t),n=Math.cos(t);return this.x=i*e.x,this.y=i*e.y,this.z=i*e.z,this.w=n,this},t.setFromEulerAngles=function(e,t,i){if(e instanceof me){var n=e;e=n.x,t=n.y,i=n.z}var s=.5*ce.DEG_TO_RAD;e*=s,t*=s,i*=s;var r=Math.sin(e),a=Math.cos(e),o=Math.sin(t),h=Math.cos(t),l=Math.sin(i),c=Math.cos(i);return this.x=r*h*c-a*o*l,this.y=a*o*c+r*h*l,this.z=a*h*l-r*o*c,this.w=a*h*c+r*o*l,this},t.setFromMat4=function(e){var t,i,n,s,r,a,o,h,l,c,u,d,f,p;if(t=(e=e.data)[0],i=e[1],n=e[2],s=e[4],r=e[5],a=e[6],o=e[8],h=e[9],l=e[10],0===(d=t*t+i*i+n*n))return this;if(d=1/Math.sqrt(d),0===(f=s*s+r*r+a*a))return this;if(f=1/Math.sqrt(f),0===(p=o*o+h*h+l*l))return this;i*=d,n*=d,s*=f,a*=f,o*=p=1/Math.sqrt(p),h*=p;var m=(t*=d)+(r*=f)+(l*=p);return m>=0?(c=Math.sqrt(m+1),this.w=.5*c,c=.5/c,this.x=(a-h)*c,this.y=(o-n)*c,this.z=(i-s)*c):t>r?t>l?(u=t-(r+l)+1,u=Math.sqrt(u),this.x=.5*u,u=.5/u,this.w=(a-h)*u,this.y=(i+s)*u,this.z=(n+o)*u):(u=l-(t+r)+1,u=Math.sqrt(u),this.z=.5*u,u=.5/u,this.w=(i-s)*u,this.x=(o+n)*u,this.y=(h+a)*u):r>l?(u=r-(l+t)+1,u=Math.sqrt(u),this.y=.5*u,u=.5/u,this.w=(o-n)*u,this.z=(a+h)*u,this.x=(s+i)*u):(u=l-(t+r)+1,u=Math.sqrt(u),this.z=.5*u,u=.5/u,this.w=(i-s)*u,this.x=(o+n)*u,this.y=(h+a)*u),this},t.setFromDirections=function(e,t){var i=1+e.dot(t);return i<Number.EPSILON?Math.abs(e.x)>Math.abs(e.y)?(this.x=-e.z,this.y=0,this.z=e.x,this.w=0):(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=i),this.normalize()},t.slerp=function(e,t,i){var n=e.x,s=e.y,r=e.z,a=e.w,o=t.x,h=t.y,l=t.z,c=t.w,u=a*c+n*o+s*h+r*l;if(u<0&&(c=-c,o=-o,h=-h,l=-l,u=-u),Math.abs(u)>=1)return this.w=a,this.x=n,this.y=s,this.z=r,this;var d=Math.acos(u),f=Math.sqrt(1-u*u);if(Math.abs(f)<.001)return this.w=.5*a+.5*c,this.x=.5*n+.5*o,this.y=.5*s+.5*h,this.z=.5*r+.5*l,this;var p=Math.sin((1-i)*d)/f,m=Math.sin(i*d)/f;return this.w=a*p+c*m,this.x=n*p+o*m,this.y=s*p+h*m,this.z=r*p+l*m,this},t.transformVector=function(e,t){void 0===t&&(t=new me);var i=e.x,n=e.y,s=e.z,r=this.x,a=this.y,o=this.z,h=this.w,l=h*i+a*s-o*n,c=h*n+o*i-r*s,u=h*s+r*n-a*i,d=-r*i-a*n-o*s;return t.x=l*h+d*-r+c*-o-u*-a,t.y=c*h+d*-a+u*-r-l*-o,t.z=u*h+d*-o+l*-a-c*-r,t},t.toString=function(){return"["+this.x+", "+this.y+", "+this.z+", "+this.w+"]"},e}();Ae.IDENTITY=Object.freeze(new Ae(0,0,0,1)),Ae.ZERO=Object.freeze(new Ae(0,0,0,0));var Ce=new me,Ee=new me,Me=new me,Pe=new me,Re=new me,Ie=function(){function e(e,t){void 0===e&&(e=new me),void 0===t&&(t=new me(.5,.5,.5)),this.center=void 0,this.halfExtents=void 0,this._min=new me,this._max=new me,this.center=e,this.halfExtents=t}var t=e.prototype;return t.add=function(e){var t=this.center,i=t.x,n=t.y,s=t.z,r=this.halfExtents,a=r.x,o=r.y,h=r.z,l=i-a,c=i+a,u=n-o,d=n+o,f=s-h,p=s+h,m=e.center,_=m.x,g=m.y,v=m.z,y=e.halfExtents,x=y.x,S=y.y,b=y.z,w=_-x,T=_+x,A=g-S,C=g+S,E=v-b,M=v+b;w<l&&(l=w),T>c&&(c=T),A<u&&(u=A),C>d&&(d=C),E<f&&(f=E),M>p&&(p=M),t.x=.5*(l+c),t.y=.5*(u+d),t.z=.5*(f+p),r.x=.5*(c-l),r.y=.5*(d-u),r.z=.5*(p-f)},t.copy=function(e){this.center.copy(e.center),this.halfExtents.copy(e.halfExtents)},t.clone=function(){return new e(this.center.clone(),this.halfExtents.clone())},t.intersects=function(e){var t=this.getMax(),i=this.getMin(),n=e.getMax(),s=e.getMin();return i.x<=n.x&&t.x>=s.x&&i.y<=n.y&&t.y>=s.y&&i.z<=n.z&&t.z>=s.z},t._intersectsRay=function(e,t){var i=Ce.copy(this.getMin()).sub(e.origin),n=Ee.copy(this.getMax()).sub(e.origin),s=e.direction;0===s.x?(i.x=i.x<0?-Number.MAX_VALUE:Number.MAX_VALUE,n.x=n.x<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.x/=s.x,n.x/=s.x),0===s.y?(i.y=i.y<0?-Number.MAX_VALUE:Number.MAX_VALUE,n.y=n.y<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.y/=s.y,n.y/=s.y),0===s.z?(i.z=i.z<0?-Number.MAX_VALUE:Number.MAX_VALUE,n.z=n.z<0?-Number.MAX_VALUE:Number.MAX_VALUE):(i.z/=s.z,n.z/=s.z);var r=Me.set(Math.min(i.x,n.x),Math.min(i.y,n.y),Math.min(i.z,n.z)),a=Pe.set(Math.max(i.x,n.x),Math.max(i.y,n.y),Math.max(i.z,n.z)),o=Math.min(Math.min(a.x,a.y),a.z),h=Math.max(Math.max(r.x,r.y),r.z),l=o>=h&&h>=0;return l&&t.copy(e.direction).mulScalar(h).add(e.origin),l},t._fastIntersectsRay=function(e){var t=Ce,i=Ee,n=Me,s=Pe,r=Re,a=e.direction;return t.sub2(e.origin,this.center),s.set(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z)),n.mul2(t,a),!(s.x>this.halfExtents.x&&n.x>=0)&&(!(s.y>this.halfExtents.y&&n.y>=0)&&(!(s.z>this.halfExtents.z&&n.z>=0)&&(r.set(Math.abs(a.x),Math.abs(a.y),Math.abs(a.z)),i.cross(a,t),i.set(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z)),!(i.x>this.halfExtents.y*r.z+this.halfExtents.z*r.y)&&(!(i.y>this.halfExtents.x*r.z+this.halfExtents.z*r.x)&&!(i.z>this.halfExtents.x*r.y+this.halfExtents.y*r.x)))))},t.intersectsRay=function(e,t){return t?this._intersectsRay(e,t):this._fastIntersectsRay(e)},t.setMinMax=function(e,t){this.center.add2(t,e).mulScalar(.5),this.halfExtents.sub2(t,e).mulScalar(.5)},t.getMin=function(){return this._min.copy(this.center).sub(this.halfExtents)},t.getMax=function(){return this._max.copy(this.center).add(this.halfExtents)},t.containsPoint=function(e){var t=this.getMin(),i=this.getMax();return!(e.x<t.x||e.x>i.x||e.y<t.y||e.y>i.y||e.z<t.z||e.z>i.z)},t.setFromTransformedAabb=function(e,t,i){void 0===i&&(i=!1);var n=e.center,s=e.halfExtents,r=t.data,a=r[0],o=r[4],h=r[8],l=r[1],c=r[5],u=r[9],d=r[2],f=r[6],p=r[10];if(i){var m=a*a+o*o+h*h;if(m>0){var _=1/Math.sqrt(m);a*=_,o*=_,h*=_}if((m=l*l+c*c+u*u)>0){var g=1/Math.sqrt(m);l*=g,c*=g,u*=g}if((m=d*d+f*f+p*p)>0){var v=1/Math.sqrt(m);d*=v,f*=v,p*=v}}this.center.set(r[12]+a*n.x+o*n.y+h*n.z,r[13]+l*n.x+c*n.y+u*n.z,r[14]+d*n.x+f*n.y+p*n.z),this.halfExtents.set(Math.abs(a)*s.x+Math.abs(o)*s.y+Math.abs(h)*s.z,Math.abs(l)*s.x+Math.abs(c)*s.y+Math.abs(u)*s.z,Math.abs(d)*s.x+Math.abs(f)*s.y+Math.abs(p)*s.z)},e.computeMinMax=function(e,t,i,n){if(void 0===n&&(n=e.length/3),n>0){for(var s=e[0],r=e[1],a=e[2],o=s,h=r,l=a,c=3*n,u=3;u<c;u+=3){var d=e[u],f=e[u+1],p=e[u+2];d<s&&(s=d),f<r&&(r=f),p<a&&(a=p),d>o&&(o=d),f>h&&(h=f),p>l&&(l=p)}t.set(s,r,a),i.set(o,h,l)}},t.compute=function(t,i){e.computeMinMax(t,Ce,Ee,i),this.setMinMax(Ce,Ee)},t.intersectsBoundingSphere=function(e){return this._distanceToBoundingSphereSq(e)<=e.radius*e.radius},t._distanceToBoundingSphereSq=function(e){for(var t=this.getMin(),i=this.getMax(),n=0,s=["x","y","z"],r=0;r<3;++r){var a=0,o=e.center[s[r]],h=t[s[r]],l=i[s[r]],c=0;o<h&&(a+=(c=h-o)*c),o>l&&(a+=(c=o-l)*c),n+=a}return n},t._expand=function(e,t){Ce.add2(this.getMin(),e),Ee.add2(this.getMax(),t),this.setMinMax(Ce,Ee)},e}(),Le=new me,De=new me,Oe=function(){function e(e,t){void 0===e&&(e=new me),void 0===t&&(t=.5),this.center=void 0,this.radius=void 0,this.center=e,this.radius=t}var t=e.prototype;return t.containsPoint=function(e){var t=Le.sub2(e,this.center).lengthSq(),i=this.radius;return t<i*i},t.intersectsRay=function(e,t){var i=Le.copy(e.origin).sub(this.center),n=i.dot(De.copy(e.direction).normalize()),s=i.dot(i)-this.radius*this.radius;if(s>0&&n>0)return!1;var r=n*n-s;if(r<0)return!1;var a=Math.abs(-n-Math.sqrt(r));return t&&t.copy(e.direction).mulScalar(a).add(e.origin),!0},t.intersectsBoundingSphere=function(e){Le.sub2(e.center,this.center);var t=e.radius+this.radius;return Le.lengthSq()<=t*t},e}(),ke=function(){function e(){this.planes=[];for(var e=0;e<6;e++)this.planes[e]=[]}var t=e.prototype;return t.setFromMat4=function(e){var t,i=e.data,n=this.planes;(t=n[0])[0]=i[3]-i[0],t[1]=i[7]-i[4],t[2]=i[11]-i[8],t[3]=i[15]-i[12];var s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s,(t=n[1])[0]=i[3]+i[0],t[1]=i[7]+i[4],t[2]=i[11]+i[8],t[3]=i[15]+i[12],s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s,(t=n[2])[0]=i[3]+i[1],t[1]=i[7]+i[5],t[2]=i[11]+i[9],t[3]=i[15]+i[13],s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s,(t=n[3])[0]=i[3]-i[1],t[1]=i[7]-i[5],t[2]=i[11]-i[9],t[3]=i[15]-i[13],s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s,(t=n[4])[0]=i[3]-i[2],t[1]=i[7]-i[6],t[2]=i[11]-i[10],t[3]=i[15]-i[14],s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s,(t=n[5])[0]=i[3]+i[2],t[1]=i[7]+i[6],t[2]=i[11]+i[10],t[3]=i[15]+i[14],s=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]),t[0]/=s,t[1]/=s,t[2]/=s,t[3]/=s},t.containsPoint=function(e){var t,i;for(t=0;t<6;t++)if((i=this.planes[t])[0]*e.x+i[1]*e.y+i[2]*e.z+i[3]<=0)return!1;return!0},t.containsSphere=function(e){var t,i,n,s=0,r=e.radius,a=e.center,o=a.x,h=a.y,l=a.z,c=this.planes;for(i=0;i<6;i++){if((t=(n=c[i])[0]*o+n[1]*h+n[2]*l+n[3])<=-r)return 0;t>r&&s++}return 6===s?2:1},e}(),Fe=function(){function e(e,t){this.origin=new me,this.direction=me.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}(),Be=new Fe,Ne=new me,Ue=new Oe,ze=new Te,Ve=function(){function e(e,t){void 0===e&&(e=new Te),void 0===t&&(t=new me(.5,.5,.5)),this.halfExtents=void 0,this._modelTransform=void 0,this._worldTransform=void 0,this._aabb=void 0,this.halfExtents=t,this._modelTransform=e.clone().invert(),this._worldTransform=e.clone(),this._aabb=new Ie(new me,this.halfExtents)}var t=e.prototype;return t.intersectsRay=function(e,t){if(this._modelTransform.transformPoint(e.origin,Be.origin),this._modelTransform.transformVector(e.direction,Be.direction),t){var i=this._aabb._intersectsRay(Be,t);return ze.copy(this._modelTransform).invert().transformPoint(t,t),i}return this._aabb._fastIntersectsRay(Be)},t.containsPoint=function(e){return this._modelTransform.transformPoint(e,Ne),this._aabb.containsPoint(Ne)},t.intersectsBoundingSphere=function(e){return this._modelTransform.transformPoint(e.center,Ue.center),Ue.radius=e.radius,!!this._aabb.intersectsBoundingSphere(Ue)},Z(e,[{key:"worldTransform",get:function(){return this._worldTransform},set:function(e){this._worldTransform.copy(e),this._modelTransform.copy(e).invert()}}]),e}(),Ge=function(){function e(e,t){void 0===e&&(e=me.UP),void 0===t&&(t=0),this.normal=new me,this.distance=void 0,this.normal.copy(e),this.distance=t}var t=e.prototype;return t.setFromPointNormal=function(e,t){return this.normal.copy(t),this.distance=-this.normal.dot(e),this},t.intersectsLine=function(e,t,i){var n=this.distance,s=this.normal.dot(e)+n,r=s/(s-(this.normal.dot(t)+n)),a=r>=0&&r<=1;return a&&i&&i.lerp(e,t,r),a},t.intersectsRay=function(e,t){var i=this.normal.dot(e.direction);if(0===i)return!1;var n=-(this.normal.dot(e.origin)+this.distance)/i;return n>=0&&t&&t.copy(e.direction).mulScalar(n).add(e.origin),n>=0},t.copy=function(e){return this.normal.copy(e.normal),this.distance=e.distance,this},t.clone=function(){return(new(0,this.constructor)).copy(this)},e}(),He="linear",We="inverse",Xe="exponential",je=10,qe=11,Ye=12,Ke=13,Ze=14,$e=15,Qe=16,Je=17,et=18,tt=21,it=24,nt=25,st=26,rt=27,at=new Map([[0,{name:"A8",size:1}],[1,{name:"L8",size:1}],[2,{name:"LA8",size:2}],[3,{name:"RGB565",size:2}],[4,{name:"RGBA5551",size:2}],[5,{name:"RGBA4",size:2}],[6,{name:"RGB8",size:4}],[7,{name:"RGBA8",size:4}],[qe,{name:"RGB16F",size:8}],[Ye,{name:"RGBA16F",size:8}],[Ke,{name:"RGB32F",size:16}],[Ze,{name:"RGBA32F",size:16}],[$e,{name:"R32F",size:4}],[Qe,{name:"DEPTH",size:4}],[Je,{name:"DEPTHSTENCIL",size:4}],[et,{name:"111110F",size:4}],[19,{name:"SRGB",size:4}],[20,{name:"SRGBA",size:4}],[31,{name:"BGRA8",size:4}],[8,{name:"DXT1",blockSize:8}],[9,{name:"DXT3",blockSize:16}],[je,{name:"DXT5",blockSize:16}],[tt,{name:"ETC1",blockSize:8}],[22,{name:"ETC2_RGB",blockSize:8}],[23,{name:"ETC2_RGBA",blockSize:16}],[it,{name:"PVRTC_2BPP_RGB_1",blockSize:8}],[nt,{name:"PVRTC_2BPP_RGBA_1",blockSize:8}],[st,{name:"PVRTC_4BPP_RGB_1",blockSize:8}],[rt,{name:"PVRTC_4BPP_RGBA_1",blockSize:8}],[28,{name:"ASTC_4x4",blockSize:16}],[29,{name:"ATC_RGB",blockSize:8}],[30,{name:"ATC_RGBA",blockSize:16}]]),ot=function(e){return void 0!==at.get(e).blockSize},ht=function(e){switch(e){case Ke:case Ze:return Float32Array;case 3:case 4:case 5:case qe:case Ye:return Uint16Array;default:return Uint8Array}},lt="POSITION",ct="NORMAL",ut="TANGENT",dt="BLENDWEIGHT",ft="BLENDINDICES",pt="COLOR",mt="TEXCOORD",_t="TEXCOORD0",gt="TEXCOORD1",vt="TEXCOORD2",yt="TEXCOORD3",xt="TEXCOORD4",St="TEXCOORD5",bt="TEXCOORD6",wt="TEXCOORD7",Tt="ATTR",At="ATTR0",Ct="ATTR1",Et="ATTR2",Mt="ATTR3",Pt="ATTR4",Rt="ATTR5",It="ATTR6",Lt="ATTR7",Dt="ATTR8",Ot="ATTR9",kt="ATTR10",Ft="ATTR11",Bt="ATTR12",Nt="ATTR13",Ut="ATTR14",zt="ATTR15",Vt="default",Gt="rgbm",Ht="rgbe",Wt="rgbp",Xt="swizzleGGGR",jt="2d",qt="2d-array",Yt="cube",Kt="3d",Zt="none",$t="cube",Qt="equirect",Jt="octahedral",ei="wgsl",ti=14,ii=["bool","int","float","vec2","vec3","vec4","ivec2","ivec3","ivec4","bec2","bec3","bec4","mat2","mat3","mat4","sampler2D","samplerCube","","sampler2DShadow","samplerCubeShadow","sampler3D","","",""],ni="webgl1",si="webgl2",ri="webgpu",ai="default",oi=["view","mesh"],hi=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array],li=[1,1,2,2,4,4,4],ci={Int8Array:0,Uint8Array:1,Int16Array:2,Uint16Array:3,Int32Array:4,Uint32Array:5,Float32Array:6},ui=[Uint8Array,Uint16Array,Uint32Array],di=[1,2,4],fi={};fi[lt]=0,fi[ct]=1,fi[dt]=2,fi[ft]=3,fi[pt]=4,fi[_t]=5,fi[gt]=6,fi[vt]=7,fi[yt]=8,fi[xt]=9,fi[St]=10,fi[bt]=11,fi[wt]=12,fi[ut]=13,fi[At]=0,fi[Ct]=1,fi[Et]=2,fi[Mt]=3,fi[Pt]=4,fi[Rt]=5,fi[It]=6,fi[Lt]=7,fi[Dt]=8,fi[Ot]=9,fi[kt]=10,fi[Ft]=11,fi[Bt]=12,fi[Nt]=13,fi[Ut]=14,fi[zt]=15;var pi="1.62",mi=function(e,t,i,n){return void 0===n&&(n=1),e&~(n<<i)|t<<i},_i=function(e,t,i){return void 0===i&&(i=1),e>>t&i},gi=function(e,t,i){void 0===i&&(i=1);var n=i<<t;return(e&n)===n},vi=15,yi=function(){function e(e,t,i,n,s,r,a,o,h,l,c){void 0===e&&(e=!1),void 0===t&&(t=0),void 0===i&&(i=1),void 0===n&&(n=0),void 0===o&&(o=!0),void 0===h&&(h=!0),void 0===l&&(l=!0),void 0===c&&(c=!0),this.target0=0,this.setColorBlend(t,i,n),this.setAlphaBlend(null!=s?s:t,null!=r?r:i,null!=a?a:n),this.setColorWrite(o,h,l,c),this.blend=e}var t=e.prototype;return t.setColorBlend=function(e,t,i){this.target0=mi(this.target0,e,0,7),this.target0=mi(this.target0,t,3,vi),this.target0=mi(this.target0,i,7,vi)},t.setAlphaBlend=function(e,t,i){this.target0=mi(this.target0,e,11,7),this.target0=mi(this.target0,t,14,vi),this.target0=mi(this.target0,i,18,vi)},t.setColorWrite=function(e,t,i,n){this.redWrite=e,this.greenWrite=t,this.blueWrite=i,this.alphaWrite=n},t.copy=function(e){return this.target0=e.target0,this},t.clone=function(){var e=new this.constructor;return e.copy(this)},t.equals=function(e){return this.target0===e.target0},Z(e,[{key:"blend",get:function(){return gi(this.target0,26)},set:function(e){this.target0=mi(this.target0,e?1:0,26)}},{key:"colorOp",get:function(){return _i(this.target0,0,7)}},{key:"colorSrcFactor",get:function(){return _i(this.target0,3,vi)}},{key:"colorDstFactor",get:function(){return _i(this.target0,7,vi)}},{key:"alphaOp",get:function(){return _i(this.target0,11,7)}},{key:"alphaSrcFactor",get:function(){return _i(this.target0,14,vi)}},{key:"alphaDstFactor",get:function(){return _i(this.target0,18,vi)}},{key:"redWrite",get:function(){return gi(this.target0,22)},set:function(e){this.target0=mi(this.target0,e?1:0,22)}},{key:"greenWrite",get:function(){return gi(this.target0,23)},set:function(e){this.target0=mi(this.target0,e?1:0,23)}},{key:"blueWrite",get:function(){return gi(this.target0,24)},set:function(e){this.target0=mi(this.target0,e?1:0,24)}},{key:"alphaWrite",get:function(){return gi(this.target0,25)},set:function(e){this.target0=mi(this.target0,e?1:0,25)}},{key:"allWrite",get:function(){return _i(this.target0,22,15)}},{key:"key",get:function(){return this.target0}}]),e}();yi.NOBLEND=Object.freeze(new yi),yi.NOWRITE=Object.freeze(new yi(void 0,void 0,void 0,void 0,void 0,void 0,void 0,!1,!1,!1,!1)),yi.ALPHABLEND=Object.freeze(new yi(!0,0,6,8));var xi=function(){function e(e,t){void 0===e&&(e=3),void 0===t&&(t=!0),this.data=0,this.func=e,this.write=t}var t=e.prototype;return t.copy=function(e){return this.data=e.data,this},t.clone=function(){var e=new this.constructor;return e.copy(this)},t.equals=function(e){return this.data===e.data},Z(e,[{key:"test",get:function(){return 7!==this.func},set:function(e){this.func=e?3:7}},{key:"write",get:function(){return gi(this.data,3)},set:function(e){this.data=mi(this.data,e?1:0,3)}},{key:"func",get:function(){return _i(this.data,0,7)},set:function(e){this.data=mi(this.data,e,0,7)}},{key:"key",get:function(){return this.data}}]),e}();xi.DEFAULT=Object.freeze(new xi),xi.NODEPTH=Object.freeze(new xi(7,!1)),xi.WRITEDEPTH=Object.freeze(new xi(7,!0));var Si=function(){function e(){this.globalId=0,this.revision=0}var t=e.prototype;return t.equals=function(e){return this.globalId===e.globalId&&this.revision===e.revision},t.copy=function(e){this.globalId=e.globalId,this.revision=e.revision},t.reset=function(){this.globalId=0,this.revision=0},e}(),bi=0,wi=function(){function e(){bi++,this.version=new Si,this.version.globalId=bi}return e.prototype.increment=function(){this.version.revision++},e}(),Ti=function(){function e(e){this.name=e,this.value=null,this.versionObject=new wi}var t=e.prototype;return t.toJSON=function(e){},t.setValue=function(e){this.value=e,this.versionObject.increment()},t.getValue=function(){return this.value},e}(),Ai=function(){function e(e){this.name=e,this.variables=new Map}var t=e.prototype;return t.resolve=function(e){return this.variables.has(e)||this.variables.set(e,new Ti(e)),this.variables.get(e)},t.removeValue=function(e){for(var t in this.variables){var i=this.variables[t];i.value===e&&(i.value=null)}},e}(),Ci=0,Ei=function(){function e(e,t,i,n,s){void 0===n&&(n=0),this.device=e,this.format=t,this.numVertices=i,this.usage=n,this.id=Ci++,this.impl=e.createVertexBufferImpl(this,t),this.numBytes=t.verticesByteSize?t.verticesByteSize:t.size*i,this.adjustVramSizeTracking(e._vram,this.numBytes),s?this.setData(s):this.storage=new ArrayBuffer(this.numBytes),this.device.buffers.push(this)}var t=e.prototype;return t.destroy=function(){var e=this.device,t=e.buffers.indexOf(this);-1!==t&&e.buffers.splice(t,1),this.impl.initialized&&(this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this.storage.byteLength))},t.adjustVramSizeTracking=function(e,t){e.vb+=t},t.loseContext=function(){this.impl.loseContext()},t.getFormat=function(){return this.format},t.getUsage=function(){return this.usage},t.getNumVertices=function(){return this.numVertices},t.lock=function(){return this.storage},t.unlock=function(){this.impl.unlock(this)},t.setData=function(e){return e.byteLength===this.numBytes&&(this.storage=e,this.unlock(),!0)},e}();function Mi(e){for(var t=0,i=0,n=e.length;i<n;i++)t=(t<<5)-t+e.charCodeAt(i),t|=0;return t}var Pi=function(){function e(e,t,i){this.device=e,this._elements=[],this.hasUv0=!1,this.hasUv1=!1,this.hasColor=!1,this.hasTangents=!1,this.verticesByteSize=0,this.vertexCount=i,this.interleaved=void 0===i,this.instancing=!1,this.size=t.reduce((function(e,t){return e+4*Math.ceil(t.components*li[t.type]/4)}),0);for(var n,s=0,r=0,a=t.length;r<a;r++){var o,h=t[r];n=h.components*li[h.type],i&&(s=ce.roundUp(s,n));var l={name:h.semantic,offset:i?s:h.hasOwnProperty("offset")?h.offset:s,stride:i?n:h.hasOwnProperty("stride")?h.stride:this.size,dataType:h.type,numComponents:h.components,normalize:null!=(o=h.normalize)&&o,size:n};this._elements.push(l),s+=i?n*i:4*Math.ceil(n/4),h.semantic===_t?this.hasUv0=!0:h.semantic===gt?this.hasUv1=!0:h.semantic===pt?this.hasColor=!0:h.semantic===ut&&(this.hasTangents=!0)}i&&(this.verticesByteSize=s),this._evaluateHash()}e.getDefaultInstancingFormat=function(t){return e._defaultInstancingFormat||(e._defaultInstancingFormat=new e(t,[{semantic:Bt,components:4,type:6},{semantic:Nt,components:4,type:6},{semantic:Ut,components:4,type:6},{semantic:zt,components:4,type:6}])),e._defaultInstancingFormat};var t=e.prototype;return t.update=function(){this._evaluateHash()},t._evaluateHash=function(){for(var e,t,i=[],n=[],s=this._elements.length,r=0;r<s;r++){var a=this._elements[r];e=a.name,e+=a.dataType,e+=a.numComponents,e+=a.normalize,i.push(e),t=e,t+=a.offset,t+=a.stride,t+=a.size,n.push(t)}i.sort(),this.batchingHash=Mi(i.join()),this.renderingHashString=n.join("_"),this.renderingHash=Mi(this.renderingHashString)},Z(e,[{key:"elements",get:function(){return this._elements}}]),e}();Pi._defaultInstancingFormat=null;var Ri=function(){function e(e){var t,i,n,s,r,a,o;void 0===e&&(e={}),this.func=void 0,this.ref=void 0,this.fail=void 0,this.zfail=void 0,this.zpass=void 0,this.readMask=void 0,this.writeMask=void 0,this.func=null!=(t=e.func)?t:7,this.ref=null!=(i=e.ref)?i:0,this.readMask=null!=(n=e.readMask)?n:255,this.writeMask=null!=(s=e.writeMask)?s:255,this.fail=null!=(r=e.fail)?r:0,this.zfail=null!=(a=e.zfail)?a:0,this.zpass=null!=(o=e.zpass)?o:0}var t=e.prototype;return t.copy=function(e){return this.func=e.func,this.ref=e.ref,this.readMask=e.readMask,this.writeMask=e.writeMask,this.fail=e.fail,this.zfail=e.zfail,this.zpass=e.zpass,this},t.clone=function(){var e=new this.constructor;return e.copy(this)},Z(e,[{key:"key",get:function(){return this.func+","+this.ref+","+this.fail+","+this.zfail+","+this.zpass+","+this.readMask+","+this.writeMask}}]),e}();Ri.DEFAULT=Object.freeze(new Ri);var Ii=function(e){function t(t,i){var n,s,r,a,o;(o=e.call(this)||this).canvas=void 0,o.isWebGPU=!1,o.scope=void 0,o.boneLimit=void 0,o.maxAnisotropy=void 0,o.maxCubeMapSize=void 0,o.maxTextureSize=void 0,o.maxVolumeSize=void 0,o.maxColorAttachments=1,o.precision=void 0,o.samples=void 0,o.supportsStencil=void 0,o.supportsMrt=!1,o.supportsVolumeTextures=!1,o.renderTarget=null,o.renderVersion=0,o.renderPassIndex=void 0,o.insideRenderPass=!1,o.supportsInstancing=void 0,o.supportsUniformBuffers=!1,o.textureFloatRenderable=void 0,o.textureHalfFloatRenderable=void 0,o.quadVertexBuffer=void 0,o.blendState=new yi,o.depthState=new xi,o.stencilEnabled=!1,o.stencilFront=new Ri,o.stencilBack=new Ri,o.defaultClearOptions={color:[0,0,0,1],depth:1,stencil:0,flags:3},o.canvas=t,o.initOptions=$({},i),null!=(n=o.initOptions).depth||(n.depth=!0),null!=(s=o.initOptions).stencil||(s.stencil=!0),null!=(r=o.initOptions).antialias||(r.antialias=!0),null!=(a=o.initOptions).powerPreference||(a.powerPreference="high-performance"),o._width=0,o._height=0,o._maxPixelRatio=M.browser?Math.min(1,window.devicePixelRatio):1,o.shaders=[],o.buffers=[],o.textures=[],o.targets=[],o._vram={tex:0,vb:0,ib:0,ub:0},o._shaderStats={vsCompiled:0,fsCompiled:0,linked:0,materialShaders:0,compileTime:0},o.initializeContextCaches(),o._drawCallsPerFrame=0,o._shaderSwitchesPerFrame=0,o._primsPerFrame=[];for(var h=0;h<=6;h++)o._primsPerFrame[h]=0;return o._renderTargetCreationTime=0,o.scope=new Ai("Device"),o.textureBias=o.scope.resolve("textureBias"),o.textureBias.setValue(0),o}Q(t,e);var i=t.prototype;return i.postInit=function(){var e=new Pi(this,[{semantic:lt,components:2,type:6}]),t=new Float32Array([-1,-1,1,-1,-1,1,1,1]);this.quadVertexBuffer=new Ei(this,e,4,0,t)},i.destroy=function(){var e;this.fire("destroy"),null==(e=this.quadVertexBuffer)||e.destroy(),this.quadVertexBuffer=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.toJSON=function(e){},i.initializeContextCaches=function(){this.indexBuffer=null,this.vertexBuffers=[],this.shader=null,this.renderTarget=null},i.initializeRenderState=function(){this.blendState=new yi,this.depthState=new xi,this.cullMode=1,this.vx=this.vy=this.vw=this.vh=0,this.sx=this.sy=this.sw=this.sh=0},i.setStencilState=function(e,t){},i.setBlendState=function(e){},i.setDepthState=function(e){},i.setCullMode=function(e){},i.setRenderTarget=function(e){this.renderTarget=e},i.setIndexBuffer=function(e){this.indexBuffer=e},i.setVertexBuffer=function(e){e&&this.vertexBuffers.push(e)},i.getRenderTarget=function(){return this.renderTarget},i.initRenderTarget=function(e){e.initialized||(e.init(),this.targets.push(e))},i._isBrowserInterface=function(e){return this._isImageBrowserInterface(e)||this._isImageCanvasInterface(e)||this._isImageVideoInterface(e)},i._isImageBrowserInterface=function(e){return"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement},i._isImageCanvasInterface=function(e){return"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement},i._isImageVideoInterface=function(e){return"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement},i.resizeCanvas=function(e,t){},i.setResolution=function(e,i){this._width=e,this._height=i,this.canvas.width=e,this.canvas.height=i,this.fire(t.EVENT_RESIZE,e,i)},i.updateClientRect=function(){this.clientRect=this.canvas.getBoundingClientRect()},i.getBoneLimit=function(){return this.boneLimit},i.setBoneLimit=function(e){this.boneLimit=e},i.frameStart=function(){this.renderPassIndex=0,this.renderVersion++},Z(t,[{key:"width",get:function(){return this.canvas.width}},{key:"height",get:function(){return this.canvas.height}},{key:"fullscreen",get:function(){return!1},set:function(e){}},{key:"maxPixelRatio",get:function(){return this._maxPixelRatio},set:function(e){this._maxPixelRatio!==e&&(this._maxPixelRatio=e,this.resizeCanvas(this._width,this._height))}},{key:"deviceType",get:function(){return this._deviceType}}]),t}(p);Ii.EVENT_RESIZE="resizecanvas";var Li=0,Di=function(){function e(e){var t,i,n,s,r,a,o;void 0===e&&(e={}),this.name=void 0,this._device=void 0,this._colorBuffer=void 0,this._colorBuffers=void 0,this._depthBuffer=void 0,this._depth=void 0,this._stencil=void 0,this._samples=void 0,this.autoResolve=void 0,this._face=void 0,this.flipY=void 0,this.id=Li++;var h=arguments[1],l=arguments[2];if(e instanceof Ii?(this._colorBuffer=h,e=l):this._colorBuffer=e.colorBuffer,this._colorBuffer&&(this._colorBuffers=[this._colorBuffer]),this._depthBuffer=e.depthBuffer,this._face=null!=(t=e.face)?t:0,this._depthBuffer){var c=this._depthBuffer._format;c===Qe?(this._depth=!0,this._stencil=!1):c===Je?(this._depth=!0,this._stencil=!0):(this._depth=!1,this._stencil=!1)}else{var u,d;this._depth=null==(u=e.depth)||u,this._stencil=null!=(d=e.stencil)&&d}e.colorBuffers&&(this._colorBuffers||(this._colorBuffers=[].concat(e.colorBuffers),this._colorBuffer=e.colorBuffers[0]));var f=(null==(i=this._colorBuffer)?void 0:i.device)||(null==(n=this._depthBuffer)?void 0:n.device)||e.graphicsDevice;this._device=f,null==(s=this._colorBuffers)||s.forEach((function(e){e._isRenderTarget=!0}));var p,m,_=this._device.maxSamples;(this._samples=Math.min(null!=(r=e.samples)?r:1,_),f.isWebGPU&&(this._samples=this._samples>1?_:1),this.autoResolve=null==(a=e.autoResolve)||a,this.name=e.name,this.name)||(this.name=null==(p=this._colorBuffer)?void 0:p.name);this.name||(this.name=null==(m=this._depthBuffer)?void 0:m.name);this.name||(this.name="Untitled"),this.flipY=null!=(o=e.flipY)&&o,this.validateMrt(),this.impl=f.createRenderTargetImpl(this)}var t=e.prototype;return t.destroy=function(){var e=this._device;if(e){var t=e.targets.indexOf(this);-1!==t&&e.targets.splice(t,1),e.renderTarget===this&&e.setRenderTarget(null),this.destroyFrameBuffers()}},t.destroyFrameBuffers=function(){var e=this._device;e&&this.impl.destroy(e)},t.destroyTextureBuffers=function(){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},t.validateMrt=function(){},t.init=function(){this.impl.init(this._device,this)},t.loseContext=function(){this.impl.loseContext()},t.resolve=function(e,t){void 0===e&&(e=!0),void 0===t&&(t=!!this._depthBuffer),this._device&&this._samples>1&&this.impl.resolve(this._device,this,e,t)},t.copy=function(e,t,i){if(!this._device){if(!e._device)return!1;this._device=e._device}return this._device.copyRenderTarget(e,this,t,i)},t.getColorBuffer=function(e){var t;return null==(t=this._colorBuffers)?void 0:t[e]},Z(e,[{key:"initialized",get:function(){return this.impl.initialized}},{key:"samples",get:function(){return this._samples}},{key:"depth",get:function(){return this._depth}},{key:"stencil",get:function(){return this._stencil}},{key:"colorBuffer",get:function(){return this._colorBuffer}},{key:"depthBuffer",get:function(){return this._depthBuffer}},{key:"face",get:function(){return this._face}},{key:"width",get:function(){var e,t;return(null==(e=this._colorBuffer)?void 0:e.width)||(null==(t=this._depthBuffer)?void 0:t.width)||this._device.width}},{key:"height",get:function(){var e,t;return(null==(e=this._colorBuffer)?void 0:e.height)||(null==(t=this._depthBuffer)?void 0:t.height)||this._device.height}}]),e}();new Map;var Oi=function(){function e(){this.bindGroup=void 0}var t=e.prototype;return t.update=function(e){this.destroy();var t=e.device,i=this.createDescriptor(t,e);this.bindGroup=t.wgpu.createBindGroup(i)},t.destroy=function(){this.bindGroup=null},t.createDescriptor=function(e,t){var i=[],n=t.format,s=0;return t.uniformBuffers.forEach((function(e){var t=e.impl.buffer;i.push({binding:s++,resource:{buffer:t}})})),t.textures.forEach((function(t,r){var a=t.impl,o=n.textureFormats[r],h=a.getView(e);i.push({binding:s++,resource:h});var l=a.getSampler(e,o.sampleType);i.push({binding:s++,resource:l})})),{layout:t.format.impl.bindGroupLayout,entries:i}},e}(),ki=function(){function e(){}return e.shaderStage=function(e){var t=0;return 1&e&&(t|=GPUShaderStage.VERTEX),2&e&&(t|=GPUShaderStage.FRAGMENT),4&e&&(t|=GPUShaderStage.COMPUTE),t},e}(),Fi=[];Fi[0]="filtering",Fi[1]="non-filtering",Fi[2]="comparison";var Bi=[];Bi[0]="float",Bi[1]="unfilterable-float",Bi[2]="depth";var Ni=function(){function e(e){var t=e.device,i=this.createDescriptor(e),n=i.key,s=i.descr;this.key=n,this.bindGroupLayout=t.wgpu.createBindGroupLayout(s)}var t=e.prototype;return t.destroy=function(){this.bindGroupLayout=null},t.loseContext=function(){},t.getTextureSlot=function(e,t){return e.bufferFormats.length+2*t},t.createDescriptor=function(e){var t=[],i="",n=0;return e.bufferFormats.forEach((function(e){var s=ki.shaderStage(e.visibility);i+="#"+n+"U:"+s,t.push({binding:n++,visibility:s,buffer:{type:"uniform",hasDynamicOffset:!1}})})),e.textureFormats.forEach((function(e){var s=ki.shaderStage(e.visibility),r=e.sampleType,a=e.textureDimension,o=Bi[r];i+="#"+n+"T:"+s+"-"+o+"-"+a+"-false",t.push({binding:n++,visibility:s,texture:{sampleType:o,viewDimension:a,multisampled:false}});var h=Fi[r];i+="#"+n+"S:"+s+"-"+h,t.push({binding:n++,visibility:s,sampler:{type:h}})})),{key:i,descr:{entries:t}}},e}(),Ui=function(){function e(){this.buffer=null}var t=e.prototype;return t.destroy=function(e){this.buffer&&(this.buffer.destroy(),this.buffer=null)},t.loseContext=function(){},t.unlock=function(e,t,i,n){var s,r,a=e.wgpu;if(!this.buffer){var o=n.byteLength+3&-4;this.buffer=e.wgpu.createBuffer({size:o,usage:i|GPUBufferUsage.COPY_DST})}var h=null!=(s=n.byteOffset)?s:0,l=new Uint8Array(null!=(r=n.buffer)?r:n,h,n.byteLength),c=new Uint8Array(this.buffer.size);c.set(l),a.queue.writeBuffer(this.buffer,0,c,0,c.length)},Z(e,[{key:"initialized",get:function(){return!!this.buffer}}]),e}(),zi=function(e){function t(t){var i;return(i=e.call(this)||this).format=null,i.format=1===t.format?"uint16":"uint32",i}return Q(t,e),t.prototype.unlock=function(t){var i=t.device;e.prototype.unlock.call(this,i,t.usage,GPUBufferUsage.INDEX,t.storage)},t}(Ui),Vi=[];Vi[0]="sint8",Vi[1]="uint8",Vi[2]="sint16",Vi[3]="uint16",Vi[4]="sint32",Vi[5]="uint32",Vi[6]="float32";var Gi=[];Gi[0]="snorm8",Gi[1]="unorm8",Gi[2]="snorm16",Gi[3]="unorm16",Gi[4]="sint32",Gi[5]="uint32",Gi[6]="float32";var Hi=function(){function e(){this.cache=new Map}var t=e.prototype;return t.get=function(e,t){void 0===t&&(t=null);var i=this.getKey(e,t),n=this.cache.get(i);return n||(n=this.create(e,t),this.cache.set(i,n)),n},t.getKey=function(e,t){var i;return void 0===t&&(t=null),"VB["+(null==e?void 0:e.renderingHashString)+", "+(null==(i=t)?void 0:i.renderingHashString)+"]"},t.create=function(e,t){var i=[],n=function(e){for(var t=e.interleaved,n=e.instancing?"instance":"vertex",s=[],r=e.elements.length,a=0;a<r;a++){var o=e.elements[a],h=fi[o.name],l=o.normalize?Gi:Vi;s.push({shaderLocation:h,offset:t?o.offset:0,format:l[o.dataType]+(o.numComponents>1?"x"+o.numComponents:"")}),t&&a!==r-1||(i.push({attributes:s,arrayStride:o.stride,stepMode:n}),s=[])}};return e&&n(e),t&&n(t),i},e}(),Wi=["point-list","line-list",void 0,"line-strip","triangle-list","triangle-strip",void 0],Xi=["add","subtract","reverse-subtract","min","max"],ji=["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"],qi=["never","less","equal","less-equal","greater","not-equal","greater-equal","always"],Yi=["none","back","front"],Ki=["keep","zero","replace","increment-clamp","increment-wrap","decrement-clamp","decrement-wrap","invert"],Zi=[],$i=function(){function e(e){this.device=e,this.vertexBufferLayout=new Hi,this.cache=new Map}var t=e.prototype;return t.get=function(e,t,i,n,s,r,a,o,h,l,c,u){var d=this.getKey(e,t,i,n,s,r,a,o,h,l,c,u),f=this.cache.get(d);if(!f){var p=Wi[e.type],m=this.getPipelineLayout(r),_=this.vertexBufferLayout.get(t,i);f=this.create(p,n,s,m,a,o,_,h,l,c,u),this.cache.set(d,f)}return f},t.getKey=function(e,t,i,n,s,r,a,o,h,l,c,u){for(var d="",f=0;f<r.length;f++)d+=r[f].key;var p=this.vertexBufferLayout.getKey(t,i),m=s.impl.key,_=l?c.key+u.key:"";return p+n.impl.vertexCode+n.impl.fragmentCode+m+e.type+d+a.key+o.key+h+_},t.getPipelineLayout=function(e){e.forEach((function(e){Zi.push(e.bindGroupLayout)}));var t={bindGroupLayouts:Zi},i=this.device.wgpu.createPipelineLayout(t);return Zi.length=0,i},t.getBlend=function(e){var t;return e.blend&&(t={color:{operation:Xi[e.colorOp],srcFactor:ji[e.colorSrcFactor],dstFactor:ji[e.colorDstFactor]},alpha:{operation:Xi[e.alphaOp],srcFactor:ji[e.alphaSrcFactor],dstFactor:ji[e.alphaDstFactor]}}),t},t.getDepthStencil=function(e,t,i,n,s){var r,a=t.depth,o=t.stencil;return(a||o)&&(r={format:t.impl.depthFormat},a?(r.depthWriteEnabled=e.write,r.depthCompare=qi[e.func]):(r.depthWriteEnabled=!1,r.depthCompare="always"),o&&i&&(r.stencilReadMas=n.readMask,r.stencilWriteMask=n.writeMask,r.stencilFront={compare:qi[n.func],failOp:Ki[n.fail],passOp:Ki[n.zpass],depthFailOp:Ki[n.zfail]},r.stencilBack={compare:qi[s.func],failOp:Ki[s.fail],passOp:Ki[s.zpass],depthFailOp:Ki[s.zfail]})),r},t.create=function(e,t,i,n,s,r,a,o,h,l,c){var u=this.device.wgpu,d=t.impl,f={vertex:{module:d.getVertexShaderModule(),entryPoint:d.vertexEntryPoint,buffers:a},fragment:{module:d.getFragmentShaderModule(),entryPoint:d.fragmentEntryPoint,targets:[]},primitive:{topology:e,frontFace:"ccw",cullMode:Yi[o]},depthStencil:this.getDepthStencil(r,i,h,l,c),multisample:{count:i.samples},layout:n},p=i.impl.colorAttachments;if(p.length>0){var m=0;s.redWrite&&(m|=GPUColorWrite.RED),s.greenWrite&&(m|=GPUColorWrite.GREEN),s.blueWrite&&(m|=GPUColorWrite.BLUE),s.alphaWrite&&(m|=GPUColorWrite.ALPHA);var _=this.getBlend(s);p.forEach((function(e){f.fragment.targets.push({format:e.format,writeMask:m,blend:_})}))}return u.createRenderPipeline(f)},e}(),Qi=function(){function e(){this.format=void 0,this.multisampledBuffer=void 0}return e.prototype.destroy=function(){var e;null==(e=this.multisampledBuffer)||e.destroy(),this.multisampledBuffer=null},e}(),Ji=function(){function e(e){var t=this;this.initialized=!1,this.key=void 0,this.colorAttachments=[],this.depthFormat=void 0,this.hasStencil=void 0,this.depthTexture=null,this.depthTextureInternal=!1,this.assignedColorTexture=null,this.renderPassDescriptor={},this.renderTarget=e,e._colorBuffers&&e._colorBuffers.forEach((function(e,i){t.setColorAttachment(i,void 0,e.impl.format)})),this.updateKey()}var t=e.prototype;return t.destroy=function(e){var t;(this.initialized=!1,this.depthTextureInternal)&&(null==(t=this.depthTexture)||t.destroy(),this.depthTexture=null);this.assignedColorTexture=null,this.colorAttachments.forEach((function(e){e.destroy()})),this.colorAttachments.length=0},t.updateKey=function(){var e=this,t=this.renderTarget;this.key="",this.colorAttachments.forEach((function(t,i){e.key+=i+":"+t.format+"-"})),this.key+=(t.depth?this.depthFormat:"")+"-"+t.samples},t.setDepthFormat=function(e){this.depthFormat=e,this.hasStencil="depth24plus-stencil8"===e},t.assignColorTexture=function(e){this.assignedColorTexture=e;var t=e.createView(),i=this.renderPassDescriptor.colorAttachments[0];this.renderTarget.samples>1?i.resolveTarget=t:i.view=t,this.setColorAttachment(0,void 0,e.format),this.updateKey()},t.setColorAttachment=function(e,t,i){this.colorAttachments[e]||(this.colorAttachments[e]=new Qi),t&&(this.colorAttachments[e].multisampledBuffer=t),i&&(this.colorAttachments[e].format=i)},t.init=function(e,t){var i,n,s=e.wgpu;this.initDepthStencil(s,t),this.renderPassDescriptor.colorAttachments=[];for(var r=null!=(i=null==(n=t._colorBuffers)?void 0:n.length)?i:1,a=0;a<r;++a){var o,h=this.initColor(s,t,a),l=0===a&&(null==(o=this.colorAttachments[0])?void 0:o.format);(h.view||l)&&this.renderPassDescriptor.colorAttachments.push(h)}this.initialized=!0},t.initDepthStencil=function(e,t){var i=t.samples,n=t.width,s=t.height,r=t.depth,a=t.depthBuffer;if(r||a){if(a)this.depthTexture=a.impl.gpuTexture,this.setDepthFormat(a.impl.format);else{this.setDepthFormat("depth24plus-stencil8");var o={size:[n,s,1],dimension:"2d",sampleCount:i,format:this.depthFormat,usage:GPUTextureUsage.RENDER_ATTACHMENT};i<=1&&(o.usage|=GPUTextureUsage.COPY_SRC),this.depthTexture=e.createTexture(o),this.depthTextureInternal=!0}this.renderPassDescriptor.depthStencilAttachment={view:this.depthTexture.createView()}}},t.initColor=function(e,t,i){var n={},s=t.samples,r=t.width,a=t.height,o=t.getColorBuffer(i),h=null;if(o){h=o.cubemap?o.impl.createView({dimension:"2d",baseArrayLayer:t.face,arrayLayerCount:1,mipLevelCount:1}):o.impl.createView({mipLevelCount:1})}if(s>1){var l,c,u={size:[r,a,1],dimension:"2d",sampleCount:s,format:null!=(l=null==(c=this.colorAttachments[i])?void 0:c.format)?l:o.impl.format,usage:GPUTextureUsage.RENDER_ATTACHMENT},d=e.createTexture(u);this.setColorAttachment(i,d),n.view=d.createView(),n.resolveTarget=h}else n.view=h;return n},t.setupForRenderPass=function(e){for(var t,i,n=null!=(t=null==(i=this.renderPassDescriptor.colorAttachments)?void 0:i.length)?t:0,s=0;s<n;++s){var r=this.renderPassDescriptor.colorAttachments[s],a=e.colorArrayOps[s];r.clearValue=a.clearValue,r.loadOp=a.clear?"clear":"load",r.storeOp=a.store?"store":"discard"}var o=this.renderPassDescriptor.depthStencilAttachment;o&&(o.depthClearValue=e.depthStencilOps.clearDepthValue,o.depthLoadOp=e.depthStencilOps.clearDepth?"clear":"load",o.depthStoreOp=e.depthStencilOps.storeDepth?"store":"discard",o.depthReadOnly=!1,this.hasStencil&&(o.stencilClearValue=e.depthStencilOps.clearStencilValue,o.stencilLoadOp=e.depthStencilOps.clearStencil?"clear":"load",o.stencilStoreOp=e.depthStencilOps.storeStencil?"store":"discard",o.stencilReadOnly=!1))},t.loseContext=function(){this.initialized=!1},t.resolve=function(e,t,i,n){},e}(),en=[];en[2]=1,en[3]=2,en[4]=3,en[5]=4,en[1]=1,en[6]=2,en[7]=3,en[8]=4,en[0]=1,en[9]=2,en[10]=3,en[11]=4,en[12]=8,en[13]=12,en[14]=16;var tn,nn=function(){function e(e,t,i){if(void 0===i&&(i=0),this.name=void 0,this.type=void 0,this.byteSize=void 0,this.offset=void 0,this.scopeId=void 0,this.count=void 0,this.shortName=e,this.name=i?e+"[0]":e,this.type=t,this.updateType=t,i)switch(t){case 2:this.updateType=17;break;case 3:this.updateType=21;break;case 4:this.updateType=22;break;case 5:this.updateType=23;break;case ti:this.updateType=24}this.count=i;var n=en[t];i&&(n=ce.roundUp(n,4)),this.byteSize=4*n,i&&(this.byteSize*=i)}return e.prototype.calculateOffset=function(e){var t=this.byteSize<=8?this.byteSize:16;this.count&&(t=16),e=ce.roundUp(e,t),this.offset=e/4},e}(),sn=function(){function e(e,t){this.byteSize=0,this.map=new Map,this.scope=e.scope,this.uniforms=t;for(var i=0,n=0;n<t.length;n++){var s=t[n];s.calculateOffset(i),i=4*s.offset+s.byteSize,s.scopeId=this.scope.resolve(s.name),this.map.set(s.name,s)}this.byteSize=ce.roundUp(i,16)}var t=e.prototype;return t.get=function(e){return this.map.get(e)},t.getShaderDeclaration=function(e,t){var i="layout(set = "+e+", binding = "+t+", std140) uniform ub_"+oi[e]+" {\n";return this.uniforms.forEach((function(e){var t=ii[e.type];i+=" "+t+" "+e.shortName+(e.count?"["+e.count+"]":"")+";\n"})),i+"};\n"},e}(),rn=0,an=((tn={})[jt]="texture2D",tn[Yt]="textureCube",tn[Kt]="texture3D",tn),on=function(e,t){this.name=e,this.visibility=t},hn=function(e,t,i,n){void 0===i&&(i=jt),void 0===n&&(n=0),this.scopeId=void 0,this.name=e,this.visibility=t,this.textureDimension=i,this.sampleType=n},ln=function(){function e(e,t,i){var n=this;void 0===t&&(t=[]),void 0===i&&(i=[]),this.id=rn++,this.device=e,this.bufferFormats=t,this.bufferFormatsMap=new Map,t.forEach((function(e,t){return n.bufferFormatsMap.set(e.name,t)})),this.textureFormats=i;var s=e.scope;this.textureFormatsMap=new Map,i.forEach((function(e,t){n.textureFormatsMap.set(e.name,t),e.scopeId=s.resolve(e.name)})),this.impl=e.createBindGroupFormatImpl(this)}var t=e.prototype;return t.destroy=function(){this.impl.destroy()},t.getTexture=function(e){var t=this.textureFormatsMap.get(e);return void 0!==t?this.textureFormats[t]:null},t.getShaderDeclarationTextures=function(e){var t="",i=this.bufferFormats.length;return this.textureFormats.forEach((function(n){var s=an[n.textureDimension];t+="layout(set = "+e+", binding = "+i+++") uniform "+s+" "+n.name+";\nlayout(set = "+e+", binding = "+i+++") uniform sampler "+n.name+"_sampler;\n"})),t},t.loseContext=function(){},e}(),cn=/[ \t]*(\battribute\b|\bvarying\b|\buniform\b)/g,un=/(\battribute\b|\bvarying\b|\bout\b|\buniform\b)[ \t]*([^;]+)([;]+)/g,dn="@@@",fn=/([\w-]+)\[(.*?)\]/,pn=new Set(["highp","mediump","lowp"]),mn=new Set(["sampler2DShadow","samplerCubeShadow"]),_n={sampler2D:jt,sampler3D:Kt,samplerCube:Yt,samplerCubeShadow:Yt,sampler2DShadow:jt,sampler2DArray:qt,sampler2DArrayShadow:qt},gn=function(e,t){this.line=e;var i=e.trim().split(/\s+/);if(pn.has(i[0])&&(this.precision=i.shift()),this.type=i.shift(),e.includes(","),e.includes("[")){var n=i.join(" "),s=fn.exec(n);this.name=s[1],this.arraySize=Number(s[2]),isNaN(this.arraySize)&&(t.failed=!0)}else this.name=i.shift(),this.arraySize=0;this.isSampler=-1!==this.type.indexOf("sampler")},vn=function(){function e(){}return e.run=function(t,i,n){var s=new Map,r=e.extract(i.vshader),a=e.extract(i.fshader),o=e.processAttributes(r.attributes,i.attributes,i.processingOptions),h=e.processVaryings(r.varyings,s,!0),l=e.processVaryings(a.varyings,s,!1),c=e.processOuts(a.outs),u=r.uniforms.concat(a.uniforms),d=Array.from(new Set(u)).map((function(e){return new gn(e,n)})),f=e.processUniforms(t,d,i.processingOptions,n),p=o+"\n"+h+"\n"+f.code,m=r.src.replace(dn,p),_=l+"\n"+c+"\n"+f.code;return{vshader:m,fshader:a.src.replace(dn,_),meshUniformBufferFormat:f.meshUniformBufferFormat,meshBindGroupFormat:f.meshBindGroupFormat}},e.extract=function(t){for(var i,n=[],s=[],r=[],a=[],o=dn+"\n";null!==(i=cn.exec(t));){var h=i[1];switch(h){case"attribute":case"varying":case"uniform":case"out":un.lastIndex=i.index;var l=un.exec(t);"attribute"===h?n.push(l[2]):"varying"===h?s.push(l[2]):"out"===h?r.push(l[2]):"uniform"===h&&a.push(l[2]),t=e.cutOut(t,i.index,un.lastIndex,o),cn.lastIndex=i.index+o.length,o=""}}return{src:t,attributes:n,varyings:s,outs:r,uniforms:a}},e.processUniforms=function(e,t,i,n){var s=[],r=[];t.forEach((function(e){e.isSampler?s.push(e):r.push(e)}));var a=[];r.forEach((function(e){if(!i.hasUniform(e.name)){var t=ii.indexOf(e.type),n=new nn(e.name,t,e.arraySize);a.push(n)}}));var o=a.length?new sn(e,a):null,h=[];o&&h.push(new on(ai,3));var l=[];s.forEach((function(e){if(!i.hasTexture(e.name)){var t=0;"highp"===e.precision&&(t=1),mn.has(e.type)&&(t=2);var n=_n[e.type];l.push(new hn(e.name,3,n,t))}}));var c=new ln(e,h,l),u="";return i.uniformFormats.forEach((function(e,t){e&&(u+=e.getShaderDeclaration(t,0))})),o&&(u+=o.getShaderDeclaration(0,0)),i.bindGroupFormats.forEach((function(e,t){e&&(u+=e.getShaderDeclarationTextures(t))})),{code:u+=c.getShaderDeclarationTextures(0),meshUniformBufferFormat:o,meshBindGroupFormat:c}},e.processVaryings=function(t,i,n){var s="",r=n?"out":"in";return t.forEach((function(t,a){var o=e.splitToWords(t),h=o[0],l=o[1];n?i.set(l,a):a=i.get(l),s+="layout(location = "+a+") "+r+" "+h+" "+l+";\n"})),s},e.processOuts=function(e){var t="";return e.forEach((function(e,i){t+="layout(location = "+i+") out "+e+";\n"})),t},e.getTypeCount=function(e){var t=e.substring(e.length-1),i=parseInt(t,10);return isNaN(i)?1:i},e.processAttributes=function(t,i,n){var s="";return t.forEach((function(t){var r=e.splitToWords(t),a=r[0],o=r[1];if(i.hasOwnProperty(o)){var h,l=i[o],c=fi[l],u=n.getVertexElement(l);if(u){var d=u.dataType;if(6!==d&&!u.normalize){var f=e.getTypeCount(a),p="_private_"+o;h="vec"+f+" "+o+" = vec"+f+"("+p+");\n",o=p;var m=0===d||2===d||4===d;a=1===f?m?"int":"uint":m?"ivec"+f:"uvec"+f}}s+="layout(location = "+c+") in "+a+" "+o+";\n",h&&(s+=h)}})),s},e.splitToWords=function(e){return(e=e.replace(/\s+/g," ").trim()).split(" ")},e.cutOut=function(e,t,i,n){return e.substring(0,t)+n+e.substring(i)},e}(),yn=function(){function e(e){this._vertexCode=void 0,this._fragmentCode=void 0,this.vertexEntryPoint="main",this.fragmentEntryPoint="main",this.shader=e;var t=e.definition;t.shaderLanguage===ei?(this._vertexCode=t.vshader,this._fragmentCode=t.fshader,this.vertexEntryPoint="vertexMain",this.fragmentEntryPoint="fragmentMain",e.ready=!0):t.processingOptions&&this.process()}var t=e.prototype;return t.destroy=function(e){this._vertexCode=null,this._fragmentCode=null},t.createShaderModule=function(e,t){return this.shader.device.wgpu.createShaderModule({code:e})},t.getVertexShaderModule=function(){return this.createShaderModule(this._vertexCode,"Vertex")},t.getFragmentShaderModule=function(){return this.createShaderModule(this._fragmentCode,"Fragment")},t.process=function(){var e=this.shader,t=vn.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=!0:e.failed=!0,e.meshUniformBufferFormat=t.meshUniformBufferFormat,e.meshBindGroupFormat=t.meshBindGroupFormat},t.transpile=function(e,t,i){try{var n=this.shader.device.glslang.compileGLSL(e,t);return this.shader.device.twgsl.convertSpirV2WGSL(n)}catch(n){console.error("Failed to transpile webgl "+t+" shader ["+this.shader.label+"] to WebGPU: ["+n.message+"]",{processed:e,original:i,shader:this.shader})}},t.loseContext=function(){},t.restoreContext=function(e,t){},Z(e,[{key:"vertexCode",get:function(){return this._vertexCode}},{key:"fragmentCode",get:function(){return this._fragmentCode}}]),e}(),xn=function(){function e(){}return e.calcLevelDimension=function(e,t){return Math.max(e>>t,1)},e.calcLevelGpuSize=function(e,t,i){var n,s,r,a=at.get(i),o=null!=(n=null==(s=at.get(i))?void 0:s.size)?n:0;if(o>0)return e*t*o;var h=null!=(r=a.blockSize)?r:0,l=Math.floor((e+3)/4),c=Math.floor((t+3)/4);return i!==it&&i!==nt||(l=Math.max(Math.floor(l/2),1)),l*c*h},e.calcGpuSize=function(t,i,n,s,r,a){for(var o=0;o+=e.calcLevelGpuSize(t,i,s),r&&(1!==t||1!==i||1!==n);)t=Math.max(t>>1,1),i=Math.max(i>>1,1),n=Math.max(n>>1,1);return o*(a?6:1)},e}(),Sn=[];Sn[0]="",Sn[1]="r8unorm",Sn[2]="rg8unorm",Sn[3]="",Sn[4]="",Sn[5]="",Sn[6]="rgba8unorm",Sn[7]="rgba8unorm",Sn[8]="bc1-rgba-unorm",Sn[9]="bc2-rgba-unorm",Sn[10]="bc3-rgba-unorm",Sn[11]="",Sn[12]="rgba16float",Sn[13]="",Sn[14]="rgba32float",Sn[15]="r32float",Sn[16]="depth32float",Sn[17]="depth24plus-stencil8",Sn[18]="rg11b10ufloat",Sn[19]="",Sn[20]="",Sn[21]="",Sn[22]="etc2-rgb8unorm",Sn[23]="etc2-rgba8unorm",Sn[24]="",Sn[25]="",Sn[26]="",Sn[27]="",Sn[28]="astc-4x4-unorm",Sn[29]="",Sn[30]="",Sn[31]="bgra8unorm";var bn=[];bn[0]="repeat",bn[1]="clamp-to-edge",bn[2]="mirror-repeat";var wn=[];wn[0]={level:"nearest",mip:"nearest"},wn[1]={level:"linear",mip:"nearest"},wn[2]={level:"nearest",mip:"nearest"},wn[3]={level:"nearest",mip:"linear"},wn[4]={level:"linear",mip:"nearest"},wn[5]={level:"linear",mip:"linear"};var Tn=function(){function e(e){this.gpuTexture=void 0,this.view=void 0,this.samplers=[],this.descr=void 0,this.format=void 0,this.texture=e,this.format=Sn[e.format],this.create(e.device)}var t=e.prototype;return t.create=function(e){var t,i=this.texture,n=e.wgpu,s=i.requiredMipLevels;this.descr={size:{width:i.width,height:i.height,depthOrArrayLayers:i.cubemap?6:1},format:this.format,mipLevelCount:s,sampleCount:1,dimension:i.volume?"3d":"2d",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC},this.gpuTexture=n.createTexture(this.descr),this.texture.format===Je&&(t={format:"depth24plus",aspect:"depth-only"}),this.view=this.createView(t)},t.destroy=function(e){},t.propertyChanged=function(e){this.samplers.length=0},t.getView=function(e){return this.uploadImmediate(e,this.texture),this.view},t.createView=function(e){var t,i,n,s,r,a,o,h=null!=e?e:{},l=this.descr,c=this.texture,u={format:null!=(t=h.format)?t:l.format,dimension:null!=(i=h.dimension)?i:c.cubemap?"cube":c.volume?"3d":"2d",aspect:null!=(n=h.aspect)?n:"all",baseMipLevel:null!=(s=h.baseMipLevel)?s:0,mipLevelCount:null!=(r=h.mipLevelCount)?r:l.mipLevelCount,baseArrayLayer:null!=(a=h.baseArrayLayer)?a:0,arrayLayerCount:null!=(o=h.arrayLayerCount)?o:l.depthOrArrayLayers};return this.gpuTexture.createView(u)},t.getSampler=function(e,t){var i=this.samplers[t];if(!i){var n=this.texture,s={addressModeU:bn[n.addressU],addressModeV:bn[n.addressV],addressModeW:bn[n.addressW],maxAnisotropy:ce.clamp(Math.round(n._anisotropy),1,e.maxTextureAnisotropy)};!t&&n.compareOnRead&&(t=2),2===t?(s.compare="less",s.magFilter="linear",s.minFilter="linear"):1===t||this.texture.format===Ze||this.texture.format===Je||this.texture.format===Ye?(s.magFilter="nearest",s.minFilter="nearest",s.mipmapFilter="nearest"):(s.magFilter=wn[n.magFilter].level,s.minFilter=wn[n.minFilter].level,s.mipmapFilter=wn[n.minFilter].mip),i=e.wgpu.createSampler(s),this.samplers[t]=i}return i},t.loseContext=function(){},t.uploadImmediate=function(e,t){(t._needsUpload||t._needsMipmapsUpload)&&(this.uploadData(e),t._needsUpload=!1,t._needsMipmapsUpload=!1)},t.uploadData=function(e){var t=this.texture;if(t._levels){for(var i=e.wgpu,n=!1,s=t.requiredMipLevels,r=0;r<s;r++){var a=t._levels[r];if(a)if(t.cubemap)for(var o=0;o<6;o++){var h=a[o];h&&(this.isExternalImage(h)?(this.uploadExternalImage(e,h,r,o),n=!0):ArrayBuffer.isView(h)&&(this.uploadTypedArrayData(i,h,r,o),n=!0))}else t._volume||(this.isExternalImage(a)?(this.uploadExternalImage(e,a,r,0),n=!0):ArrayBuffer.isView(a)&&(this.uploadTypedArrayData(i,a,r,0),n=!0))}n&&t.mipmaps&&e.mipmapRenderer.generate(this)}},t.isExternalImage=function(e){return e instanceof ImageBitmap||e instanceof HTMLVideoElement||e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas},t.uploadExternalImage=function(e,t,i,n){var s={source:t,origin:[0,0],flipY:!1},r={texture:this.gpuTexture,mipLevel:i,origin:[0,0,n],aspect:"all"},a={width:this.descr.size.width,height:this.descr.size.height,depthOrArrayLayers:1};e.wgpu.queue.copyExternalImageToTexture(s,r,a)},t.uploadTypedArrayData=function(e,t,i,n){var s,r=this.texture,a={texture:this.gpuTexture,origin:[0,0,n],mipLevel:i},o=xn.calcLevelDimension(r.width,i),h=xn.calcLevelDimension(r.height,i);xn.calcLevelGpuSize(o,h,r.format);var l={offset:0,bytesPerRow:(null!=(s=at.get(r.format).size)?s:0)*o,rowsPerImage:h},c={width:o,height:h,depthOrArrayLayers:1};e.queue.writeTexture(a,t,l,c)},e}(),An=function(e){function t(t){return e.call(this)||this}Q(t,e);var i=t.prototype;return i.destroy=function(t){e.prototype.destroy.call(this,t)},i.unlock=function(t){var i=t.device;e.prototype.unlock.call(this,i,void 0,GPUBufferUsage.UNIFORM,t.storage)},t}(Ui),Cn=function(e){function t(t,i){return e.call(this)||this}Q(t,e);var i=t.prototype;return i.destroy=function(t){e.prototype.destroy.call(this,t)},i.unlock=function(t){var i=t.device;e.prototype.unlock.call(this,i,t.usage,GPUBufferUsage.VERTEX,t.storage)},t}(Ui),En=/[ \t]*#(ifn?def|if|endif|else|elif|define|undef|extension)/g,Mn=/define[ \t]+([^\n]+)\r?(?:\n|$)/g,Pn=/extension[ \t]+([\w-]+)[ \t]*:[ \t]*(enable|require)/g,Rn=/undef[ \t]+([^\n]+)\r?(?:\n|$)/g,In=/(ifdef|ifndef|if)[ \t]*([^\r\n]+)\r?\n/g,Ln=/(endif|else|elif)([ \t]+[^\r\n]+)?\r?(?:\n|$)/g,Dn=/([\w-]+)/,On=/(!|\s)?defined\(([\w-]+)\)/,kn=/[><=|&+-]/g,Fn=function(){function e(){}return e.run=function(e,t){void 0===t&&(t=!1),e=(e=e.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm,"$1")).split(/\r?\n/).map((function(e){return e.trimEnd()})).join("\n");var i=new Map;if(t){var n=new Map,s=e.match(/(pcFragColor[1-8])\b/g);null==s||s.forEach((function(e){var t,i=parseInt(e.charAt(e.length-1),10);n.set(i,(null!=(t=n.get(i))?t:0)+1)})),n.forEach((function(e,t){1===e&&i.set("REMOVE_COLOR_ATTACHMENT_"+t,"")}))}return null!==(e=this._preprocess(e,i))&&(e=(e=e.split(/\r?\n/).map((function(e){return""===e.trim()?"":e})).join("\n")).replace(/(\n\n){3,}/gm,"\n\n")),e},e._preprocess=function(t,i){void 0===i&&(i=new Map);for(var n,s=t,r=[],a=!1;null!==(n=En.exec(t));){var o=n[1];switch(o){case"define":Mn.lastIndex=n.index;var h=Mn.exec(t);a||(a=null===h);var l=h[1];Dn.lastIndex=h.index;var c=Dn.exec(l)[1],u=l.substring(c.length).trim();""===u&&(u="true"),e._keep(r)&&i.set(c,u),En.lastIndex=h.index+h[0].length;break;case"undef":Rn.lastIndex=n.index;var d=Rn.exec(t),f=d[1].trim();e._keep(r)&&i.delete(f),En.lastIndex=d.index+d[0].length;break;case"extension":Pn.lastIndex=n.index;var p=Pn.exec(t);if(a||(a=null===p),p){var m=p[1];e._keep(r)&&i.set(m,"true")}En.lastIndex=p.index+p[0].length;break;case"ifdef":case"ifndef":case"if":In.lastIndex=n.index;var _=In.exec(t),g=_[2],v=e.evaluate(g,i);a||(a=v.error);var y=v.result;"ifndef"===o&&(y=!y),r.push({anyKeep:y,keep:y,start:n.index,end:In.lastIndex}),En.lastIndex=_.index+_[0].length;break;case"endif":case"else":case"elif":Ln.lastIndex=n.index;var x=Ln.exec(t),S=r.pop(),b=S.keep?t.substring(S.end,n.index):"";t=t.substring(0,S.start)+b+t.substring(Ln.lastIndex),En.lastIndex=S.start+b.length;var w=x[1];if("else"===w||"elif"===w){var T=!1;if(!S.anyKeep)if("else"===w)T=!S.keep;else{var A=e.evaluate(x[2],i);T=A.result,a||(a=A.error)}r.push({anyKeep:S.anyKeep||T,keep:T,start:En.lastIndex,end:En.lastIndex})}}}return a?(console.warn("Failed to preprocess shader: ",{source:s}),s):t},e._keep=function(e){for(var t=0;t<e.length;t++)if(!e[t].keep)return!1;return!0},e.evaluate=function(e,t){var i=null===kn.exec(e),n=!1,s=On.exec(e);s&&(n="!"===s[1],e=s[2]),e=e.trim();var r=t.has(e);return n&&(r=!r),{result:r,error:!i}},e}(),Bn=0,Nn=function(){function e(e,t){this.meshUniformBufferFormat=void 0,this.meshBindGroupFormat=void 0,this.id=Bn++,this.device=e,this.definition=t,this.name=t.name||"Untitled",t.vshader=Fn.run(t.vshader),t.fshader=Fn.run(t.fshader,e.webgl2),this.init(),this.impl=e.createShaderImpl(this)}var t=e.prototype;return t.init=function(){this.ready=!1,this.failed=!1},t.destroy=function(){this.device.onDestroyShader(this),this.impl.destroy(this)},t.loseContext=function(){this.init(),this.impl.loseContext()},t.restoreContext=function(){this.impl.restoreContext(this.device,this)},Z(e,[{key:"label",get:function(){return"Shader Id "+this.id+" "+this.name}}]),e}(),Un=0,zn=function(){function e(e,t,i){this.renderVersionUpdated=-1,this.id=Un++,this.device=e,this.format=t,this.dirty=!0,this.impl=e.createBindGroupImpl(this),this.textures=[],this.uniformBuffers=[],this.defaultUniformBuffer=i,i&&this.setUniformBuffer(ai,i)}var t=e.prototype;return t.destroy=function(){this.impl.destroy(),this.impl=null,this.format=null,this.defaultUniformBuffer=null},t.setUniformBuffer=function(e,t){var i=this.format.bufferFormatsMap.get(e);this.uniformBuffers[i]!==t&&(this.uniformBuffers[i]=t,this.dirty=!0)},t.setTexture=function(e,t){var i=this.format.textureFormatsMap.get(e);this.textures[i]!==t?(this.textures[i]=t,this.dirty=!0):this.renderVersionUpdated<t.renderVersionDirty&&(this.dirty=!0)},t.update=function(){for(var e=this.format.textureFormats,t=0;t<e.length;t++){var i=e[t],n=i.scopeId.value;this.setTexture(i.name,n)}this.dirty&&(this.dirty=!1,this.renderVersionUpdated=this.device.renderVersion,this.impl.update(this))},e}(),Vn=[];Vn[2]=function(e,t,i){e.storageFloat32[i]=t},Vn[3]=function(e,t,i){var n=e.storageFloat32;n[i]=t[0],n[i+1]=t[1]},Vn[4]=function(e,t,i){var n=e.storageFloat32;n[i]=t[0],n[i+1]=t[1],n[i+2]=t[2]},Vn[5]=function(e,t,i){var n=e.storageFloat32;n[i]=t[0],n[i+1]=t[1],n[i+2]=t[2],n[i+3]=t[3]},Vn[1]=function(e,t,i){e.storageInt32[i]=t},Vn[6]=function(e,t,i){var n=e.storageInt32;n[i]=t[0],n[i+1]=t[1]},Vn[7]=function(e,t,i){var n=e.storageInt32;n[i]=t[0],n[i+1]=t[1],n[i+2]=t[2]},Vn[8]=function(e,t,i){var n=e.storageInt32;n[i]=t[0],n[i+1]=t[1],n[i+2]=t[2],n[i+3]=t[3]},Vn[12]=function(e,t,i){var n=e.storageFloat32;n[i]=t[0],n[i+1]=t[1],n[i+4]=t[2],n[i+5]=t[3],n[i+8]=t[4],n[i+9]=t[5]},Vn[13]=function(e,t,i){var n=e.storageFloat32;n[i]=t[0],n[i+1]=t[1],n[i+2]=t[2],n[i+4]=t[3],n[i+5]=t[4],n[i+6]=t[5],n[i+8]=t[6],n[i+9]=t[7],n[i+10]=t[8]},Vn[17]=function(e,t,i,n){for(var s=e.storageFloat32,r=0;r<n;r++)s[i+4*r]=t[r]},Vn[21]=function(e,t,i,n){for(var s=e.storageFloat32,r=0;r<n;r++)s[i+4*r]=t[2*r],s[i+4*r+1]=t[2*r+1]},Vn[22]=function(e,t,i,n){for(var s=e.storageFloat32,r=0;r<n;r++)s[i+4*r]=t[3*r],s[i+4*r+1]=t[3*r+1],s[i+4*r+2]=t[3*r+2]};var Gn=function(){function e(e,t){this.device=e,this.format=t,this.impl=e.createUniformBufferImpl(this),this.storage=new ArrayBuffer(t.byteSize),this.storageFloat32=new Float32Array(this.storage),this.storageInt32=new Int32Array(this.storage),e._vram.ub+=this.format.byteSize}var t=e.prototype;return t.destroy=function(){var e=this.device;this.impl.destroy(e),e._vram.ub-=this.format.byteSize},t.loseContext=function(){this.impl.loseContext()},t.setUniform=function(e){var t=e.offset,i=e.scopeId.value;if(null!=i){var n=Vn[e.updateType];n?n(this,i,t,e.count):this.storageFloat32.set(i,t)}},t.set=function(e){var t=this.format.map.get(e);t&&this.setUniform(t)},t.update=function(){for(var e=this.format.uniforms,t=0;t<e.length;t++)this.setUniform(e[t]);this.impl.unlock(this)},e}(),Hn={type:5,base:0,count:4,indexed:!1},Wn=function(){function e(e){var t="\n\n struct ub_mesh {\n color : vec4f,\n depth: f32\n }\n\n @group(0) @binding(0) var<uniform> ubMesh : ub_mesh;\n\n var<private> pos : array<vec2f, 4> = array<vec2f, 4>(\n vec2(-1.0, 1.0), vec2(1.0, 1.0),\n vec2(-1.0, -1.0), vec2(1.0, -1.0)\n );\n\n struct VertexOutput {\n @builtin(position) position : vec4f\n }\n\n @vertex\n fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput {\n var output : VertexOutput;\n output.position = vec4(pos[vertexIndex], ubMesh.depth, 1.0);\n return output;\n }\n\n @fragment\n fn fragmentMain() -> @location(0) vec4f {\n return ubMesh.color;\n }\n ";this.shader=new Nn(e,{name:"WebGPUClearRendererShader",shaderLanguage:ei,vshader:t,fshader:t}),this.uniformBuffer=new Gn(e,new sn(e,[new nn("color",5),new nn("depth",2)]));var i=new ln(e,[new on(ai,3)]);this.bindGroup=new zn(e,i,this.uniformBuffer),this.colorData=new Float32Array(4),this.colorId=e.scope.resolve("color"),this.depthId=e.scope.resolve("depth")}return e.prototype.clear=function(e,t,i,n){var s,r=null!=(s=(i=i||n).flags)?s:n.flags;if(0!==r){if(1&r&&t.colorBuffer){var a,o=null!=(a=i.color)?a:n.color;this.colorData.set(o),e.setBlendState(yi.NOBLEND)}else e.setBlendState(yi.NOWRITE);if(this.colorId.setValue(this.colorData),2&r&&t.depth){var h,l=null!=(h=i.depth)?h:n.depth;this.depthId.setValue(l),e.setDepthState(xi.WRITEDEPTH)}else this.depthId.setValue(1),e.setDepthState(xi.NODEPTH);4&r&&t.stencil,e.setCullMode(0),e.setShader(this.shader);var c=this.bindGroup;c.defaultUniformBuffer&&c.defaultUniformBuffer.update(),c.update(),e.setBindGroup(0,c),e.draw(Hn)}},e}(),Xn=function(){function e(e){this.device=void 0,this.device=e;var t=e.wgpu,i="\n \n var<private> pos : array<vec2f, 4> = array<vec2f, 4>(\n vec2(-1.0, 1.0), vec2(1.0, 1.0),\n vec2(-1.0, -1.0), vec2(1.0, -1.0)\n );\n\n struct VertexOutput {\n @builtin(position) position : vec4f,\n @location(0) texCoord : vec2f\n };\n\n @vertex\n fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput {\n var output : VertexOutput;\n output.texCoord = pos[vertexIndex] * vec2f(0.5, -0.5) + vec2f(0.5);\n output.position = vec4f(pos[vertexIndex], 0, 1);\n return output;\n }\n\n @group(0) @binding(0) var imgSampler : sampler;\n @group(0) @binding(1) var img : texture_2d<f32>;\n\n @fragment\n fn fragmentMain(@location(0) texCoord : vec2f) -> @location(0) vec4f {\n return textureSample(img, imgSampler, texCoord);\n }\n ";this.shader=new Nn(e,{name:"WebGPUMipmapRendererShader",shaderLanguage:ei,vshader:i,fshader:i}),this.minSampler=t.createSampler({minFilter:"linear"})}return e.prototype.generate=function(e){var t=e.descr;if(!(t.mipLevelCount<=1||e.texture.volume)){for(var i=this.device,n=i.wgpu,s=this.shader.impl,r=n.createRenderPipeline({layout:"auto",vertex:{module:s.getVertexShaderModule(),entryPoint:s.vertexEntryPoint},fragment:{module:s.getFragmentShaderModule(),entryPoint:s.fragmentEntryPoint,targets:[{format:t.format}]},primitive:{topology:"triangle-strip"}}),a=e.texture.cubemap?6:1,o=[],h=0;h<a;h++)o.push(e.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:h}));for(var l=n.createCommandEncoder(),c=1;c<t.mipLevelCount;c++)for(var u=0;u<a;u++){var d=e.createView({dimension:"2d",baseMipLevel:c,mipLevelCount:1,baseArrayLayer:u}),f=l.beginRenderPass({colorAttachments:[{view:d,loadOp:"clear",storeOp:"store"}]}),p=n.createBindGroup({layout:r.getBindGroupLayout(0),entries:[{binding:0,resource:this.minSampler},{binding:1,resource:o[u]}]});f.setPipeline(r),f.setBindGroup(0,p),f.draw(4),f.end(),o[u]=d}n.queue.submit([l.finish()]),i.pipeline=null}},e}(),jn=function(e){function t(t,i){var n;return void 0===i&&(i={}),(n=e.call(this,t,i)||this).frameBuffer=void 0,n.renderPipeline=new $i(ee(n)),n.clearRenderer=void 0,n.mipmapRenderer=void 0,n.pipeline=void 0,n.bindGroupFormats=[],n.commandEncoder=void 0,i=n.initOptions,n.isWebGPU=!0,n._deviceType=ri,n.samples=i.antialias?4:1,n.setupPassEncoderDefaults(),n}Q(t,e);var i,n=t.prototype;return n.destroy=function(){e.prototype.destroy.call(this)},n.initDeviceCaps=function(){this.disableParticleSystem=!0;var e=this.gpuAdapter.limits;this.precision="highp",this.maxPrecision="highp",this.maxSamples=4,this.maxTextures=16,this.maxTextureSize=e.maxTextureDimension2D,this.maxCubeMapSize=e.maxTextureDimension2D,this.maxVolumeSize=e.maxTextureDimension3D,this.maxColorAttachments=e.maxColorAttachments,this.maxPixelRatio=1,this.maxAnisotropy=16,this.supportsInstancing=!0,this.supportsUniformBuffers=!0,this.supportsVolumeTextures=!0,this.supportsBoneTextures=!0,this.supportsMorphTargetTexturesCore=!0,this.supportsAreaLights=!0,this.supportsDepthShadow=!0,this.supportsGpuParticles=!1,this.supportsMrt=!0,this.extUintElement=!0,this.extTextureFloat=!0,this.textureFloatRenderable=!0,this.extTextureHalfFloat=!0,this.textureHalfFloatRenderable=!0,this.textureHalfFloatUpdatable=!0,this.boneLimit=1024,this.supportsImageBitmap=!0,this.extStandardDerivatives=!0,this.extBlendMinmax=!0,this.areaLightLutFormat=this.floatFilterable?Ze:7,this.supportsTextureFetch=!0},n.initWebGpu=(i=Y(j().mark((function e(t,i){var n,s,r,a,o,h,l,c=this;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(window.navigator.gpu){e.next=2;break}throw new Error("Unable to retrieve GPU. Ensure you are using a browser that supports WebGPU rendering.");case 2:return n=function(e){return new Promise((function(t,i){var n=document.createElement("script");n.src=e,n.async=!1,n.onload=function(){t(e)},n.onerror=function(){i(new Error("Failed to download script "+e))},document.body.appendChild(n)}))},e.next=5,n(t);case 5:return e.next=7,n(i);case 7:return e.next=9,glslang();case 9:return this.glslang=e.sent,s=i.replace(".js",".wasm"),e.next=13,twgsl(s);case 13:return this.twgsl=e.sent,r={powerPreference:"default"!==this.initOptions.powerPreference?this.initOptions.powerPreference:void 0},e.next=17,window.navigator.gpu.requestAdapter(r);case 17:return this.gpuAdapter=e.sent,a=[],o=function(e){return!!c.gpuAdapter.features.has(e)&&(a.push(e),!0)},this.floatFilterable=o("float32-filterable"),this.extCompressedTextureS3TC=o("texture-compression-bc"),this.extCompressedTextureETC=o("texture-compression-etc2"),this.extCompressedTextureASTC=o("texture-compression-astc"),h={requiredFeatures:a,requiredLimits:{},defaultQueue:{label:"Default Queue"}},e.next=27,this.gpuAdapter.requestDevice(h);case 27:return this.wgpu=e.sent,this.initDeviceCaps(),this.setResolution(window.innerWidth,window.innerHeight),this.gpuContext=this.canvas.getContext("webgpu"),l=navigator.gpu.getPreferredCanvasFormat(),this.framebufferFormat="rgba8unorm"===l?7:31,this.canvasConfig={device:this.wgpu,colorSpace:"srgb",alphaMode:"opaque",format:l,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST,viewFormats:[]},this.gpuContext.configure(this.canvasConfig),this.createFramebuffer(),this.clearRenderer=new Wn(this),this.mipmapRenderer=new Xn(this),this.postInit(),e.abrupt("return",this);case 40:case"end":return e.stop()}}),e,this)}))),function(e,t){return i.apply(this,arguments)}),n.createFramebuffer=function(){this.supportsStencil=this.initOptions.stencil,this.frameBufferDimensions=new ge,this.frameBuffer=new Di({name:"WebgpuFramebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples})},n.resizeCanvas=function(e,t){this._width=e,this._height=t,this.canvas.width===e&&this.canvas.height===t||(this.canvas.width=e,this.canvas.height=t,this.fire(Ii.EVENT_RESIZE,e,t))},n.frameStart=function(){e.prototype.frameStart.call(this);var t=this.gpuContext.getCurrentTexture();this.frameBufferDimensions.x===t.width&&this.frameBufferDimensions.y===t.height||(this.frameBufferDimensions.set(t.width,t.height),this.frameBuffer.destroy(),this.frameBuffer=null,this.createFramebuffer());var i=this.frameBuffer,n=i.impl;n.setColorAttachment(0,void 0,t.format),this.initRenderTarget(i),n.assignColorTexture(t)},n.createUniformBufferImpl=function(e){return new An(e)},n.createVertexBufferImpl=function(e,t){return new Cn(e,t)},n.createIndexBufferImpl=function(e){return new zi(e)},n.createShaderImpl=function(e){return new yn(e)},n.createTextureImpl=function(e){return new Tn(e)},n.createRenderTargetImpl=function(e){return new Ji(e)},n.createBindGroupFormatImpl=function(e){return new Ni(e)},n.createBindGroupImpl=function(e){return new Oi},n.setBindGroup=function(e,t){this.passEncoder&&(this.passEncoder.setBindGroup(e,t.impl.bindGroup),this.bindGroupFormats[e]=t.format.impl)},n.submitVertexBuffer=function(e,t){for(var i=e.format.elements,n=i.length,s=e.impl.buffer,r=0;r<n;r++)this.passEncoder.setVertexBuffer(t+r,s,i[r].offset);return n},n.draw=function(e,t,i){if(void 0===t&&(t=1),this.shader.ready&&!this.shader.failed){var n=this.passEncoder,s=this.vertexBuffers[0],r=this.vertexBuffers[1];if(this.vertexBuffers.length=0,s){var a=this.submitVertexBuffer(s,0);r&&this.submitVertexBuffer(r,a)}var o=this.renderPipeline.get(e,null==s?void 0:s.format,null==r?void 0:r.format,this.shader,this.renderTarget,this.bindGroupFormats,this.blendState,this.depthState,this.cullMode,this.stencilEnabled,this.stencilFront,this.stencilBack);this.pipeline!==o&&(this.pipeline=o,n.setPipeline(o));var h=this.indexBuffer;h?(this.indexBuffer=null,n.setIndexBuffer(h.impl.buffer,h.impl.format),n.drawIndexed(e.count,t,0,0,0)):n.draw(e.count,t,0,0)}},n.setShader=function(e){return this.shader=e,!0},n.setBlendState=function(e){this.blendState.copy(e)},n.setDepthState=function(e){this.depthState.copy(e)},n.setStencilState=function(e,t){if(e||t){this.stencilEnabled=!0,this.stencilFront.copy(null!=e?e:Ri.DEFAULT),this.stencilBack.copy(null!=t?t:Ri.DEFAULT);var i=this.stencilFront.ref;this.stencilRef!==i&&(this.stencilRef=i,this.passEncoder.setStencilReference(i))}else this.stencilEnabled=!1},n.setBlendColor=function(e,t,i,n){},n.setCullMode=function(e){this.cullMode=e},n.setAlphaToCoverage=function(e){},n.initializeContextCaches=function(){e.prototype.initializeContextCaches.call(this)},n.setupPassEncoderDefaults=function(){this.stencilRef=0},n.startPass=function(e){var t=e.renderTarget||this.frameBuffer;this.renderTarget=t;var i=t.impl;t!==this.frameBuffer&&this.initRenderTarget(t),i.setupForRenderPass(e),this.commandEncoder=this.wgpu.createCommandEncoder(),this.pipeline=null,this.passEncoder=this.commandEncoder.beginRenderPass(i.renderPassDescriptor),this.setupPassEncoderDefaults();var n=t.width,s=t.height;this.setViewport(0,0,n,s),this.setScissor(0,0,n,s),this.insideRenderPass=!0},n.endPass=function(e){this.passEncoder.end(),this.passEncoder=null,this.wgpu.queue.submit([this.commandEncoder.finish()]),this.commandEncoder=null,this.bindGroupFormats.length=0,this.insideRenderPass=!1;for(var t=0;t<e.colorArrayOps.length;t++){e.colorArrayOps[t].mipmaps&&this.mipmapRenderer.generate(e.renderTarget._colorBuffers[t].impl)}},n.clear=function(e){e.flags&&this.clearRenderer.clear(this,this.renderTarget,e,this.defaultClearOptions)},n.setDepthBias=function(e){},n.setDepthBiasValues=function(e,t){},n.setViewport=function(e,t,i,n){this.passEncoder&&(this.renderTarget.flipY||(t=this.renderTarget.height-t-n),this.vx=e,this.vy=t,this.vw=i,this.vh=n,this.passEncoder.setViewport(e,t,i,n,0,1))},n.setScissor=function(e,t,i,n){this.passEncoder&&(this.renderTarget.flipY||(t=this.renderTarget.height-t-n),this.sx=e,this.sy=t,this.sw=i,this.sh=n,this.passEncoder.setScissorRect(e,t,i,n))},n.copyRenderTarget=function(e,t,i,n){var s,r={width:e?e.width:t.width,height:e?e.height:t.height,depthOrArrayLayers:1},a=null!=(s=this.commandEncoder)?s:this.wgpu.createCommandEncoder();if(i){var o={texture:e?e.colorBuffer.impl.gpuTexture:this.renderTarget.impl.assignedColorTexture,mipLevel:0},h={texture:t?t.colorBuffer.impl.gpuTexture:this.renderTarget.impl.assignedColorTexture,mipLevel:0};a.copyTextureToTexture(o,h,r)}if(n){var l={texture:(e||this.renderTarget).impl.depthTexture,mipLevel:0},c={texture:t?t.depthBuffer.impl.gpuTexture:this.renderTarget.impl.depthTexture,mipLevel:0};a.copyTextureToTexture(l,c,r)}return this.commandEncoder||this.wgpu.queue.submit([a.finish()]),!0},Z(t,[{key:"width",get:function(){return this._width}},{key:"height",get:function(){return this._height}}]),t}(Ii),qn=0,Yn=function(){function e(e,t){var i,n,s,r,a,o,h,l,c,u,d,f,p,m,_,g,v,y,x,S;(void 0===t&&(t={}),this.name=void 0,this._isRenderTarget=!1,this._gpuSize=0,this.id=qn++,this._invalid=!1,this._lockedLevel=-1,this.renderVersionDirty=0,this.device=e,this.name=null!=(i=t.name)?i:null,this._width=null!=(n=t.width)?n:4,this._height=null!=(s=t.height)?s:4,this._format=null!=(r=t.format)?r:7,this._compressed=ot(this._format),e.supportsVolumeTextures)?(this._volume=null!=(x=t.volume)&&x,this._depth=null!=(S=t.depth)?S:1):(this._volume=!1,this._depth=1);this._cubemap=null!=(a=t.cubemap)&&a,this.fixCubemapSeams=null!=(o=t.fixCubemapSeams)&&o,this._flipY=null!=(h=t.flipY)&&h,this._premultiplyAlpha=null!=(l=t.premultiplyAlpha)&&l,this._mipmaps=null==(c=null!=(u=t.mipmaps)?u:t.autoMipmap)||c,this._minFilter=null!=(d=t.minFilter)?d:5,this._magFilter=null!=(f=t.magFilter)?f:1,this._anisotropy=null!=(p=t.anisotropy)?p:1,this._addressU=null!=(m=t.addressU)?m:0,this._addressV=null!=(_=t.addressV)?_:0,this._addressW=null!=(g=t.addressW)?g:0,this._compareOnRead=null!=(v=t.compareOnRead)&&v,this._compareFunc=null!=(y=t.compareFunc)?y:1,this.type=Vt,t.hasOwnProperty("type")?this.type=t.type:t.hasOwnProperty("rgbm")?this.type=t.rgbm?Gt:Vt:t.hasOwnProperty("swizzleGGGR")&&(this.type=t.swizzleGGGR?Xt:Vt),this.projection=Zt,this._cubemap?this.projection=$t:t.projection&&t.projection!==$t&&(this.projection=t.projection),this.impl=e.createTextureImpl(this),this.dirtyAll(),this._levels=t.levels,this._levels?this.upload():this._levels=this._cubemap?[[null,null,null,null,null,null]]:[null],e.textures.push(this)}var t,i=e.prototype;return i.destroy=function(){if(this.device){var e=this.device,t=e.textures.indexOf(this);-1!==t&&e.textures.splice(t,1),e.scope.removeValue(this),this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this._gpuSize),this._levels=null,this.device=null}},i.loseContext=function(){this.impl.loseContext(),this.dirtyAll()},i.adjustVramSizeTracking=function(e,t){e.tex+=t},i.propertyChanged=function(e){this.impl.propertyChanged(e),this.renderVersionDirty=this.device.renderVersion},i.dirtyAll=function(){this._levelsUpdated=this._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0],this._needsUpload=!0,this._needsMipmapsUpload=this._mipmaps,this._mipmapsUploaded=!1,this.propertyChanged(255)},i.lock=function(e){void 0===e&&(e={}),void 0===e.level&&(e.level=0),void 0===e.face&&(e.face=0),void 0===e.mode&&(e.mode=2),this._lockedLevel=e.level;var t=this.cubemap?this._levels[e.face]:this._levels;if(null===t[e.level]){var i=Math.max(1,this._width>>e.level),n=Math.max(1,this._height>>e.level),s=new ArrayBuffer(xn.calcLevelGpuSize(i,n,this._format));t[e.level]=new(ht(this._format))(s)}return t[e.level]},i.setSource=function(e,t){void 0===t&&(t=0);var i,n,s=!1;if(this._cubemap){if(e[0]){i=e[0].width||0,n=e[0].height||0;for(var r=0;r<6;r++){var a=e[r];if(!a||a.width!==i||a.height!==n||!this.device._isBrowserInterface(a)){s=!0;break}}}else s=!0;if(!s)for(var o=0;o<6;o++)this._levels[t][o]!==e[o]&&(this._levelsUpdated[t][o]=!0)}else this.device._isBrowserInterface(e)||(s=!0),s||(e!==this._levels[t]&&(this._levelsUpdated[t]=!0),i=e.width,n=e.height);if(s)if(this._width=4,this._height=4,this._cubemap)for(var h=0;h<6;h++)this._levels[t][h]=null,this._levelsUpdated[t][h]=!0;else this._levels[t]=null,this._levelsUpdated[t]=!0;else 0===t&&(this._width=i,this._height=n),this._levels[t]=e;this._invalid===s&&s||(this._invalid=s,this.upload())},i.getSource=function(e){return void 0===e&&(e=0),this._levels[e]},i.unlock=function(){this._lockedLevel,this.upload(),this._lockedLevel=-1},i.upload=function(){var e,t;this._needsUpload=!0,this._needsMipmapsUpload=this._mipmaps,null==(e=(t=this.impl).uploadImmediate)||e.call(t,this.device,this)},i.downloadAsync=(t=Y(j().mark((function e(){var t,i,n,s=this;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=[],i=j().mark((function e(){var i,r,a,o;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=new Di({colorBuffer:s,depth:!1,face:n}),s.device.setRenderTarget(i),s.device.initRenderTarget(i),(r=s.cubemap?s._levels[n]:s._levels)[0],r[0]&&s.device._isBrowserInterface(r[0])&&(r[0]=null),a=s.lock({face:n}),o=null==s.device.readPixelsAsync?void 0:s.device.readPixelsAsync(0,0,s.width,s.height,a).then((function(){return i.destroy()})),t.push(o);case 9:case"end":return e.stop()}}),e)})),n=0;case 3:if(!(n<(this.cubemap?6:1))){e.next=8;break}return e.delegateYield(i(),"t0",5);case 5:n++,e.next=3;break;case 8:return e.next=10,Promise.all(t);case 10:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)}),i.getDds=function(){for(var e=128,t=0;this._levels[t];){if(this.cubemap)for(var i=0;i<6;i++){if(!this._levels[t][i])return;var n=this._levels[t][i].length;if(!n)return;e+=n}else{var s=this._levels[t].length;if(!s)return;e+=s}e+=this._levels[t].length,t++}var r=new ArrayBuffer(e),a=new Uint32Array(r,0,32),o=528391;this._levels.length>1&&(o|=131072);var h=4096;this._levels.length>1&&(h|=4194304),(this._levels.length>1||this.cubemap)&&(h|=8);var l=this.cubemap?65024:0;a[0]=542327876,a[1]=124,a[2]=o,a[3]=this.height,a[4]=this.width,a[5]=this.width*this.height*4,a[6]=0,a[7]=this._levels.length;for(var c=0;c<11;c++)a[8+c]=0;a[19]=32,a[20]=65,a[21]=0,a[22]=32,a[23]=16711680,a[24]=65280,a[25]=255,a[26]=4278190080,a[27]=h,a[28]=l,a[29]=0,a[30]=0,a[31]=0;var u=128;if(this.cubemap)for(var d=0;d<6;d++)for(var f=0;f<this._levels.length;f++){for(var p=this._levels[f][d],m=new Uint8Array(r,u,p.length),_=0;_<p.length;_++)m[_]=p[_];u+=p.length}else for(var g=0;g<this._levels.length;g++){for(var v=this._levels[g],y=new Uint8Array(r,u,v.length),x=0;x<v.length;x++)y[x]=v[x];u+=v.length}return r},Z(e,[{key:"requiredMipLevels",get:function(){return this.mipmaps?Math.floor(Math.log2(Math.max(this.width,this.height)))+1:1}},{key:"minFilter",get:function(){return this._minFilter},set:function(e){this._minFilter!==e&&(this._minFilter=e,this.propertyChanged(1))}},{key:"magFilter",get:function(){return this._magFilter},set:function(e){this._magFilter!==e&&(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.device.supportsVolumeTextures&&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._mipmaps=e,this.device.isWebGPU,e&&(this._needsMipmapsUpload=!0))}},{key:"width",get:function(){return this._width}},{key:"height",get:function(){return this._height}},{key:"depth",get:function(){return this._depth}},{key:"format",get:function(){return this._format}},{key:"cubemap",get:function(){return this._cubemap}},{key:"gpuSize",get:function(){var e=this.pot&&this._mipmaps&&!(this._compressed&&1===this._levels.length);return xn.calcGpuSize(this._width,this._height,this._depth,this._format,e,this._cubemap)}},{key:"volume",get:function(){return this._volume}},{key:"flipY",get:function(){return this._flipY},set:function(e){this._flipY!==e&&(this._flipY=e,this._needsUpload=!0)}},{key:"premultiplyAlpha",get:function(){return this._premultiplyAlpha},set:function(e){this._premultiplyAlpha!==e&&(this._premultiplyAlpha=e,this._needsUpload=!0)}},{key:"pot",get:function(){return ce.powerOfTwo(this._width)&&ce.powerOfTwo(this._height)}},{key:"encoding",get:function(){switch(this.type){case Gt:return"rgbm";case Ht:return"rgbe";case Wt:return"rgbp";default:return this.format===qe||this.format===Ke||this.format===Ye||this.format===Ze?"linear":"srgb"}}}]),e}(),Kn=function(){function e(){this.bufferId=null}var t=e.prototype;return t.destroy=function(e){this.bufferId&&(e.gl.deleteBuffer(this.bufferId),this.bufferId=null)},t.loseContext=function(){this.bufferId=null},t.unlock=function(e,t,i,n){var s,r=e.gl;switch(this.bufferId||(this.bufferId=r.createBuffer()),t){case 0:s=r.STATIC_DRAW;break;case 1:s=r.DYNAMIC_DRAW;break;case 2:s=r.STREAM_DRAW;break;case 3:s=e.webgl2?r.DYNAMIC_COPY:r.STATIC_DRAW}r.bindBuffer(i,this.bufferId),r.bufferData(i,n,s)},Z(e,[{key:"initialized",get:function(){return!!this.bufferId}}]),e}(),Zn=function(e){function t(){for(var t,i=arguments.length,n=new Array(i),s=0;s<i;s++)n[s]=arguments[s];return(t=e.call.apply(e,[this].concat(n))||this).vao=null,t}Q(t,e);var i=t.prototype;return i.destroy=function(t){e.prototype.destroy.call(this,t),t.boundVao=null,t.gl.bindVertexArray(null)},i.loseContext=function(){e.prototype.loseContext.call(this),this.vao=null},i.unlock=function(t){var i=t.device;e.prototype.unlock.call(this,i,t.usage,i.gl.ARRAY_BUFFER,t.storage)},t}(Kn),$n=function(e){function t(t){var i;i=e.call(this)||this;var n=t.device.gl,s=t.format;return 0===s?i.glFormat=n.UNSIGNED_BYTE:1===s?i.glFormat=n.UNSIGNED_SHORT:2===s&&(i.glFormat=n.UNSIGNED_INT),i}return Q(t,e),t.prototype.unlock=function(t){var i=t.device;e.prototype.unlock.call(this,i,t.usage,i.gl.ELEMENT_ARRAY_BUFFER,t.storage)},t}(Kn),Qn=function(e,t,i,n){if(this.locationId=n,this.scopeId=e.scope.resolve(t),this.version=new Si,"[0]"===t.substring(t.length-3))switch(i){case 2:i=17;break;case 3:i=21;break;case 4:i=22;break;case 5:i=23}this.dataType=i,this.value=[null,null,null,null],this.array=[]},Jn=function(){function e(){this._cache=new Map}var t=e.prototype;return t.get=function(e,t){var i=this;return this._cache.has(e)||(this._cache.set(e,t()),e.on("destroy",(function(){i.remove(e)})),e.on("devicelost",(function(){var t;null==(t=i._cache.get(e))||null==t.loseContext||t.loseContext(e)}))),this._cache.get(e)},t.remove=function(e){var t;null==(t=this._cache.get(e))||null==t.destroy||t.destroy(e),this._cache.delete(e)},e}(),es=["gl_VertexID","gl_InstanceID","gl_DrawID","gl_BaseVertex","gl_BaseInstance"],ts=function(){function e(){this.map=new Map}var t=e.prototype;return t.destroy=function(e){this.map.forEach((function(t){e.gl.deleteShader(t)}))},t.loseContext=function(e){this.map.clear()},e}(),is=function(){function e(){this.shaders=[]}return e.prototype.loseContext=function(e){this.shaders=[]},e}(),ns=new Jn,ss=new Jn,rs=new Jn,as=function(){function e(t){this.compileDuration=0,this.init(),this.compile(t.device,t),e.getBatchShaders(t.device).push(t),t.device.shaders.push(t)}var t=e.prototype;return t.destroy=function(e){this.glProgram&&(e.device.gl.deleteProgram(this.glProgram),this.glProgram=null)},t.init=function(){this.uniforms=[],this.samplers=[],this.attributes=[],this.glProgram=null,this.glVertexShader=null,this.glFragmentShader=null},e.getBatchShaders=function(e){return rs.get(e,(function(){return new is})).shaders},e.endShaderBatch=function(t){var i=e.getBatchShaders(t);i.forEach((function(e){return e.impl.link(t,e)})),i.length=0},t.loseContext=function(){this.init()},t.restoreContext=function(e,t){this.compile(e,t)},t.compile=function(e,t){var i=t.definition;this.glVertexShader=this._compileShaderSource(e,i.vshader,!0),this.glFragmentShader=this._compileShaderSource(e,i.fshader,!1)},t.link=function(e,t){if(!this.glProgram){var i=e.gl,n=i.createProgram();this.glProgram=n,i.attachShader(n,this.glVertexShader),i.attachShader(n,this.glFragmentShader);var s=t.definition,r=s.attributes;if(e.webgl2&&s.useTransformFeedback){var a=[];for(var o in r)r.hasOwnProperty(o)&&a.push("out_"+o);i.transformFeedbackVaryings(n,a,i.INTERLEAVED_ATTRIBS)}for(var h in r)if(r.hasOwnProperty(h)){var l=r[h],c=fi[l];i.bindAttribLocation(n,c,h)}i.linkProgram(n)}},t._compileShaderSource=function(e,t,i){var n=e.gl,s=(i?ns:ss).get(e,(function(){return new ts})),r=s.map.get(t);return r||(r=n.createShader(i?n.VERTEX_SHADER:n.FRAGMENT_SHADER),n.shaderSource(r,t),n.compileShader(r),s.map.set(t,r)),r},t.finalize=function(e,t){this.glProgram||this.link(e,t);var i=e.gl,n=this.glProgram,s=t.definition;if(!i.getProgramParameter(n,i.LINK_STATUS)){if(!this._isCompiled(e,t,this.glVertexShader,s.vshader,"vertex"))return!1;if(!this._isCompiled(e,t,this.glFragmentShader,s.fshader,"fragment"))return!1;var r="Failed to link shader program. Error: "+i.getProgramInfoLog(n);return console.error(r),!1}for(var a=0,o=i.getProgramParameter(n,i.ACTIVE_ATTRIBUTES);a<o;){var h=i.getActiveAttrib(n,a++),l=i.getAttribLocation(n,h.name);if(-1===es.indexOf(h.name)){void 0===s.attributes[h.name]&&(console.error('Vertex shader attribute "'+h.name+'" is not mapped to a semantic in shader definition, shader ['+t.label+"]",t),t.failed=!0);var c=new Qn(e,s.attributes[h.name],e.pcUniformType[h.type],l);this.attributes.push(c)}}a=0;for(var u=i.getProgramParameter(n,i.ACTIVE_UNIFORMS);a<u;){var d=i.getActiveUniform(n,a++),f=i.getUniformLocation(n,d.name),p=new Qn(e,d.name,e.pcUniformType[d.type],f);d.type===i.SAMPLER_2D||d.type===i.SAMPLER_CUBE||e.webgl2&&(d.type===i.SAMPLER_2D_SHADOW||d.type===i.SAMPLER_CUBE_SHADOW||d.type===i.SAMPLER_3D)?this.samplers.push(p):this.uniforms.push(p)}return t.ready=!0,!0},t._isCompiled=function(e,t,i,n,s){var r=e.gl;if(!r.getShaderParameter(i,r.COMPILE_STATUS)){var a=r.getShaderInfoLog(i),o=this._processError(n,a),h=o[0];o[1];var l="Failed to compile "+s+" shader:\n\n"+a+"\n"+h;return console.error(l),!1}return!0},t._processError=function(e,t){var i={},n="";if(e){var s=e.split("\n"),r=0,a=s.length;if(t&&t.startsWith("ERROR:")){var o=t.match(/^ERROR:\s([0-9]+):([0-9]+):\s*(.+)/);o&&(i.message=o[3],i.line=parseInt(o[2],10),r=Math.max(0,i.line-6),a=Math.min(s.length,i.line+5))}for(var h=r;h<a;h++)n+=h+1+":\t"+s[h]+"\n";i.source=e}return[n,i]},e}();function os(e,t){var i=e.width,n=e.height;if(i>t||n>t){var s=t/Math.max(i,n),r=Math.floor(i*s),a=Math.floor(n*s),o=document.createElement("canvas");return o.width=r,o.height=a,o.getContext("2d").drawImage(e,0,0,i,n,0,0,r,a),o}return e}var hs=function(){function e(){this._glTexture=null,this._glTarget=void 0,this._glFormat=void 0,this._glInternalFormat=void 0,this._glPixelType=void 0,this.dirtyParameterFlags=0}var t=e.prototype;return t.destroy=function(e){if(this._glTexture){for(var t=0;t<e.textureUnits.length;t++)for(var i=e.textureUnits[t],n=0;n<i.length;n++)i[n]===this._glTexture&&(i[n]=null);e.gl.deleteTexture(this._glTexture),this._glTexture=null}},t.loseContext=function(){this._glTexture=null},t.propertyChanged=function(e){this.dirtyParameterFlags|=e},t.initialize=function(e,t){var i=e.gl;switch(this._glTexture=i.createTexture(),this._glTarget=t._cubemap?i.TEXTURE_CUBE_MAP:t._volume?i.TEXTURE_3D:i.TEXTURE_2D,t._format){case 0:this._glFormat=i.ALPHA,this._glInternalFormat=i.ALPHA,this._glPixelType=i.UNSIGNED_BYTE;break;case 1:this._glFormat=i.LUMINANCE,this._glInternalFormat=i.LUMINANCE,this._glPixelType=i.UNSIGNED_BYTE;break;case 2:this._glFormat=i.LUMINANCE_ALPHA,this._glInternalFormat=i.LUMINANCE_ALPHA,this._glPixelType=i.UNSIGNED_BYTE;break;case 3:this._glFormat=i.RGB,this._glInternalFormat=i.RGB,this._glPixelType=i.UNSIGNED_SHORT_5_6_5;break;case 4:this._glFormat=i.RGBA,this._glInternalFormat=i.RGBA,this._glPixelType=i.UNSIGNED_SHORT_5_5_5_1;break;case 5:this._glFormat=i.RGBA,this._glInternalFormat=i.RGBA,this._glPixelType=i.UNSIGNED_SHORT_4_4_4_4;break;case 6:this._glFormat=i.RGB,this._glInternalFormat=e.webgl2?i.RGB8:i.RGB,this._glPixelType=i.UNSIGNED_BYTE;break;case 7:this._glFormat=i.RGBA,this._glInternalFormat=e.webgl2?i.RGBA8:i.RGBA,this._glPixelType=i.UNSIGNED_BYTE;break;case 8:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;break;case 9:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;break;case je:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;break;case tt:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTextureETC1.COMPRESSED_RGB_ETC1_WEBGL;break;case it:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTexturePVRTC.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;break;case nt:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTexturePVRTC.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;break;case st:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTexturePVRTC.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;break;case rt:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTexturePVRTC.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;break;case 22:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTextureETC.COMPRESSED_RGB8_ETC2;break;case 23:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTextureETC.COMPRESSED_RGBA8_ETC2_EAC;break;case 28:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTextureASTC.COMPRESSED_RGBA_ASTC_4x4_KHR;break;case 29:this._glFormat=i.RGB,this._glInternalFormat=e.extCompressedTextureATC.COMPRESSED_RGB_ATC_WEBGL;break;case 30:this._glFormat=i.RGBA,this._glInternalFormat=e.extCompressedTextureATC.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL;break;case qe:this._glFormat=i.RGB,e.webgl2?(this._glInternalFormat=i.RGB16F,this._glPixelType=i.HALF_FLOAT):(this._glInternalFormat=i.RGB,this._glPixelType=e.extTextureHalfFloat.HALF_FLOAT_OES);break;case Ye:this._glFormat=i.RGBA,e.webgl2?(this._glInternalFormat=i.RGBA16F,this._glPixelType=i.HALF_FLOAT):(this._glInternalFormat=i.RGBA,this._glPixelType=e.extTextureHalfFloat.HALF_FLOAT_OES);break;case Ke:this._glFormat=i.RGB,e.webgl2?this._glInternalFormat=i.RGB32F:this._glInternalFormat=i.RGB,this._glPixelType=i.FLOAT;break;case Ze:this._glFormat=i.RGBA,e.webgl2?this._glInternalFormat=i.RGBA32F:this._glInternalFormat=i.RGBA,this._glPixelType=i.FLOAT;break;case $e:this._glFormat=i.RED,this._glInternalFormat=i.R32F,this._glPixelType=i.FLOAT;break;case Qe:e.webgl2?(this._glFormat=i.DEPTH_COMPONENT,this._glInternalFormat=i.DEPTH_COMPONENT32F,this._glPixelType=i.FLOAT):(this._glFormat=i.DEPTH_COMPONENT,this._glInternalFormat=i.DEPTH_COMPONENT,this._glPixelType=i.UNSIGNED_SHORT);break;case Je:this._glFormat=i.DEPTH_STENCIL,e.webgl2?(this._glInternalFormat=i.DEPTH24_STENCIL8,this._glPixelType=i.UNSIGNED_INT_24_8):(this._glInternalFormat=i.DEPTH_STENCIL,this._glPixelType=e.extDepthTexture.UNSIGNED_INT_24_8_WEBGL);break;case et:this._glFormat=i.RGB,this._glInternalFormat=i.R11F_G11F_B10F,this._glPixelType=i.UNSIGNED_INT_10F_11F_11F_REV;break;case 19:this._glFormat=i.RGB,this._glInternalFormat=i.SRGB8,this._glPixelType=i.UNSIGNED_BYTE;break;case 20:this._glFormat=i.RGBA,this._glInternalFormat=i.SRGB8_ALPHA8,this._glPixelType=i.UNSIGNED_BYTE}},t.upload=function(e,t){var i=e.gl;if(t._needsUpload||!(t._needsMipmapsUpload&&t._mipmapsUploaded||!t.pot)){for(var n,s,r=0,a=t.requiredMipLevels;t._levels[r]||0===r;)if(t._needsUpload||0!==r){if(r&&(!t._needsMipmapsUpload||!t._mipmaps))break;if(n=t._levels[r],1===r&&!t._compressed&&t._levels.length<a&&(i.generateMipmap(this._glTarget),t._mipmapsUploaded=!0),t._cubemap){var o=void 0;if(e._isBrowserInterface(n[0])){for(o=0;o<6;o++)if(t._levelsUpdated[0][o]){var h=n[o];e._isImageBrowserInterface(h)&&(h.width>e.maxCubeMapSize||h.height>e.maxCubeMapSize)&&(h=os(h,e.maxCubeMapSize),0===r&&(t._width=h.width,t._height=h.height)),e.setUnpackFlipY(!1),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+o,r,this._glInternalFormat,this._glFormat,this._glPixelType,h)}}else for(s=1/Math.pow(2,r),o=0;o<6;o++)if(t._levelsUpdated[0][o]){var l=n[o];t._compressed?i.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+o,r,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),0,l):(e.setUnpackFlipY(!1),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+o,r,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),0,this._glFormat,this._glPixelType,l))}}else t._volume?(s=1/Math.pow(2,r),t._compressed?i.compressedTexImage3D(i.TEXTURE_3D,r,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),Math.max(t._depth*s,1),0,n):(e.setUnpackFlipY(!1),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),i.texImage3D(i.TEXTURE_3D,r,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),Math.max(t._depth*s,1),0,this._glFormat,this._glPixelType,n))):(e._isBrowserInterface(n)?(e._isImageBrowserInterface(n)&&(n.width>e.maxTextureSize||n.height>e.maxTextureSize)&&(n=os(n,e.maxTextureSize),0===r&&(t._width=n.width,t._height=n.height)),e.setUnpackFlipY(t._flipY),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),i.texImage2D(i.TEXTURE_2D,r,this._glInternalFormat,this._glFormat,this._glPixelType,n)):(s=1/Math.pow(2,r),t._compressed?i.compressedTexImage2D(i.TEXTURE_2D,r,this._glInternalFormat,Math.max(Math.floor(t._width*s),1),Math.max(Math.floor(t._height*s),1),0,n):(e.setUnpackFlipY(!1),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),i.texImage2D(i.TEXTURE_2D,r,this._glInternalFormat,Math.max(t._width*s,1),Math.max(t._height*s,1),0,this._glFormat,this._glPixelType,n))),t._mipmapsUploaded=0!==r);r++}else r++;if(t._needsUpload)if(t._cubemap)for(var c=0;c<6;c++)t._levelsUpdated[0][c]=!1;else t._levelsUpdated[0]=!1;!t._compressed&&t._mipmaps&&t._needsMipmapsUpload&&(t.pot||e.webgl2)&&1===t._levels.length&&(i.generateMipmap(this._glTarget),t._mipmapsUploaded=!0),t._gpuSize&&t.adjustVramSizeTracking(e._vram,-t._gpuSize),t._gpuSize=t.gpuSize,t.adjustVramSizeTracking(e._vram,t._gpuSize)}},e}(),ls=function(){function e(e,t){this.msaaFB=void 0,this.resolveFB=void 0,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}(),cs=function(){function e(){this._glFrameBuffer=null,this._glDepthBuffer=null,this._glResolveFrameBuffer=null,this.colorMrtFramebuffers=null,this._glMsaaColorBuffers=[],this._glMsaaDepthBuffer=null}var t=e.prototype;return t.destroy=function(e){var t,i=e.gl;this._glFrameBuffer&&(i.deleteFramebuffer(this._glFrameBuffer),this._glFrameBuffer=null),this._glDepthBuffer&&(i.deleteRenderbuffer(this._glDepthBuffer),this._glDepthBuffer=null),this._glResolveFrameBuffer&&(i.deleteFramebuffer(this._glResolveFrameBuffer),this._glResolveFrameBuffer=null),this._glMsaaColorBuffers.forEach((function(e){i.deleteRenderbuffer(e)})),this._glMsaaColorBuffers.length=0,null==(t=this.colorMrtFramebuffers)||t.forEach((function(e){e.destroy(i)})),this.colorMrtFramebuffers=null,this._glMsaaDepthBuffer&&(i.deleteRenderbuffer(this._glMsaaDepthBuffer),this._glMsaaDepthBuffer=null)},t.init=function(e,t){var i,n,s,r,a=e.gl;this._glFrameBuffer=a.createFramebuffer(),e.setFramebuffer(this._glFrameBuffer);for(var o=null!=(i=null==(n=t._colorBuffers)?void 0:n.length)?i:0,h=e.webgl2?a.COLOR_ATTACHMENT0:null!=(s=null==(r=e.extDrawBuffers)?void 0:r.COLOR_ATTACHMENT0_WEBGL)?s:a.COLOR_ATTACHMENT0,l=[],c=0;c<o;++c){var u=t.getColorBuffer(c);u&&(u.impl._glTexture||(u._width=Math.min(u.width,e.maxRenderBufferSize),u._height=Math.min(u.height,e.maxRenderBufferSize),e.setTexture(u,0)),a.framebufferTexture2D(a.FRAMEBUFFER,h+c,u._cubemap?a.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:a.TEXTURE_2D,u.impl._glTexture,0),l.push(h+c))}e.drawBuffers&&e.drawBuffers(l);var d=t._depthBuffer;if(d)d.impl._glTexture||(d._width=Math.min(d.width,e.maxRenderBufferSize),d._height=Math.min(d.height,e.maxRenderBufferSize),e.setTexture(d,0)),t._stencil?a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,d._cubemap?a.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:a.TEXTURE_2D,t._depthBuffer.impl._glTexture,0):a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,d._cubemap?a.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:a.TEXTURE_2D,t._depthBuffer.impl._glTexture,0);else if(t._depth){if(!(t._samples>1&&e.webgl2)){if(this._glDepthBuffer||(this._glDepthBuffer=a.createRenderbuffer()),a.bindRenderbuffer(a.RENDERBUFFER,this._glDepthBuffer),t._stencil)a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_STENCIL,t.width,t.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.RENDERBUFFER,this._glDepthBuffer);else{var f=e.webgl2?a.DEPTH_COMPONENT32F:a.DEPTH_COMPONENT16;a.renderbufferStorage(a.RENDERBUFFER,f,t.width,t.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.RENDERBUFFER,this._glDepthBuffer)}a.bindRenderbuffer(a.RENDERBUFFER,null)}}if(e.webgl2&&t._samples>1){var p,m;this._glResolveFrameBuffer=this._glFrameBuffer,this._glFrameBuffer=a.createFramebuffer(),e.setFramebuffer(this._glFrameBuffer);for(var _=null!=(p=null==(m=t._colorBuffers)?void 0:m.length)?p:0,g=0;g<_;++g){var v=t.getColorBuffer(g);if(v){var y=a.createRenderbuffer();this._glMsaaColorBuffers.push(y),a.bindRenderbuffer(a.RENDERBUFFER,y),a.renderbufferStorageMultisample(a.RENDERBUFFER,t._samples,v.impl._glInternalFormat,t.width,t.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0+g,a.RENDERBUFFER,y)}}t._depth&&(this._glMsaaDepthBuffer||(this._glMsaaDepthBuffer=a.createRenderbuffer()),a.bindRenderbuffer(a.RENDERBUFFER,this._glMsaaDepthBuffer),t._stencil?(a.renderbufferStorageMultisample(a.RENDERBUFFER,t._samples,a.DEPTH24_STENCIL8,t.width,t.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.RENDERBUFFER,this._glMsaaDepthBuffer)):(a.renderbufferStorageMultisample(a.RENDERBUFFER,t._samples,a.DEPTH_COMPONENT32F,t.width,t.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.RENDERBUFFER,this._glMsaaDepthBuffer))),_>1&&(this._createMsaaMrtFramebuffers(e,t,_),e.setFramebuffer(this._glFrameBuffer),e.drawBuffers(l))}},t._createMsaaMrtFramebuffers=function(e,t,i){var n=e.gl;this.colorMrtFramebuffers=[];for(var s=0;s<i;++s){var r=t.getColorBuffer(s),a=n.createFramebuffer();e.setFramebuffer(a);var o=this._glMsaaColorBuffers[s];n.bindRenderbuffer(n.RENDERBUFFER,o),n.renderbufferStorageMultisample(n.RENDERBUFFER,t._samples,r.impl._glInternalFormat,t.width,t.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.RENDERBUFFER,o),e.drawBuffers([n.COLOR_ATTACHMENT0]);var h=n.createFramebuffer();e.setFramebuffer(h),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,r._cubemap?n.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:n.TEXTURE_2D,r.impl._glTexture,0),this.colorMrtFramebuffers[s]=new ls(a,h)}},t._checkFbo=function(e,t,i){var n=e.gl;switch(n.checkFramebufferStatus(n.FRAMEBUFFER)){case n.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:case n.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:case n.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:case n.FRAMEBUFFER_UNSUPPORTED:}},t.loseContext=function(){this._glFrameBuffer=null,this._glDepthBuffer=null,this._glResolveFrameBuffer=null,this._glMsaaColorBuffers.length=0,this._glMsaaDepthBuffer=null,this.colorMrtFramebuffers=null},t.internalResolve=function(e,t,i,n,s){var r=e.gl;r.bindFramebuffer(r.READ_FRAMEBUFFER,t),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,i),r.blitFramebuffer(0,0,n.width,n.height,0,0,n.width,n.height,s,r.NEAREST)},t.resolve=function(e,t,i,n){if(e.webgl2){var s=e.gl;if(this.colorMrtFramebuffers){if(i)for(var r=0;r<this.colorMrtFramebuffers.length;r++){var a=this.colorMrtFramebuffers[r];this.internalResolve(e,a.msaaFB,a.resolveFB,t,s.COLOR_BUFFER_BIT)}n&&this.internalResolve(e,this._glFrameBuffer,this._glResolveFrameBuffer,t,s.DEPTH_BUFFER_BIT)}else this.internalResolve(e,this._glFrameBuffer,this._glResolveFrameBuffer,t,(i?s.COLOR_BUFFER_BIT:0)|(n?s.DEPTH_BUFFER_BIT:0));s.bindFramebuffer(s.FRAMEBUFFER,this._glFrameBuffer)}},Z(e,[{key:"initialized",get:function(){return null!==this._glFrameBuffer}}]),e}(),us="\n\n#define pcFragColor0 gl_FragData[0]\n\n#if COLOR_ATTACHMENT_1\n#define pcFragColor1 gl_FragData[1]\n#endif\n\n#if COLOR_ATTACHMENT_2\n#define pcFragColor2 gl_FragData[2]\n#endif\n\n#if COLOR_ATTACHMENT_3\n#define pcFragColor3 gl_FragData[3]\n#endif\n\n#if COLOR_ATTACHMENT_4\n#define pcFragColor4 gl_FragData[4]\n#endif\n\n#if COLOR_ATTACHMENT_5\n#define pcFragColor5 gl_FragData[5]\n#endif\n\n#if COLOR_ATTACHMENT_6\n#define pcFragColor6 gl_FragData[6]\n#endif\n\n#if COLOR_ATTACHMENT_7\n#define pcFragColor7 gl_FragData[7]\n#endif\n\n#define texture2DBias texture2D\n\n// pass / accept shadow map or texture as a function parameter, on webgl this is simply passed as is\n// but this is needed for WebGPU\n#define SHADOWMAP_PASS(name) name\n#define SHADOWMAP_ACCEPT(name) sampler2D name\n#define TEXTURE_PASS(name) name\n#define TEXTURE_ACCEPT(name) sampler2D name\n\n#ifndef SUPPORTS_TEXLOD\n\n // fallback for lod instructions\n #define texture2DLodEXT texture2D\n #define texture2DProjLodEXT textureProj\n #define textureCubeLodEXT textureCube\n #define textureShadow texture2D\n\n#else\n\n #define textureShadow(res, uv) texture2DGradEXT(res, uv, vec2(1, 1), vec2(1, 1))\n\n#endif\n\n#ifdef SUPPORTS_MRT\n #define gl_FragColor pcFragColor0\n#endif\n\n",ds="\nlayout(location = 0) out highp vec4 pc_fragColor;\n\n#ifndef REMOVE_COLOR_ATTACHMENT_1\n#if COLOR_ATTACHMENT_1\nlayout(location = 1) out highp vec4 pc_fragColor1;\n#endif\n#endif\n\n#ifndef REMOVE_COLOR_ATTACHMENT_2\n#if COLOR_ATTACHMENT_2\nlayout(location = 2) out highp vec4 pc_fragColor2;\n#endif\n#endif\n\n#ifndef REMOVE_COLOR_ATTACHMENT_3\n#if COLOR_ATTACHMENT_3\nlayout(location = 3) out highp vec4 pc_fragColor3;\n#endif\n#endif\n\n#ifndef REMOVE_COLOR_ATTACHMENT_4\n#if COLOR_ATTACHMENT_4\nlayout(location = 4) out highp vec4 pc_fragColor4;\n#endif\n#endif\n\n#ifndef REMOVE_COLOR_ATTACHMENT_5\n#if COLOR_ATTACHMENT_5\nlayout(location = 5) out highp vec4 pc_fragColor5;\n#endif\n#endif\n\n#ifndef REMOVE_COLOR_ATTACHMENT_6\n#if COLOR_ATTACHMENT_6\nlayout(location = 6) out highp vec4 pc_fragColor6;\n#endif\n#endif\n\n#ifndef REMOVE_COLOR_ATTACHMENT_7\n#if COLOR_ATTACHMENT_7\nlayout(location = 7) out highp vec4 pc_fragColor7;\n#endif\n#endif\n\n#define gl_FragColor pc_fragColor\n\n#define pcFragColor0 pc_fragColor\n#define pcFragColor1 pc_fragColor1\n#define pcFragColor2 pc_fragColor2\n#define pcFragColor3 pc_fragColor3\n#define pcFragColor4 pc_fragColor4\n#define pcFragColor5 pc_fragColor5\n#define pcFragColor6 pc_fragColor6\n#define pcFragColor7 pc_fragColor7\n\n#define varying in\n\n#define texture2D texture\n#define texture2DBias texture\n#define textureCube texture\n#define texture2DProj textureProj\n#define texture2DLodEXT textureLod\n#define texture2DProjLodEXT textureProjLod\n#define textureCubeLodEXT textureLod\n#define texture2DGradEXT textureGrad\n#define texture2DProjGradEXT textureProjGrad\n#define textureCubeGradEXT textureGrad\n\n// sample shadows using textureGrad to remove derivatives in the dynamic loops (which are used by\n// clustered lighting) - as DirectX shader compiler tries to unroll the loops and takes long time\n// to compile the shader. Using textureLod would be even better, but WebGl does not translate it to\n// lod instruction for DirectX correctly and uses SampleCmp instead of SampleCmpLevelZero or similar.\n#define textureShadow(res, uv) textureGrad(res, uv, vec2(1, 1), vec2(1, 1))\n\n// pass / accept shadow map or texture as a function parameter, on webgl this is simply passed as is\n// but this is needed for WebGPU\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\n#define GL2\n#define SUPPORTS_TEXLOD\n#define SUPPORTS_MRT\n",fs="\n#define attribute in\n#define varying out\n#define texture2D texture\n#define GL2\n#define VERTEXSHADER\n",ps="\n\n// texelFetch support and others\n#extension GL_EXT_samplerless_texture_functions : require\n\nlayout(location = 0) out highp vec4 pc_fragColor;\nlayout(location = 1) out highp vec4 pc_fragColor1;\nlayout(location = 2) out highp vec4 pc_fragColor2;\nlayout(location = 3) out highp vec4 pc_fragColor3;\nlayout(location = 4) out highp vec4 pc_fragColor4;\nlayout(location = 5) out highp vec4 pc_fragColor5;\nlayout(location = 6) out highp vec4 pc_fragColor6;\nlayout(location = 7) out highp vec4 pc_fragColor7;\n\n#define gl_FragColor pc_fragColor\n\n#define pcFragColor0 pc_fragColor\n#define pcFragColor1 pc_fragColor1\n#define pcFragColor2 pc_fragColor2\n#define pcFragColor3 pc_fragColor3\n#define pcFragColor4 pc_fragColor4\n#define pcFragColor5 pc_fragColor5\n#define pcFragColor6 pc_fragColor6\n#define pcFragColor7 pc_fragColor7\n\n#define texture2D(res, uv) texture(sampler2D(res, res ## _sampler), uv)\n#define texture2DBias(res, uv, bias) texture(sampler2D(res, res ## _sampler), uv, bias)\n#define texture2DLodEXT(res, uv, lod) textureLod(sampler2D(res, res ## _sampler), uv, lod)\n#define textureCube(res, uv) texture(samplerCube(res, res ## _sampler), uv)\n#define textureCubeLodEXT(res, uv, lod) textureLod(samplerCube(res, res ## _sampler), uv, lod)\n#define textureShadow(res, uv) textureLod(sampler2DShadow(res, res ## _sampler), uv, 0.0)\n\n// TODO: implement other texture sampling macros\n// #define texture2DProj textureProj\n// #define texture2DProjLodEXT textureProjLod\n// #define texture2DGradEXT textureGrad\n// #define texture2DProjGradEXT textureProjGrad\n// #define textureCubeGradEXT textureGrad\n\n// pass / accept shadow map as a function parameter, passes both the texture as well as sampler\n// as the combined sampler can be only created at a point of use\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\n#define GL2\n#define WEBGPU\n#define SUPPORTS_TEXLOD\n#define SUPPORTS_MRT\n",ms="\n\n// texelFetch support and others\n#extension GL_EXT_samplerless_texture_functions : require\n\n#define texture2D(res, uv) texture(sampler2D(res, res ## _sampler), uv)\n\n#define GL2\n#define WEBGPU\n#define VERTEXSHADER\n",_s="\n\n// convert clip space position into texture coordinates to sample scene grab textures\nvec2 getGrabScreenPos(vec4 clipPos) {\n vec2 uv = (clipPos.xy / clipPos.w) * 0.5 + 0.5;\n\n #ifdef WEBGPU\n uv.y = 1.0 - uv.y;\n #endif\n\n return uv;\n}\n\n// convert uv coordinates to sample image effect texture (render target texture rendered without\n// forward renderer which does the flip in the projection matrix)\nvec2 getImageEffectUV(vec2 uv) {\n #ifdef WEBGPU\n uv.y = 1.0 - uv.y;\n #endif\n\n return uv;\n}\n",gs={vertex_position:lt,vertex_normal:ct,vertex_tangent:ut,vertex_texCoord0:_t,vertex_texCoord1:gt,vertex_texCoord2:vt,vertex_texCoord3:yt,vertex_texCoord4:xt,vertex_texCoord5:St,vertex_texCoord6:bt,vertex_texCoord7:wt,vertex_color:pt,vertex_boneIndices:ft,vertex_boneWeights:dt},vs=function(){function e(){}return e.createDefinition=function(t,i){var n,s,r=function(n,s,r,a){for(var o=t.isWebGPU?n:t.webgl2?s:e.gl1Extensions(t,i)+r,h="",l=0;l<t.maxColorAttachments;l++)h+="#define COLOR_ATTACHMENT_"+l+"\n";return h+o},a=null!=(n=i.name)?n:"Untitled",o=i.vertexDefines||r(ms,fs,""),h=e.versionCode(t)+o+_s+e.getShaderNameCode(a)+i.vertexCode,l=i.fragmentDefines||r(ps,ds,us),c=(i.fragmentPreamble||"")+e.versionCode(t)+l+e.precisionCode(t)+"\n"+_s+e.getShaderNameCode(a)+(i.fragmentCode||e.dummyFragmentCode());return{name:a,attributes:null!=(s=i.attributes)?s:e.collectAttributes(i.vertexCode),vshader:h,fshader:c,useTransformFeedback:i.useTransformFeedback}},e.getShaderNameCode=function(e){return"#define SHADER_NAME "+e+"\n"},e.gl1Extensions=function(e,t,i){var n;return i?n=t.vertexExtensions?t.vertexExtensions+"\n":"":(n=t.fragmentExtensions?t.fragmentExtensions+"\n":"",e.extStandardDerivatives&&(n+="#extension GL_OES_standard_derivatives : enable\n"),e.extTextureLod&&(n+="#extension GL_EXT_shader_texture_lod : enable\n",n+="#define SUPPORTS_TEXLOD\n"),e.extDrawBuffers&&(n+="#extension GL_EXT_draw_buffers : require\n",n+="#define SUPPORTS_MRT\n")),n},e.dummyFragmentCode=function(){return"void main(void) {gl_FragColor = vec4(0.0);}"},e.versionCode=function(e){return e.isWebGPU?"#version 450\n":e.webgl2?"#version 300 es\n":""},e.precisionCode=function(e,t){var i="";t&&"highp"!==t&&"mediump"!==t&&"lowp"!==t&&(t=null),t&&("highp"===t&&"highp"!==e.maxPrecision&&(t="mediump"),"mediump"===t&&"lowp"===e.maxPrecision&&(t="lowp"));var n=t||e.precision;return e.isWebGPU?i="precision "+n+" float;\nprecision "+n+" int;\n":(i="precision "+n+" float;\n",e.webgl2&&(i+="precision "+n+" sampler2DShadow;\n")),i},e.collectAttributes=function(e){for(var t={},i=0,n=e.indexOf("attribute");n>=0&&!(n>0&&"/"===e[n-1]);){var s=e.indexOf(";",n),r=e.lastIndexOf(" ",s),a=e.substring(r+1,s),o=gs[a];void 0!==o?t[a]=o:(t[a]="ATTR"+i,i++),n=e.indexOf("attribute",n+1)}return t},e}(),ys=[],xs="\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";function Ss(e,t,i){var n=e.renderTarget;e.setRenderTarget(t),e.updateBegin(),e.setCullMode(0),e.setBlendState(yi.NOBLEND),e.setDepthState(xi.NODEPTH),e.setStencilState(null,null),e.setVertexBuffer(e.quadVertexBuffer,0),e.setShader(i),e.draw({type:5,base:0,count:4,indexed:!1}),e.updateEnd(),e.setRenderTarget(n),e.updateBegin()}function bs(e,t){var i=!0,n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,2,2,0,e.RGBA,t,null);var s=e.createFramebuffer();return e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0),e.checkFramebufferStatus(e.FRAMEBUFFER)!==e.FRAMEBUFFER_COMPLETE&&(i=!1),e.bindTexture(e.TEXTURE_2D,null),e.deleteTexture(n),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteFramebuffer(s),i}var ws=function(e){function t(t,i){var n;void 0===i&&(i={}),(n=e.call(this,t,i)||this).gl=void 0,n.webgl2=void 0,i=n.initOptions,n.defaultFramebuffer=null,n.updateClientRect(),n.contextLost=!1,n._contextLostHandler=function(e){e.preventDefault(),n.contextLost=!0,n.loseContext(),n.fire("devicelost")},n._contextRestoredHandler=function(){n.restoreContext(),n.contextLost=!1,n.fire("devicerestored")};var s="undefined"!=typeof navigator&&navigator.userAgent;n.forceDisableMultisampling=s&&s.includes("AppleWebKit")&&(s.includes("15.4")||s.includes("15_4")),n.forceDisableMultisampling&&(i.antialias=!1);var r=null;if(i.gl)r=i.gl;else for(var a=void 0===i.preferWebGl2||i.preferWebGl2?["webgl2","webgl","experimental-webgl"]:["webgl","experimental-webgl"],o=0;o<a.length&&!(r=t.getContext(a[o],i));o++);if(!r)throw new Error("WebGL not supported");n.gl=r,n.webgl2="undefined"!=typeof WebGL2RenderingContext&&r instanceof WebGL2RenderingContext,n._deviceType=n.webgl2?si:ni;var l=r.getParameter(r.ALPHA_BITS);n.framebufferFormat=l?7:6;var c,u,d,f,p,m="chrome"===M.browserName,_="safari"===M.browserName,g=M.browser&&-1!==navigator.appVersion.indexOf("Mac");n._tempEnableSafariTextureUnitWorkaround=_,n._tempMacChromeBlitFramebufferWorkaround=g&&m&&!i.alpha,n.webgl2||function(e){if(e.getSupportedExtensions){if(-1!=e.getSupportedExtensions().indexOf("OES_vertex_array_object"))return}else if(e.getExtension&&e.getExtension("OES_vertex_array_object"))return;if(e.getSupportedExtensions){var t=e.getSupportedExtensions;e.getSupportedExtensions=function(){var e=t.call(this)||[];return e.push("OES_vertex_array_object"),e}}var i=e.getExtension;e.getExtension=function(t){return"OES_vertex_array_object"==t?(e.__OESVertexArrayObject||(e.__OESVertexArrayObject=new h(e)),e.__OESVertexArrayObject):i?i.call(this,t):null}}(r),t.addEventListener("webglcontextlost",n._contextLostHandler,!1),t.addEventListener("webglcontextrestored",n._contextRestoredHandler,!1),n.initializeExtensions(),n.initializeCapabilities(),n.initializeRenderState(),n.initializeContextCaches(),n.supportsImageBitmap=!_&&"undefined"!=typeof ImageBitmap,n.glAddress=[r.REPEAT,r.CLAMP_TO_EDGE,r.MIRRORED_REPEAT],n.glBlendEquation=[r.FUNC_ADD,r.FUNC_SUBTRACT,r.FUNC_REVERSE_SUBTRACT,n.webgl2?r.MIN:n.extBlendMinmax?n.extBlendMinmax.MIN_EXT:r.FUNC_ADD,n.webgl2?r.MAX:n.extBlendMinmax?n.extBlendMinmax.MAX_EXT:r.FUNC_ADD],n.glBlendFunctionColor=[r.ZERO,r.ONE,r.SRC_COLOR,r.ONE_MINUS_SRC_COLOR,r.DST_COLOR,r.ONE_MINUS_DST_COLOR,r.SRC_ALPHA,r.SRC_ALPHA_SATURATE,r.ONE_MINUS_SRC_ALPHA,r.DST_ALPHA,r.ONE_MINUS_DST_ALPHA,r.CONSTANT_COLOR,r.ONE_MINUS_CONSTANT_COLOR],n.glBlendFunctionAlpha=[r.ZERO,r.ONE,r.SRC_COLOR,r.ONE_MINUS_SRC_COLOR,r.DST_COLOR,r.ONE_MINUS_DST_COLOR,r.SRC_ALPHA,r.SRC_ALPHA_SATURATE,r.ONE_MINUS_SRC_ALPHA,r.DST_ALPHA,r.ONE_MINUS_DST_ALPHA,r.CONSTANT_ALPHA,r.ONE_MINUS_CONSTANT_ALPHA],n.glComparison=[r.NEVER,r.LESS,r.EQUAL,r.LEQUAL,r.GREATER,r.NOTEQUAL,r.GEQUAL,r.ALWAYS],n.glStencilOp=[r.KEEP,r.ZERO,r.REPLACE,r.INCR,r.INCR_WRAP,r.DECR,r.DECR_WRAP,r.INVERT],n.glClearFlag=[0,r.COLOR_BUFFER_BIT,r.DEPTH_BUFFER_BIT,r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT,r.STENCIL_BUFFER_BIT,r.STENCIL_BUFFER_BIT|r.COLOR_BUFFER_BIT,r.STENCIL_BUFFER_BIT|r.DEPTH_BUFFER_BIT,r.STENCIL_BUFFER_BIT|r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT],n.glCull=[0,r.BACK,r.FRONT,r.FRONT_AND_BACK],n.glFilter=[r.NEAREST,r.LINEAR,r.NEAREST_MIPMAP_NEAREST,r.NEAREST_MIPMAP_LINEAR,r.LINEAR_MIPMAP_NEAREST,r.LINEAR_MIPMAP_LINEAR],n.glPrimitive=[r.POINTS,r.LINES,r.LINE_LOOP,r.LINE_STRIP,r.TRIANGLES,r.TRIANGLE_STRIP,r.TRIANGLE_FAN],n.glType=[r.BYTE,r.UNSIGNED_BYTE,r.SHORT,r.UNSIGNED_SHORT,r.INT,r.UNSIGNED_INT,r.FLOAT],n.pcUniformType={},n.pcUniformType[r.BOOL]=0,n.pcUniformType[r.INT]=1,n.pcUniformType[r.FLOAT]=2,n.pcUniformType[r.FLOAT_VEC2]=3,n.pcUniformType[r.FLOAT_VEC3]=4,n.pcUniformType[r.FLOAT_VEC4]=5,n.pcUniformType[r.INT_VEC2]=6,n.pcUniformType[r.INT_VEC3]=7,n.pcUniformType[r.INT_VEC4]=8,n.pcUniformType[r.BOOL_VEC2]=9,n.pcUniformType[r.BOOL_VEC3]=10,n.pcUniformType[r.BOOL_VEC4]=11,n.pcUniformType[r.FLOAT_MAT2]=12,n.pcUniformType[r.FLOAT_MAT3]=13,n.pcUniformType[r.FLOAT_MAT4]=ti,n.pcUniformType[r.SAMPLER_2D]=15,n.pcUniformType[r.SAMPLER_CUBE]=16,n.webgl2&&(n.pcUniformType[r.SAMPLER_2D_SHADOW]=18,n.pcUniformType[r.SAMPLER_CUBE_SHADOW]=19,n.pcUniformType[r.SAMPLER_3D]=20),n.targetToSlot={},n.targetToSlot[r.TEXTURE_2D]=0,n.targetToSlot[r.TEXTURE_CUBE_MAP]=1,n.targetToSlot[r.TEXTURE_3D]=2,n.commitFunction=[],n.commitFunction[0]=function(e,t){e.value!==t&&(r.uniform1i(e.locationId,t),e.value=t)},n.commitFunction[1]=n.commitFunction[0],n.commitFunction[2]=function(e,t){e.value!==t&&(r.uniform1f(e.locationId,t),e.value=t)},n.commitFunction[3]=function(e,t){p=e.value,c=t[0],u=t[1],p[0]===c&&p[1]===u||(r.uniform2fv(e.locationId,t),p[0]=c,p[1]=u)},n.commitFunction[4]=function(e,t){p=e.value,c=t[0],u=t[1],d=t[2],p[0]===c&&p[1]===u&&p[2]===d||(r.uniform3fv(e.locationId,t),p[0]=c,p[1]=u,p[2]=d)},n.commitFunction[5]=function(e,t){p=e.value,c=t[0],u=t[1],d=t[2],f=t[3],p[0]===c&&p[1]===u&&p[2]===d&&p[3]===f||(r.uniform4fv(e.locationId,t),p[0]=c,p[1]=u,p[2]=d,p[3]=f)},n.commitFunction[6]=function(e,t){p=e.value,c=t[0],u=t[1],p[0]===c&&p[1]===u||(r.uniform2iv(e.locationId,t),p[0]=c,p[1]=u)},n.commitFunction[9]=n.commitFunction[6],n.commitFunction[7]=function(e,t){p=e.value,c=t[0],u=t[1],d=t[2],p[0]===c&&p[1]===u&&p[2]===d||(r.uniform3iv(e.locationId,t),p[0]=c,p[1]=u,p[2]=d)},n.commitFunction[10]=n.commitFunction[7],n.commitFunction[8]=function(e,t){p=e.value,c=t[0],u=t[1],d=t[2],f=t[3],p[0]===c&&p[1]===u&&p[2]===d&&p[3]===f||(r.uniform4iv(e.locationId,t),p[0]=c,p[1]=u,p[2]=d,p[3]=f)},n.commitFunction[11]=n.commitFunction[8],n.commitFunction[12]=function(e,t){r.uniformMatrix2fv(e.locationId,!1,t)},n.commitFunction[13]=function(e,t){r.uniformMatrix3fv(e.locationId,!1,t)},n.commitFunction[14]=function(e,t){r.uniformMatrix4fv(e.locationId,!1,t)},n.commitFunction[17]=function(e,t){r.uniform1fv(e.locationId,t)},n.commitFunction[21]=function(e,t){r.uniform2fv(e.locationId,t)},n.commitFunction[22]=function(e,t){r.uniform3fv(e.locationId,t)},n.commitFunction[23]=function(e,t){r.uniform4fv(e.locationId,t)},n.supportsBoneTextures=n.extTextureFloat&&n.maxVertexTextures>0;var v=n.vertexUniformsCount;return v-=16,v-=8,v-=1,v-=16,n.boneLimit=Math.floor(v/3),n.boneLimit=Math.min(n.boneLimit,128),"Mali-450 MP"===n.unmaskedRenderer&&(n.boneLimit=34),n.constantTexSource=n.scope.resolve("source"),n.extTextureFloat?n.webgl2?n.textureFloatRenderable=!!n.extColorBufferFloat:n.textureFloatRenderable=bs(r,r.FLOAT):n.textureFloatRenderable=!1,n.extColorBufferHalfFloat?n.textureHalfFloatRenderable=!!n.extColorBufferHalfFloat:n.extTextureHalfFloat?n.webgl2?n.textureHalfFloatRenderable=!!n.extColorBufferFloat:n.textureHalfFloatRenderable=bs(r,n.extTextureHalfFloat.HALF_FLOAT_OES):n.textureHalfFloatRenderable=!1,n.supportsMorphTargetTexturesCore="highp"===n.maxPrecision&&n.maxVertexTextures>=2,n.supportsDepthShadow=n.webgl2,n._textureFloatHighPrecision=void 0,n._textureHalfFloatUpdatable=void 0,n.areaLightLutFormat=7,n.extTextureHalfFloat&&n.textureHalfFloatUpdatable&&n.extTextureHalfFloatLinear?n.areaLightLutFormat=Ye:n.extTextureFloat&&n.extTextureFloatLinear&&(n.areaLightLutFormat=Ze),n.postInit(),n}Q(t,e);var i,n=t.prototype;return n.destroy=function(){e.prototype.destroy.call(this);var t=this.gl;this.webgl2&&this.feedback&&t.deleteTransformFeedback(this.feedback),this.clearVertexArrayObjectCache(),this.canvas.removeEventListener("webglcontextlost",this._contextLostHandler,!1),this.canvas.removeEventListener("webglcontextrestored",this._contextRestoredHandler,!1),this._contextLostHandler=null,this._contextRestoredHandler=null,this.gl=null,e.prototype.postDestroy.call(this)},n.createVertexBufferImpl=function(e,t){return new Zn},n.createIndexBufferImpl=function(e){return new $n(e)},n.createShaderImpl=function(e){return new as(e)},n.createTextureImpl=function(e){return new hs},n.createRenderTargetImpl=function(e){return new cs},n.getPrecision=function(){var e=this.gl,t="highp";if(e.getShaderPrecisionFormat){var i=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT),n=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT),s=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT),r=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT),a=i.precision>0&&s.precision>0,o=n.precision>0&&r.precision>0;a||(t=o?"mediump":"lowp")}return t},n.getExtension=function(){for(var e=0;e<arguments.length;e++)if(-1!==this.supportedExtensions.indexOf(arguments[e]))return this.gl.getExtension(arguments[e]);return null},n.initializeExtensions=function(){var e=this.gl,t=e.getSupportedExtensions();if(this.supportedExtensions=t,this.webgl2)this.extBlendMinmax=!0,this.extDrawBuffers=!0,this.drawBuffers=e.drawBuffers.bind(e),this.extInstancing=!0,this.extStandardDerivatives=!0,this.extTextureFloat=!0,this.extTextureHalfFloat=!0,this.extTextureLod=!0,this.extUintElement=!0,this.extVertexArrayObject=!0,this.extColorBufferFloat=this.getExtension("EXT_color_buffer_float"),this.extDepthTexture=!0;else{var i;if(this.extBlendMinmax=this.getExtension("EXT_blend_minmax"),this.extDrawBuffers=this.getExtension("WEBGL_draw_buffers"),this.extInstancing=this.getExtension("ANGLE_instanced_arrays"),this.drawBuffers=null==(i=this.extDrawBuffers)?void 0:i.drawBuffersWEBGL.bind(this.extDrawBuffers),this.extInstancing){var n=this.extInstancing;e.drawArraysInstanced=n.drawArraysInstancedANGLE.bind(n),e.drawElementsInstanced=n.drawElementsInstancedANGLE.bind(n),e.vertexAttribDivisor=n.vertexAttribDivisorANGLE.bind(n)}if(this.extStandardDerivatives=this.getExtension("OES_standard_derivatives"),this.extTextureFloat=this.getExtension("OES_texture_float"),this.extTextureHalfFloat=this.getExtension("OES_texture_half_float"),this.extTextureLod=this.getExtension("EXT_shader_texture_lod"),this.extUintElement=this.getExtension("OES_element_index_uint"),this.extVertexArrayObject=this.getExtension("OES_vertex_array_object"),this.extVertexArrayObject){var s=this.extVertexArrayObject;e.createVertexArray=s.createVertexArrayOES.bind(s),e.deleteVertexArray=s.deleteVertexArrayOES.bind(s),e.isVertexArray=s.isVertexArrayOES.bind(s),e.bindVertexArray=s.bindVertexArrayOES.bind(s)}this.extColorBufferFloat=null,this.extDepthTexture=e.getExtension("WEBGL_depth_texture")}this.extDebugRendererInfo=this.getExtension("WEBGL_debug_renderer_info"),this.extTextureFloatLinear=this.getExtension("OES_texture_float_linear"),this.extTextureHalfFloatLinear=this.getExtension("OES_texture_half_float_linear"),this.extFloatBlend=this.getExtension("EXT_float_blend"),this.extTextureFilterAnisotropic=this.getExtension("EXT_texture_filter_anisotropic","WEBKIT_EXT_texture_filter_anisotropic"),this.extCompressedTextureETC1=this.getExtension("WEBGL_compressed_texture_etc1"),this.extCompressedTextureETC=this.getExtension("WEBGL_compressed_texture_etc"),this.extCompressedTexturePVRTC=this.getExtension("WEBGL_compressed_texture_pvrtc","WEBKIT_WEBGL_compressed_texture_pvrtc"),this.extCompressedTextureS3TC=this.getExtension("WEBGL_compressed_texture_s3tc","WEBKIT_WEBGL_compressed_texture_s3tc"),this.extCompressedTextureATC=this.getExtension("WEBGL_compressed_texture_atc"),this.extCompressedTextureASTC=this.getExtension("WEBGL_compressed_texture_astc"),this.extParallelShaderCompile=this.getExtension("KHR_parallel_shader_compile"),this.extColorBufferHalfFloat=this.getExtension("EXT_color_buffer_half_float")},n.initializeCapabilities=function(){var e,t=this.gl,i="undefined"!=typeof navigator?navigator.userAgent:"";this.maxPrecision=this.precision=this.getPrecision();var n=t.getContextAttributes();this.supportsMsaa=n.antialias,this.supportsStencil=n.stencil,this.supportsInstancing=!!this.extInstancing,this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE),this.maxCubeMapSize=t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),this.maxRenderBufferSize=t.getParameter(t.MAX_RENDERBUFFER_SIZE),this.maxTextures=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),this.maxCombinedTextures=t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS),this.maxVertexTextures=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS),this.vertexUniformsCount=t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),this.fragmentUniformsCount=t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),this.webgl2?(this.maxDrawBuffers=t.getParameter(t.MAX_DRAW_BUFFERS),this.maxColorAttachments=t.getParameter(t.MAX_COLOR_ATTACHMENTS),this.maxVolumeSize=t.getParameter(t.MAX_3D_TEXTURE_SIZE),this.supportsMrt=!0,this.supportsVolumeTextures=!0):(e=this.extDrawBuffers,this.supportsMrt=!!e,this.maxDrawBuffers=e?t.getParameter(e.MAX_DRAW_BUFFERS_WEBGL):1,this.maxColorAttachments=e?t.getParameter(e.MAX_COLOR_ATTACHMENTS_WEBGL):1,this.maxVolumeSize=1),e=this.extDebugRendererInfo,this.unmaskedRenderer=e?t.getParameter(e.UNMASKED_RENDERER_WEBGL):"",this.unmaskedVendor=e?t.getParameter(e.UNMASKED_VENDOR_WEBGL):"";this.supportsGpuParticles=!("ARM"===this.unmaskedVendor&&i.match(/SM-[a-zA-Z0-9]+/)||this.unmaskedRenderer.match(/\bMali-G52+/)),e=this.extTextureFilterAnisotropic,this.maxAnisotropy=e?t.getParameter(e.MAX_TEXTURE_MAX_ANISOTROPY_EXT):1,this.samples=t.getParameter(t.SAMPLES),this.maxSamples=this.webgl2&&!this.forceDisableMultisampling?t.getParameter(t.MAX_SAMPLES):1,this.supportsAreaLights=this.webgl2||!M.android,this.supportsTextureFetch=this.webgl2,this.maxTextures<=8&&(this.supportsAreaLights=!1)},n.initializeRenderState=function(){e.prototype.initializeRenderState.call(this);var t=this.gl;t.disable(t.BLEND),t.blendFunc(t.ONE,t.ZERO),t.blendEquation(t.FUNC_ADD),t.colorMask(!0,!0,!0,!0),this.blendColor=new ue(0,0,0,0),t.blendColor(0,0,0,0),t.enable(t.CULL_FACE),t.cullFace(t.BACK),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.depthMask(!0),this.stencil=!1,t.disable(t.STENCIL_TEST),this.stencilFuncFront=this.stencilFuncBack=7,this.stencilRefFront=this.stencilRefBack=0,this.stencilMaskFront=this.stencilMaskBack=255,t.stencilFunc(t.ALWAYS,0,255),this.stencilFailFront=this.stencilFailBack=0,this.stencilZfailFront=this.stencilZfailBack=0,this.stencilZpassFront=this.stencilZpassBack=0,this.stencilWriteMaskFront=255,this.stencilWriteMaskBack=255,t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.stencilMask(255),this.alphaToCoverage=!1,this.raster=!0,this.webgl2&&(t.disable(t.SAMPLE_ALPHA_TO_COVERAGE),t.disable(t.RASTERIZER_DISCARD)),this.depthBiasEnabled=!1,t.disable(t.POLYGON_OFFSET_FILL),this.clearDepth=1,t.clearDepth(1),this.clearColor=new ue(0,0,0,0),t.clearColor(0,0,0,0),this.clearStencil=0,t.clearStencil(0),this.webgl2?t.hint(t.FRAGMENT_SHADER_DERIVATIVE_HINT,t.NICEST):this.extStandardDerivatives&&t.hint(this.extStandardDerivatives.FRAGMENT_SHADER_DERIVATIVE_HINT_OES,t.NICEST),t.enable(t.SCISSOR_TEST),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,t.NONE),this.unpackFlipY=!1,t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),this.unpackPremultiplyAlpha=!1,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),t.pixelStorei(t.UNPACK_ALIGNMENT,1)},n.initializeContextCaches=function(){e.prototype.initializeContextCaches.call(this),this._vaoMap=new Map,this.boundVao=null,this.activeFramebuffer=null,this.feedback=null,this.transformFeedbackBuffer=null,this.textureUnit=0,this.textureUnits=[];for(var t=0;t<this.maxCombinedTextures;t++)this.textureUnits.push([null,null,null])},n.loseContext=function(){for(var e,t=ie(this.shaders);!(e=t()).done;){e.value.loseContext()}for(var i,n=ie(this.textures);!(i=n()).done;){i.value.loseContext()}for(var s,r=ie(this.buffers);!(s=r()).done;){s.value.loseContext()}for(var a,o=ie(this.targets);!(a=o()).done;){a.value.loseContext()}},n.restoreContext=function(){this.initializeExtensions(),this.initializeCapabilities(),this.initializeRenderState(),this.initializeContextCaches();for(var e,t=ie(this.shaders);!(e=t()).done;){e.value.restoreContext()}for(var i,n=ie(this.buffers);!(i=n()).done;){i.value.unlock()}},n.endShaderBatch=function(){as.endShaderBatch(this)},n.setViewport=function(e,t,i,n){this.vx===e&&this.vy===t&&this.vw===i&&this.vh===n||(this.gl.viewport(e,t,i,n),this.vx=e,this.vy=t,this.vw=i,this.vh=n)},n.setScissor=function(e,t,i,n){this.sx===e&&this.sy===t&&this.sw===i&&this.sh===n||(this.gl.scissor(e,t,i,n),this.sx=e,this.sy=t,this.sw=i,this.sh=n)},n.setFramebuffer=function(e){if(this.activeFramebuffer!==e){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,e),this.activeFramebuffer=e}},n.copyRenderTarget=function(e,t,i,n){var s=this.gl;if(!this.webgl2&&n)return!1;if(i)if(t){if(e){if(!e._colorBuffer||!t._colorBuffer)return!1;if(e._colorBuffer._format!==t._colorBuffer._format)return!1}}else if(!e._colorBuffer)return!1;if(n&&e&&!e._depth){if(!e._depthBuffer||!t._depthBuffer)return!1;if(e._depthBuffer._format!==t._depthBuffer._format)return!1}if(this.webgl2&&t){var r=this.renderTarget;this.renderTarget=t,this.updateBegin(),s.bindFramebuffer(s.READ_FRAMEBUFFER,e?e.impl._glFrameBuffer:null),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,t.impl._glFrameBuffer);var a=e?e.width:t.width,o=e?e.height:t.height;s.blitFramebuffer(0,0,a,o,0,0,a,o,(i?s.COLOR_BUFFER_BIT:0)|(n?s.DEPTH_BUFFER_BIT:0),s.NEAREST),this.renderTarget=r,s.bindFramebuffer(s.FRAMEBUFFER,r?r.impl._glFrameBuffer:null)}else{var h=this.getCopyShader();this.constantTexSource.setValue(e._colorBuffer),Ss(this,t,h)}return!0},n.getCopyShader=function(){return this._copyShader||(this._copyShader=new Nn(this,vs.createDefinition(this,{name:"outputTex2D",vertexCode:xs,fragmentCode:"\nvarying vec2 vUv0;\nuniform sampler2D source;\nvoid main(void) {\n gl_FragColor = texture2D(source, vUv0);\n}\n"}))),this._copyShader},n.startPass=function(e){this.setRenderTarget(e.renderTarget),this.updateBegin();var t=e.colorOps,i=e.depthStencilOps;if(null!=t&&t.clear||i.clearDepth||i.clearStencil){var n=e.renderTarget,s=n?n.width:this.width,r=n?n.height:this.height;this.setViewport(0,0,s,r),this.setScissor(0,0,s,r);var a=0,o={};null!=t&&t.clear&&(a|=1,o.color=[t.clearValue.r,t.clearValue.g,t.clearValue.b,t.clearValue.a]),i.clearDepth&&(a|=2,o.depth=i.clearDepthValue),i.clearStencil&&(a|=4,o.stencil=i.clearStencilValue),o.flags=a,this.clear(o)}this.insideRenderPass=!0},n.endPass=function(e){this.unbindVertexArray();var t=this.renderTarget,i=e.colorArrayOps.length;if(t){var n;if(this.webgl2){ys.length=0;for(var s=this.gl,r=0;r<i;r++){var a=e.colorArrayOps[r];a.store||a.resolve||ys.push(s.COLOR_ATTACHMENT0+r)}e.depthStencilOps.storeDepth||ys.push(s.DEPTH_ATTACHMENT),e.depthStencilOps.storeStencil||ys.push(s.STENCIL_ATTACHMENT),ys.length>0&&e.fullSizeClearRect&&s.invalidateFramebuffer(s.DRAW_FRAMEBUFFER,ys)}null!=(n=e.colorOps)&&n.resolve&&this.webgl2&&e.samples>1&&t.autoResolve&&t.resolve(!0,!1);for(var o=0;o<i;o++){if(e.colorArrayOps[o].mipmaps){var h=t._colorBuffers[o];h&&h.impl._glTexture&&h.mipmaps&&(h.pot||this.webgl2)&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(h),this.gl.generateMipmap(h.impl._glTarget))}}}this.insideRenderPass=!1},n.updateBegin=function(){if(this.boundVao=null,this._tempEnableSafariTextureUnitWorkaround)for(var e=0;e<this.textureUnits.length;++e)for(var t=0;t<3;++t)this.textureUnits[e][t]=null;var i=this.renderTarget;i?i.impl.initialized?this.setFramebuffer(i.impl._glFrameBuffer):this.initRenderTarget(i):this.setFramebuffer(this.defaultFramebuffer)},n.updateEnd=function(){this.unbindVertexArray();var e=this.renderTarget;if(e){this.webgl2&&e._samples>1&&e.autoResolve&&e.resolve();var t=e._colorBuffer;t&&t.impl._glTexture&&t.mipmaps&&(t.pot||this.webgl2)&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(t),this.gl.generateMipmap(t.impl._glTarget))}},n.setUnpackFlipY=function(e){if(this.unpackFlipY!==e){this.unpackFlipY=e;var t=this.gl;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,e)}},n.setUnpackPremultiplyAlpha=function(e){if(this.unpackPremultiplyAlpha!==e){this.unpackPremultiplyAlpha=e;var t=this.gl;t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e)}},n.activeTexture=function(e){this.textureUnit!==e&&(this.gl.activeTexture(this.gl.TEXTURE0+e),this.textureUnit=e)},n.bindTexture=function(e){var t=e.impl,i=t._glTarget,n=t._glTexture,s=this.textureUnit,r=this.targetToSlot[i];this.textureUnits[s][r]!==n&&(this.gl.bindTexture(i,n),this.textureUnits[s][r]=n)},n.bindTextureOnUnit=function(e,t){var i=e.impl,n=i._glTarget,s=i._glTexture,r=this.targetToSlot[n];this.textureUnits[t][r]!==s&&(this.activeTexture(t),this.gl.bindTexture(n,s),this.textureUnits[t][r]=s)},n.setTextureParameters=function(e){var t=this.gl,i=e.impl.dirtyParameterFlags,n=e.impl._glTarget;if(1&i){var s=e._minFilter;(!e.pot&&!this.webgl2||!e._mipmaps||e._compressed&&1===e._levels.length)&&(2===s||3===s?s=0:4!==s&&5!==s||(s=1)),t.texParameteri(n,t.TEXTURE_MIN_FILTER,this.glFilter[s])}if(2&i&&t.texParameteri(n,t.TEXTURE_MAG_FILTER,this.glFilter[e._magFilter]),4&i&&(this.webgl2?t.texParameteri(n,t.TEXTURE_WRAP_S,this.glAddress[e._addressU]):t.texParameteri(n,t.TEXTURE_WRAP_S,this.glAddress[e.pot?e._addressU:1])),8&i&&(this.webgl2?t.texParameteri(n,t.TEXTURE_WRAP_T,this.glAddress[e._addressV]):t.texParameteri(n,t.TEXTURE_WRAP_T,this.glAddress[e.pot?e._addressV:1])),16&i&&this.webgl2&&t.texParameteri(n,t.TEXTURE_WRAP_R,this.glAddress[e._addressW]),32&i&&this.webgl2&&t.texParameteri(n,t.TEXTURE_COMPARE_MODE,e._compareOnRead?t.COMPARE_REF_TO_TEXTURE:t.NONE),64&i&&this.webgl2&&t.texParameteri(n,t.TEXTURE_COMPARE_FUNC,this.glComparison[e._compareFunc]),128&i){var r=this.extTextureFilterAnisotropic;r&&t.texParameterf(n,r.TEXTURE_MAX_ANISOTROPY_EXT,ce.clamp(Math.round(e._anisotropy),1,this.maxAnisotropy))}},n.setTexture=function(e,t){var i=e.impl;i._glTexture||i.initialize(this,e),i.dirtyParameterFlags>0||e._needsUpload||e._needsMipmapsUpload?(this.activeTexture(t),this.bindTexture(e),i.dirtyParameterFlags&&(this.setTextureParameters(e),i.dirtyParameterFlags=0),(e._needsUpload||e._needsMipmapsUpload)&&(i.upload(this,e),e._needsUpload=!1,e._needsMipmapsUpload=!1)):this.bindTextureOnUnit(e,t)},n.createVertexArray=function(e){var t,i,n=e.length>1;if(n){t="";for(var s=0;s<e.length;s++){var r=e[s];t+=r.id+r.format.renderingHash}i=this._vaoMap.get(t)}if(!i){var a=this.gl;i=a.createVertexArray(),a.bindVertexArray(i),a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,null);for(var o=0;o<e.length;o++){var h=e[o];a.bindBuffer(a.ARRAY_BUFFER,h.impl.bufferId);for(var l=h.format.elements,c=0;c<l.length;c++){var u=l[c],d=fi[u.name];a.vertexAttribPointer(d,u.numComponents,this.glType[u.dataType],u.normalize,u.stride,u.offset),a.enableVertexAttribArray(d),h.format.instancing&&a.vertexAttribDivisor(d,1)}}a.bindVertexArray(null),a.bindBuffer(a.ARRAY_BUFFER,null),n&&this._vaoMap.set(t,i)}return i},n.unbindVertexArray=function(){this.boundVao&&(this.boundVao=null,this.gl.bindVertexArray(null))},n.setBuffers=function(){var e,t=this.gl;if(1===this.vertexBuffers.length){var i=this.vertexBuffers[0];i.impl.vao||(i.impl.vao=this.createVertexArray(this.vertexBuffers)),e=i.impl.vao}else e=this.createVertexArray(this.vertexBuffers);this.boundVao!==e&&(this.boundVao=e,t.bindVertexArray(e)),this.vertexBuffers.length=0;var n=this.indexBuffer?this.indexBuffer.impl.bufferId:null;t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n)},n.draw=function(e,t,i){var n,s,r,a,o,h,l,c,u=this.gl,d=this.shader;if(d){var f=d.impl.samplers,p=d.impl.uniforms;i||this.setBuffers();for(var m=0,_=0,g=f.length;_<g;_++){if(!(s=(n=f[_]).scopeId.value))return;if(s instanceof Yn)r=s,this.setTexture(r,m),n.slot!==m&&(u.uniform1i(n.locationId,m),n.slot=m),m++;else{n.array.length=0,a=s.length;for(var v=0;v<a;v++)r=s[v],this.setTexture(r,m),n.array[v]=m,m++;u.uniform1iv(n.locationId,n.array)}}for(var y=0,x=p.length;y<x;y++)h=(o=p[y]).scopeId,l=o.version,c=h.versionObject.version,l.globalId===c.globalId&&l.revision===c.revision||(l.globalId=c.globalId,l.revision=c.revision,null!==h.value&&this.commitFunction[o.dataType](o,h.value));this.webgl2&&this.transformFeedbackBuffer&&(u.bindBufferBase(u.TRANSFORM_FEEDBACK_BUFFER,0,this.transformFeedbackBuffer.impl.bufferId),u.beginTransformFeedback(u.POINTS));var S=this.glPrimitive[e.type],b=e.count;if(e.indexed){var w=this.indexBuffer,T=w.impl.glFormat,A=e.base*w.bytesPerIndex;t>0?u.drawElementsInstanced(S,b,T,A,t):u.drawElements(S,b,T,A)}else{var C=e.base;t>0?u.drawArraysInstanced(S,C,b,t):u.drawArrays(S,C,b)}this.webgl2&&this.transformFeedbackBuffer&&(u.endTransformFeedback(),u.bindBufferBase(u.TRANSFORM_FEEDBACK_BUFFER,0,null)),this._drawCallsPerFrame++}},n.clear=function(e){var t,i=this.defaultClearOptions,n=null!=(t=(e=e||i).flags)?t:i.flags;if(0!==n){var s=this.gl;if(1&n){var r,a=null!=(r=e.color)?r:i.color,o=a[0],h=a[1],l=a[2],c=a[3],u=this.clearColor;o===u.r&&h===u.g&&l===u.b&&c===u.a||(this.gl.clearColor(o,h,l,c),this.clearColor.set(o,h,l,c)),this.setBlendState(yi.NOBLEND)}if(2&n){var d,f=null!=(d=e.depth)?d:i.depth;f!==this.clearDepth&&(this.gl.clearDepth(f),this.clearDepth=f),this.setDepthState(xi.WRITEDEPTH)}if(4&n){var p,m=null!=(p=e.stencil)?p:i.stencil;m!==this.clearStencil&&(this.gl.clearStencil(m),this.clearStencil=m)}s.clear(this.glClearFlag[n])}},n.readPixels=function(e,t,i,n,s){var r=this.gl;r.readPixels(e,t,i,n,r.RGBA,r.UNSIGNED_BYTE,s)},n.readPixelsAsync=(i=Y(j().mark((function e(t,i,n,s,r){var a,o,h,l,c,u,d,f,p;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(l=this.gl,this.webgl2){e.next=3;break}return e.abrupt("return",this.readPixels(t,i,n,s,r));case 3:return c=function(e,t){var i=l.fenceSync(l.SYNC_GPU_COMMANDS_COMPLETE,0);return l.flush(),new Promise((function(n,s){!function r(){var a=l.clientWaitSync(i,e,0);a===l.WAIT_FAILED?(l.deleteSync(i),s(new Error("webgl clientWaitSync sync failed"))):a===l.TIMEOUT_EXPIRED?setTimeout(r,t):(l.deleteSync(i),n())}()}))},u=null==(a=this.renderTarget.colorBuffer)?void 0:a.impl,d=null!=(o=null==u?void 0:u._glFormat)?o:l.RGBA,f=null!=(h=null==u?void 0:u._glPixelType)?h:l.UNSIGNED_BYTE,p=l.createBuffer(),l.bindBuffer(l.PIXEL_PACK_BUFFER,p),l.bufferData(l.PIXEL_PACK_BUFFER,r.byteLength,l.STREAM_READ),l.readPixels(t,i,n,s,d,f,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),e.next=14,c(0,20);case 14:l.bindBuffer(l.PIXEL_PACK_BUFFER,p),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,r),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteBuffer(p);case 18:case"end":return e.stop()}}),e,this)}))),function(e,t,n,s,r){return i.apply(this,arguments)}),n.setAlphaToCoverage=function(e){this.webgl2&&this.alphaToCoverage!==e&&(this.alphaToCoverage=e,e?this.gl.enable(this.gl.SAMPLE_ALPHA_TO_COVERAGE):this.gl.disable(this.gl.SAMPLE_ALPHA_TO_COVERAGE))},n.setTransformFeedbackBuffer=function(e){if(this.transformFeedbackBuffer!==e&&(this.transformFeedbackBuffer=e,this.webgl2)){var t=this.gl;e?(this.feedback||(this.feedback=t.createTransformFeedback()),t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,this.feedback)):t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,null)}},n.setRaster=function(e){this.raster!==e&&(this.raster=e,this.webgl2&&(e?this.gl.disable(this.gl.RASTERIZER_DISCARD):this.gl.enable(this.gl.RASTERIZER_DISCARD)))},n.setDepthBias=function(e){this.depthBiasEnabled!==e&&(this.depthBiasEnabled=e,e?this.gl.enable(this.gl.POLYGON_OFFSET_FILL):this.gl.disable(this.gl.POLYGON_OFFSET_FILL))},n.setDepthBiasValues=function(e,t){this.gl.polygonOffset(t,e)},n.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}},n.setStencilFunc=function(e,t,i){this.stencilFuncFront===e&&this.stencilRefFront===t&&this.stencilMaskFront===i&&this.stencilFuncBack===e&&this.stencilRefBack===t&&this.stencilMaskBack===i||(this.gl.stencilFunc(this.glComparison[e],t,i),this.stencilFuncFront=this.stencilFuncBack=e,this.stencilRefFront=this.stencilRefBack=t,this.stencilMaskFront=this.stencilMaskBack=i)},n.setStencilFuncFront=function(e,t,i){if(this.stencilFuncFront!==e||this.stencilRefFront!==t||this.stencilMaskFront!==i){var n=this.gl;n.stencilFuncSeparate(n.FRONT,this.glComparison[e],t,i),this.stencilFuncFront=e,this.stencilRefFront=t,this.stencilMaskFront=i}},n.setStencilFuncBack=function(e,t,i){if(this.stencilFuncBack!==e||this.stencilRefBack!==t||this.stencilMaskBack!==i){var n=this.gl;n.stencilFuncSeparate(n.BACK,this.glComparison[e],t,i),this.stencilFuncBack=e,this.stencilRefBack=t,this.stencilMaskBack=i}},n.setStencilOperation=function(e,t,i,n){this.stencilFailFront===e&&this.stencilZfailFront===t&&this.stencilZpassFront===i&&this.stencilFailBack===e&&this.stencilZfailBack===t&&this.stencilZpassBack===i||(this.gl.stencilOp(this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[i]),this.stencilFailFront=this.stencilFailBack=e,this.stencilZfailFront=this.stencilZfailBack=t,this.stencilZpassFront=this.stencilZpassBack=i),this.stencilWriteMaskFront===n&&this.stencilWriteMaskBack===n||(this.gl.stencilMask(n),this.stencilWriteMaskFront=n,this.stencilWriteMaskBack=n)},n.setStencilOperationFront=function(e,t,i,n){this.stencilFailFront===e&&this.stencilZfailFront===t&&this.stencilZpassFront===i||(this.gl.stencilOpSeparate(this.gl.FRONT,this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[i]),this.stencilFailFront=e,this.stencilZfailFront=t,this.stencilZpassFront=i),this.stencilWriteMaskFront!==n&&(this.gl.stencilMaskSeparate(this.gl.FRONT,n),this.stencilWriteMaskFront=n)},n.setStencilOperationBack=function(e,t,i,n){this.stencilFailBack===e&&this.stencilZfailBack===t&&this.stencilZpassBack===i||(this.gl.stencilOpSeparate(this.gl.BACK,this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[i]),this.stencilFailBack=e,this.stencilZfailBack=t,this.stencilZpassBack=i),this.stencilWriteMaskBack!==n&&(this.gl.stencilMaskSeparate(this.gl.BACK,n),this.stencilWriteMaskBack=n)},n.setBlendState=function(e){var t=this.blendState;if(!t.equals(e)){var i=this.gl,n=e.blend,s=e.colorOp,r=e.alphaOp,a=e.colorSrcFactor,o=e.colorDstFactor,h=e.alphaSrcFactor,l=e.alphaDstFactor;if(t.blend!==n&&(n?i.enable(i.BLEND):i.disable(i.BLEND)),t.colorOp!==s||t.alphaOp!==r){var c=this.glBlendEquation;i.blendEquationSeparate(c[s],c[r])}t.colorSrcFactor===a&&t.colorDstFactor===o&&t.alphaSrcFactor===h&&t.alphaDstFactor===l||i.blendFuncSeparate(this.glBlendFunctionColor[a],this.glBlendFunctionColor[o],this.glBlendFunctionAlpha[h],this.glBlendFunctionAlpha[l]),t.allWrite!==e.allWrite&&this.gl.colorMask(e.redWrite,e.greenWrite,e.blueWrite,e.alphaWrite),t.copy(e)}},n.setBlendColor=function(e,t,i,n){var s=this.blendColor;e===s.r&&t===s.g&&i===s.b&&n===s.a||(this.gl.blendColor(e,t,i,n),s.set(e,t,i,n))},n.setStencilState=function(e,t){e||t?(this.setStencilTest(!0),e===t?(this.setStencilFunc(e.func,e.ref,e.readMask),this.setStencilOperation(e.fail,e.zfail,e.zpass,e.writeMask)):(null!=e||(e=Ri.DEFAULT),this.setStencilFuncFront(e.func,e.ref,e.readMask),this.setStencilOperationFront(e.fail,e.zfail,e.zpass,e.writeMask),null!=t||(t=Ri.DEFAULT),this.setStencilFuncBack(t.func,t.ref,t.readMask),this.setStencilOperationBack(t.fail,t.zfail,t.zpass,t.writeMask))):this.setStencilTest(!1)},n.setDepthState=function(e){var t=this.depthState;if(!t.equals(e)){var i=this.gl,n=e.write;t.write!==n&&i.depthMask(n);var s=e.func,r=e.test;!r&&n&&(r=!0,s=7),t.func!==s&&i.depthFunc(this.glComparison[s]),t.test!==r&&(r?i.enable(i.DEPTH_TEST):i.disable(i.DEPTH_TEST)),t.copy(e)}},n.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}},n.setShader=function(e){if(e!==this.shader){if(e.failed)return!1;if(!e.ready&&!e.impl.finalize(this,e))return e.failed=!0,!1;this.shader=e,this.gl.useProgram(e.impl.glProgram),this.attributesInvalidated=!0}return!0},n.getHdrFormat=function(e,t,i,n){var s=this.extTextureHalfFloat&&(!t||this.textureHalfFloatRenderable)&&(!i||this.textureHalfFloatUpdatable)&&(!n||this.extTextureHalfFloatLinear),r=this.extTextureFloat&&(!t||this.textureFloatRenderable)&&(!n||this.extTextureFloatLinear);return s&&r?e?Ze:Ye:s?Ye:r?Ze:null},n.clearVertexArrayObjectCache=function(){var e=this.gl;this._vaoMap.forEach((function(t,i,n){e.deleteVertexArray(t)})),this._vaoMap.clear()},n.resizeCanvas=function(e,t){this._width=e,this._height=t;var i=Math.min(this._maxPixelRatio,M.browser?window.devicePixelRatio:1);e=Math.floor(e*i),t=Math.floor(t*i),this.canvas.width===e&&this.canvas.height===t||(this.canvas.width=e,this.canvas.height=t,this.fire(Ii.EVENT_RESIZE,e,t))},Z(t,[{key:"extDisjointTimerQuery",get:function(){return this._extDisjointTimerQuery||this.webgl2&&(this._extDisjointTimerQuery=this.getExtension("EXT_disjoint_timer_query_webgl2","EXT_disjoint_timer_query")),this._extDisjointTimerQuery}},{key:"width",get:function(){return this.gl.drawingBufferWidth||this.canvas.width}},{key:"height",get:function(){return this.gl.drawingBufferHeight||this.canvas.height}},{key:"fullscreen",get:function(){return!!document.fullscreenElement},set:function(e){e?this.gl.canvas.requestFullscreen():document.exitFullscreen()}},{key:"textureFloatHighPrecision",get:function(){return void 0===this._textureFloatHighPrecision&&(this._textureFloatHighPrecision=function(e){if(!e.textureFloatRenderable)return!1;var t=new Nn(e,vs.createDefinition(e,{name:"ptest1",vertexCode:xs,fragmentCode:"\nvoid main(void) { \n gl_FragColor = vec4(2147483648.0);\n}\n"})),i=new Nn(e,vs.createDefinition(e,{name:"ptest2",vertexCode:xs,fragmentCode:"\nuniform sampler2D source;\nvec4 packFloat(float depth) {\n const vec4 bit_shift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);\n vec4 res = mod(depth * bit_shift * vec4(255), vec4(256) ) / vec4(255);\n res -= res.xxyz * bit_mask;\n return res;\n}\nvoid main(void) {\n float c = texture2D(source, vec2(0.0)).r;\n float diff = abs(c - 2147483648.0) / 2147483648.0;\n gl_FragColor = packFloat(diff);\n}\n"})),n={format:Ze,width:1,height:1,mipmaps:!1,minFilter:0,magFilter:0,name:"testFHP"},s=new Yn(e,n),r=new Di({colorBuffer:s,depth:!1});Ss(e,r,t),n.format=7;var a=new Yn(e,n),o=new Di({colorBuffer:a,depth:!1});e.constantTexSource.setValue(s),Ss(e,o,i);var h=e.activeFramebuffer;e.setFramebuffer(o.impl._glFrameBuffer);var l=new Uint8Array(4);e.readPixels(0,0,1,1,l),e.setFramebuffer(h);var c=l[0]/255/16777216+l[1]/255/65536+l[2]/255/256+l[3]/255;return s.destroy(),r.destroy(),a.destroy(),o.destroy(),t.destroy(),i.destroy(),0===c}(this)),this._textureFloatHighPrecision}},{key:"textureHalfFloatUpdatable",get:function(){return void 0===this._textureHalfFloatUpdatable&&(this.webgl2?this._textureHalfFloatUpdatable=!0:this._textureHalfFloatUpdatable=function(e,t){var i=!0,n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE);var s=new Uint16Array(16);return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,2,2,0,e.RGBA,t,s),e.getError()!==e.NO_ERROR&&(i=!1,console.log("Above error related to HALF_FLOAT_OES can be ignored, it was triggered by testing half float texture support")),e.bindTexture(e.TEXTURE_2D,null),e.deleteTexture(n),i}(this.gl,this.extTextureHalfFloat.HALF_FLOAT_OES)),this._textureHalfFloatUpdatable}}]),t}(Ii);var Ts=0,As=function(){function e(e,t,i,n,s){void 0===n&&(n=0),this.device=e,this.format=t,this.numIndices=i,this.usage=n,this.id=Ts++,this.impl=e.createIndexBufferImpl(this);var r=di[t];this.bytesPerIndex=r,this.numBytes=this.numIndices*r,s?this.setData(s):this.storage=new ArrayBuffer(this.numBytes),this.adjustVramSizeTracking(e._vram,this.numBytes),this.device.buffers.push(this)}var t=e.prototype;return t.destroy=function(){var e=this.device,t=e.buffers.indexOf(this);-1!==t&&e.buffers.splice(t,1),this.device.indexBuffer===this&&(this.device.indexBuffer=null),this.impl.initialized&&(this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this.storage.byteLength))},t.adjustVramSizeTracking=function(e,t){e.ib+=t},t.loseContext=function(){this.impl.loseContext()},t.getFormat=function(){return this.format},t.getNumIndices=function(){return this.numIndices},t.lock=function(){return this.storage},t.unlock=function(){this.impl.unlock(this)},t.setData=function(e){return e.byteLength===this.numBytes&&(this.storage=e,this.unlock(),!0)},t._lockTypedArray=function(){var e=this.lock();return 2===this.format?new Uint32Array(e):1===this.format?new Uint16Array(e):new Uint8Array(e)},t.writeData=function(e,t){var i=this._lockTypedArray();if(e.length>t)if(ArrayBuffer.isView(e))e=e.subarray(0,t),i.set(e);else for(var n=0;n<t;n++)i[n]=e[n];else i.set(e);this.unlock()},t.readData=function(e){var t=this._lockTypedArray(),i=this.numIndices;if(ArrayBuffer.isView(e))e.set(t);else{e.length=0;for(var n=0;n<i;n++)e[n]=t[n]}return i},e}(),Cs=function(){function e(e,t){void 0===t&&(t=3),this.device=e.device;var i=this.device.gl;this._inputBuffer=e,3===t&&e.usage!==t&&(i.bindBuffer(i.ARRAY_BUFFER,e.impl.bufferId),i.bufferData(i.ARRAY_BUFFER,e.storage,i.DYNAMIC_COPY)),this._outputBuffer=new Ei(e.device,e.format,e.numVertices,t,e.storage)}e.createShader=function(e,t,i){return new Nn(e,vs.createDefinition(e,{name:i,vertexCode:t,useTransformFeedback:!0}))};var t=e.prototype;return t.destroy=function(){this._outputBuffer.destroy()},t.process=function(e,t){void 0===t&&(t=!0);var i=this.device,n=i.getRenderTarget();if(i.setRenderTarget(null),i.updateBegin(),i.setVertexBuffer(this._inputBuffer,0),i.setRaster(!1),i.setTransformFeedbackBuffer(this._outputBuffer),i.setShader(e),i.draw({type:0,base:0,count:this._inputBuffer.numVertices,indexed:!1}),i.setTransformFeedbackBuffer(null),i.setRaster(!0),i.updateEnd(),i.setRenderTarget(n),t){var s=this._inputBuffer.impl.bufferId;this._inputBuffer.impl.bufferId=this._outputBuffer.impl.bufferId,this._outputBuffer.impl.bufferId=s,s=this._inputBuffer.impl.vao,this._inputBuffer.impl.vao=this._outputBuffer.impl.vao,this._outputBuffer.impl.vao=s}},Z(e,[{key:"inputBuffer",get:function(){return this._inputBuffer}},{key:"outputBuffer",get:function(){return this._outputBuffer}}]),e}();function Es(e){this.array[this.index]=e}function Ms(e,t){this.array[this.index]=e,this.array[this.index+1]=t}function Ps(e,t,i){this.array[this.index]=e,this.array[this.index+1]=t,this.array[this.index+2]=i}function Rs(e,t,i,n){this.array[this.index]=e,this.array[this.index+1]=t,this.array[this.index+2]=i,this.array[this.index+3]=n}function Is(e,t,i){this.array[e]=t[i]}function Ls(e,t,i){this.array[e]=t[i],this.array[e+1]=t[i+1]}function Ds(e,t,i){this.array[e]=t[i],this.array[e+1]=t[i+1],this.array[e+2]=t[i+2]}function Os(e,t,i){this.array[e]=t[i],this.array[e+1]=t[i+1],this.array[e+2]=t[i+2],this.array[e+3]=t[i+3]}function ks(e,t,i){t[i]=this.array[e]}function Fs(e,t,i){t[i]=this.array[e],t[i+1]=this.array[e+1]}function Bs(e,t,i){t[i]=this.array[e],t[i+1]=this.array[e+1],t[i+2]=this.array[e+2]}function Ns(e,t,i){t[i]=this.array[e],t[i+1]=this.array[e+1],t[i+2]=this.array[e+2],t[i+3]=this.array[e+3]}var Us=function(){function e(e,t,i){switch(this.index=0,this.numComponents=t.numComponents,i.interleaved?this.array=new hi[t.dataType](e,t.offset):this.array=new hi[t.dataType](e,t.offset,i.vertexCount*t.numComponents),this.stride=t.stride/this.array.constructor.BYTES_PER_ELEMENT,t.numComponents){case 1:this.set=Es,this.getToArray=ks,this.setFromArray=Is;break;case 2:this.set=Ms,this.getToArray=Fs,this.setFromArray=Ls;break;case 3:this.set=Ps,this.getToArray=Bs,this.setFromArray=Ds;break;case 4:this.set=Rs,this.getToArray=Ns,this.setFromArray=Os}}var t=e.prototype;return t.get=function(e){return this.array[this.index+e]},t.set=function(e,t,i,n){},t.getToArray=function(e,t,i){},t.setFromArray=function(e,t,i){},e}(),zs=function(){function e(e){this.vertexBuffer=e,this.vertexFormatSize=e.getFormat().size,this.buffer=this.vertexBuffer.lock(),this.accessors=[],this.element={};for(var t=this.vertexBuffer.getFormat(),i=0;i<t.elements.length;i++){var n=t.elements[i];this.accessors[i]=new Us(this.buffer,n,t),this.element[n.name]=this.accessors[i]}}var t=e.prototype;return t.next=function(e){void 0===e&&(e=1);for(var t=0,i=this.accessors,n=this.accessors.length;t<n;){var s=i[t++];s.index+=e*s.stride}},t.end=function(){this.vertexBuffer.unlock()},t.writeData=function(e,t,i){var n=this.element[e];if(n){i>this.vertexBuffer.numVertices&&(i=this.vertexBuffer.numVertices);var s=n.numComponents;if(this.vertexBuffer.getFormat().interleaved)for(var r=0,a=0;a<i;a++)n.setFromArray(r,t,a*s),r+=n.stride;else if(t.length>i*s){var o=i*s;if(ArrayBuffer.isView(t))t=t.subarray(0,o),n.array.set(t);else for(var h=0;h<o;h++)n.array[h]=t[h]}else n.array.set(t)}},t.readData=function(e,t){var i=this.element[e],n=0;if(i){var s;n=this.vertexBuffer.numVertices;var r=i.numComponents;if(this.vertexBuffer.getFormat().interleaved){Array.isArray(t)&&(t.length=0),i.index=0;var a=0;for(s=0;s<n;s++)i.getToArray(a,t,s*r),a+=i.stride}else if(ArrayBuffer.isView(t))t.set(i.array);else{t.length=0;var o=n*r;for(s=0;s<o;s++)t[s]=i.array[s]}}return n},e}(),Vs="mouse",Gs="keyboard",Hs="gamepad",Ws="mousedown",Xs="mousemove",js="mouseup",qs="mousewheel",Ys="gamepadconnected",Ks="gamepaddisconnected",Zs=function(e,t){t?(this.key=t.keyCode,this.element=t.target,this.event=t):(this.key=null,this.element=null,this.event=null)},$s=new Zs;function Qs(e){return $s.key=e.keyCode,$s.element=e.target,$s.event=e,$s}function Js(e){return"string"==typeof e?e.toUpperCase().charCodeAt(0):e}var er={9:"Tab",13:"Enter",16:"Shift",17:"Control",18:"Alt",27:"Escape",37:"Left",38:"Up",39:"Right",40:"Down",46:"Delete",91:"Win"},tr=function(e){function t(t,i){var n;return void 0===i&&(i={}),(n=e.call(this)||this)._element=null,n._keyDownHandler=n._handleKeyDown.bind(ee(n)),n._keyUpHandler=n._handleKeyUp.bind(ee(n)),n._keyPressHandler=n._handleKeyPress.bind(ee(n)),n._visibilityChangeHandler=n._handleVisibilityChange.bind(ee(n)),n._windowBlurHandler=n._handleWindowBlur.bind(ee(n)),n._keymap={},n._lastmap={},t&&n.attach(t),n.preventDefault=i.preventDefault||!1,n.stopPropagation=i.stopPropagation||!1,n}Q(t,e);var i=t.prototype;return i.attach=function(e){this._element&&this.detach(),this._element=e,this._element.addEventListener("keydown",this._keyDownHandler,!1),this._element.addEventListener("keypress",this._keyPressHandler,!1),this._element.addEventListener("keyup",this._keyUpHandler,!1),document.addEventListener("visibilitychange",this._visibilityChangeHandler,!1),window.addEventListener("blur",this._windowBlurHandler,!1)},i.detach=function(){this._element&&(this._element.removeEventListener("keydown",this._keyDownHandler),this._element.removeEventListener("keypress",this._keyPressHandler),this._element.removeEventListener("keyup",this._keyUpHandler),this._element=null,document.removeEventListener("visibilitychange",this._visibilityChangeHandler,!1),window.removeEventListener("blur",this._windowBlurHandler,!1))},i.toKeyIdentifier=function(e){e=Js(e);var t=er[e.toString()];if(t)return t;for(var i=e.toString(16).toUpperCase(),n=i.length,s=0;s<4-n;s++)i="0"+i;return"U+"+i},i._handleKeyDown=function(e){var t=e.keyCode||e.charCode;if(void 0!==t){var i=this.toKeyIdentifier(t);this._keymap[i]=!0,this.fire("keydown",Qs(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation()}},i._handleKeyUp=function(e){var t=e.keyCode||e.charCode;if(void 0!==t){var i=this.toKeyIdentifier(t);delete this._keymap[i],this.fire("keyup",Qs(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation()}},i._handleKeyPress=function(e){this.fire("keypress",Qs(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation()},i._handleVisibilityChange=function(){"hidden"===document.visibilityState&&this._handleWindowBlur()},i._handleWindowBlur=function(){this._keymap={},this._lastmap={}},i.update=function(){for(var e in this._lastmap)delete this._lastmap[e];for(var t in this._keymap)this._keymap.hasOwnProperty(t)&&(this._lastmap[t]=this._keymap[t])},i.isPressed=function(e){var t=Js(e),i=this.toKeyIdentifier(t);return!!this._keymap[i]},i.wasPressed=function(e){var t=Js(e),i=this.toKeyIdentifier(t);return!!this._keymap[i]&&!this._lastmap[i]},i.wasReleased=function(e){var t=Js(e),i=this.toKeyIdentifier(t);return!this._keymap[i]&&!!this._lastmap[i]},t}(p);function ir(){return!!(document.pointerLockElement||document.mozPointerLockElement||document.webkitPointerLockElement)}var nr=function e(t,i){var n={x:0,y:0};if(i){if(i instanceof e)throw Error("Expected MouseEvent");n=t._getTargetCoords(i)}else i={};if(n)this.x=n.x,this.y=n.y;else{if(!ir())return;this.x=0,this.y=0}this.wheelDelta=0,"wheel"===i.type&&(i.deltaY>0?this.wheelDelta=1:i.deltaY<0&&(this.wheelDelta=-1)),ir()?(this.dx=i.movementX||i.webkitMovementX||i.mozMovementX||0,this.dy=i.movementY||i.webkitMovementY||i.mozMovementY||0):(this.dx=this.x-t._lastX,this.dy=this.y-t._lastY),"mousedown"===i.type||"mouseup"===i.type?this.button=i.button:this.button=-1,this.buttons=t._buttons.slice(0),this.element=i.target,this.ctrlKey=i.ctrlKey||!1,this.altKey=i.altKey||!1,this.shiftKey=i.shiftKey||!1,this.metaKey=i.metaKey||!1,this.event=i},sr=function(e){function t(t){var i;return(i=e.call(this)||this)._lastX=0,i._lastY=0,i._buttons=[!1,!1,!1],i._lastbuttons=[!1,!1,!1],i._upHandler=i._handleUp.bind(ee(i)),i._downHandler=i._handleDown.bind(ee(i)),i._moveHandler=i._handleMove.bind(ee(i)),i._wheelHandler=i._handleWheel.bind(ee(i)),i._contextMenuHandler=function(e){e.preventDefault()},i._target=null,i._attached=!1,i.attach(t),i}Q(t,e),t.isPointerLocked=function(){return ir()};var i=t.prototype;return i.attach=function(e){if(this._target=e,!this._attached){this._attached=!0;var t=!!M.passiveEvents&&{passive:!1};window.addEventListener("mouseup",this._upHandler,t),window.addEventListener("mousedown",this._downHandler,t),window.addEventListener("mousemove",this._moveHandler,t),window.addEventListener("wheel",this._wheelHandler,t)}},i.detach=function(){if(this._attached){this._attached=!1,this._target=null;var e=!!M.passiveEvents&&{passive:!1};window.removeEventListener("mouseup",this._upHandler,e),window.removeEventListener("mousedown",this._downHandler,e),window.removeEventListener("mousemove",this._moveHandler,e),window.removeEventListener("wheel",this._wheelHandler,e)}},i.disableContextMenu=function(){this._target&&this._target.addEventListener("contextmenu",this._contextMenuHandler)},i.enableContextMenu=function(){this._target&&this._target.removeEventListener("contextmenu",this._contextMenuHandler)},i.enablePointerLock=function(e,t){if(document.body.requestPointerLock){e&&document.addEventListener("pointerlockchange",(function t(){e(),document.removeEventListener("pointerlockchange",t)}),!1),t&&document.addEventListener("pointerlockerror",(function e(){t(),document.removeEventListener("pointerlockerror",e)}),!1),document.body.requestPointerLock()}else t&&t()},i.disablePointerLock=function(e){if(document.exitPointerLock){e&&document.addEventListener("pointerlockchange",(function t(){e(),document.removeEventListener("pointerlockchange",t)}),!1),document.exitPointerLock()}},i.update=function(){this._lastbuttons[0]=this._buttons[0],this._lastbuttons[1]=this._buttons[1],this._lastbuttons[2]=this._buttons[2]},i.isPressed=function(e){return this._buttons[e]},i.wasPressed=function(e){return this._buttons[e]&&!this._lastbuttons[e]},i.wasReleased=function(e){return!this._buttons[e]&&this._lastbuttons[e]},i._handleUp=function(e){this._buttons[e.button]=!1;var t=new nr(this,e);t.event&&this.fire(js,t)},i._handleDown=function(e){this._buttons[e.button]=!0;var t=new nr(this,e);t.event&&this.fire(Ws,t)},i._handleMove=function(e){var t=new nr(this,e);t.event&&(this.fire(Xs,t),this._lastX=t.x,this._lastY=t.y)},i._handleWheel=function(e){var t=new nr(this,e);t.event&&this.fire(qs,t)},i._getTargetCoords=function(e){var t=this._target.getBoundingClientRect(),i=Math.floor(t.left),n=Math.floor(t.top);return e.clientX<i||e.clientX>=i+this._target.clientWidth||e.clientY<n||e.clientY>=n+this._target.clientHeight?null:{x:e.clientX-i,y:e.clientY-n}},t}(p),rr=function(){function e(e,t){void 0===t&&(t={}),this._keyboard=t.keyboard||null,this._mouse=t.mouse||null,this._gamepads=t.gamepads||null,this._element=null,this._actions={},this._axes={},this._axesValues={},e&&this.attach(e)}var t=e.prototype;return t.attach=function(e){this._element=e,this._keyboard&&this._keyboard.attach(e),this._mouse&&this._mouse.attach(e)},t.detach=function(){this._keyboard&&this._keyboard.detach(),this._mouse&&this._mouse.detach(),this._element=null},t.disableContextMenu=function(){this._mouse||this._enableMouse(),this._mouse.disableContextMenu()},t.enableContextMenu=function(){this._mouse||this._enableMouse(),this._mouse.enableContextMenu()},t.update=function(e){for(var t in this._keyboard&&this._keyboard.update(),this._mouse&&this._mouse.update(),this._gamepads&&this._gamepads.update(),this._axesValues={},this._axes)this._axesValues[t]=[]},t.appendAction=function(e,t){this._actions[e]=this._actions[e]||[],this._actions[e].push(t)},t.registerKeys=function(e,t){if(this._keyboard||this._enableKeyboard(),this._actions[e])throw new Error("Action: "+e+" already registered");if(void 0===t)throw new Error("Invalid button");t.length||(t=[t]),this.appendAction(e,{type:Gs,keys:t})},t.registerMouse=function(e,t){if(this._mouse||this._enableMouse(),void 0===t)throw new Error("Invalid button");this.appendAction(e,{type:Vs,button:t})},t.registerPadButton=function(e,t,i){if(void 0===i)throw new Error("Invalid button");this.appendAction(e,{type:Hs,button:i,pad:t})},t.registerAxis=function(e){var t=e.name;this._axes[t]||(this._axes[t]=[]);var i=this._axes[t].push(t);(e=e||{}).pad=e.pad||0;var n=function(n,s,r,a){switch(s){case"mousex":n._mouse.on(Xs,(function(e){n._axesValues[t][i]=e.dx/10}));break;case"mousey":n._mouse.on(Xs,(function(e){n._axesValues[t][i]=e.dy/10}));break;case"key":n._axes[t].push((function(){return n._keyboard.isPressed(a)?r:0}));break;case"padrx":n._axes[t].push((function(){return n._gamepads.getAxis(e.pad,2)}));break;case"padry":n._axes[t].push((function(){return n._gamepads.getAxis(e.pad,3)}));break;case"padlx":n._axes[t].push((function(){return n._gamepads.getAxis(e.pad,0)}));break;case"padly":n._axes[t].push((function(){return n._gamepads.getAxis(e.pad,1)}));break;default:throw new Error("Unknown axis")}};n(this,e.positive,1,e.positiveKey),(e.negativeKey||e.negative!==e.positive)&&n(this,e.negative,-1,e.negativeKey)},t.isPressed=function(e){if(!this._actions[e])return!1;for(var t=this._actions[e].length,i=0;i<t;++i){var n=this._actions[e][i];switch(n.type){case Gs:if(this._keyboard)for(var s=n.keys.length,r=0;r<s;r++)if(this._keyboard.isPressed(n.keys[r]))return!0;break;case Vs:if(this._mouse&&this._mouse.isPressed(n.button))return!0;break;case Hs:if(this._gamepads&&this._gamepads.isPressed(n.pad,n.button))return!0}}return!1},t.wasPressed=function(e){if(!this._actions[e])return!1;for(var t=this._actions[e].length,i=0;i<t;++i){var n=this._actions[e][i];switch(n.type){case Gs:if(this._keyboard)for(var s=n.keys.length,r=0;r<s;r++)if(this._keyboard.wasPressed(n.keys[r]))return!0;break;case Vs:if(this._mouse&&this._mouse.wasPressed(n.button))return!0;break;case Hs:if(this._gamepads&&this._gamepads.wasPressed(n.pad,n.button))return!0}}return!1},t.getAxis=function(e){var t=0;if(this._axes[e])for(var i=this._axes[e].length,n=0;n<i;n++)if("function"===d(this._axes[e][n])){var s=this._axes[e][n]();Math.abs(s)>Math.abs(t)&&(t=s)}else this._axesValues[e]&&Math.abs(this._axesValues[e][n])>Math.abs(t)&&(t=this._axesValues[e][n]);return t},t._enableMouse=function(){if(this._mouse=new sr,!this._element)throw new Error("Controller must be attached to an Element");this._mouse.attach(this._element)},t._enableKeyboard=function(){if(this._keyboard=new tr,!this._element)throw new Error("Controller must be attached to an Element");this._keyboard.attach(this._element)},e}(),ar=Object.freeze([]),or=function(){return ar};"undefined"!=typeof navigator&&(or=(navigator.getGamepads||navigator.webkitGetGamepads||or).bind(navigator));var hr={buttons:{PAD_FACE_1:0,PAD_FACE_2:1,PAD_FACE_3:2,PAD_FACE_4:3,PAD_L_SHOULDER_1:4,PAD_R_SHOULDER_1:5,PAD_L_SHOULDER_2:6,PAD_R_SHOULDER_2:7,PAD_SELECT:8,PAD_START:9,PAD_L_STICK_BUTTON:10,PAD_R_STICK_BUTTON:11,PAD_UP:12,PAD_DOWN:13,PAD_LEFT:14,PAD_RIGHT:15,PAD_VENDOR:16,XRPAD_TRIGGER:0,XRPAD_SQUEEZE:1,XRPAD_TOUCHPAD_BUTTON:2,XRPAD_STICK_BUTTON:3,XRPAD_A:4,XRPAD_B:5},axes:{PAD_L_STICK_X:0,PAD_L_STICK_Y:1,PAD_R_STICK_X:2,PAD_R_STICK_Y:3,XRPAD_TOUCHPAD_X:0,XRPAD_TOUCHPAD_Y:1,XRPAD_STICK_X:2,XRPAD_STICK_Y:3}},lr={DEFAULT:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_3","PAD_FACE_4","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_UP","PAD_DOWN","PAD_LEFT","PAD_RIGHT","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"]},DEFAULT_DUAL:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_3","PAD_FACE_4","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"],synthesizedButtons:{PAD_UP:{axis:0,min:0,max:1},PAD_DOWN:{axis:0,min:-1,max:0},PAD_LEFT:{axis:0,min:-1,max:0},PAD_RIGHT:{axis:0,min:0,max:1}}},PS3:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_4","PAD_FACE_3","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_UP","PAD_DOWN","PAD_LEFT","PAD_RIGHT","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"],mapping:"standard"},DEFAULT_XR:{buttons:["XRPAD_TRIGGER","XRPAD_SQUEEZE","XRPAD_TOUCHPAD_BUTTON","XRPAD_STICK_BUTTON","XRPAD_A","XRPAD_B"],axes:["XRPAD_TOUCHPAD_X","XRPAD_TOUCHPAD_Y","XRPAD_STICK_X","XRPAD_STICK_Y"],mapping:"xr-standard"}},cr={"Product: 0268":"PS3"},ur={};function dr(e){var t=ur[e.id];if(t)return t;for(var i in cr)if(-1!==e.id.indexOf(i)){var n=cr[i];if(!e.mapping){var s=lr["RAW_"+n];if(s)return s}return lr[n]}if("xr-standard"===e.mapping)return lr.DEFAULT_XR;var r=lr.DEFAULT,a=e.buttons.length<r.buttons.length?lr.DEFAULT_DUAL:r;return a.mapping=e.mapping,a}var fr=.25;function pr(e){return new Promise((function(t){setTimeout(t,e)}))}var mr=function(){function e(e,t){var i,n;(this.value=0,this.pressed=!1,this.touched=!1,this.wasPressed=!1,this.wasReleased=!1,this.wasTouched=!1,"number"==typeof e)?(this.value=e,this.pressed=1===e,this.touched=e>0):(this.value=e.value,this.pressed=e.pressed,this.touched=null!=(i=e.touched)?i: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!=(n=t.touched)?n:t.value>0)&&this.touched))}return e.prototype.update=function(e){var t,i=e.value,n=e.pressed,s=null!=(t=e.touched)?t:i>0;this.wasPressed=!this.pressed&&n,this.wasReleased=this.pressed&&!n,this.wasTouched=!this.touched&&s,this.value=i,this.pressed=n,this.touched=s},e}(),_r=Object.freeze(new mr(0)),gr=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 mr(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,i=e.prototype;return i._compileMapping=function(){var e=this,t=this._compiledMapping,i=t.axes,n=t.buttons,s=hr.axes,r=hr.buttons;i.length=0,n.length=0,this.map.axes&&this.map.axes.forEach((function(t,n){i[s[t]]=function(){return e.pad.axes[n]||0}}));for(var a=0,o=i.length;a<o;a++)i[a]||(i[a]=function(){return 0});var h=this.map.buttons;h&&h.forEach((function(t,i){n[r[t]]=function(){return e._buttons[i]||_r}}));var l=this.map.synthesizedButtons;l&&Object.entries(l).forEach((function(t){var i=t[1],s=i.axis,a=i.max,o=i.min;n[r[t[0]]]=function(){var t,i;return new mr(Math.abs(ce.clamp(null!=(t=e._axes[s])?t:0,o,a)),Math.abs(ce.clamp(null!=(i=e._previousAxes[s])?i:0,o,a)))}}));for(var c=0,u=n.length;c<u;c++)n[c]||(n[c]=function(){return _r})},i.update=function(e){this.pad=e;var t=this._previousAxes,i=this._axes;t.length=0,t.push.apply(t,i),i.length=0,i.push.apply(i,e.axes);for(var n=this._buttons,s=0,r=n.length;s<r;s++)n[s].update(e.buttons[s]);return this},i.updateMap=function(e){e.mapping="custom",ur[this.id]=e,this.map=e,this.mapping="custom",this._compileMapping()},i.resetMap=function(){if(ur[this.id]){delete ur[this.id];var e=dr(this.pad);this.map=e,this.mapping=e.mapping,this._compileMapping()}},i.pulse=(t=Y(j().mark((function e(t,i,n){var s,r,a,o,h,l,c,u;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(s=this.pad.vibrationActuator?[this.pad.vibrationActuator]:this.pad.hapticActuators||ar).length){e.next=9;break}return h=null!=(r=null==n?void 0:n.startDelay)?r:0,l=null!=(a=null==n?void 0:n.strongMagnitude)?a:t,c=null!=(o=null==n?void 0:n.weakMagnitude)?o:t,e.next=7,Promise.all(s.map(function(){var e=Y(j().mark((function e(n){return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n){e.next=2;break}return e.abrupt("return",!0);case 2:if(!n.playEffect){e.next=6;break}return e.abrupt("return",n.playEffect(n.type,{duration:i,startDelay:h,strongMagnitude:l,weakMagnitude:c}));case 6:if(!n.pulse){e.next=10;break}return e.next=9,pr(h);case 9:return e.abrupt("return",n.pulse(t,i));case 10:return e.abrupt("return",!1);case 11:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 7:return u=e.sent,e.abrupt("return",u.some((function(e){return!0===e||"complete"===e})));case 9:return e.abrupt("return",!1);case 10:case"end":return e.stop()}}),e,this)}))),function(e,i,n){return t.apply(this,arguments)}),i.getButton=function(e){var t=this._compiledMapping.buttons[e];return t?t():_r},i.isPressed=function(e){return this.getButton(e).pressed},i.wasPressed=function(e){return this.getButton(e).wasPressed},i.wasReleased=function(e){return this.getButton(e).wasReleased},i.isTouched=function(e){return this.getButton(e).touched},i.wasTouched=function(e){return this.getButton(e).wasTouched},i.getValue=function(e){return this.getButton(e).value},i.getAxis=function(e){var t=this.axes[e];return t&&Math.abs(t)>fr?t:0},Z(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}(),vr=function(e){function t(){var t;return(t=e.call(this)||this).gamepadsSupported=M.gamepads,t.current=[],t._previous=[],t._ongamepadconnectedHandler=t._ongamepadconnected.bind(ee(t)),t._ongamepaddisconnectedHandler=t._ongamepaddisconnected.bind(ee(t)),window.addEventListener("gamepadconnected",t._ongamepadconnectedHandler,!1),window.addEventListener("gamepaddisconnected",t._ongamepaddisconnectedHandler,!1),t.poll(),t}Q(t,e);var i=t.prototype;return i._ongamepadconnected=function(e){for(var t=new gr(e.gamepad,this.getMap(e.gamepad)),i=this.current,n=i.findIndex((function(e){return e.index===t.index}));-1!==n;)i.splice(n,1),n=i.findIndex((function(e){return e.index===t.index}));i.push(t),this.fire(Ys,t)},i._ongamepaddisconnected=function(e){var t=this.current,i=t.findIndex((function(t){return t.index===e.gamepad.index}));-1!==i&&(this.fire(Ks,t[i]),t.splice(i,1))},i.update=function(){this.poll()},i.poll=function(e){void 0===e&&(e=[]),e.length>0&&(e.length=0);for(var t=or(),i=0,n=t.length;i<n;i++)if(t[i]){var s=this.findByIndex(t[i].index);if(s)e.push(s.update(t[i]));else{var r=new gr(t[i],this.getMap(t[i]));this.current.push(r),e.push(r)}}return e},i.destroy=function(){window.removeEventListener("gamepadconnected",this._ongamepadconnectedHandler,!1),window.removeEventListener("gamepaddisconnected",this._ongamepaddisconnectedHandler,!1)},i.getMap=function(e){return dr(e)},i.isPressed=function(e,t){var i;return(null==(i=this.current[e])?void 0:i.isPressed(t))||!1},i.wasPressed=function(e,t){var i;return(null==(i=this.current[e])?void 0:i.wasPressed(t))||!1},i.wasReleased=function(e,t){var i;return(null==(i=this.current[e])?void 0:i.wasReleased(t))||!1},i.getAxis=function(e,t){var i;return(null==(i=this.current[e])?void 0:i.getAxis(t))||0},i.pulse=function(e,t,i,n){var s=this.current[e];return s?s.pulse(t,i,n):Promise.resolve(!1)},i.pulseAll=function(e,t,i){return Promise.all(this.current.map((function(n){return n.pulse(e,t,i)})))},i.findById=function(e){return this.current.find((function(t){return t&&t.id===e}))||null},i.findByIndex=function(e){return this.current.find((function(t){return t&&t.index===e}))||null},Z(t,[{key:"deadZone",get:function(){return fr},set:function(e){fr=e}},{key:"previous",get:function(){for(var e=this.current,t=0,i=e.length;t<i;t++){var n=e[t]._buttons;this._previous[t]||(this._previous[t]=[]);for(var s=0,r=n.length;s<r;s++){var a=n[t];this.previous[t][s]=!!a&&(!a.wasPressed&&a.pressed||a.wasReleased)}}return this._previous.length=this.current.length,this._previous}}]),t}(p);function yr(e){for(var t=0,i=0,n=e.target;!(n instanceof HTMLElement);)n=n.parentNode;var s=n;do{t+=s.offsetLeft-s.scrollLeft,i+=s.offsetTop-s.scrollTop,s=s.offsetParent}while(s);return{x:e.pageX-t,y:e.pageY-i}}var xr=function(e){var t=yr(e);this.id=e.identifier,this.x=t.x,this.y=t.y,this.target=e.target,this.touch=e},Sr=function(){function e(e,t){if(this.element=t.target,this.event=t,this.touches=[],this.changedTouches=[],t){for(var i=0,n=t.touches.length;i<n;i++)this.touches.push(new xr(t.touches[i]));for(var s=0,r=t.changedTouches.length;s<r;s++)this.changedTouches.push(new xr(t.changedTouches[s]))}}return e.prototype.getTouchById=function(e,t){for(var i=0,n=t.length;i<n;i++)if(t[i].id===e)return t[i];return null},e}(),br=function(e){function t(t){var i;return(i=e.call(this)||this)._element=null,i._startHandler=i._handleTouchStart.bind(ee(i)),i._endHandler=i._handleTouchEnd.bind(ee(i)),i._moveHandler=i._handleTouchMove.bind(ee(i)),i._cancelHandler=i._handleTouchCancel.bind(ee(i)),i.attach(t),i}Q(t,e);var i=t.prototype;return i.attach=function(e){this._element&&this.detach(),this._element=e,this._element.addEventListener("touchstart",this._startHandler,!1),this._element.addEventListener("touchend",this._endHandler,!1),this._element.addEventListener("touchmove",this._moveHandler,!1),this._element.addEventListener("touchcancel",this._cancelHandler,!1)},i.detach=function(){this._element&&(this._element.removeEventListener("touchstart",this._startHandler,!1),this._element.removeEventListener("touchend",this._endHandler,!1),this._element.removeEventListener("touchmove",this._moveHandler,!1),this._element.removeEventListener("touchcancel",this._cancelHandler,!1)),this._element=null},i._handleTouchStart=function(e){this.fire("touchstart",new Sr(this,e))},i._handleTouchEnd=function(e){this.fire("touchend",new Sr(this,e))},i._handleTouchMove=function(e){e.preventDefault(),this.fire("touchmove",new Sr(this,e))},i._handleTouchCancel=function(e){this.fire("touchcancel",new Sr(this,e))},t}(p),wr=function(){function e(){}var t=e.prototype;return t.get=function(e,t,i){return"function"==typeof t&&(i=t,t={}),this.request("GET",e,t,i)},t.post=function(e,t,i,n){return"function"==typeof i&&(n=i,i={}),i.postdata=t,this.request("POST",e,i,n)},t.put=function(e,t,i,n){return"function"==typeof i&&(n=i,i={}),i.postdata=t,this.request("PUT",e,i,n)},t.del=function(e,t,i){return"function"==typeof t&&(i=t,t={}),this.request("DELETE",e,t,i)},t.request=function(t,i,n,s){var r,a,o,h=this,l=!1;if("function"==typeof n&&(s=n,n={}),n.retry&&(n=Object.assign({retries:0,maxRetries:5},n)),n.callback=s,null==n.async&&(n.async=!0),null==n.headers&&(n.headers={}),null!=n.postdata)if(n.postdata instanceof Document)o=n.postdata;else if(n.postdata instanceof FormData)o=n.postdata;else if(n.postdata instanceof Object){var c=n.headers["Content-Type"];switch(void 0===c&&(n.headers["Content-Type"]=e.ContentType.FORM_URLENCODED,c=n.headers["Content-Type"]),c){case e.ContentType.FORM_URLENCODED:o="";var u=!0;for(var d in n.postdata){if(n.postdata.hasOwnProperty(d))u?u=!1:o+="&",o+=encodeURIComponent(d)+"="+encodeURIComponent(n.postdata[d])}break;default:case e.ContentType.JSON:null==c&&(n.headers["Content-Type"]=e.ContentType.JSON),o=JSON.stringify(n.postdata)}}else o=n.postdata;if(!1===n.cache){var p=oe();(r=new le(i)).query?r.query=r.query+"&ts="+p:r.query="ts="+p,i=r.toString()}n.query&&(a=f((r=new le(i)).getQuery(),n.query),r.setQuery(a),i=r.toString());var m=new XMLHttpRequest;for(var _ in m.open(t,i,n.async),m.withCredentials=void 0!==n.withCredentials&&n.withCredentials,m.responseType=n.responseType||this._guessResponseType(i),n.headers)n.headers.hasOwnProperty(_)&&m.setRequestHeader(_,n.headers[_]);m.onreadystatechange=function(){h._onReadyStateChange(t,i,n,m)},m.onerror=function(){h._onError(t,i,n,m),l=!0};try{m.send(o)}catch(e){l||n.error(m.status,m,e)}return m},t._guessResponseType=function(t){var i=new le(t),n=v.getExtension(i.path).toLowerCase();return e.binaryExtensions.indexOf(n)>=0?e.ResponseType.ARRAY_BUFFER:".json"===n?e.ResponseType.JSON:".xml"===n?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,i,n){if(4===n.readyState)switch(n.status){case 0:n.responseURL&&n.responseURL.startsWith("file:///")?this._onSuccess(e,t,i,n):this._onError(e,t,i,n);break;case 200:case 201:case 206:case 304:this._onSuccess(e,t,i,n);break;default:this._onError(e,t,i,n)}},t._onSuccess=function(t,i,n,s){var r,a,o=s.getResponseHeader("Content-Type");o&&(a=o.split(";")[0].trim());try{r=this._isBinaryContentType(a)||this._isBinaryResponseType(s.responseType)?s.response:a===e.ContentType.JSON||i.split("?")[0].endsWith(".json")?JSON.parse(s.responseText):s.responseType===e.ResponseType.DOCUMENT||a===e.ContentType.XML?s.responseXML:s.responseText,n.callback(null,r)}catch(e){n.callback(e)}},t._onError=function(t,i,n,s){var r=this;if(!n.retrying)if(n.retry&&n.retries<n.maxRetries){n.retries++,n.retrying=!0;var a=ce.clamp(Math.pow(2,n.retries)*e.retryDelay,0,n.maxRetryDelay||5e3);console.log(t+": "+i+" - Error "+s.status+". Retrying in "+a+" ms"),setTimeout((function(){n.retrying=!1,r.request(t,i,n,n.callback)}),a)}else n.callback(0===s.status?"Network error":s.status,null)},e}();wr.ContentType={AAC:"audio/aac",BASIS:"image/basis",BIN:"application/octet-stream",DDS:"image/dds",FORM_URLENCODED:"application/x-www-form-urlencoded",GIF:"image/gif",GLB:"model/gltf-binary",JPEG:"image/jpeg",JSON:"application/json",MP3:"audio/mpeg",MP4:"audio/mp4",OGG:"audio/ogg",OPUS:'audio/ogg; codecs="opus"',PNG:"image/png",TEXT:"text/plain",WAV:"audio/x-wav",XML:"application/xml"},wr.ResponseType={TEXT:"text",ARRAY_BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json"},wr.binaryExtensions=[".model",".wav",".ogg",".mp3",".mp4",".m4a",".aac",".dds",".basis",".glb",".opus"],wr.retryDelay=100;var Tr=new wr;function Ar(){return!("undefined"==typeof AudioContext&&"undefined"==typeof webkitAudioContext)}var Cr=function(){function e(e,t,i){var n,s,r;if(void 0===i&&(i={}),this.volume=null!=(n=i.volume)?n:1,this.loop=null!=(s=i.loop)&&s,this.pitch=null!=(r=i.pitch)?r:1,this.sound=t,this.paused=!1,this.suspended=!1,this.manager=e,this.source=null,Ar()){this.startTime=0,this.startOffset=0;var a=e.context;this.gain=a.createGain()}else t.audio&&(this.source=t.audio.cloneNode(!1),this.source.pause())}var t=e.prototype;return t.getVolume=function(){return this.volume},t.getLoop=function(){return this.loop},t.setLoop=function(e){this.loop=e,this.source&&(this.source.loop=e)},t.getPitch=function(){return this.pitch},t.onManagerVolumeChange=function(){this.setVolume(this.getVolume())},t.onManagerSuspend=function(){this.isPlaying()&&!this.suspended&&(this.suspended=!0,this.pause())},t.onManagerResume=function(){this.suspended&&(this.suspended=!1,this.unpause())},t.play=function(){if(this.source)throw new Error("Call stop() before calling play()");this._createSource(),this.source&&(this.startTime=this.manager.context.currentTime,this.source.start(0,this.startOffset%this.source.buffer.duration),this.setVolume(this.volume),this.setLoop(this.loop),this.setPitch(this.pitch),this.manager.on("volumechange",this.onManagerVolumeChange,this),this.manager.on("suspend",this.onManagerSuspend,this),this.manager.on("resume",this.onManagerResume,this),this.manager.suspended&&this.onManagerSuspend())},t.pause=function(){this.source&&(this.paused=!0,this.startOffset+=this.manager.context.currentTime-this.startTime,this.source.stop(0),this.source=null)},t.unpause=function(){!this.source&&this.paused?(this._createSource(),this.source&&(this.startTime=this.manager.context.currentTime,this.source.start(0,this.startOffset%this.source.buffer.duration),this.setVolume(this.volume),this.setLoop(this.loop),this.setPitch(this.pitch),this.paused=!1)):console.warn("Call pause() before unpausing.")},t.stop=function(){this.source&&(this.source.stop(0),this.source=null),this.manager.off("volumechange",this.onManagerVolumeChange,this),this.manager.off("suspend",this.onManagerSuspend,this),this.manager.off("resume",this.onManagerResume,this)},t.setVolume=function(e){e=ce.clamp(e,0,1),this.volume=e,this.gain&&(this.gain.gain.value=e*this.manager.volume)},t.setPitch=function(e){this.pitch=e,this.source&&(this.source.playbackRate.value=e)},t.isPlaying=function(){return!this.paused&&this.source.playbackState===this.source.PLAYING_STATE},t.getDuration=function(){return this.source?this.source.buffer.duration:0},t._createSource=function(){var e=this.manager.context;this.sound.buffer&&(this.source=e.createBufferSource(),this.source.buffer=this.sound.buffer,this.source.connect(this.gain),this.gain.connect(e.destination),this.loop||(this.source.onended=this.pause.bind(this)))},e}();Ar()||Object.assign(Cr.prototype,{play:function(){this.source&&(this.paused=!1,this.setVolume(this.volume),this.setLoop(this.loop),this.setPitch(this.pitch),this.source.play()),this.manager.on("volumechange",this.onManagerVolumeChange,this),this.manager.on("suspend",this.onManagerSuspend,this),this.manager.on("resume",this.onManagerResume,this),this.manager.suspended&&this.onManagerSuspend()},pause:function(){this.source&&(this.paused=!0,this.source.pause())},unpause:function(){this.source&&(this.paused=!1,this.source.play())},stop:function(){this.source&&this.source.pause(),this.manager.off("volumechange",this.onManagerVolumeChange,this),this.manager.off("suspend",this.onManagerSuspend,this),this.manager.off("resume",this.onManagerResume,this)},setVolume:function(e){e=ce.clamp(e,0,1),this.volume=e,this.source&&(this.source.volume=e*this.manager.volume)},setPitch:function(e){this.pitch=e,this.source&&(this.source.playbackRate=e)},getDuration:function(){return this.source&&!isNaN(this.source.duration)?this.source.duration:0},isPlaying:function(){return!this.source.paused}});var Er=function(e){function t(t,i,n){var s;return(s=e.call(this,t,i,n)||this).position=new me,s.velocity=new me,Ar()?s.panner=t.context.createPanner():(s.maxDistance=1e4,s.minDistance=1,s.rollOffFactor=1,s.distanceModel=We),s}Q(t,e);var i=t.prototype;return i.getPosition=function(){return this.position},i.setPosition=function(e){this.position.copy(e);var t=this.panner;"positionX"in t?(t.positionX.value=e.x,t.positionY.value=e.y,t.positionZ.value=e.z):t.setPosition&&t.setPosition(e.x,e.y,e.z)},i.getVelocity=function(){return this.velocity},i.setVelocity=function(e){this.velocity.copy(e)},i.getMaxDistance=function(){return this.panner.maxDistance},i.setMaxDistance=function(e){this.panner.maxDistance=e},i.getMinDistance=function(){return this.panner.refDistance},i.setMinDistance=function(e){this.panner.refDistance=e},i.getRollOffFactor=function(){return this.panner.rolloffFactor},i.setRollOffFactor=function(e){this.panner.rolloffFactor=e},i.getDistanceModel=function(){return this.panner.distanceModel},i.setDistanceModel=function(e){this.panner.distanceModel=e},i._createSource=function(){var e=this.manager.context;this.source=e.createBufferSource(),this.source.buffer=this.sound.buffer,this.source.connect(this.panner),this.panner.connect(this.gain),this.gain.connect(e.destination),this.loop||(this.source.onended=this.pause.bind(this))},t}(Cr);if(!Ar()){var Mr=new me;Object.assign(Er.prototype,{setPosition:function(e){if(this.position.copy(e),this.source){var t=function(e,t,i,n,s,r){var a=(Mr=Mr.sub2(e,t)).length();if(a<i)return 1;if(a>n)return 0;var o=0;return r===He?o=1-s*(a-i)/(n-i):r===We?o=i/(i+s*(a-i)):r===Xe&&(o=Math.pow(a/i,-s)),ce.clamp(o,0,1)}(this.manager.listener.getPosition(),this.position,this.minDistance,this.maxDistance,this.rollOffFactor,this.distanceModel),i=this.getVolume();this.source.volume=i*t}},getMaxDistance:function(){return this.maxDistance},setMaxDistance:function(e){this.maxDistance=e},getMinDistance:function(){return this.minDistance},setMinDistance:function(e){this.minDistance=e},getRollOffFactor:function(){return this.rollOffFactor},setRollOffFactor:function(e){this.rollOffFactor=e},getDistanceModel:function(){return this.distanceModel},setDistanceModel:function(e){this.distanceModel=e}})}var Pr=function(){function e(e){this._manager=e,this.position=new me,this.velocity=new me,this.orientation=new Te}var t=e.prototype;return t.getPosition=function(){return this.position},t.setPosition=function(e){this.position.copy(e);var t=this.listener;t&&("positionX"in t?(t.positionX.value=e.x,t.positionY.value=e.y,t.positionZ.value=e.z):t.setPosition&&t.setPosition(e.x,e.y,e.z))},t.getVelocity=function(){return this.velocity},t.setVelocity=function(e){},t.setOrientation=function(e){this.orientation.copy(e);var t=this.listener;if(t){var i=e.data;"forwardX"in t?(t.forwardX.value=-i[8],t.forwardY.value=-i[9],t.forwardZ.value=-i[10],t.upX.value=i[4],t.upY.value=i[5],t.upZ.value=i[6]):t.setOrientation&&t.setOrientation(-i[8],-i[9],-i[10],i[4],i[5],i[6])}},t.getOrientation=function(){return this.orientation},Z(e,[{key:"listener",get:function(){var e=this._manager.context;return e?e.listener:null}}]),e}(),Rr="running",Ir=["click","touchstart","mousedown"],Lr=function(e){function t(){var t;return(t=e.call(this)||this)._context=null,t.AudioContext="undefined"!=typeof AudioContext&&AudioContext||"undefined"!=typeof webkitAudioContext&&webkitAudioContext,t.AudioContext,t._unlockHandlerFunc=t._unlockHandler.bind(ee(t)),t._userSuspended=!1,t.listener=new Pr(ee(t)),t._volume=1,t}Q(t,e);var i=t.prototype;return i.suspend=function(){this._userSuspended||(this._userSuspended=!0,this._context&&this._context.state===Rr&&this._suspend())},i.resume=function(){this._userSuspended&&(this._userSuspended=!1,this._context&&this._context.state!==Rr&&this._resume())},i.destroy=function(){var e;(this.fire("destroy"),this._context)&&(this._removeUnlockListeners(),null==(e=this._context)||e.close(),this._context=null)},i.playSound=function(e,t){void 0===t&&(t={});var i=null;return Cr&&(i=new Cr(this,e,t)).play(),i},i.playSound3d=function(e,t,i){void 0===i&&(i={});var n=null;return Er&&((n=new Er(this,e,i)).setPosition(t),i.volume&&n.setVolume(i.volume),i.loop&&n.setLoop(i.loop),i.maxDistance&&n.setMaxDistance(i.maxDistance),i.minDistance&&n.setMinDistance(i.minDistance),i.rollOffFactor&&n.setRollOffFactor(i.rollOffFactor),i.distanceModel&&n.setDistanceModel(i.distanceModel),n.play()),n},i._resume=function(){var e=this;this._context.resume().then((function(){var t=e._context.createBufferSource();t.buffer=e._context.createBuffer(1,1,e._context.sampleRate),t.connect(e._context.destination),t.start(0),t.onended=function(i){t.disconnect(0),e.fire("resume")}}),(function(e){})).catch((function(e){}))},i._suspend=function(){var e=this;this._context.suspend().then((function(){e.fire("suspend")}),(function(e){})).catch((function(e){}))},i._unlockHandler=function(){this._removeUnlockListeners(),this._userSuspended||this._context.state===Rr||this._resume()},i._registerUnlockListeners=function(){var e=this;Ir.forEach((function(t){window.addEventListener(t,e._unlockHandlerFunc,!1)}))},i._removeUnlockListeners=function(){var e=this;Ir.forEach((function(t){window.removeEventListener(t,e._unlockHandlerFunc,!1)}))},Z(t,[{key:"volume",get:function(){return this._volume},set:function(e){e=ce.clamp(e,0,1),this._volume=e,this.fire("volumechange",e)}},{key:"suspended",get:function(){return this._userSuspended}},{key:"context",get:function(){return!this._context&&this.AudioContext&&(this._context=new this.AudioContext,this._context.state!==Rr&&this._registerUnlockListeners()),this._context}}]),t}(p),Dr=function(){function e(e){this.audio=void 0,this.buffer=void 0,e instanceof Audio?this.audio=e:this.buffer=e}return Z(e,[{key:"duration",get:function(){var e=0;return this.buffer?e=this.buffer.duration:this.audio&&(e=this.audio.duration),e||0}}]),e}();function Or(e,t){return e%t||0}var kr=function(e){function t(t,i,n){var s;return(s=e.call(this)||this).source=null,s._manager=t,s._volume=void 0!==n.volume?ce.clamp(Number(n.volume)||0,0,1):1,s._pitch=void 0!==n.pitch?Math.max(.01,Number(n.pitch)||0):1,s._loop=!(void 0===n.loop||!n.loop),s._sound=i,s._state=2,s._suspended=!1,s._suspendEndEvent=0,s._suspendInstanceEvents=!1,s._playWhenLoaded=!0,s._startTime=Math.max(0,Number(n.startTime)||0),s._duration=Math.max(0,Number(n.duration)||0),s._startOffset=null,s._onPlayCallback=n.onPlay,s._onPauseCallback=n.onPause,s._onResumeCallback=n.onResume,s._onStopCallback=n.onStop,s._onEndCallback=n.onEnd,Ar()?(s._startedAt=0,s._currentTime=0,s._currentOffset=0,s._inputNode=null,s._connectorNode=null,s._firstNode=null,s._lastNode=null,s._waitingContextSuspension=!1,s._initializeNodes(),s._endedHandler=s._onEnded.bind(ee(s))):(s._isReady=!1,s._loadedMetadataHandler=s._onLoadedMetadata.bind(ee(s)),s._timeUpdateHandler=s._onTimeUpdate.bind(ee(s)),s._endedHandler=s._onEnded.bind(ee(s)),s._createSource()),s}Q(t,e);var i=t.prototype;return i._onPlay=function(){this.fire("play"),this._onPlayCallback&&this._onPlayCallback(this)},i._onPause=function(){this.fire("pause"),this._onPauseCallback&&this._onPauseCallback(this)},i._onResume=function(){this.fire("resume"),this._onResumeCallback&&this._onResumeCallback(this)},i._onStop=function(){this.fire("stop"),this._onStopCallback&&this._onStopCallback(this)},i._onEnded=function(){this._suspendEndEvent>0?this._suspendEndEvent--:(this.fire("end"),this._onEndCallback&&this._onEndCallback(this),this.stop())},i._onManagerVolumeChange=function(){this.volume=this._volume},i._onManagerSuspend=function(){0!==this._state||this._suspended||(this._suspended=!0,this.pause())},i._onManagerResume=function(){this._suspended&&(this._suspended=!1,this.resume())},i._initializeNodes=function(){this.gain=this._manager.context.createGain(),this._inputNode=this.gain,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination)},i.play=function(){return 2!==this._state&&this.stop(),this._state=0,this._playWhenLoaded=!1,!this._waitingContextSuspension&&(this._manager.suspended?(this._manager.once("resume",this._playAudioImmediate,this),this._waitingContextSuspension=!0,!1):(this._playAudioImmediate(),!0))},i._playAudioImmediate=function(){if(this._waitingContextSuspension=!1,0===this._state){this.source||this._createSource();var e=Or(this._startOffset,this.duration);e=Or(this._startTime+e,this._sound.duration),this._startOffset=null,this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentTime=0,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._manager.on("volumechange",this._onManagerVolumeChange,this),this._manager.on("suspend",this._onManagerSuspend,this),this._manager.on("resume",this._onManagerResume,this),this._manager.on("destroy",this._onManagerDestroy,this),this._suspendInstanceEvents||this._onPlay()}},i.pause=function(){return this._playWhenLoaded=!1,0===this._state&&(this._state=1,this._waitingContextSuspension||(this._updateCurrentTime(),this._suspendEndEvent++,this.source.stop(0),this.source=null,this._startOffset=null,this._suspendInstanceEvents||this._onPause()),!0)},i.resume=function(){if(1!==this._state)return!1;var e=this.currentTime;return this._state=0,this._waitingContextSuspension||(this.source||this._createSource(),null!==this._startOffset&&(e=Or(this._startOffset,this.duration),e=Or(this._startTime+e,this._sound.duration),this._startOffset=null),this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._playWhenLoaded=!1,this._suspendInstanceEvents||this._onResume()),!0},i.stop=function(){if(this._playWhenLoaded=!1,2===this._state)return!1;var e=0===this._state;return this._state=2,this._waitingContextSuspension||(this._manager.off("volumechange",this._onManagerVolumeChange,this),this._manager.off("suspend",this._onManagerSuspend,this),this._manager.off("resume",this._onManagerResume,this),this._manager.off("destroy",this._onManagerDestroy,this),this._startedAt=0,this._currentTime=0,this._currentOffset=0,this._startOffset=null,this._suspendEndEvent++,e&&this.source&&this.source.stop(0),this.source=null,this._suspendInstanceEvents||this._onStop()),!0},i.setExternalNodes=function(e,t){if(e){t||(t=e);var i=this._manager.context.destination;this._firstNode!==e&&(this._firstNode?this._connectorNode.disconnect(this._firstNode):this._connectorNode.disconnect(i),this._firstNode=e,this._connectorNode.connect(e)),this._lastNode!==t&&(this._lastNode&&this._lastNode.disconnect(i),this._lastNode=t,this._lastNode.connect(i))}else console.error("The firstNode must be a valid Audio Node")},i.clearExternalNodes=function(){var e=this._manager.context.destination;this._firstNode&&(this._connectorNode.disconnect(this._firstNode),this._firstNode=null),this._lastNode&&(this._lastNode.disconnect(e),this._lastNode=null),this._connectorNode.connect(e)},i.getExternalNodes=function(){return[this._firstNode,this._lastNode]},i._createSource=function(){if(!this._sound)return null;var e=this._manager.context;return this._sound.buffer&&(this.source=e.createBufferSource(),this.source.buffer=this._sound.buffer,this.source.connect(this._inputNode),this.source.onended=this._endedHandler,this.source.loopStart=Or(this._startTime,this.source.buffer.duration),this._duration&&(this.source.loopEnd=Math.max(this.source.loopStart,Or(this._startTime+this._duration,this.source.buffer.duration)))),this.source},i._updateCurrentTime=function(){this._currentTime=Or((this._manager.context.currentTime-this._startedAt)*this._pitch+this._currentOffset,this.duration)},i._onManagerDestroy=function(){this.source&&0===this._state&&(this.source.stop(0),this.source=null)},Z(t,[{key:"currentTime",get:function(){return null!==this._startOffset?this._startOffset:1===this._state?this._currentTime:2!==this._state&&this.source?(this._updateCurrentTime(),this._currentTime):0},set:function(e){if(!(e<0))if(0===this._state){var t=this._suspendInstanceEvents;this._suspendInstanceEvents=!0,this.stop(),this._startOffset=e,this.play(),this._suspendInstanceEvents=t}else this._startOffset=e,this._currentTime=e}},{key:"duration",get:function(){return this._sound?this._duration?Or(this._duration,this._sound.duration):this._sound.duration:0},set:function(e){this._duration=Math.max(0,Number(e)||0);var t=0===this._state;this.stop(),t&&this.play()}},{key:"isPaused",get:function(){return 1===this._state}},{key:"isPlaying",get:function(){return 0===this._state}},{key:"isStopped",get:function(){return 2===this._state}},{key:"isSuspended",get:function(){return this._suspended}},{key:"loop",get:function(){return this._loop},set:function(e){this._loop=!!e,this.source&&(this.source.loop=this._loop)}},{key:"pitch",get:function(){return this._pitch},set:function(e){this._currentOffset=this.currentTime,this._startedAt=this._manager.context.currentTime,this._pitch=Math.max(Number(e)||0,.01),this.source&&(this.source.playbackRate.value=this._pitch)}},{key:"sound",get:function(){return this._sound},set:function(e){this._sound=e,2!==this._state?this.stop():this._createSource()}},{key:"startTime",get:function(){return this._startTime},set:function(e){this._startTime=Math.max(0,Number(e)||0);var t=0===this._state;this.stop(),t&&this.play()}},{key:"volume",get:function(){return this._volume},set:function(e){e=ce.clamp(e,0,1),this._volume=e,this.gain&&(this.gain.gain.value=e*this._manager.volume)}}]),t}(p);Ar()||(Object.assign(kr.prototype,{play:function(){return 2!==this._state&&this.stop(),!(!this.source&&!this._createSource())&&(this.volume=this._volume,this.pitch=this._pitch,this.loop=this._loop,this.source.play(),this._state=0,this._playWhenLoaded=!1,this._manager.on("volumechange",this._onManagerVolumeChange,this),this._manager.on("suspend",this._onManagerSuspend,this),this._manager.on("resume",this._onManagerResume,this),this._manager.on("destroy",this._onManagerDestroy,this),this._manager.suspended&&this._onManagerSuspend(),this._suspendInstanceEvents||this._onPlay(),!0)},pause:function(){return!(!this.source||0!==this._state)&&(this._suspendEndEvent++,this.source.pause(),this._playWhenLoaded=!1,this._state=1,this._startOffset=null,this._suspendInstanceEvents||this._onPause(),!0)},resume:function(){return!(!this.source||1!==this._state)&&(this._state=0,this._playWhenLoaded=!1,this.source.paused&&(this.source.play(),this._suspendInstanceEvents||this._onResume()),!0)},stop:function(){return!(!this.source||2===this._state)&&(this._manager.off("volumechange",this._onManagerVolumeChange,this),this._manager.off("suspend",this._onManagerSuspend,this),this._manager.off("resume",this._onManagerResume,this),this._manager.off("destroy",this._onManagerDestroy,this),this._suspendEndEvent++,this.source.pause(),this._playWhenLoaded=!1,this._state=2,this._startOffset=null,this._suspendInstanceEvents||this._onStop(),!0)},setExternalNodes:function(){},clearExternalNodes:function(){},getExternalNodes:function(){return[null,null]},_onLoadedMetadata:function(){this.source.removeEventListener("loadedmetadata",this._loadedMetadataHandler),this._isReady=!0;var e=Or(this._startOffset,this.duration);e=Or(this._startTime+e,this._sound.duration),this._startOffset=null,this.source.currentTime=e},_createSource:function(){return this._sound&&this._sound.audio&&(this._isReady=!1,this.source=this._sound.audio.cloneNode(!0),this.source.addEventListener("loadedmetadata",this._loadedMetadataHandler),this.source.addEventListener("timeupdate",this._timeUpdateHandler),this.source.onended=this._endedHandler),this.source},_onTimeUpdate:function(){this._duration&&this.source.currentTime>Or(this._startTime+this._duration,this.source.duration)&&(this.loop?this.source.currentTime=Or(this._startTime,this.source.duration):(this.source.removeEventListener("timeupdate",this._timeUpdateHandler),this.source.pause(),this._onEnded()))},_onManagerDestroy:function(){this.source&&this.source.pause()}}),Object.defineProperty(kr.prototype,"volume",{get:function(){return this._volume},set:function(e){e=ce.clamp(e,0,1),this._volume=e,this.source&&(this.source.volume=e*this._manager.volume)}}),Object.defineProperty(kr.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(kr.prototype,"sound",{get:function(){return this._sound},set:function(e){this.stop(),this._sound=e}}),Object.defineProperty(kr.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=Or(this._startTime+Or(e,this.duration),this._sound.duration),this._startOffset=null))}}));var Fr=function(e){function t(t,i,n){var s;return void 0===n&&(n={}),(s=e.call(this,t,i,n)||this)._position=new me,s._velocity=new me,n.position&&(s.position=n.position),s.maxDistance=void 0!==n.maxDistance?Number(n.maxDistance):1e4,s.refDistance=void 0!==n.refDistance?Number(n.refDistance):1,s.rollOffFactor=void 0!==n.rollOffFactor?Number(n.rollOffFactor):1,s.distanceModel=void 0!==n.distanceModel?n.distanceModel:He,s}return Q(t,e),t.prototype._initializeNodes=function(){this.gain=this._manager.context.createGain(),this.panner=this._manager.context.createPanner(),this.panner.connect(this.gain),this._inputNode=this.panner,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination)},Z(t,[{key:"position",get:function(){return this._position},set:function(e){this._position.copy(e);var t=this.panner;"positionX"in t?(t.positionX.value=e.x,t.positionY.value=e.y,t.positionZ.value=e.z):t.setPosition&&t.setPosition(e.x,e.y,e.z)}},{key:"velocity",get:function(){return this._velocity},set:function(e){this._velocity.copy(e)}},{key:"maxDistance",get:function(){return this.panner.maxDistance},set:function(e){this.panner.maxDistance=e}},{key:"refDistance",get:function(){return this.panner.refDistance},set:function(e){this.panner.refDistance=e}},{key:"rollOffFactor",get:function(){return this.panner.rolloffFactor},set:function(e){this.panner.rolloffFactor=e}},{key:"distanceModel",get:function(){return this.panner.distanceModel},set:function(e){this.panner.distanceModel=e}}]),t}(kr);if(!Ar()){var Br=new me;Object.defineProperty(Fr.prototype,"position",{get:function(){return this._position},set:function(e){if(this._position.copy(e),this.source){var t=function(e,t,i,n,s,r){var a=(Br=Br.sub2(e,t)).length();if(a<i)return 1;if(a>n)return 0;var o=0;return r===He?o=1-s*(a-i)/(n-i):r===We?o=i/(i+s*(a-i)):r===Xe&&(o=Math.pow(a/i,-s)),ce.clamp(o,0,1)}(this._manager.listener.getPosition(),this._position,this.refDistance,this.maxDistance,this.rollOffFactor,this.distanceModel),i=this.volume;this.source.volume=i*t*this._manager.volume}}}),Object.defineProperty(Fr.prototype,"maxDistance",{get:function(){return this._maxDistance},set:function(e){this._maxDistance=e}}),Object.defineProperty(Fr.prototype,"refDistance",{get:function(){return this._refDistance},set:function(e){this._refDistance=e}}),Object.defineProperty(Fr.prototype,"rollOffFactor",{get:function(){return this._rollOffFactor},set:function(e){this._rollOffFactor=e}}),Object.defineProperty(Fr.prototype,"distanceModel",{get:function(){return this._distanceModel},set:function(e){this._distanceModel=e}})}var Nr="none",Ur="linear",zr={0:"PCF3",1:"VSM8",2:"VSM16",3:"VSM32",4:"PCF5",5:"PCF1",6:"PCSS"},Vr="mul",Gr=128,Hr=256,Wr=1024,Xr=2048,jr=4096,qr=8192,Yr=function(){function e(){this._refCount=0}var t=e.prototype;return t.incRefCount=function(){this._refCount++},t.decRefCount=function(){this._refCount--},Z(e,[{key:"refCount",get:function(){return this._refCount}}]),e}(),Kr=function(){function e(){}return e.set=function(t){e._graphicsDevice=t},e.get=function(){return e._graphicsDevice},e}();Kr._graphicsDevice=null;var Zr=0,$r=function(){function e(){this.initDefaults()}var t=e.prototype;return t.initDefaults=function(){this.recreate=!1,this.verticesUsage=0,this.indicesUsage=0,this.maxVertices=0,this.maxIndices=0,this.vertexCount=0,this.indexCount=0,this.vertexStreamsUpdated=!1,this.indexStreamUpdated=!1,this.vertexStreamDictionary={},this.indices=null},t._changeVertexCount=function(e,t){this.vertexCount||(this.vertexCount=e)},e}();$r.DEFAULT_COMPONENTS_POSITION=3,$r.DEFAULT_COMPONENTS_NORMAL=3,$r.DEFAULT_COMPONENTS_UV=2,$r.DEFAULT_COMPONENTS_COLORS=4;var Qr=function(e,t,i,n){this.data=e,this.componentCount=t,this.dataType=i,this.dataTypeNormalize=n},Jr=function(e){function t(t){var i;return(i=e.call(this)||this).id=Zr++,i.device=t||Kr.get(),i.vertexBuffer=null,i.indexBuffer=[null],i.primitive=[{type:0,base:0,count:0}],i.skin=null,i._morph=null,i._geometryData=null,i._aabb=new Ie,i.boneAabb=null,i}Q(t,e);var i=t.prototype;return i.destroy=function(){var e=this.morph;e&&(this.morph=null,e.refCount<1&&e.destroy()),this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);for(var t=0;t<this.indexBuffer.length;t++)this._destroyIndexBuffer(t);this.indexBuffer.length=0,this._geometryData=null},i._destroyIndexBuffer=function(e){this.indexBuffer[e]&&(this.indexBuffer[e].destroy(),this.indexBuffer[e]=null)},i._initBoneAabbs=function(e){var t,i,n,s,r;this.boneAabb=[],this.boneUsed=[];for(var a,o,h,l=[],c=[],u=this.boneUsed,d=this.skin.boneNames.length,f=0;f<d;f++)l[f]=new me(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),c[f]=new me(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(var p=new zs(this.vertexBuffer),m=p.element[lt],_=p.element[dt],g=p.element[ft],v=this.vertexBuffer.numVertices,y=0;y<v;y++){for(var x=0;x<4;x++){if(_.array[_.index+x]>0){var S=g.array[g.index+x];if(u[S]=!0,t=m.array[m.index],i=m.array[m.index+1],n=m.array[m.index+2],s=c[S],(r=l[S]).x>t&&(r.x=t),r.y>i&&(r.y=i),r.z>n&&(r.z=n),s.x<t&&(s.x=t),s.y<i&&(s.y=i),s.z<n&&(s.z=n),e){for(var b=a=t,w=o=i,T=h=n,A=0;A<e.length;A++){var C=e[A],E=C.deltaPositions[3*y],M=C.deltaPositions[3*y+1],P=C.deltaPositions[3*y+2];E<0?b+=E:a+=E,M<0?w+=M:o+=M,P<0?T+=P:h+=P}r.x>b&&(r.x=b),r.y>w&&(r.y=w),r.z>T&&(r.z=T),s.x<a&&(s.x=a),s.y<o&&(s.y=o),s.z<h&&(s.z=h)}}}p.next()}var R=this.vertexBuffer.getFormat().elements.find((function(e){return e.name===lt}));if(R&&R.normalize)for(var I=function(){switch(R.dataType){case 0:return function(e){return Math.max(e/127,-1)};case 1:return function(e){return e/255};case 2:return function(e){return Math.max(e/32767,-1)};case 3:return function(e){return e/65535};default:return function(e){return e}}}(),L=0;L<d;L++)if(u[L]){var D=l[L],O=c[L];D.set(I(D.x),I(D.y),I(D.z)),O.set(I(O.x),I(O.y),I(O.z))}for(var k=0;k<d;k++){var F=new Ie;F.setMinMax(l[k],c[k]),this.boneAabb.push(F)}},i._initGeometryData=function(){this._geometryData||(this._geometryData=new $r,this.vertexBuffer&&(this._geometryData.vertexCount=this.vertexBuffer.numVertices,this._geometryData.maxVertices=this.vertexBuffer.numVertices),this.indexBuffer.length>0&&this.indexBuffer[0]&&(this._geometryData.indexCount=this.indexBuffer[0].numIndices,this._geometryData.maxIndices=this.indexBuffer[0].numIndices))},i.clear=function(e,t,i,n){void 0===i&&(i=0),void 0===n&&(n=0),this._initGeometryData(),this._geometryData.initDefaults(),this._geometryData.recreate=!0,this._geometryData.maxVertices=i,this._geometryData.maxIndices=n,this._geometryData.verticesUsage=e?0:1,this._geometryData.indicesUsage=t?0:1},i.setVertexStream=function(e,t,i,n,s,r){void 0===s&&(s=6),void 0===r&&(r=!1),this._initGeometryData();var a=n||t.length/i;this._geometryData._changeVertexCount(a,e),this._geometryData.vertexStreamsUpdated=!0,this._geometryData.vertexStreamDictionary[e]=new Qr(t,i,s,r)},i.getVertexStream=function(e,t){var i=0,n=!1;if(this._geometryData){var s=this._geometryData.vertexStreamDictionary[e];s&&(n=!0,i=this._geometryData.vertexCount,ArrayBuffer.isView(t)?t.set(s.data):(t.length=0,t.push(s.data)))}n||this.vertexBuffer&&(i=new zs(this.vertexBuffer).readData(e,t));return i},i.setPositions=function(e,t,i){void 0===t&&(t=$r.DEFAULT_COMPONENTS_POSITION),this.setVertexStream(lt,e,t,i,6,!1)},i.setNormals=function(e,t,i){void 0===t&&(t=$r.DEFAULT_COMPONENTS_NORMAL),this.setVertexStream(ct,e,t,i,6,!1)},i.setUvs=function(e,t,i,n){void 0===i&&(i=$r.DEFAULT_COMPONENTS_UV),this.setVertexStream(mt+e,t,i,n,6,!1)},i.setColors=function(e,t,i){void 0===t&&(t=$r.DEFAULT_COMPONENTS_COLORS),this.setVertexStream(pt,e,t,i,6,!1)},i.setColors32=function(e,t){this.setVertexStream(pt,e,$r.DEFAULT_COMPONENTS_COLORS,t,1,!0)},i.setIndices=function(e,t){this._initGeometryData(),this._geometryData.indexStreamUpdated=!0,this._geometryData.indices=e,this._geometryData.indexCount=t||e.length},i.getPositions=function(e){return this.getVertexStream(lt,e)},i.getNormals=function(e){return this.getVertexStream(ct,e)},i.getUvs=function(e,t){return this.getVertexStream(mt+e,t)},i.getColors=function(e){return this.getVertexStream(pt,e)},i.getIndices=function(e){var t=0;if(this._geometryData&&this._geometryData.indices){var i=this._geometryData.indices;t=this._geometryData.indexCount,ArrayBuffer.isView(e)?e.set(i):(e.length=0,e.push(i))}else{if(this.indexBuffer.length>0&&this.indexBuffer[0])t=this.indexBuffer[0].readData(e)}return t},i.update=function(e,t){if(void 0===e&&(e=4),void 0===t&&(t=!0),this._geometryData){if(t){var i=this._geometryData.vertexStreamDictionary[lt];i&&3===i.componentCount&&this._aabb.compute(i.data,this._geometryData.vertexCount)}var n=this._geometryData.recreate;this._geometryData.vertexCount>this._geometryData.maxVertices&&(n=!0,this._geometryData.maxVertices=this._geometryData.vertexCount),n&&this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);var s=this._geometryData.recreate;this._geometryData.indexCount>this._geometryData.maxIndices&&(s=!0,this._geometryData.maxIndices=this._geometryData.indexCount),s&&this.indexBuffer.length>0&&this.indexBuffer[0]&&(this.indexBuffer[0].destroy(),this.indexBuffer[0]=null),this._geometryData.vertexStreamsUpdated&&this._updateVertexBuffer(),this._geometryData.indexStreamUpdated&&this._updateIndexBuffer(),this.primitive[0].type=e,this.indexBuffer.length>0&&this.indexBuffer[0]?this._geometryData.indexStreamUpdated&&(this.primitive[0].count=this._geometryData.indexCount,this.primitive[0].indexed=!0):this._geometryData.vertexStreamsUpdated&&(this.primitive[0].count=this._geometryData.vertexCount,this.primitive[0].indexed=!1),this._geometryData.vertexCount=0,this._geometryData.indexCount=0,this._geometryData.vertexStreamsUpdated=!1,this._geometryData.indexStreamUpdated=!1,this._geometryData.recreate=!1,this.updateRenderStates()}},i._buildVertexFormat=function(e){var t=[];for(var i in this._geometryData.vertexStreamDictionary){var n=this._geometryData.vertexStreamDictionary[i];t.push({semantic:i,components:n.componentCount,type:n.dataType,normalize:n.dataTypeNormalize})}return new Pi(this.device,t,e)},i._updateVertexBuffer=function(){if(!this.vertexBuffer){var e=this._geometryData.maxVertices,t=this._buildVertexFormat(e);this.vertexBuffer=new Ei(this.device,t,e,this._geometryData.verticesUsage)}var i=new zs(this.vertexBuffer),n=this._geometryData.vertexCount;for(var s in this._geometryData.vertexStreamDictionary){var r=this._geometryData.vertexStreamDictionary[s];i.writeData(s,r.data,n),delete this._geometryData.vertexStreamDictionary[s]}i.end()},i._updateIndexBuffer=function(){if(this.indexBuffer.length<=0||!this.indexBuffer[0]){var e=this._geometryData.maxVertices>65535?2:1;this.indexBuffer[0]=new As(this.device,e,this._geometryData.maxIndices,this._geometryData.indicesUsage)}var t=this._geometryData.indices;t&&(this.indexBuffer[0].writeData(t,this._geometryData.indexCount),this._geometryData.indices=null)},i.prepareRenderState=function(e){1===e?this.generateWireframe():2===e&&(this.primitive[2]={type:0,base:0,count:this.vertexBuffer?this.vertexBuffer.numVertices:0,indexed:!1})},i.updateRenderStates=function(){this.primitive[2]&&this.prepareRenderState(2),this.primitive[1]&&this.prepareRenderState(1)},i.generateWireframe=function(){this._destroyIndexBuffer(1);var e,t=this.vertexBuffer.numVertices,i=[];if(this.indexBuffer.length>0&&this.indexBuffer[0]){for(var n=[[0,1],[1,2],[2,0]],s=this.primitive[0].base,r=this.primitive[0].count,a=this.indexBuffer[0],o=new ui[a.format](a.storage),h=new Set,l=s;l<s+r;l+=3)for(var c=0;c<3;c++){var u=o[l+n[c][0]],d=o[l+n[c][1]],f=u>d?d*t+u:u*t+d;h.has(f)||(h.add(f),i.push(u,d))}e=a.format}else{for(var p=0;p<t;p+=3)i.push(p,p+1,p+1,p+2,p+2,p);e=i.length>65535?2:1}var m=new As(this.vertexBuffer.device,e,i.length);new ui[m.format](m.storage).set(i),m.unlock(),this.primitive[1]={type:1,base:0,count:i.length,indexed:!0},this.indexBuffer[1]=m},Z(t,[{key:"morph",get:function(){return this._morph},set:function(e){e!==this._morph&&(this._morph&&this._morph.decRefCount(),this._morph=e,e&&e.incRefCount())}},{key:"aabb",get:function(){return this._aabb},set:function(e){this._aabb=e}}]),t}(Yr),ea=4/64,ta=.875,ia=[];function na(e,t){for(var i=t.length/3,n=e.length/3,s=new me,r=new me,a=new me,o=new me,h=new me,l=new me,c=[],u=0;u<e.length;u++)c[u]=0;for(var d=0;d<i;d++){var f=t[3*d],p=t[3*d+1],m=t[3*d+2];s.set(e[3*f],e[3*f+1],e[3*f+2]),r.set(e[3*p],e[3*p+1],e[3*p+2]),a.set(e[3*m],e[3*m+1],e[3*m+2]),o.sub2(r,s),h.sub2(a,s),l.cross(o,h).normalize(),c[3*f]+=l.x,c[3*f+1]+=l.y,c[3*f+2]+=l.z,c[3*p]+=l.x,c[3*p+1]+=l.y,c[3*p+2]+=l.z,c[3*m]+=l.x,c[3*m+1]+=l.y,c[3*m+2]+=l.z}for(var _=0;_<n;_++){var g=c[3*_],v=c[3*_+1],y=c[3*_+2],x=1/Math.sqrt(g*g+v*v+y*y);c[3*_]*=x,c[3*_+1]*=x,c[3*_+2]*=x}return c}function sa(e,t,i,n){for(var s=n.length/3,r=e.length/3,a=new me,o=new me,h=new me,l=new ge,c=new ge,u=new ge,d=new me,f=new me,p=new Float32Array(3*r),m=new Float32Array(3*r),_=[],g=0;g<s;g++){var v=n[3*g],y=n[3*g+1],x=n[3*g+2];a.set(e[3*v],e[3*v+1],e[3*v+2]),o.set(e[3*y],e[3*y+1],e[3*y+2]),h.set(e[3*x],e[3*x+1],e[3*x+2]),l.set(i[2*v],i[2*v+1]),c.set(i[2*y],i[2*y+1]),u.set(i[2*x],i[2*x+1]);var S=o.x-a.x,b=h.x-a.x,w=o.y-a.y,T=h.y-a.y,A=o.z-a.z,C=h.z-a.z,E=c.x-l.x,M=u.x-l.x,P=c.y-l.y,R=u.y-l.y,I=E*R-M*P;if(0===I)d.set(0,1,0),f.set(1,0,0);else{var L=1/I;d.set((R*S-P*b)*L,(R*w-P*T)*L,(R*A-P*C)*L),f.set((E*b-M*S)*L,(E*T-M*w)*L,(E*C-M*A)*L)}p[3*v+0]+=d.x,p[3*v+1]+=d.y,p[3*v+2]+=d.z,p[3*y+0]+=d.x,p[3*y+1]+=d.y,p[3*y+2]+=d.z,p[3*x+0]+=d.x,p[3*x+1]+=d.y,p[3*x+2]+=d.z,m[3*v+0]+=f.x,m[3*v+1]+=f.y,m[3*v+2]+=f.z,m[3*y+0]+=f.x,m[3*y+1]+=f.y,m[3*y+2]+=f.z,m[3*x+0]+=f.x,m[3*x+1]+=f.y,m[3*x+2]+=f.z}for(var D=new me,O=new me,k=new me,F=new me,B=0;B<r;B++){k.set(t[3*B],t[3*B+1],t[3*B+2]),D.set(p[3*B],p[3*B+1],p[3*B+2]),O.set(m[3*B],m[3*B+1],m[3*B+2]);var N=k.dot(D);F.copy(k).mulScalar(N),F.sub2(D,F).normalize(),_[4*B]=F.x,_[4*B+1]=F.y,_[4*B+2]=F.z,F.cross(k,D),_[4*B+3]=F.dot(O)<0?-1:1}return _}function ra(e,t,i){var n=new Jr(e);return n.setPositions(t),i&&(i.normals&&n.setNormals(i.normals),i.tangents&&n.setVertexStream(ut,i.tangents,4),i.colors&&n.setColors32(i.colors),i.uvs&&n.setUvs(0,i.uvs),i.uvs1&&n.setUvs(1,i.uvs1),i.blendIndices&&n.setVertexStream(ft,i.blendIndices,4,i.blendIndices.length/4,1),i.blendWeights&&n.setVertexStream(dt,i.blendWeights,4),i.indices&&n.setIndices(i.indices)),n.update(),n}function aa(e,t){var i,n,s,r,a;void 0===t&&(t={});for(var o=null!=(i=t.tubeRadius)?i:.2,h=null!=(n=t.ringRadius)?n:.3,l=null!=(s=t.segments)?s:30,c=null!=(r=t.sides)?r:20,u=null!=(a=t.calculateTangents)&&a,d=[],f=[],p=[],m=[],_=0;_<=c;_++)for(var g=0;g<=l;g++){var v=Math.cos(2*Math.PI*g/l)*(h+o*Math.cos(2*Math.PI*_/c)),y=Math.sin(2*Math.PI*_/c)*o,x=Math.sin(2*Math.PI*g/l)*(h+o*Math.cos(2*Math.PI*_/c)),S=Math.cos(2*Math.PI*g/l)*Math.cos(2*Math.PI*_/c),b=Math.sin(2*Math.PI*_/c),w=Math.sin(2*Math.PI*g/l)*Math.cos(2*Math.PI*_/c),T=_/c,A=1-g/l;if(d.push(v,y,x),f.push(S,b,w),p.push(T,1-A),_<c&&g<l){var C=_*(l+1)+g,E=(_+1)*(l+1)+g,M=_*(l+1)+(g+1),P=(_+1)*(l+1)+(g+1);m.push(C,E,M),m.push(E,P,M)}}var R={normals:f,uvs:p,uvs1:p,indices:m};return u&&(R.tangents=sa(d,f,p,m)),ra(e,d,R)}function oa(e,t,i,n,s,r){var a,o=new me,h=new me,l=new me,c=new me,u=new me,d=new me,f=[],p=[],m=[],_=[],g=[];if(i>0)for(var v=0;v<=n;v++)for(var y=0;y<=s;y++){var x=y/s*2*Math.PI-Math.PI,S=Math.sin(x),b=Math.cos(x);u.set(S*e,-i/2,b*e),c.set(S*t,i/2,b*t),o.lerp(u,c,v/n),h.sub2(c,u).normalize(),d.set(b,0,-S),l.cross(d,h).normalize(),f.push(o.x,o.y,o.z),p.push(l.x,l.y,l.z);var w=y/s,T=v/n;m.push(w,1-T);var A=T;if(T=w,w=(w=A)*ta+ea,T=T*ta+ea,w/=3,_.push(w,1-T),v<n&&y<s){var C=v*(s+1)+y,E=v*(s+1)+(y+1),M=(v+1)*(s+1)+y,P=(v+1)*(s+1)+(y+1);g.push(C,E,M),g.push(E,P,M)}}if(r){for(var R=Math.floor(s/2),I=s,L=i/2,D=0;D<=R;D++)for(var O=D*Math.PI*.5/R,k=Math.sin(O),F=Math.cos(O),B=0;B<=I;B++){var N=2*B*Math.PI/I-Math.PI/2,U=Math.sin(N),z=Math.cos(N)*k,V=F,G=U*k,H=1-B/I,W=1-D/R;f.push(z*t,V*t+L,G*t),p.push(z,V,G),m.push(H,1-W),H=H*ta+ea,W=W*ta+ea,H/=3,W/=3,H+=1/3,_.push(H,1-W)}a=(n+1)*(s+1);for(var X=0;X<R;++X)for(var j=0;j<I;++j){var q=X*(I+1)+j,Y=q+I+1;g.push(a+q+1,a+Y,a+q),g.push(a+q+1,a+Y+1,a+Y)}for(var K=0;K<=R;K++)for(var Z=.5*Math.PI+K*Math.PI*.5/R,$=Math.sin(Z),Q=Math.cos(Z),J=0;J<=I;J++){var ee=2*J*Math.PI/I-Math.PI/2,te=Math.sin(ee),ie=Math.cos(ee)*$,ne=Q,se=te*$,re=1-J/I,ae=1-K/R;f.push(ie*t,ne*t-L,se*t),p.push(ie,ne,se),m.push(re,1-ae),re=re*ta+ea,ae=ae*ta+ea,re/=3,ae/=3,re+=2/3,_.push(re,1-ae)}a=(n+1)*(s+1)+(I+1)*(R+1);for(var oe=0;oe<R;++oe)for(var he=0;he<I;++he){var le=oe*(I+1)+he,ce=le+I+1;g.push(a+le+1,a+ce,a+le),g.push(a+le+1,a+ce+1,a+ce)}}else{if(a=(n+1)*(s+1),e>0)for(var ue=0;ue<s;ue++){var de=ue/s*2*Math.PI,fe=Math.sin(de),pe=-i/2,_e=Math.cos(de),ge=1-(fe+1)/2,ve=(_e+1)/2;f.push(fe*e,pe,_e*e),p.push(0,-1,0),m.push(ge,1-ve),ge=ge*ta+ea,ve=ve*ta+ea,ge/=3,ve/=3,ge+=1/3,_.push(ge,1-ve),ue>1&&g.push(a,a+ue,a+ue-1)}if(a+=s,t>0)for(var ye=0;ye<s;ye++){var xe=ye/s*2*Math.PI,Se=Math.sin(xe),be=i/2,we=Math.cos(xe),Te=1-(Se+1)/2,Ae=(we+1)/2;f.push(Se*t,be,we*t),p.push(0,1,0),m.push(Te,1-Ae),Te=Te*ta+ea,Ae=Ae*ta+ea,Te/=3,Ae/=3,Te+=2/3,_.push(Te,1-Ae),ye>1&&g.push(a,a+ye-1,a+ye)}}return{positions:f,normals:p,uvs:m,uvs1:_,indices:g}}function ha(e,t){var i,n,s,r,a;void 0===t&&(t={});var o=null!=(i=t.radius)?i:.5,h=null!=(n=t.height)?n:1,l=null!=(s=t.heightSegments)?s:5,c=null!=(r=t.capSegments)?r:20,u=null!=(a=t.calculateTangents)&&a,d=oa(o,o,h,l,c,!1);return u&&(d.tangents=sa(d.positions,d.normals,d.uvs,d.indices)),ra(e,d.positions,d)}function la(e,t){var i,n,s,r,a;void 0===t&&(t={});var o=null!=(i=t.radius)?i:.3,h=null!=(n=t.height)?n:1,l=null!=(s=t.heightSegments)?s:1,c=null!=(r=t.sides)?r:20,u=null!=(a=t.calculateTangents)&&a,d=oa(o,o,h-2*o,l,c,!0);return u&&(d.tangents=sa(d.positions,d.normals,d.uvs,d.indices)),ra(e,d.positions,d)}function ca(e,t){var i,n,s,r,a,o;void 0===t&&(t={});var h=null!=(i=t.baseRadius)?i:.5,l=null!=(n=t.peakRadius)?n:0,c=null!=(s=t.height)?s:1,u=null!=(r=t.heightSegments)?r:5,d=null!=(a=t.capSegments)?a:18,f=null!=(o=t.calculateTangents)&&o,p=oa(h,l,c,u,d,!1);return f&&(p.tangents=sa(p.positions,p.normals,p.uvs,p.indices)),ra(e,p.positions,p)}function ua(e,t){var i,n,s,r;void 0===t&&(t={});for(var a=null!=(i=t.radius)?i:.5,o=null!=(n=t.latitudeBands)?n:16,h=null!=(s=t.longitudeBands)?s:16,l=null!=(r=t.calculateTangents)&&r,c=[],u=[],d=[],f=[],p=0;p<=o;p++)for(var m=p*Math.PI/o,_=Math.sin(m),g=Math.cos(m),v=0;v<=h;v++){var y=2*v*Math.PI/h-Math.PI/2,x=Math.sin(y),S=Math.cos(y)*_,b=g,w=x*_,T=1-v/h,A=1-p/o;c.push(S*a,b*a,w*a),u.push(S,b,w),d.push(T,1-A)}for(var C=0;C<o;++C)for(var E=0;E<h;++E){var M=C*(h+1)+E,P=M+h+1;f.push(M+1,P,M),f.push(M+1,P+1,P)}var R={normals:u,uvs:d,uvs1:d,indices:f};return l&&(R.tangents=sa(c,u,d,f)),ra(e,c,R)}function da(e,t){var i,n,s,r;void 0===t&&(t={});for(var a=null!=(i=t.halfExtents)?i:new ge(.5,.5),o=null!=(n=t.widthSegments)?n:5,h=null!=(s=t.lengthSegments)?s:5,l=null!=(r=t.calculateTangents)&&r,c=[],u=[],d=[],f=[],p=0,m=0;m<=o;m++)for(var _=0;_<=h;_++){var g=-a.x+2*a.x*m/o,v=-(-a.y+2*a.y*_/h),y=m/o,x=_/h;c.push(g,0,v),u.push(0,1,0),d.push(y,1-x),m<o&&_<h&&(f.push(p+h+1,p+1,p),f.push(p+h+1,p+h+2,p+1)),p++}var S={normals:u,uvs:d,uvs1:d,indices:f};return l&&(S.tangents=sa(c,u,d,f)),ra(e,c,S)}function fa(e,t){var i,n,s,r,a;void 0===t&&(t={});var o=null!=(i=t.halfExtents)?i:new me(.5,.5,.5),h=null!=(n=t.widthSegments)?n:1,l=null!=(s=t.lengthSegments)?s:1,c=null!=(r=t.heightSegments)?r:1,u=null!=(a=t.calculateTangents)&&a,d=[new me(-o.x,-o.y,o.z),new me(o.x,-o.y,o.z),new me(o.x,o.y,o.z),new me(-o.x,o.y,o.z),new me(o.x,-o.y,-o.z),new me(-o.x,-o.y,-o.z),new me(-o.x,o.y,-o.z),new me(o.x,o.y,-o.z)],f=[[0,1,3],[4,5,7],[3,2,6],[1,0,4],[1,4,2],[5,0,6]],p=[[0,0,1],[0,0,-1],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0]],m=1,_=2,g=3,v=4,y=5,x=[],S=[],b=[],w=[],T=[],A=0,C=function(e,t,i){for(var n=new me,s=new me,r=new me,a=new me,o=0;o<=t;o++)for(var h=0;h<=i;h++){n.lerp(d[f[e][0]],d[f[e][1]],o/t),s.lerp(d[f[e][0]],d[f[e][2]],h/i),r.sub2(s,d[f[e][0]]),a.add2(n,r);var l=o/t,c=h/i;x.push(a.x,a.y,a.z),S.push(p[e][0],p[e][1],p[e][2]),b.push(l,1-c),l=l*ta+ea,c=c*ta+ea,l/=3,c/=3,l+=e%3/3,c+=Math.floor(e/3)/3,w.push(l,1-c),o<t&&h<i&&(T.push(A+i+1,A+1,A),T.push(A+i+1,A+i+2,A+1)),A++}};C(0,h,c),C(m,h,c),C(_,h,l),C(g,h,l),C(v,l,c),C(y,l,c);var E={normals:S,uvs:b,uvs1:w,indices:T};return u&&(E.tangents=sa(x,S,b,T)),ra(e,x,E)}function pa(e,t){for(var i=null,n=0;n<ia.length;n++)ia[n].type===t&&ia[n].device===e&&(i=ia[n].primData);if(!i){var s,r;switch(t){case"box":s=fa(e),r={x:2,y:2,z:2,uv:2/3};break;case"capsule":s=la(e,{radius:.5,height:2}),r={x:2*Math.PI,y:Math.PI,z:2*Math.PI,uv:1/3+1/3/3*2};break;case"cone":s=ca(e,{baseRadius:.5,peakRadius:0,height:1}),r={x:2.54,y:2.54,z:2.54,uv:1/3+1/3/3};break;case"cylinder":s=ha(e,{radius:.5,height:1}),r={x:Math.PI,y:1.58,z:Math.PI,uv:1/3+1/3/3*2};break;case"plane":s=da(e,{halfExtents:new ge(.5,.5),widthSegments:1,lengthSegments:1}),r={x:0,y:1,z:0,uv:1};break;case"sphere":s=ua(e,{radius:.5}),r={x:Math.PI,y:Math.PI,z:Math.PI,uv:1};break;case"torus":s=aa(e,{tubeRadius:.2,ringRadius:.3}),r={x:.5*Math.PI*.5-.1*Math.PI*.1,y:.4,z:.4,uv:1};break;default:throw new Error("Invalid primitive type: "+t)}s.incRefCount(),i={mesh:s,area:r},ia.push({type:t,device:e,primData:i})}return i}var ma=function(){this.clearValue=new ue(0,0,0,1),this.clear=!1,this.store=!1,this.resolve=!0,this.mipmaps=!1},_a=function(){this.clearDepthValue=1,this.clearStencilValue=0,this.clearDepth=!1,this.clearStencil=!1,this.storeDepth=!1,this.storeStencil=!1},ga=function(){function e(e,t){this.name=void 0,this.renderTarget=void 0,this.samples=0,this.colorArrayOps=[],this.depthStencilOps=void 0,this.requiresCubemaps=!0,this.fullSizeClearRect=!0,this.execute=void 0,this.before=void 0,this.after=void 0,this.device=e,this.execute=t}var t=e.prototype;return t.init=function(e){var t;this.renderTarget=e||null,this.samples=Math.max(this.renderTarget?this.renderTarget.samples:this.device.samples,1),this.depthStencilOps=new _a;for(var i=e?null==(t=e._colorBuffers)?void 0:t.length:1,n=0;n<i;n++){var s,r,a=new ma;this.colorArrayOps[n]=a,1===this.samples&&(a.store=!0,a.resolve=!1),null!=(s=this.renderTarget)&&null!=(r=s._colorBuffers)&&r[n].mipmaps&&(a.mipmaps=!0)}},t.setClearColor=function(e){for(var t=this.colorArrayOps.length,i=0;i<t;i++){var n=this.colorArrayOps[i];n.clearValue.copy(e),n.clear=!0}},t.setClearDepth=function(e){this.depthStencilOps.clearDepthValue=e,this.depthStencilOps.clearDepth=!0},t.setClearStencil=function(e){this.depthStencilOps.clearStencilValue=e,this.depthStencilOps.clearStencil=!0},t.render=function(){var e,t,i,n=this.device,s=void 0!==this.renderTarget;null==(e=this.before)||e.call(this),s&&n.startPass(this),null==(t=this.execute)||t.call(this),s&&n.endPass(this),null==(i=this.after)||i.call(this),n.renderPassIndex++},Z(e,[{key:"colorOps",get:function(){return this.colorArrayOps[0]}}]),e}(),va=function(){function e(e,t,i){this.uniformFormats=[],this.bindGroupFormats=[],this.vertexFormat=void 0,this.uniformFormats[1]=e,this.bindGroupFormats[1]=t,this.vertexFormat=i}var t=e.prototype;return t.hasUniform=function(e){for(var t=0;t<this.uniformFormats.length;t++){var i=this.uniformFormats[t];if(null!=i&&i.get(e))return!0}return!1},t.hasTexture=function(e){for(var t=0;t<this.bindGroupFormats.length;t++){var i=this.bindGroupFormats[t];if(null!=i&&i.getTexture(e))return!0}return!1},t.getVertexElement=function(e){var t;return null==(t=this.vertexFormat)?void 0:t.elements.find((function(t){return t.name===e}))},t.generateKey=function(){var e;return JSON.stringify(this.uniformFormats)+JSON.stringify(this.bindGroupFormats)+(null==(e=this.vertexFormat)?void 0:e.renderingHashString)},e}(),ya="\nvec3 decodeLinear(vec4 raw) {\n return raw.rgb;\n}\n\nfloat decodeGamma(float raw) {\n return pow(raw, 2.2);\n}\n\nvec3 decodeGamma(vec3 raw) {\n return pow(raw, vec3(2.2));\n}\n\nvec3 decodeGamma(vec4 raw) {\n return pow(raw.xyz, vec3(2.2));\n}\n\nvec3 decodeRGBM(vec4 raw) {\n vec3 color = (8.0 * raw.a) * raw.rgb;\n return color * color;\n}\n\nvec3 decodeRGBP(vec4 raw) {\n vec3 color = raw.rgb * (-raw.a * 7.0 + 8.0);\n return color * color;\n}\n\nvec3 decodeRGBE(vec4 raw) {\n if (raw.a == 0.0) {\n return vec3(0.0, 0.0, 0.0);\n } else {\n return raw.xyz * pow(2.0, raw.w * 255.0 - 128.0);\n }\n}\n\nvec4 passThrough(vec4 raw) {\n return raw;\n}\n",xa="\nvec4 encodeLinear(vec3 source) {\n return vec4(source, 1.0);\n}\n\nvec4 encodeGamma(vec3 source) {\n return vec4(pow(source + 0.0000001, vec3(1.0 / 2.2)), 1.0);\n}\n\nvec4 encodeRGBM(vec3 source) { // modified RGBM\n vec4 result;\n result.rgb = pow(source.rgb, vec3(0.5));\n result.rgb *= 1.0 / 8.0;\n\n result.a = saturate( max( max( result.r, result.g ), max( result.b, 1.0 / 255.0 ) ) );\n result.a = ceil(result.a * 255.0) / 255.0;\n\n result.rgb /= result.a;\n return result;\n}\n\nvec4 encodeRGBP(vec3 source) {\n // convert incoming linear to gamma(ish)\n vec3 gamma = pow(source, vec3(0.5));\n\n // calculate the maximum component clamped to 1..8\n float maxVal = min(8.0, max(1.0, max(gamma.x, max(gamma.y, gamma.z))));\n\n // calculate storage factor\n float v = 1.0 - ((maxVal - 1.0) / 7.0);\n\n // round the value for storage in 8bit channel\n v = ceil(v * 255.0) / 255.0;\n\n return vec4(gamma / (-v * 7.0 + 8.0), v); \n}\n\nvec4 encodeRGBE(vec3 source) {\n float maxVal = max(source.x, max(source.y, source.z));\n if (maxVal < 1e-32) {\n return vec4(0, 0, 0, 0);\n } else {\n float e = ceil(log2(maxVal));\n return vec4(source / pow(2.0, e), (e + 128.0) / 255.0);\n }\n}\n",Sa={alphaTestPS:"\nuniform float alpha_ref;\n\nvoid alphaTest(float a) {\n if (a < alpha_ref) discard;\n}\n",ambientConstantPS:"\nvoid addAmbient(vec3 worldNormal) {\n dDiffuseLight += light_globalAmbient;\n}\n",ambientEnvPS:"\n#ifndef ENV_ATLAS\n#define ENV_ATLAS\nuniform sampler2D texture_envAtlas;\n#endif\n\nvoid addAmbient(vec3 worldNormal) {\n vec3 dir = normalize(cubeMapRotate(worldNormal) * vec3(-1.0, 1.0, 1.0));\n vec2 uv = mapUv(toSphericalUv(dir), vec4(128.0, 256.0 + 128.0, 64.0, 32.0) / atlasSize);\n\n vec4 raw = texture2D(texture_envAtlas, uv);\n vec3 linear = $DECODE(raw);\n dDiffuseLight += processEnvironment(linear);\n}\n",ambientSHPS:"\nuniform vec3 ambientSH[9];\n\nvoid addAmbient(vec3 worldNormal) {\n vec3 n = cubeMapRotate(worldNormal);\n\n vec3 color =\n ambientSH[0] +\n ambientSH[1] * n.x +\n ambientSH[2] * n.y +\n ambientSH[3] * n.z +\n ambientSH[4] * n.x * n.z +\n ambientSH[5] * n.z * n.y +\n ambientSH[6] * n.y * n.x +\n ambientSH[7] * (3.0 * n.z * n.z - 1.0) +\n ambientSH[8] * (n.x * n.x - n.y * n.y);\n\n dDiffuseLight += processEnvironment(max(color, vec3(0.0)));\n}\n",aoPS:"\n\nvoid getAO() {\n dAo = 1.0;\n\n #ifdef MAPTEXTURE\n float aoBase = texture2DBias($SAMPLER, $UV, textureBias).$CH;\n dAo *= addAoDetail(aoBase);\n #endif\n\n #ifdef MAPVERTEX\n dAo *= saturate(vVertexColor.$VC);\n #endif\n}\n",aoDetailMapPS:"\nfloat addAoDetail(float ao) {\n#ifdef MAPTEXTURE\n float aoDetail = texture2DBias($SAMPLER, $UV, textureBias).$CH;\n return detailMode_$DETAILMODE(vec3(ao), vec3(aoDetail)).r;\n#else\n return ao;\n#endif\n}\n",aoDiffuseOccPS:"\nvoid occludeDiffuse(float ao) {\n dDiffuseLight *= ao;\n}\n",aoSpecOccPS:"\nuniform float material_occludeSpecularIntensity;\n\nvoid occludeSpecular(float gloss, float ao, vec3 worldNormal, vec3 viewDir) {\n // approximated specular occlusion from AO\n float specPow = exp2(gloss * 11.0);\n // http://research.tri-ace.com/Data/cedec2011_RealtimePBR_Implementation_e.pptx\n float specOcc = saturate(pow(dot(worldNormal, viewDir) + ao, 0.01*specPow) - 1.0 + ao);\n specOcc = mix(1.0, specOcc, material_occludeSpecularIntensity);\n\n dSpecularLight *= specOcc;\n dReflection *= specOcc;\n \n#ifdef LIT_SHEEN\n sSpecularLight *= specOcc;\n sReflection *= specOcc;\n#endif\n}\n",aoSpecOccConstPS:"\nvoid occludeSpecular(float gloss, float ao, vec3 worldNormal, vec3 viewDir) {\n // approximated specular occlusion from AO\n float specPow = exp2(gloss * 11.0);\n // http://research.tri-ace.com/Data/cedec2011_RealtimePBR_Implementation_e.pptx\n float specOcc = saturate(pow(dot(worldNormal, viewDir) + ao, 0.01*specPow) - 1.0 + ao);\n\n dSpecularLight *= specOcc;\n dReflection *= specOcc;\n \n#ifdef LIT_SHEEN\n sSpecularLight *= specOcc;\n sReflection *= specOcc;\n#endif\n}\n",aoSpecOccConstSimplePS:"\nvoid occludeSpecular(float gloss, float ao, vec3 worldNormal, vec3 viewDir) {\n dSpecularLight *= ao;\n dReflection *= ao;\n\n#ifdef LIT_SHEEN\n sSpecularLight *= ao;\n sReflection *= ao;\n#endif\n}\n",aoSpecOccSimplePS:"\nuniform float material_occludeSpecularIntensity;\n\nvoid occludeSpecular(float gloss, float ao, vec3 worldNormal, vec3 viewDir) {\n float specOcc = mix(1.0, ao, material_occludeSpecularIntensity);\n dSpecularLight *= specOcc;\n dReflection *= specOcc;\n\n#ifdef LIT_SHEEN\n sSpecularLight *= specOcc;\n sReflection *= specOcc;\n#endif\n}\n",basePS:"\nuniform vec3 view_position;\n\nuniform vec3 light_globalAmbient;\n\nfloat square(float x) {\n return x*x;\n}\n\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n\nvec3 saturate(vec3 x) {\n return clamp(x, vec3(0.0), vec3(1.0));\n}\n",baseVS:"\nattribute vec3 vertex_position;\nattribute vec3 vertex_normal;\nattribute vec4 vertex_tangent;\nattribute vec2 vertex_texCoord0;\nattribute vec2 vertex_texCoord1;\nattribute vec4 vertex_color;\n\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\nuniform mat3 matrix_normal;\n\nvec3 dPositionW;\nmat4 dModelMatrix;\nmat3 dNormalMatrix;\n",baseNineSlicedPS:"\n#define NINESLICED\n\nvarying vec2 vMask;\nvarying vec2 vTiledUv;\n\nuniform mediump vec4 innerOffset;\nuniform mediump vec2 outerScale;\nuniform mediump vec4 atlasRect;\n\nvec2 nineSlicedUv;\n",baseNineSlicedVS:"\n#define NINESLICED\n\nvarying vec2 vMask;\nvarying vec2 vTiledUv;\n\nuniform mediump vec4 innerOffset;\nuniform mediump vec2 outerScale;\nuniform mediump vec4 atlasRect;\n",baseNineSlicedTiledPS:"\n#define NINESLICED\n#define NINESLICETILED\n\nvarying vec2 vMask;\nvarying vec2 vTiledUv;\n\nuniform mediump vec4 innerOffset;\nuniform mediump vec2 outerScale;\nuniform mediump vec4 atlasRect;\n\nvec2 nineSlicedUv;\n",biasConstPS:"\n#define SHADOWBIAS\n#define SHADOW_SAMPLE_Z_BIAS\n\nfloat getShadowBias(float resolution, float maxBias) {\n return maxBias;\n}\n",blurVSMPS:"\nvarying vec2 vUv0;\n\nuniform sampler2D source;\nuniform vec2 pixelOffset;\n\n#ifdef GAUSS\nuniform float weight[SAMPLES];\n#endif\n\n#ifdef PACKED\nfloat decodeFloatRG(vec2 rg) {\n return rg.y*(1.0/255.0) + rg.x;\n}\n\nvec2 encodeFloatRG( float v ) {\n vec2 enc = vec2(1.0, 255.0) * v;\n enc = fract(enc);\n enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n return enc;\n}\n#endif\n\nvoid main(void) {\n vec3 moments = vec3(0.0);\n vec2 uv = vUv0 - pixelOffset * (float(SAMPLES) * 0.5);\n for (int i=0; i<SAMPLES; i++) {\n vec4 c = texture2D(source, uv + pixelOffset * float(i));\n\n #ifdef PACKED\n c.xy = vec2(decodeFloatRG(c.xy), decodeFloatRG(c.zw));\n #endif\n\n #ifdef GAUSS\n moments += c.xyz * weight[i];\n #else\n moments += c.xyz;\n #endif\n }\n\n #ifndef GAUSS\n moments /= float(SAMPLES);\n #endif\n\n #ifdef PACKED\n gl_FragColor = vec4(encodeFloatRG(moments.x), encodeFloatRG(moments.y));\n #else\n gl_FragColor = vec4(moments.x, moments.y, moments.z, 1.0);\n #endif\n}\n",clearCoatPS:"\n#ifdef MAPFLOAT\nuniform float material_clearCoat;\n#endif\n\nvoid getClearCoat() {\n ccSpecularity = 1.0;\n\n #ifdef MAPFLOAT\n ccSpecularity *= material_clearCoat;\n #endif\n\n #ifdef MAPTEXTURE\n ccSpecularity *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n ccSpecularity *= saturate(vVertexColor.$VC);\n #endif\n}\n",clearCoatGlossPS:"\n#ifdef MAPFLOAT\nuniform float material_clearCoatGloss;\n#endif\n\nvoid getClearCoatGlossiness() {\n ccGlossiness = 1.0;\n\n #ifdef MAPFLOAT\n ccGlossiness *= material_clearCoatGloss;\n #endif\n\n #ifdef MAPTEXTURE\n ccGlossiness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n ccGlossiness *= saturate(vVertexColor.$VC);\n #endif\n\n #ifdef MAPINVERT\n ccGlossiness = 1.0 - ccGlossiness;\n #endif\n\n ccGlossiness += 0.0000001;\n}\n",clearCoatNormalPS:"\n#ifdef MAPTEXTURE\nuniform float material_clearCoatBumpiness;\n#endif\n\nvoid getClearCoatNormal() {\n#ifdef MAPTEXTURE\n vec3 normalMap = unpackNormal(texture2DBias($SAMPLER, $UV, textureBias));\n normalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, material_clearCoatBumpiness);\n ccNormalW = normalize(dTBN * normalMap);\n#else\n ccNormalW = dVertexNormalW;\n#endif\n}\n",clusteredLightCookiesPS:"\nvec3 _getCookieClustered(TEXTURE_ACCEPT(tex), vec2 uv, float intensity, bool isRgb, vec4 cookieChannel) {\n vec4 pixel = mix(vec4(1.0), texture2DLodEXT(tex, uv, 0.0), intensity);\n return isRgb == true ? pixel.rgb : vec3(dot(pixel, cookieChannel));\n}\n\n// getCookie2D for clustered lighting including channel selector\nvec3 getCookie2DClustered(TEXTURE_ACCEPT(tex), mat4 transform, vec3 worldPosition, float intensity, bool isRgb, vec4 cookieChannel) {\n vec4 projPos = transform * vec4(worldPosition, 1.0);\n return _getCookieClustered(TEXTURE_PASS(tex), projPos.xy / projPos.w, intensity, isRgb, cookieChannel);\n}\n\n// getCookie for clustered omni light with the cookie texture being stored in the cookie atlas\nvec3 getCookieCubeClustered(TEXTURE_ACCEPT(tex), vec3 dir, float intensity, bool isRgb, vec4 cookieChannel, float shadowTextureResolution, float shadowEdgePixels, vec3 omniAtlasViewport) {\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);\n return _getCookieClustered(TEXTURE_PASS(tex), uv, intensity, isRgb, cookieChannel);\n}\n",clusteredLightShadowsPS:"\n// Clustered Omni Sampling using atlas\n\n\nvoid _getShadowCoordPerspZbuffer(mat4 shadowMatrix, vec4 shadowParams, vec3 wPos) {\n vec4 projPos = shadowMatrix * vec4(wPos, 1.0);\n projPos.xyz /= projPos.w;\n dShadowCoord = projPos.xyz;\n // depth bias is already applied on render\n}\n\nvoid getShadowCoordPerspZbufferNormalOffset(mat4 shadowMatrix, vec4 shadowParams, vec3 normal) {\n vec3 wPos = vPositionW + normal * shadowParams.y;\n _getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, wPos);\n}\n\nvec3 normalOffsetPointShadow(vec4 shadowParams, vec3 lightPos, inout 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; //0.02\n vec3 dir = wPos - lightPos;\n return dir;\n}\n\n#ifdef GL2\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\n float getShadowOmniClusteredPCF1(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {\n\n float shadowTextureResolution = shadowParams.x;\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n\n float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;\n return textureShadow(shadowMap, vec3(uv, shadowZ));\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\n float getShadowOmniClusteredPCF3(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {\n\n float shadowTextureResolution = shadowParams.x;\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n\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\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\n float getShadowOmniClusteredPCF5(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {\n\n float shadowTextureResolution = shadowParams.x;\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n\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\n #endif\n\n#else\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\n float getShadowOmniClusteredPCF1(sampler2D shadowMap, vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {\n\n float shadowTextureResolution = shadowParams.x;\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n\n // no filter shadow sampling\n float depth = unpackFloat(textureShadow(shadowMap, uv));\n float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;\n return depth > shadowZ ? 1.0 : 0.0;\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\n float getShadowOmniClusteredPCF3(sampler2D shadowMap, vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {\n\n float shadowTextureResolution = shadowParams.x;\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n\n // pcf3\n float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;\n vec3 shadowCoord = vec3(uv, shadowZ);\n return getShadowPCF3x3(shadowMap, shadowCoord, shadowParams);\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\n // we don't have PCF5 implementation for webgl1, use PCF3\n float getShadowOmniClusteredPCF5(sampler2D shadowMap, vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {\n\n float shadowTextureResolution = shadowParams.x;\n vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);\n\n // pcf3\n float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;\n vec3 shadowCoord = vec3(uv, shadowZ);\n return getShadowPCF3x3(shadowMap, shadowCoord, shadowParams);\n }\n\n #endif\n\n#endif\n\n\n// Clustered Spot Sampling using atlas\n\n#ifdef GL2\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\n float getShadowSpotClusteredPCF1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return textureShadow(shadowMap, shadowCoord);\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\n float getShadowSpotClusteredPCF3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return getShadowSpotPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\n float getShadowSpotClusteredPCF5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);\n }\n #endif\n\n#else\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n\n float getShadowSpotClusteredPCF1(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n\n float depth = unpackFloat(textureShadow(shadowMap, shadowCoord.xy));\n\n return depth > shadowCoord.z ? 1.0 : 0.0;\n\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF3)\n\n float getShadowSpotClusteredPCF3(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n return getShadowSpotPCF3x3(shadowMap, shadowCoord, shadowParams);\n }\n\n #endif\n\n #if defined(CLUSTER_SHADOW_TYPE_PCF5)\n\n // we don't have PCF5 implementation for webgl1, use PCF3\n float getShadowSpotClusteredPCF5(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n return getShadowSpotPCF3x3(shadowMap, shadowCoord, shadowParams);\n }\n\n #endif\n\n#endif\n",clusteredLightUtilsPS:"\n// Converts unnormalized direction vector to a cubemap face index [0..5] and uv coordinates within the face in [0..1] range.\n// Additionally offset to a tile in atlas within 3x3 subdivision is provided\nvec2 getCubemapFaceCoordinates(const vec3 dir, out float faceIndex, out vec2 tileOffset)\n{\n vec3 vAbs = abs(dir);\n float ma;\n vec2 uv;\n if (vAbs.z >= vAbs.x && vAbs.z >= vAbs.y) { // front / back\n\n faceIndex = dir.z < 0.0 ? 5.0 : 4.0;\n ma = 0.5 / vAbs.z;\n uv = vec2(dir.z < 0.0 ? -dir.x : dir.x, -dir.y);\n\n tileOffset.x = 2.0;\n tileOffset.y = dir.z < 0.0 ? 1.0 : 0.0;\n\n } else if(vAbs.y >= vAbs.x) { // top index 2, bottom index 3\n\n faceIndex = dir.y < 0.0 ? 3.0 : 2.0;\n ma = 0.5 / vAbs.y;\n uv = vec2(dir.x, dir.y < 0.0 ? -dir.z : dir.z);\n\n tileOffset.x = 1.0;\n tileOffset.y = dir.y < 0.0 ? 1.0 : 0.0;\n\n } else { // left / right\n\n faceIndex = dir.x < 0.0 ? 1.0 : 0.0;\n ma = 0.5 / vAbs.x;\n uv = vec2(dir.x < 0.0 ? dir.z : -dir.z, -dir.y);\n\n tileOffset.x = 0.0;\n tileOffset.y = dir.x < 0.0 ? 1.0 : 0.0;\n\n }\n return uv * ma + 0.5;\n}\n\n// converts unnormalized direction vector to a texture coordinate for a cubemap face stored within texture atlas described by the viewport\nvec2 getCubemapAtlasCoordinates(const vec3 omniAtlasViewport, float shadowEdgePixels, float shadowTextureResolution, const vec3 dir) {\n\n float faceIndex;\n vec2 tileOffset;\n vec2 uv = getCubemapFaceCoordinates(dir, faceIndex, tileOffset);\n\n // move uv coordinates inwards inside to compensate for larger fov when rendering shadow into atlas\n float atlasFaceSize = omniAtlasViewport.z;\n float tileSize = shadowTextureResolution * atlasFaceSize;\n float offset = shadowEdgePixels / tileSize;\n uv = uv * vec2(1.0 - offset * 2.0) + vec2(offset * 1.0);\n\n // scale uv coordinates to cube face area within the viewport\n uv *= atlasFaceSize;\n\n // offset into face of the atlas (3x3 grid)\n uv += tileOffset * atlasFaceSize;\n\n // offset into the atlas viewport\n uv += omniAtlasViewport.xy;\n\n return uv;\n}\n",clusteredLightPS:"\nuniform highp sampler2D clusterWorldTexture;\nuniform highp sampler2D lightsTexture8;\nuniform highp sampler2D lightsTextureFloat;\n\n// complex ifdef expression are not supported, handle it here\n// defined(CLUSTER_COOKIES) || defined(CLUSTER_SHADOWS)\n#if defined(CLUSTER_COOKIES)\n #define CLUSTER_COOKIES_OR_SHADOWS\n#endif\n#if defined(CLUSTER_SHADOWS)\n #define CLUSTER_COOKIES_OR_SHADOWS\n#endif\n\n#ifdef CLUSTER_SHADOWS\n #ifdef GL2\n // TODO: when VSM shadow is supported, it needs to use sampler2D in webgl2\n uniform sampler2DShadow shadowAtlasTexture;\n #else\n uniform sampler2D shadowAtlasTexture;\n #endif\n#endif\n\n#ifdef CLUSTER_COOKIES\n uniform sampler2D cookieAtlasTexture;\n#endif\n\n#ifdef GL2\n uniform int clusterMaxCells;\n#else\n uniform float clusterMaxCells;\n uniform vec4 lightsTextureInvSize;\n#endif\n\n// 1.0 if clustered lighting can be skipped (0 lights in the clusters)\nuniform float clusterSkip;\n\nuniform vec3 clusterCellsCountByBoundsSize;\nuniform vec3 clusterTextureSize;\nuniform vec3 clusterBoundsMin;\nuniform vec3 clusterBoundsDelta;\nuniform vec3 clusterCellsDot;\nuniform vec3 clusterCellsMax;\nuniform vec2 clusterCompressionLimit0;\nuniform vec2 shadowAtlasParams;\n\n// structure storing light properties of a clustered light\n// it's sorted to have all vectors aligned to 4 floats to limit padding\nstruct ClusterLightData {\n\n // area light sizes / orientation\n vec3 halfWidth;\n\n // type of the light (spot or omni)\n float lightType;\n\n // area light sizes / orientation\n vec3 halfHeight;\n\n #ifdef GL2\n // light index\n int lightIndex;\n #else\n // v coordinate to look up the light textures - this is the same as lightIndex but in 0..1 range\n float lightV;\n #endif\n\n // world space position\n vec3 position;\n\n // area light shape\n float shape;\n\n // world space direction (spot light only)\n vec3 direction;\n\n // light follow mode\n float falloffMode;\n\n // color\n vec3 color;\n\n // 0.0 if the light doesn't cast shadows\n float shadowIntensity;\n\n // atlas viewport for omni light shadow and cookie (.xy is offset to the viewport slot, .z is size of the face in the atlas)\n vec3 omniAtlasViewport;\n\n // range of the light\n float range;\n\n // channel mask - one of the channels has 1, the others are 0\n vec4 cookieChannelMask;\n\n // shadow bias values\n float shadowBias;\n float shadowNormalBias;\n\n // spot light inner and outer angle cosine\n float innerConeAngleCos;\n float outerConeAngleCos;\n\n // 1.0 if the light has a cookie texture\n float cookie;\n\n // 1.0 if cookie texture is rgb, otherwise it is using a single channel selectable by cookieChannelMask\n float cookieRgb;\n\n // intensity of the cookie\n float cookieIntensity;\n\n // light mask\n float mask;\n};\n\n// Note: on some devices (tested on Pixel 3A XL), this matrix when stored inside the light struct has lower precision compared to\n// when stored outside, so we store it outside to avoid spot shadow flickering. This might need to be done to other / all members\n// of the structure if further similar issues are observed.\n\n// shadow (spot light only) / cookie projection matrix\nmat4 lightProjectionMatrix;\n\n// macros for light properties\n#define isClusteredLightCastShadow(light) ( light.shadowIntensity > 0.0 )\n#define isClusteredLightCookie(light) (light.cookie > 0.5 )\n#define isClusteredLightCookieRgb(light) (light.cookieRgb > 0.5 )\n#define isClusteredLightSpot(light) ( light.lightType > 0.5 )\n#define isClusteredLightFalloffLinear(light) ( light.falloffMode < 0.5 )\n\n// macros to test light shape\n// Note: Following functions need to be called serially in listed order as they do not test both '>' and '<'\n#define isClusteredLightArea(light) ( light.shape > 0.1 )\n#define isClusteredLightRect(light) ( light.shape < 0.3 )\n#define isClusteredLightDisk(light) ( light.shape < 0.6 )\n\n// macro to test light mask (mesh accepts dynamic vs lightmapped lights)\n#ifdef CLUSTER_MESH_DYNAMIC_LIGHTS\n // accept lights marked as dynamic or both dynamic and lightmapped\n #define acceptLightMask(light) ( light.mask < 0.75)\n#else\n // accept lights marked as lightmapped or both dynamic and lightmapped\n #define acceptLightMask(light) ( light.mask > 0.25)\n#endif\n\nvec4 decodeClusterLowRange4Vec4(vec4 d0, vec4 d1, vec4 d2, vec4 d3) {\n return vec4(\n bytes2floatRange4(d0, -2.0, 2.0),\n bytes2floatRange4(d1, -2.0, 2.0),\n bytes2floatRange4(d2, -2.0, 2.0),\n bytes2floatRange4(d3, -2.0, 2.0)\n );\n}\n\n#ifdef GL2\n\n vec4 sampleLightsTexture8(const ClusterLightData clusterLightData, int index) {\n return texelFetch(lightsTexture8, ivec2(index, clusterLightData.lightIndex), 0);\n }\n\n vec4 sampleLightTextureF(const ClusterLightData clusterLightData, int index) {\n return texelFetch(lightsTextureFloat, ivec2(index, clusterLightData.lightIndex), 0);\n }\n\n#else\n\n vec4 sampleLightsTexture8(const ClusterLightData clusterLightData, float index) {\n return texture2DLodEXT(lightsTexture8, vec2(index * lightsTextureInvSize.z, clusterLightData.lightV), 0.0);\n }\n\n vec4 sampleLightTextureF(const ClusterLightData clusterLightData, float index) {\n return texture2DLodEXT(lightsTextureFloat, vec2(index * lightsTextureInvSize.x, clusterLightData.lightV), 0.0);\n }\n\n#endif\n\nvoid decodeClusterLightCore(inout ClusterLightData clusterLightData, float lightIndex) {\n\n // light index\n #ifdef GL2\n clusterLightData.lightIndex = int(lightIndex);\n #else\n clusterLightData.lightV = (lightIndex + 0.5) * lightsTextureInvSize.w;\n #endif\n\n // shared data from 8bit texture\n vec4 lightInfo = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_FLAGS);\n clusterLightData.lightType = lightInfo.x;\n clusterLightData.shape = lightInfo.y;\n clusterLightData.falloffMode = lightInfo.z;\n clusterLightData.shadowIntensity = lightInfo.w;\n\n // color\n vec4 colorA = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COLOR_A);\n vec4 colorB = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COLOR_B);\n clusterLightData.color = vec3(bytes2float2(colorA.xy), bytes2float2(colorA.zw), bytes2float2(colorB.xy)) * clusterCompressionLimit0.y;\n\n // cookie\n clusterLightData.cookie = colorB.z;\n\n // light mask\n clusterLightData.mask = colorB.w;\n\n #ifdef CLUSTER_TEXTURE_FLOAT\n\n vec4 lightPosRange = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_POSITION_RANGE);\n clusterLightData.position = lightPosRange.xyz;\n clusterLightData.range = lightPosRange.w;\n\n // spot light direction\n vec4 lightDir_Unused = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_SPOT_DIRECTION);\n clusterLightData.direction = lightDir_Unused.xyz;\n\n #else // 8bit\n\n vec4 encPosX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_POSITION_X);\n vec4 encPosY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_POSITION_Y);\n vec4 encPosZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_POSITION_Z);\n clusterLightData.position = vec3(bytes2float4(encPosX), bytes2float4(encPosY), bytes2float4(encPosZ)) * clusterBoundsDelta + clusterBoundsMin;\n\n vec4 encRange = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_RANGE);\n clusterLightData.range = bytes2float4(encRange) * clusterCompressionLimit0.x;\n\n // spot light direction\n vec4 encDirX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_DIRECTION_X);\n vec4 encDirY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_DIRECTION_Y);\n vec4 encDirZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_DIRECTION_Z);\n clusterLightData.direction = vec3(bytes2float4(encDirX), bytes2float4(encDirY), bytes2float4(encDirZ)) * 2.0 - 1.0;\n\n #endif\n}\n\nvoid decodeClusterLightSpot(inout ClusterLightData clusterLightData) {\n\n // spot light cos angles\n vec4 coneAngle = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SPOT_ANGLES);\n clusterLightData.innerConeAngleCos = bytes2float2(coneAngle.xy) * 2.0 - 1.0;\n clusterLightData.outerConeAngleCos = bytes2float2(coneAngle.zw) * 2.0 - 1.0;\n}\n\nvoid decodeClusterLightOmniAtlasViewport(inout ClusterLightData clusterLightData) {\n #ifdef CLUSTER_TEXTURE_FLOAT\n clusterLightData.omniAtlasViewport = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_0).xyz;\n #else\n vec4 viewportA = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_ATLAS_VIEWPORT_A);\n vec4 viewportB = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_ATLAS_VIEWPORT_B);\n clusterLightData.omniAtlasViewport = vec3(bytes2float2(viewportA.xy), bytes2float2(viewportA.zw), bytes2float2(viewportB.xy));\n #endif\n}\n\nvoid decodeClusterLightAreaData(inout ClusterLightData clusterLightData) {\n #ifdef CLUSTER_TEXTURE_FLOAT\n clusterLightData.halfWidth = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_AREA_DATA_WIDTH).xyz;\n clusterLightData.halfHeight = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_AREA_DATA_HEIGHT).xyz;\n #else\n vec4 areaWidthX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_WIDTH_X);\n vec4 areaWidthY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_WIDTH_Y);\n vec4 areaWidthZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_WIDTH_Z);\n clusterLightData.halfWidth = vec3(mantissaExponent2Float(areaWidthX), mantissaExponent2Float(areaWidthY), mantissaExponent2Float(areaWidthZ));\n\n vec4 areaHeightX = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_HEIGHT_X);\n vec4 areaHeightY = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_HEIGHT_Y);\n vec4 areaHeightZ = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_AREA_DATA_HEIGHT_Z);\n clusterLightData.halfHeight = vec3(mantissaExponent2Float(areaHeightX), mantissaExponent2Float(areaHeightY), mantissaExponent2Float(areaHeightZ));\n #endif\n}\n\nvoid decodeClusterLightProjectionMatrixData(inout ClusterLightData clusterLightData) {\n \n // shadow matrix\n #ifdef CLUSTER_TEXTURE_FLOAT\n vec4 m0 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_0);\n vec4 m1 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_1);\n vec4 m2 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_2);\n vec4 m3 = sampleLightTextureF(clusterLightData, CLUSTER_TEXTURE_F_PROJ_MAT_3);\n #else\n vec4 m00 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_00);\n vec4 m01 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_01);\n vec4 m02 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_02);\n vec4 m03 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_03);\n vec4 m0 = decodeClusterLowRange4Vec4(m00, m01, m02, m03);\n\n vec4 m10 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_10);\n vec4 m11 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_11);\n vec4 m12 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_12);\n vec4 m13 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_13);\n vec4 m1 = decodeClusterLowRange4Vec4(m10, m11, m12, m13);\n\n vec4 m20 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_20);\n vec4 m21 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_21);\n vec4 m22 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_22);\n vec4 m23 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_23);\n vec4 m2 = decodeClusterLowRange4Vec4(m20, m21, m22, m23);\n\n vec4 m30 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_30);\n vec4 m31 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_31);\n vec4 m32 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_32);\n vec4 m33 = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_PROJ_MAT_33);\n vec4 m3 = vec4(mantissaExponent2Float(m30), mantissaExponent2Float(m31), mantissaExponent2Float(m32), mantissaExponent2Float(m33));\n #endif\n \n lightProjectionMatrix = mat4(m0, m1, m2, m3);\n}\n\nvoid decodeClusterLightShadowData(inout ClusterLightData clusterLightData) {\n \n // shadow biases\n vec4 biases = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_SHADOW_BIAS);\n clusterLightData.shadowBias = bytes2floatRange2(biases.xy, -1.0, 20.0),\n clusterLightData.shadowNormalBias = bytes2float2(biases.zw);\n}\n\nvoid decodeClusterLightCookieData(inout ClusterLightData clusterLightData) {\n\n vec4 cookieA = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COOKIE_A);\n clusterLightData.cookieIntensity = cookieA.x;\n clusterLightData.cookieRgb = cookieA.y;\n\n clusterLightData.cookieChannelMask = sampleLightsTexture8(clusterLightData, CLUSTER_TEXTURE_8_COOKIE_B);\n}\n\nvoid evaluateLight(\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 ClearcoatArgs clearcoat, \n SheenArgs sheen, \n IridescenceArgs iridescence\n) {\n\n vec3 cookieAttenuation = vec3(1.0);\n float diffuseAttenuation = 1.0;\n float falloffAttenuation = 1.0;\n\n // evaluate omni part of the light\n getLightDirPoint(light.position);\n\n #ifdef CLUSTER_AREALIGHTS\n\n // distance attenuation\n if (isClusteredLightArea(light)) { // area light\n\n // area lights\n decodeClusterLightAreaData(light);\n\n // handle light shape\n if (isClusteredLightRect(light)) {\n calcRectLightValues(light.position, light.halfWidth, light.halfHeight);\n } else if (isClusteredLightDisk(light)) {\n calcDiskLightValues(light.position, light.halfWidth, light.halfHeight);\n } else { // sphere\n calcSphereLightValues(light.position, light.halfWidth, light.halfHeight);\n }\n\n falloffAttenuation = getFalloffWindow(light.range, dLightDirW);\n\n } else\n\n #endif\n\n { // punctual light\n\n if (isClusteredLightFalloffLinear(light))\n falloffAttenuation = getFalloffLinear(light.range, dLightDirW);\n else\n falloffAttenuation = getFalloffInvSquared(light.range, dLightDirW);\n }\n\n if (falloffAttenuation > 0.00001) {\n\n #ifdef CLUSTER_AREALIGHTS\n\n if (isClusteredLightArea(light)) { // area light\n\n // handle light shape\n if (isClusteredLightRect(light)) {\n diffuseAttenuation = getRectLightDiffuse(worldNormal, viewDir, dLightDirW, dLightDirNormW) * 16.0;\n } else if (isClusteredLightDisk(light)) {\n diffuseAttenuation = getDiskLightDiffuse(worldNormal, viewDir, dLightDirW, dLightDirNormW) * 16.0;\n } else { // sphere\n diffuseAttenuation = getSphereLightDiffuse(worldNormal, viewDir, dLightDirW, dLightDirNormW) * 16.0;\n }\n\n } else\n\n #endif\n\n {\n falloffAttenuation *= getLightDiffuse(worldNormal, viewDir, dLightDirW, dLightDirNormW); \n }\n\n // spot light falloff\n if (isClusteredLightSpot(light)) {\n decodeClusterLightSpot(light);\n falloffAttenuation *= getSpotEffect(light.direction, light.innerConeAngleCos, light.outerConeAngleCos, dLightDirNormW);\n }\n\n #if defined(CLUSTER_COOKIES_OR_SHADOWS)\n\n if (falloffAttenuation > 0.00001) {\n\n // shadow / cookie\n if (isClusteredLightCastShadow(light) || isClusteredLightCookie(light)) {\n\n // shared shadow / cookie data depends on light type\n if (isClusteredLightSpot(light)) {\n decodeClusterLightProjectionMatrixData(light);\n } else {\n decodeClusterLightOmniAtlasViewport(light);\n }\n\n float shadowTextureResolution = shadowAtlasParams.x;\n float shadowEdgePixels = shadowAtlasParams.y;\n\n #ifdef CLUSTER_COOKIES\n\n // cookie\n if (isClusteredLightCookie(light)) {\n decodeClusterLightCookieData(light);\n\n if (isClusteredLightSpot(light)) {\n cookieAttenuation = getCookie2DClustered(TEXTURE_PASS(cookieAtlasTexture), lightProjectionMatrix, vPositionW, light.cookieIntensity, isClusteredLightCookieRgb(light), light.cookieChannelMask);\n } else {\n cookieAttenuation = getCookieCubeClustered(TEXTURE_PASS(cookieAtlasTexture), dLightDirW, light.cookieIntensity, isClusteredLightCookieRgb(light), light.cookieChannelMask, shadowTextureResolution, shadowEdgePixels, light.omniAtlasViewport);\n }\n }\n\n #endif\n\n #ifdef CLUSTER_SHADOWS\n\n // shadow\n if (isClusteredLightCastShadow(light)) {\n decodeClusterLightShadowData(light);\n\n vec4 shadowParams = vec4(shadowTextureResolution, light.shadowNormalBias, light.shadowBias, 1.0 / light.range);\n\n if (isClusteredLightSpot(light)) {\n\n // spot shadow\n getShadowCoordPerspZbufferNormalOffset(lightProjectionMatrix, shadowParams, geometricNormal);\n \n #if defined(CLUSTER_SHADOW_TYPE_PCF1)\n float shadow = getShadowSpotClusteredPCF1(SHADOWMAP_PASS(shadowAtlasTexture), dShadowCoord, shadowParams);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF3)\n float shadow = getShadowSpotClusteredPCF3(SHADOWMAP_PASS(shadowAtlasTexture), dShadowCoord, shadowParams);\n #elif defined(CLUSTER_SHADOW_TYPE_PCF5)\n float shadow = getShadowSpotClusteredPCF5(SHADOWMAP_PASS(shadowAtlasTexture), dShadowCoord, shadowParams);\n #elif defined(CLUSTER_SHADOW_TYPE_PCSS)\n float shadow = getShadowSpotClusteredPCSS(SHADOWMAP_PASS(shadowAtlasTexture), dShadowCoord, shadowParams);\n #endif\n falloffAttenuation *= mix(1.0, shadow, light.shadowIntensity);\n\n } else {\n\n // omni shadow\n vec3 dir = normalOffsetPointShadow(shadowParams, dLightPosW, dLightDirW, dLightDirNormW, geometricNormal); // normalBias adjusted for distance\n\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\n #endif\n }\n }\n\n #endif\n\n // diffuse / specular / clearcoat\n #ifdef CLUSTER_AREALIGHTS\n\n if (isClusteredLightArea(light)) { // area light\n\n // area light diffuse\n {\n vec3 areaDiffuse = (diffuseAttenuation * falloffAttenuation) * light.color * cookieAttenuation;\n\n #if defined(LIT_SPECULAR)\n #if defined(LIT_CONSERVE_ENERGY)\n areaDiffuse = mix(areaDiffuse, vec3(0), dLTCSpecFres);\n #endif\n #endif\n\n // area light diffuse - it does not mix diffuse lighting into specular attenuation\n dDiffuseLight += areaDiffuse;\n }\n\n // specular and clear coat are material settings and get included by a define based on the material\n #ifdef LIT_SPECULAR\n\n // area light specular\n float areaLightSpecular;\n\n if (isClusteredLightRect(light)) {\n areaLightSpecular = getRectLightSpecular(worldNormal, viewDir);\n } else if (isClusteredLightDisk(light)) {\n areaLightSpecular = getDiskLightSpecular(worldNormal, viewDir);\n } else { // sphere\n areaLightSpecular = getSphereLightSpecular(worldNormal, viewDir);\n }\n\n dSpecularLight += dLTCSpecFres * areaLightSpecular * falloffAttenuation * light.color * cookieAttenuation;\n\n #ifdef LIT_CLEARCOAT\n\n // area light specular clear coat\n float areaLightSpecularCC;\n\n if (isClusteredLightRect(light)) {\n areaLightSpecularCC = getRectLightSpecular(clearcoat.worldNormal, viewDir);\n } else if (isClusteredLightDisk(light)) {\n areaLightSpecularCC = getDiskLightSpecular(clearcoat.worldNormal, viewDir);\n } else { // sphere\n areaLightSpecularCC = getSphereLightSpecular(clearcoat.worldNormal, viewDir);\n }\n\n ccSpecularLight += ccLTCSpecFres * areaLightSpecularCC * falloffAttenuation * light.color * cookieAttenuation;\n\n #endif\n\n #endif\n\n } else\n\n #endif\n\n { // punctual light\n\n // punctual light diffuse\n {\n vec3 punctualDiffuse = falloffAttenuation * light.color * cookieAttenuation;\n\n #if defined(CLUSTER_AREALIGHTS)\n #if defined(LIT_SPECULAR)\n #if defined(LIT_CONSERVE_ENERGY)\n punctualDiffuse = mix(punctualDiffuse, vec3(0), specularity);\n #endif\n #endif\n #endif\n\n dDiffuseLight += punctualDiffuse;\n }\n \n // specular and clear coat are material settings and get included by a define based on the material\n #ifdef LIT_SPECULAR\n\n vec3 halfDir = normalize(-dLightDirNormW + viewDir);\n \n // specular\n #ifdef LIT_SPECULAR_FRESNEL\n dSpecularLight += \n getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, dLightDirNormW, 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\n #endif\n );\n #else\n dSpecularLight += getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, dLightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * specularity;\n #endif\n\n #ifdef LIT_CLEARCOAT\n #ifdef LIT_SPECULAR_FRESNEL\n ccSpecularLight += getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat.worldNormal, viewDir, dLightDirNormW, clearcoat.gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * getFresnelCC(dot(viewDir, halfDir));\n #else\n ccSpecularLight += getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat.worldNormal, viewDir, dLightDirNormW, clearcoat.gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation; \n #endif\n #endif\n\n #ifdef LIT_SHEEN\n sSpecularLight += getLightSpecularSheen(halfDir, worldNormal, viewDir, dLightDirNormW, sheen.gloss) * falloffAttenuation * light.color * cookieAttenuation;\n #endif\n\n #endif\n }\n }\n\n // Write to global attenuation values (for lightmapper)\n dAtten = falloffAttenuation;\n dAttenD = diffuseAttenuation;\n dAtten3 = cookieAttenuation;\n}\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 ClearcoatArgs clearcoat, \n SheenArgs sheen, \n IridescenceArgs iridescence\n) {\n\n // decode core light data from textures\n ClusterLightData clusterLightData;\n decodeClusterLightCore(clusterLightData, lightIndex);\n\n // evaluate light if it uses accepted light mask\n if (acceptLightMask(clusterLightData))\n evaluateLight(\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, \n sheen, \n iridescence\n );\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 ClearcoatArgs clearcoat, \n SheenArgs sheen, \n IridescenceArgs iridescence\n) {\n\n // skip lights if no lights at all\n if (clusterSkip > 0.5)\n return;\n\n // world space position to 3d integer cell cordinates in the cluster structure\n vec3 cellCoords = floor((vPositionW - clusterBoundsMin) * clusterCellsCountByBoundsSize);\n\n // no lighting when cell coordinate is out of range\n if (!(any(lessThan(cellCoords, vec3(0.0))) || any(greaterThanEqual(cellCoords, clusterCellsMax)))) {\n\n // cell index (mapping from 3d cell coordinates to linear memory)\n float cellIndex = dot(clusterCellsDot, cellCoords);\n\n // convert cell index to uv coordinates\n float clusterV = floor(cellIndex * clusterTextureSize.y);\n float clusterU = cellIndex - (clusterV * clusterTextureSize.x);\n\n #ifdef GL2\n\n // loop over maximum number of light cells\n for (int lightCellIndex = 0; lightCellIndex < clusterMaxCells; lightCellIndex++) {\n\n // using a single channel texture with data in alpha channel\n float lightIndex = texelFetch(clusterWorldTexture, ivec2(int(clusterU) + lightCellIndex, clusterV), 0).x;\n\n if (lightIndex <= 0.0)\n return;\n\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, \n sheen, \n iridescence\n ); \n }\n\n #else\n\n clusterV = (clusterV + 0.5) * clusterTextureSize.z;\n\n // loop over maximum possible number of supported light cells\n const float maxLightCells = 256.0;\n for (float lightCellIndex = 0.5; lightCellIndex < maxLightCells; lightCellIndex++) {\n\n float lightIndex = texture2DLodEXT(clusterWorldTexture, vec2(clusterTextureSize.y * (clusterU + lightCellIndex), clusterV), 0.0).x;\n\n if (lightIndex <= 0.0)\n return;\n \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, \n sheen, \n iridescence\n ); \n // end of the cell array\n if (lightCellIndex >= clusterMaxCells) {\n break;\n }\n }\n\n #endif\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\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.rgb) * clearcoatSpecularity;\n#endif\n\n return ret;\n}\n",cookiePS:"\n// light cookie functionality for non-clustered lights\nvec4 getCookie2D(sampler2D tex, mat4 transform, float intensity) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n return mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);\n}\n\nvec4 getCookie2DClip(sampler2D tex, mat4 transform, float intensity) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n if (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0);\n return mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);\n}\n\nvec4 getCookie2DXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n projPos.xy += cookieOffset;\n vec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);\n return mix(vec4(1.0), texture2D(tex, uv), intensity);\n}\n\nvec4 getCookie2DClipXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {\n vec4 projPos = transform * vec4(vPositionW, 1.0);\n projPos.xy /= projPos.w;\n projPos.xy += cookieOffset;\n if (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0);\n vec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);\n return mix(vec4(1.0), texture2D(tex, uv), intensity);\n}\n\nvec4 getCookieCube(samplerCube tex, mat4 transform, float intensity) {\n return mix(vec4(1.0), textureCube(tex, dLightDirNormW * mat3(transform)), intensity);\n}\n",cubeMapProjectBoxPS:"\nuniform vec3 envBoxMin;\nuniform vec3 envBoxMax;\n\nvec3 cubeMapProject(vec3 nrdir) {\n nrdir = cubeMapRotate(nrdir);\n\n vec3 rbmax = (envBoxMax - vPositionW) / nrdir;\n vec3 rbmin = (envBoxMin - vPositionW) / nrdir;\n\n vec3 rbminmax;\n rbminmax.x = nrdir.x>0.0? rbmax.x : rbmin.x;\n rbminmax.y = nrdir.y>0.0? rbmax.y : rbmin.y;\n rbminmax.z = nrdir.z>0.0? rbmax.z : rbmin.z;\n\n float fa = min(min(rbminmax.x, rbminmax.y), rbminmax.z);\n\n vec3 posonbox = vPositionW + nrdir * fa;\n vec3 envBoxPos = (envBoxMin + envBoxMax) * 0.5;\n return normalize(posonbox - envBoxPos);\n}\n",cubeMapProjectNonePS:"\nvec3 cubeMapProject(vec3 dir) {\n return cubeMapRotate(dir);\n}\n",cubeMapRotatePS:"\n#ifdef CUBEMAP_ROTATION\nuniform mat3 cubeMapRotationMatrix;\n#endif\n\nvec3 cubeMapRotate(vec3 refDir) {\n#ifdef CUBEMAP_ROTATION\n return refDir * cubeMapRotationMatrix;\n#else\n return refDir;\n#endif\n}\n",debugOutputPS:"\n#ifdef DEBUG_ALBEDO_PASS\ngl_FragColor = vec4(gammaCorrectOutput(litShaderArgs.albedo), 1.0);\n#endif\n\n#ifdef DEBUG_UV0_PASS\ngl_FragColor = vec4(litShaderArgs.albedo , 1.0);\n#endif\n\n#ifdef DEBUG_WORLD_NORMAL_PASS\ngl_FragColor = vec4(litShaderArgs.worldNormal * 0.5 + 0.5, 1.0);\n#endif\n\n#ifdef DEBUG_OPACITY_PASS\ngl_FragColor = vec4(vec3(litShaderArgs.opacity) , 1.0);\n#endif\n\n#ifdef DEBUG_SPECULARITY_PASS\ngl_FragColor = vec4(litShaderArgs.specularity, 1.0);\n#endif\n\n#ifdef DEBUG_GLOSS_PASS\ngl_FragColor = vec4(vec3(litShaderArgs.gloss) , 1.0);\n#endif\n\n#ifdef DEBUG_METALNESS_PASS\ngl_FragColor = vec4(vec3(litShaderArgs.metalness) , 1.0);\n#endif\n\n#ifdef DEBUG_AO_PASS\ngl_FragColor = vec4(vec3(litShaderArgs.ao) , 1.0);\n#endif\n\n#ifdef DEBUG_EMISSION_PASS\ngl_FragColor = vec4(gammaCorrectOutput(litShaderArgs.emission), 1.0);\n#endif\n",debugProcessFrontendPS:"\n#ifdef DEBUG_LIGHTING_PASS\nlitShaderArgs.albedo = vec3(0.5);\n#endif\n\n#ifdef DEBUG_UV0_PASS\n#ifdef VARYING_VUV0\nlitShaderArgs.albedo = vec3(vUv0, 0);\n#else\nlitShaderArgs.albedo = vec3(0);\n#endif\n#endif\n",detailModesPS:"\nvec3 detailMode_mul(vec3 c1, vec3 c2) {\n return c1 * c2;\n}\n\nvec3 detailMode_add(vec3 c1, vec3 c2) {\n return c1 + c2;\n}\n\n// https://en.wikipedia.org/wiki/Blend_modes#Screen\nvec3 detailMode_screen(vec3 c1, vec3 c2) {\n return 1.0 - (1.0 - c1)*(1.0 - c2);\n}\n\n// https://en.wikipedia.org/wiki/Blend_modes#Overlay\nvec3 detailMode_overlay(vec3 c1, vec3 c2) {\n return mix(1.0 - 2.0*(1.0 - c1)*(1.0 - c2), 2.0*c1*c2, step(c1, vec3(0.5)));\n}\n\nvec3 detailMode_min(vec3 c1, vec3 c2) {\n return min(c1, c2);\n}\n\nvec3 detailMode_max(vec3 c1, vec3 c2) {\n return max(c1, c2);\n}\n",diffusePS:"\n#ifdef MAPCOLOR\nuniform vec3 material_diffuse;\n#endif\n\nvoid getAlbedo() {\n dAlbedo = vec3(1.0);\n\n#ifdef MAPCOLOR\n dAlbedo *= material_diffuse.rgb;\n#endif\n\n#ifdef MAPTEXTURE\n vec3 albedoBase = $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n dAlbedo *= addAlbedoDetail(albedoBase);\n#endif\n\n#ifdef MAPVERTEX\n dAlbedo *= gammaCorrectInput(saturate(vVertexColor.$VC));\n#endif\n}\n",diffuseDetailMapPS:"\nvec3 addAlbedoDetail(vec3 albedo) {\n#ifdef MAPTEXTURE\n vec3 albedoDetail = $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n return detailMode_$DETAILMODE(albedo, albedoDetail);\n#else\n return albedo;\n#endif\n}\n",decodePS:ya,emissivePS:"\n#ifdef MAPCOLOR\nuniform vec3 material_emissive;\n#endif\n\n#ifdef MAPFLOAT\nuniform float material_emissiveIntensity;\n#endif\n\nvoid getEmission() {\n dEmission = vec3(1.0);\n\n #ifdef MAPFLOAT\n dEmission *= material_emissiveIntensity;\n #endif\n\n #ifdef MAPCOLOR\n dEmission *= material_emissive;\n #endif\n\n #ifdef MAPTEXTURE\n dEmission *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n #endif\n\n #ifdef MAPVERTEX\n dEmission *= gammaCorrectInput(saturate(vVertexColor.$VC));\n #endif\n}\n",encodePS:xa,endPS:"\n gl_FragColor.rgb = combineColor(litShaderArgs.albedo, litShaderArgs.sheen.specularity, litShaderArgs.clearcoat.specularity);\n\n gl_FragColor.rgb += litShaderArgs.emission;\n gl_FragColor.rgb = addFog(gl_FragColor.rgb);\n\n #ifndef HDR\n gl_FragColor.rgb = toneMap(gl_FragColor.rgb);\n gl_FragColor.rgb = gammaCorrectOutput(gl_FragColor.rgb);\n #endif\n",endVS:"\n",envAtlasPS:"\n// the envAtlas is fixed at 512 pixels. every equirect is generated with 1 pixel boundary.\nconst float atlasSize = 512.0;\nconst float seamSize = 1.0 / atlasSize;\n\n// map a normalized equirect UV to the given rectangle (taking 1 pixel seam into account).\nvec2 mapUv(vec2 uv, vec4 rect) {\n return vec2(mix(rect.x + seamSize, rect.x + rect.z - seamSize, uv.x),\n mix(rect.y + seamSize, rect.y + rect.w - seamSize, uv.y));\n}\n\n// map a normalized equirect UV and roughness level to the correct atlas rect.\nvec2 mapRoughnessUv(vec2 uv, float level) {\n float t = 1.0 / exp2(level);\n return mapUv(uv, vec4(0, 1.0 - t, t, t * 0.5));\n}\n\n// map shiny level UV\nvec2 mapShinyUv(vec2 uv, float level) {\n float t = 1.0 / exp2(level);\n return mapUv(uv, vec4(1.0 - t, 1.0 - t, t, t * 0.5));\n}\n",envConstPS:"\nvec3 processEnvironment(vec3 color) {\n return color;\n}\n",envMultiplyPS:"\nuniform float skyboxIntensity;\n\nvec3 processEnvironment(vec3 color) {\n return color * skyboxIntensity;\n}\n",extensionPS:"\n",extensionVS:"\n",falloffInvSquaredPS:"\nfloat getFalloffWindow(float lightRadius, 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}\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\n falloff *= 16.0;\n falloff *= square( saturate( 1.0 - square( sqrDist * square(invRadius) ) ) );\n\n return falloff;\n}\n",falloffLinearPS:"\nfloat getFalloffLinear(float lightRadius, vec3 lightDir) {\n float d = length(lightDir);\n return max(((lightRadius - d) / lightRadius), 0.0);\n}\n",fixCubemapSeamsNonePS:"\nvec3 fixSeams(vec3 vec, float mipmapIndex) {\n return vec;\n}\n\nvec3 fixSeams(vec3 vec) {\n return vec;\n}\n\nvec3 fixSeamsStatic(vec3 vec, float invRecMipSize) {\n return vec;\n}\n\nvec3 calcSeam(vec3 vec) {\n return vec3(0);\n}\n\nvec3 applySeam(vec3 vec, vec3 seam, float scale) {\n return vec;\n}\n",fixCubemapSeamsStretchPS:"\nvec3 fixSeams(vec3 vec, float mipmapIndex) {\n vec3 avec = abs(vec);\n float scale = 1.0 - exp2(mipmapIndex) / 128.0;\n float M = max(max(avec.x, avec.y), avec.z);\n if (avec.x != M) vec.x *= scale;\n if (avec.y != M) vec.y *= scale;\n if (avec.z != M) vec.z *= scale;\n return vec;\n}\n\nvec3 fixSeams(vec3 vec) {\n vec3 avec = abs(vec);\n float scale = 1.0 - 1.0 / 128.0;\n float M = max(max(avec.x, avec.y), avec.z);\n if (avec.x != M) vec.x *= scale;\n if (avec.y != M) vec.y *= scale;\n if (avec.z != M) vec.z *= scale;\n return vec;\n}\n\nvec3 fixSeamsStatic(vec3 vec, float invRecMipSize) {\n vec3 avec = abs(vec);\n float scale = invRecMipSize;\n float M = max(max(avec.x, avec.y), avec.z);\n if (avec.x != M) vec.x *= scale;\n if (avec.y != M) vec.y *= scale;\n if (avec.z != M) vec.z *= scale;\n return vec;\n}\n\nvec3 calcSeam(vec3 vec) {\n vec3 avec = abs(vec);\n float M = max(avec.x, max(avec.y, avec.z));\n return vec3(avec.x != M ? 1.0 : 0.0,\n avec.y != M ? 1.0 : 0.0,\n avec.z != M ? 1.0 : 0.0);\n}\n\nvec3 applySeam(vec3 vec, vec3 seam, float scale) {\n return vec * (seam * -scale + vec3(1.0));\n}\n",floatUnpackingPS:"\n// float unpacking functionality, complimentary to float-packing.js\nfloat bytes2float2(vec2 data) {\n return dot(data, vec2(1.0, 1.0 / 255.0));\n}\n\nfloat bytes2float3(vec3 data) {\n return dot(data, vec3(1.0, 1.0 / 255.0, 1.0 / 65025.0));\n}\n\nfloat bytes2float4(vec4 data) {\n return dot(data, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n}\n\nfloat bytes2floatRange2(vec2 data, float min, float max) {\n return mix(min, max, bytes2float2(data));\n}\n\nfloat bytes2floatRange3(vec3 data, float min, float max) {\n return mix(min, max, bytes2float3(data));\n}\n\nfloat bytes2floatRange4(vec4 data, float min, float max) {\n return mix(min, max, bytes2float4(data));\n}\n\nfloat mantissaExponent2Float(vec4 pack)\n{\n float value = bytes2floatRange3(pack.xyz, -1.0, 1.0);\n float exponent = floor(pack.w * 255.0 - 127.0);\n return value * exp2(exponent);\n}\n",fogExpPS:"\nuniform vec3 fog_color;\nuniform float fog_density;\nfloat dBlendModeFogFactor = 1.0;\n\nvec3 addFog(vec3 color) {\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n float fogFactor = exp(-depth * fog_density);\n fogFactor = clamp(fogFactor, 0.0, 1.0);\n return mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogExp2PS:"\nuniform vec3 fog_color;\nuniform float fog_density;\nfloat dBlendModeFogFactor = 1.0;\n\nvec3 addFog(vec3 color) {\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n float fogFactor = exp(-depth * depth * fog_density * fog_density);\n fogFactor = clamp(fogFactor, 0.0, 1.0);\n return mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogLinearPS:"\nuniform vec3 fog_color;\nuniform float fog_start;\nuniform float fog_end;\nfloat dBlendModeFogFactor = 1.0;\n\nvec3 addFog(vec3 color) {\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n float fogFactor = (fog_end - depth) / (fog_end - fog_start);\n fogFactor = clamp(fogFactor, 0.0, 1.0);\n return mix(fog_color * dBlendModeFogFactor, color, fogFactor);\n}\n",fogNonePS:"\nfloat dBlendModeFogFactor = 1.0;\n\nvec3 addFog(vec3 color) {\n return color;\n}\n",fresnelSchlickPS:"\n// Schlick's approximation\nvec3 getFresnel(\n float cosTheta, \n float gloss, \n vec3 specularity\n#if defined(LIT_IRIDESCENCE)\n , vec3 iridescenceFresnel, \n IridescenceArgs iridescence\n#endif\n ) {\n float fresnel = pow(1.0 - max(cosTheta, 0.0), 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, iridescence.intensity);\n#else\n return ret;\n#endif \n}\n\nfloat getFresnelCC(float cosTheta) {\n float fresnel = pow(1.0 - max(cosTheta, 0.0), 5.0);\n return 0.04 + (1.0 - 0.04) * fresnel;\n}\n",fullscreenQuadPS:"\nvarying vec2 vUv0;\n\nuniform sampler2D source;\n\nvoid main(void) {\n gl_FragColor = texture2D(source, vUv0);\n}\n",fullscreenQuadVS:"\nattribute vec2 vertex_position;\n\nvarying vec2 vUv0;\n\nvoid main(void)\n{\n gl_Position = vec4(vertex_position, 0.5, 1.0);\n vUv0 = vertex_position.xy*0.5+0.5;\n}\n",gamma1_0PS:"\nfloat gammaCorrectInput(float color) {\n return color;\n}\n\nvec3 gammaCorrectInput(vec3 color) {\n return color;\n}\n\nvec4 gammaCorrectInput(vec4 color) {\n return color;\n}\n\nvec3 gammaCorrectOutput(vec3 color) {\n return color;\n}\n",gamma2_2PS:"\nfloat gammaCorrectInput(float color) {\n return decodeGamma(color);\n}\n\nvec3 gammaCorrectInput(vec3 color) {\n return decodeGamma(color);\n}\n\nvec4 gammaCorrectInput(vec4 color) {\n return vec4(decodeGamma(color.xyz), color.w);\n}\n\nvec3 gammaCorrectOutput(vec3 color) {\n#ifdef HDR\n return color;\n#else\n return pow(color + 0.0000001, vec3(1.0 / 2.2));\n#endif\n}\n",gles2PS:us,gles3PS:ds,gles3VS:fs,glossPS:"\n#ifdef MAPFLOAT\nuniform float material_gloss;\n#endif\n\nvoid getGlossiness() {\n dGlossiness = 1.0;\n\n #ifdef MAPFLOAT\n dGlossiness *= material_gloss;\n #endif\n\n #ifdef MAPTEXTURE\n dGlossiness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n dGlossiness *= saturate(vVertexColor.$VC);\n #endif\n\n #ifdef MAPINVERT\n dGlossiness = 1.0 - dGlossiness;\n #endif\n\n dGlossiness += 0.0000001;\n}\n",iridescenceDiffractionPS:"\nuniform float material_iridescenceRefractionIndex;\n\n#ifndef PI\n#define PI 3.14159265\n#endif\n\nfloat iridescence_iorToFresnel(float transmittedIor, float incidentIor) {\n return pow((transmittedIor - incidentIor) / (transmittedIor + incidentIor), 2.0);\n}\n\nvec3 iridescence_iorToFresnel(vec3 transmittedIor, float incidentIor) {\n return pow((transmittedIor - vec3(incidentIor)) / (transmittedIor + vec3(incidentIor)), vec3(2.0));\n}\n\nvec3 iridescence_fresnelToIor(vec3 f0) {\n vec3 sqrtF0 = sqrt(f0);\n return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0);\n}\n\nvec3 iridescence_sensitivity(float opd, vec3 shift) {\n float phase = 2.0 * PI * opd * 1.0e-9;\n const vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13);\n const vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06);\n const vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09);\n\n vec3 xyz = val * sqrt(2.0 * PI * var) * cos(pos * phase + shift) * exp(-pow(phase, 2.0) * var);\n xyz.x += 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift[0]) * exp(-4.5282e+09 * pow(phase, 2.0));\n xyz /= vec3(1.0685e-07);\n\n const mat3 XYZ_TO_REC709 = mat3(\n 3.2404542, -0.9692660, 0.0556434,\n -1.5371385, 1.8760108, -0.2040259,\n -0.4985314, 0.0415560, 1.0572252\n );\n\n return XYZ_TO_REC709 * xyz;\n}\n\nfloat iridescence_fresnel(float cosTheta, float f0) {\n float x = clamp(1.0 - cosTheta, 0.0, 1.0);\n float x2 = x * x;\n float x5 = x * x2 * x2;\n return f0 + (1.0 - f0) * x5;\n} \n\nvec3 iridescence_fresnel(float cosTheta, vec3 f0) {\n float x = clamp(1.0 - cosTheta, 0.0, 1.0);\n float x2 = x * x;\n float x5 = x * x2 * x2; \n return f0 + (vec3(1.0) - f0) * x5;\n}\n\nvec3 calcIridescence(float outsideIor, float cosTheta, vec3 base_f0, float iridescenceThickness) {\n\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\n if (cosTheta2Sq < 0.0) {\n return vec3(1.0);\n }\n\n float cosTheta2 = sqrt(cosTheta2Sq);\n\n float r0 = iridescence_iorToFresnel(iridescenceIor, outsideIor);\n float r12 = iridescence_fresnel(cosTheta, r0);\n float r21 = r12;\n float t121 = 1.0 - r12;\n\n float phi12 = iridescenceIor < outsideIor ? PI : 0.0;\n float phi21 = PI - phi12;\n\n vec3 baseIor = iridescence_fresnelToIor(base_f0 + vec3(0.0001));\n vec3 r1 = iridescence_iorToFresnel(baseIor, iridescenceIor);\n vec3 r23 = iridescence_fresnel(cosTheta2, r1);\n\n vec3 phi23 = vec3(0.0);\n if (baseIor[0] < iridescenceIor) phi23[0] = PI;\n if (baseIor[1] < iridescenceIor) phi23[1] = PI;\n if (baseIor[2] < iridescenceIor) phi23[2] = PI;\n float opd = 2.0 * iridescenceIor * iridescenceThickness * cosTheta2;\n vec3 phi = vec3(phi21) + phi23; \n\n vec3 r123Sq = clamp(r12 * r23, 1e-5, 0.9999);\n vec3 r123 = sqrt(r123Sq);\n vec3 rs = pow(t121, 2.0) * r23 / (1.0 - r123Sq);\n\n vec3 c0 = r12 + rs;\n vec3 i = c0;\n\n vec3 cm = rs - t121;\n for (int m = 1; m <= 2; m++) {\n cm *= r123;\n vec3 sm = 2.0 * iridescence_sensitivity(float(m) * opd, float(m) * phi);\n i += cm * sm;\n }\n return max(i, vec3(0.0));\n}\n\nvec3 getIridescence(float cosTheta, vec3 specularity, inout IridescenceArgs iridescence) {\n return calcIridescence(1.0, cosTheta, specularity, iridescence.thickness);\n}\n",iridescencePS:"\n#ifdef MAPFLOAT\nuniform float material_iridescence;\n#endif\n\nvoid getIridescence() {\n float iridescence = 1.0;\n\n #ifdef MAPFLOAT\n iridescence *= material_iridescence;\n #endif\n\n #ifdef MAPTEXTURE\n iridescence *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n dIridescence = iridescence; \n}\n",iridescenceThicknessPS:"\nuniform float material_iridescenceThicknessMax;\n\n#ifdef MAPTEXTURE\nuniform float material_iridescenceThicknessMin;\n#endif\n\nvoid getIridescenceThickness() {\n\n #ifdef MAPTEXTURE\n float blend = texture2DBias($SAMPLER, $UV, textureBias).$CH;\n float iridescenceThickness = mix(material_iridescenceThicknessMin, material_iridescenceThicknessMax, blend);\n #else\n float iridescenceThickness = material_iridescenceThicknessMax;\n #endif\n\n dIridescenceThickness = iridescenceThickness; \n}\n",instancingVS:"\nattribute vec4 instance_line1;\nattribute vec4 instance_line2;\nattribute vec4 instance_line3;\nattribute vec4 instance_line4;\n",lightDiffuseLambertPS:"\nfloat getLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {\n return max(dot(worldNormal, -lightDirNorm), 0.0);\n}\n",lightDirPointPS:"\nvoid getLightDirPoint(vec3 lightPosW) {\n dLightDirW = vPositionW - lightPosW;\n dLightDirNormW = normalize(dLightDirW);\n dLightPosW = lightPosW;\n}\n",lightmapAddPS:"\nvoid addLightMap(\n 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 IridescenceArgs iridescence\n#endif\n) {\n dDiffuseLight += lightmap;\n}\n",lightmapDirAddPS:"\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 IridescenceArgs iridescence\n#endif\n) {\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\n dDiffuseLight += lightmap * nlight * 2.0;\n\n vec3 halfDir = normalize(-dir + viewDir);\n vec3 specularLight = lightmap * getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, dir, gloss, tbn);\n\n#ifdef LIT_SPECULAR_FRESNEL\n specularLight *= \n getFresnel(dot(viewDir, halfDir), \n gloss, \n specularity\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n iridescence\n #endif\n );\n#endif\n\n dSpecularLight += specularLight;\n }\n}\n",lightmapDirPS:"\nuniform sampler2D texture_lightMap;\nuniform sampler2D texture_dirLightMap;\n\nvoid getLightMap() {\n dLightmap = $DECODE(texture2DBias(texture_lightMap, $UV, textureBias)).$CH;\n\n vec3 dir = texture2DBias(texture_dirLightMap, $UV, textureBias).xyz * 2.0 - 1.0;\n float dirDot = dot(dir, dir);\n dLightmapDir = (dirDot > 0.001) ? dir / sqrt(dirDot) : vec3(0.0);\n}\n",lightmapSinglePS:"\nvoid getLightMap() {\n dLightmap = vec3(1.0);\n\n #ifdef MAPTEXTURE\n dLightmap *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n #endif\n\n #ifdef MAPVERTEX\n dLightmap *= saturate(vVertexColor.$VC);\n #endif\n}\n",lightSpecularAnisoGGXPS:"\n// Anisotropic GGX\nfloat calcLightSpecular(float 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 anisotropy = material_anisotropy * roughness;\n \n float at = max((roughness + anisotropy), roughness / 4.0);\n float ab = max((roughness - anisotropy), roughness / 4.0);\n\n float NoH = dot(worldNormal, h);\n float ToH = dot(tbn[0], h);\n float BoH = dot(tbn[1], h);\n\n float a2 = at * ab;\n vec3 v = vec3(ab * ToH, at * BoH, a2 * NoH);\n float v2 = dot(v, v);\n float w2 = a2 / v2;\n float D = a2 * w2 * w2 * (1.0 / PI);\n\n float ToV = dot(tbn[0], viewDir);\n float BoV = dot(tbn[1], viewDir);\n float ToL = dot(tbn[0], -lightDirNorm);\n float BoL = dot(tbn[1], -lightDirNorm);\n float NoV = dot(worldNormal, viewDir);\n float NoL = dot(worldNormal, -lightDirNorm);\n\n float lambdaV = NoL * length(vec3(at * ToV, ab * BoV, NoV));\n float lambdaL = NoV * length(vec3(at * ToL, ab * BoL, NoL));\n float G = 0.5 / (lambdaV + lambdaL);\n\n return D * G;\n}\n\nfloat getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) {\n return calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm, tbn);\n}\n",lightSpecularBlinnPS:"\n// Energy-conserving (hopefully) Blinn-Phong\nfloat calcLightSpecular(float gloss, vec3 worldNormal, vec3 h) {\n float nh = max( dot( h, worldNormal ), 0.0 );\n\n float specPow = exp2(gloss * 11.0); // glossiness is linear, power is not; 0 - 2048\n\n // Hack: On Mac OS X, calling pow with zero for the exponent generates hideous artifacts so bias up a little\n specPow = max(specPow, 0.0001);\n\n return pow(nh, specPow) * (specPow + 2.0) / 8.0;\n}\n\nfloat getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) {\n return calcLightSpecular(gloss, worldNormal, h);\n}\n",lightSpecularPhongPS:"\nfloat calcLightSpecular(float gloss, vec3 reflDir, vec3 lightDirNorm) {\n float specPow = gloss;\n\n // Hack: On Mac OS X, calling pow with zero for the exponent generates hideous artifacts so bias up a little\n return pow(max(dot(reflDir, -lightDirNorm), 0.0), specPow + 0.0001);\n}\n\nfloat getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) {\n return calcLightSpecular(gloss, reflDir, lightDirNorm);\n}\n",lightSheenPS:"\n\nfloat sheenD(vec3 normal, vec3 h, float roughness) {\n float invR = 1.0 / (roughness * roughness);\n float cos2h = max(dot(normal, h), 0.0);\n cos2h *= cos2h;\n float sin2h = max(1.0 - cos2h, 0.0078125);\n return (2.0 + invR) * pow(sin2h, invR * 0.5) / (2.0 * PI);\n}\n\nfloat sheenV(vec3 normal, vec3 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}\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\n#ifndef LINEARIZE_DEPTH\n#define LINEARIZE_DEPTH\n\nfloat linearizeDepth(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\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params; // x: 1 / camera_far, y: camera_far, z: camera_near, w: is_ortho\n#endif\n\n#ifdef GL2\nfloat linearizeDepth(float z) {\n return linearizeDepth(z, camera_params);\n}\n#else\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n const vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n return dot(rgbaDepth, bitShift);\n}\n#endif\n#endif\n#endif\n",litShaderArgsPS:"\n\nstruct IridescenceArgs\n{\n // Iridescence effect intensity, range [0..1]\n float intensity;\n\n // Thickness of the iridescent microfilm layer, value is in nanometers, range [0..1000]\n float thickness;\n};\n\nstruct ClearcoatArgs\n{\n // The normal used for the clearcoat layer\n vec3 worldNormal;\n\n // Intensity of the clearcoat layer, range [0..1]\n float specularity;\n\n // Glossiness of clearcoat layer, range [0..1]\n float gloss;\n};\n\nstruct SheenArgs\n{\n // The color of the f0 specularity factor for the sheen layer\n vec3 specularity;\n\n // Glossiness of the sheen layer, range [0..1]\n float gloss;\n};\n\nstruct LitShaderArguments {\n // Normal direction in world space\n vec3 worldNormal;\n\n // Transparency\n float opacity;\n\n // Surface albedo absorbance\n vec3 albedo;\n\n // Transmission factor (refraction), range [0..1]\n float transmission;\n\n // The f0 specularity factor\n vec3 specularity;\n\n // Uniform thickness of medium, used by transmission, range [0..inf]\n float thickness;\n\n // Emission color\n vec3 emission;\n\n // Ambient occlusion amount, range [0..1]\n float ao;\n\n // Light map color\n vec3 lightmap;\n\n // Specularity intensity factor, range [0..1]\n float specularityFactor;\n\n // Light map direction\n vec3 lightmapDir;\n\n // The microfacet glossiness factor, range [0..1]\n float gloss;\n\n // Iridescence extension arguments\n IridescenceArgs iridescence;\n\n // Clearcoat extension arguments\n ClearcoatArgs clearcoat;\n\n // Surface metalness factor, range [0..1]\n float metalness;\n\n // Sheen extension arguments\n SheenArgs sheen;\n};\n",ltcPS:'\n// Real-Time Polygonal-Light Shading with Linearly Transformed Cosines\n// by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt\n// code: https://github.com/selfshadow/ltc_code/\n\nmat3 transposeMat3( const in mat3 m ) {\n mat3 tmp;\n tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n return tmp;\n}\n\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n const float LUT_SIZE = 64.0;\n const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n const float LUT_BIAS = 0.5 / LUT_SIZE;\n float dotNV = saturate( dot( N, V ) );\n // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )\n vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n uv = uv * LUT_SCALE + LUT_BIAS;\n return uv;\n}\n\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n // Real-Time Area Lighting: a Journey from Research to Production (p.102)\n // An approximation of the form factor of a horizon-clipped rectangle.\n float l = length( f );\n return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\n\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n float x = dot( v1, v2 );\n float y = abs( x );\n // rational polynomial approximation to theta / sin( theta ) / 2PI\n float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n float b = 3.4175940 + ( 4.1616724 + y ) * y;\n float v = a / b;\n float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n return cross( v1, v2 ) * theta_sintheta;\n}\n\nstruct Coords {\n vec3 coord0;\n vec3 coord1;\n vec3 coord2;\n vec3 coord3;\n};\n\nfloat LTC_EvaluateRect( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in Coords rectCoords) {\n // bail if point is on back side of plane of light\n // assumes ccw winding order of light vertices\n vec3 v1 = rectCoords.coord1 - rectCoords.coord0;\n vec3 v2 = rectCoords.coord3 - rectCoords.coord0;\n \n vec3 lightNormal = cross( v1, v2 );\n // if( dot( lightNormal, P - rectCoords.coord0 ) < 0.0 ) return 0.0;\n float factor = sign(-dot( lightNormal, P - rectCoords.coord0 ));\n\n // construct orthonormal basis around N\n vec3 T1, T2;\n T1 = normalize( V - N * dot( V, N ) );\n T2 = factor * cross( N, T1 ); // negated from paper; possibly due to a different handedness of world coordinate system\n // compute transform\n mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n // transform rect\n vec3 coords[ 4 ];\n coords[ 0 ] = mat * ( rectCoords.coord0 - P );\n coords[ 1 ] = mat * ( rectCoords.coord1 - P );\n coords[ 2 ] = mat * ( rectCoords.coord2 - P );\n coords[ 3 ] = mat * ( rectCoords.coord3 - P );\n // project rect onto sphere\n coords[ 0 ] = normalize( coords[ 0 ] );\n coords[ 1 ] = normalize( coords[ 1 ] );\n coords[ 2 ] = normalize( coords[ 2 ] );\n coords[ 3 ] = normalize( coords[ 3 ] );\n // calculate vector form factor\n vec3 vectorFormFactor = vec3( 0.0 );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n // adjust for horizon clipping\n float result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\n return result;\n}\n\nCoords dLTCCoords;\nCoords getLTCLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){\n Coords coords;\n coords.coord0 = lightPos + halfWidth - halfHeight;\n coords.coord1 = lightPos - halfWidth - halfHeight;\n coords.coord2 = lightPos - halfWidth + halfHeight;\n coords.coord3 = lightPos + halfWidth + halfHeight;\n return coords;\n}\n\nfloat dSphereRadius;\nCoords getSphereLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){\n // used for simple sphere light falloff\n // also, the code only handles a spherical light, it cannot be non-uniformly scaled in world space, and so we enforce it here\n dSphereRadius = max(length(halfWidth), length(halfHeight));\n\n // Billboard the 2d light quad to reflection vector, as it\'s used for specular. This allows us to use disk math for the sphere.\n vec3 f = reflect(normalize(lightPos - view_position), vNormalW);\n vec3 w = normalize(cross(f, halfHeight));\n vec3 h = normalize(cross(f, w));\n\n return getLTCLightCoords(lightPos, w * dSphereRadius, h * dSphereRadius);\n}\n\n// used for LTC LUT texture lookup\nvec2 dLTCUV;\n#ifdef LIT_CLEARCOAT\nvec2 ccLTCUV;\n#endif\nvec2 getLTCLightUV(float 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}\n\n//used for energy conservation and to modulate specular\nvec3 dLTCSpecFres;\n#ifdef LIT_CLEARCOAT\nvec3 ccLTCSpecFres;\n#endif\nvec3 getLTCLightSpecFres(vec2 uv, vec3 specularity)\n{\n vec4 t2 = texture2DLodEXT(areaLightsLutTex2, uv, 0.0);\n\n #ifdef AREA_R8_G8_B8_A8_LUTS\n t2 *= vec4(0.693103,1,1,1);\n t2 += vec4(0.306897,0,0,0);\n #endif\n\n return specularity * t2.x + ( vec3( 1.0 ) - specularity) * t2.y;\n}\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\n#ifdef LIT_CLEARCOAT\n ccLTCUV = getLTCLightUV(clearcoatGloss, clearcoatWorldNormal, viewDir);\n ccLTCSpecFres = getLTCLightSpecFres(ccLTCUV, vec3(clearcoatSpecularity));\n#endif\n}\n\nvoid calcRectLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n dLTCCoords = getLTCLightCoords(lightPos, halfWidth, halfHeight);\n}\nvoid calcDiskLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n calcRectLightValues(lightPos, halfWidth, halfHeight);\n}\nvoid calcSphereLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight)\n{\n dLTCCoords = getSphereLightCoords(lightPos, halfWidth, halfHeight);\n}\n\n// An extended version of the implementation from\n// "How to solve a cubic equation, revisited"\n// http://momentsingraphics.de/?p=105\nvec3 SolveCubic(vec4 Coefficient)\n{\n float pi = 3.14159;\n // Normalize the polynomial\n Coefficient.xyz /= Coefficient.w;\n // Divide middle coefficients by three\n Coefficient.yz /= 3.0;\n\n float A = Coefficient.w;\n float B = Coefficient.z;\n float C = Coefficient.y;\n float D = Coefficient.x;\n\n // Compute the Hessian and the discriminant\n vec3 Delta = vec3(\n -Coefficient.z * Coefficient.z + Coefficient.y,\n -Coefficient.y * Coefficient.z + Coefficient.x,\n dot(vec2(Coefficient.z, -Coefficient.y), Coefficient.xy)\n );\n\n float Discriminant = dot(vec2(4.0 * Delta.x, -Delta.y), Delta.zy);\n\n vec3 RootsA, RootsD;\n\n vec2 xlc, xsc;\n\n // Algorithm A\n {\n float A_a = 1.0;\n float C_a = Delta.x;\n float D_a = -2.0 * B * Delta.x + Delta.y;\n\n // Take the cubic root of a normalized complex number\n float Theta = atan(sqrt(Discriminant), -D_a) / 3.0;\n\n float x_1a = 2.0 * sqrt(-C_a) * cos(Theta);\n float x_3a = 2.0 * sqrt(-C_a) * cos(Theta + (2.0 / 3.0) * pi);\n\n float xl;\n if ((x_1a + x_3a) > 2.0 * B)\n xl = x_1a;\n else\n xl = x_3a;\n\n xlc = vec2(xl - B, A);\n }\n\n // Algorithm D\n {\n float A_d = D;\n float C_d = Delta.z;\n float D_d = -D * Delta.y + 2.0 * C * Delta.z;\n\n // Take the cubic root of a normalized complex number\n float Theta = atan(D * sqrt(Discriminant), -D_d) / 3.0;\n\n float x_1d = 2.0 * sqrt(-C_d) * cos(Theta);\n float x_3d = 2.0 * sqrt(-C_d) * cos(Theta + (2.0 / 3.0) * pi);\n\n float xs;\n if (x_1d + x_3d < 2.0 * C)\n xs = x_1d;\n else\n xs = x_3d;\n\n xsc = vec2(-D, xs + C);\n }\n\n float E = xlc.y * xsc.y;\n float F = -xlc.x * xsc.y - xlc.y * xsc.x;\n float G = xlc.x * xsc.x;\n\n vec2 xmc = vec2(C * F - B * G, -B * F + C * E);\n\n vec3 Root = vec3(xsc.x / xsc.y, xmc.x / xmc.y, xlc.x / xlc.y);\n\n if (Root.x < Root.y && Root.x < Root.z)\n Root.xyz = Root.yxz;\n else if (Root.z < Root.x && Root.z < Root.y)\n Root.xyz = Root.xzy;\n\n return Root;\n}\n\nfloat LTC_EvaluateDisk(vec3 N, vec3 V, vec3 P, mat3 Minv, Coords points)\n{\n // construct orthonormal basis around N\n vec3 T1, T2;\n T1 = normalize(V - N * dot(V, N));\n T2 = cross(N, T1);\n\n // rotate area light in (T1, T2, N) basis\n //mat3 R = transpose(mat3(T1, T2, N));\n mat3 R = transposeMat3( mat3( T1, T2, N ) );\n // polygon (allocate 5 vertices for clipping)\n vec3 L_[ 3 ];\n L_[ 0 ] = R * ( points.coord0 - P );\n L_[ 1 ] = R * ( points.coord1 - P );\n L_[ 2 ] = R * ( points.coord2 - P );\n\n vec3 Lo_i = vec3(0);\n\n // init ellipse\n vec3 C = 0.5 * (L_[0] + L_[2]);\n vec3 V1 = 0.5 * (L_[1] - L_[2]);\n vec3 V2 = 0.5 * (L_[1] - L_[0]);\n\n C = Minv * C;\n V1 = Minv * V1;\n V2 = Minv * V2;\n\n //if(dot(cross(V1, V2), C) > 0.0)\n // return 0.0;\n\n // compute eigenvectors of ellipse\n float a, b;\n float d11 = dot(V1, V1);\n float d22 = dot(V2, V2);\n float d12 = dot(V1, V2);\n if (abs(d12) / sqrt(d11 * d22) > 0.0001)\n {\n float tr = d11 + d22;\n float det = -d12 * d12 + d11 * d22;\n\n // use sqrt matrix to solve for eigenvalues\n det = sqrt(det);\n float u = 0.5 * sqrt(tr - 2.0 * det);\n float v = 0.5 * sqrt(tr + 2.0 * det);\n float e_max = (u + v) * (u + v);\n float e_min = (u - v) * (u - v);\n\n vec3 V1_, V2_;\n\n if (d11 > d22)\n {\n V1_ = d12 * V1 + (e_max - d11) * V2;\n V2_ = d12 * V1 + (e_min - d11) * V2;\n }\n else\n {\n V1_ = d12*V2 + (e_max - d22)*V1;\n V2_ = d12*V2 + (e_min - d22)*V1;\n }\n\n a = 1.0 / e_max;\n b = 1.0 / e_min;\n V1 = normalize(V1_);\n V2 = normalize(V2_);\n }\n else\n {\n a = 1.0 / dot(V1, V1);\n b = 1.0 / dot(V2, V2);\n V1 *= sqrt(a);\n V2 *= sqrt(b);\n }\n\n vec3 V3 = cross(V1, V2);\n if (dot(C, V3) < 0.0)\n V3 *= -1.0;\n\n float L = dot(V3, C);\n float x0 = dot(V1, C) / L;\n float y0 = dot(V2, C) / L;\n\n float E1 = inversesqrt(a);\n float E2 = inversesqrt(b);\n\n a *= L * L;\n b *= L * L;\n\n float c0 = a * b;\n float c1 = a * b * (1.0 + x0 * x0 + y0 * y0) - a - b;\n float c2 = 1.0 - a * (1.0 + x0 * x0) - b * (1.0 + y0 * y0);\n float c3 = 1.0;\n\n vec3 roots = SolveCubic(vec4(c0, c1, c2, c3));\n float e1 = roots.x;\n float e2 = roots.y;\n float e3 = roots.z;\n\n vec3 avgDir = vec3(a * x0 / (a - e2), b * y0 / (b - e2), 1.0);\n\n mat3 rotate = mat3(V1, V2, V3);\n\n avgDir = rotate * avgDir;\n avgDir = normalize(avgDir);\n\n float L1 = sqrt(-e2 / e3);\n float L2 = sqrt(-e2 / e1);\n\n float formFactor = L1 * L2 * inversesqrt((1.0 + L1 * L1) * (1.0 + L2 * L2));\n \n const float LUT_SIZE = 64.0;\n const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n const float LUT_BIAS = 0.5 / LUT_SIZE;\n\n // use tabulated horizon-clipped sphere\n vec2 uv = vec2(avgDir.z * 0.5 + 0.5, formFactor);\n uv = uv*LUT_SCALE + LUT_BIAS;\n\n float scale = texture2DLodEXT(areaLightsLutTex2, uv, 0.0).w;\n\n return formFactor*scale;\n}\n\nfloat getRectLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {\n return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mat3( 1.0 ), dLTCCoords );\n}\n\nfloat getDiskLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {\n return LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mat3( 1.0 ), dLTCCoords );\n}\n\nfloat getSphereLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {\n // NB: this could be improved further with distance based wrap lighting\n float falloff = dSphereRadius / (dot(lightDir, lightDir) + dSphereRadius);\n return getLightDiffuse(worldNormal, viewDir, lightDir, lightDirNorm) * falloff;\n}\n\nmat3 getLTCLightInvMat(vec2 uv)\n{\n vec4 t1 = texture2DLodEXT(areaLightsLutTex1, uv, 0.0);\n\n #ifdef AREA_R8_G8_B8_A8_LUTS\n t1 *= vec4(1.001, 0.3239, 0.60437568, 1.0);\n t1 += vec4(0.0, -0.2976, -0.01381, 0.0);\n #endif\n\n return mat3(\n vec3( t1.x, 0, t1.y ),\n vec3( 0, 1, 0 ),\n vec3( t1.z, 0, t1.w )\n );\n}\n\nfloat calcRectLightSpecular(vec3 worldNormal, vec3 viewDir, vec2 uv) {\n mat3 mInv = getLTCLightInvMat(uv);\n return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );\n}\n\nfloat getRectLightSpecular(vec3 worldNormal, vec3 viewDir) {\n return calcRectLightSpecular(worldNormal, viewDir, dLTCUV);\n}\n\nfloat calcDiskLightSpecular(vec3 worldNormal, vec3 viewDir, vec2 uv) {\n mat3 mInv = getLTCLightInvMat(uv);\n return LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );\n}\n\nfloat getDiskLightSpecular(vec3 worldNormal, vec3 viewDir) {\n return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);\n}\n\nfloat getSphereLightSpecular(vec3 worldNormal, vec3 viewDir) {\n return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);\n}\n',metalnessPS:"\n#ifdef MAPFLOAT\nuniform float material_metalness;\n#endif\n\nvoid getMetalness() {\n float metalness = 1.0;\n\n #ifdef MAPFLOAT\n metalness *= material_metalness;\n #endif\n\n #ifdef MAPTEXTURE\n metalness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n metalness *= saturate(vVertexColor.$VC);\n #endif\n\n dMetalness = metalness;\n}\n",metalnessModulatePS:"\n\nuniform float material_f0;\n\nvoid getMetalnessModulate(inout LitShaderArguments litShaderArgs) {\n vec3 dielectricF0 = material_f0 * litShaderArgs.specularity;\n litShaderArgs.specularity = mix(dielectricF0, litShaderArgs.albedo, litShaderArgs.metalness);\n litShaderArgs.albedo *= 1.0 - litShaderArgs.metalness;\n}\n",msdfPS:"\nuniform sampler2D texture_msdfMap;\n\n#ifdef GL_OES_standard_derivatives\n#define USE_FWIDTH\n#endif\n\n#ifdef GL2\n#define USE_FWIDTH\n#endif\n\nfloat median(float r, float g, float b) {\n return max(min(r, g), min(max(r, g), b));\n}\n\nfloat map (float min, float max, float v) {\n return (v - min) / (max - min);\n}\n\nuniform float font_sdfIntensity; // intensity is used to boost the value read from the SDF, 0 is no boost, 1.0 is max boost\nuniform float font_pxrange; // the number of pixels between inside and outside the font in SDF\nuniform float font_textureWidth; // the width of the texture atlas\n\n#ifdef UNIFORM_TEXT_PARAMETERS\nuniform vec4 outline_color;\nuniform float outline_thickness;\nuniform vec4 shadow_color;\nuniform vec2 shadow_offset;\n#else\nvarying vec4 outline_color;\nvarying float outline_thickness;\nvarying vec4 shadow_color;\nvarying vec2 shadow_offset;\n#endif\n\nvec4 applyMsdf(vec4 color) {\n // sample the field\n vec3 tsample = texture2D(texture_msdfMap, vUv0).rgb;\n vec2 uvShdw = vUv0 - shadow_offset;\n vec3 ssample = texture2D(texture_msdfMap, uvShdw).rgb;\n // get the signed distance value\n float sigDist = median(tsample.r, tsample.g, tsample.b);\n float sigDistShdw = median(ssample.r, ssample.g, ssample.b);\n\n // smoothing limit - smaller value makes for sharper but more aliased text, especially on angles\n // too large value (0.5) creates a dark glow around the letters\n float smoothingMax = 0.2;\n\n #ifdef USE_FWIDTH\n // smoothing depends on size of texture on screen\n vec2 w = fwidth(vUv0);\n float smoothing = clamp(w.x * font_textureWidth / font_pxrange, 0.0, smoothingMax);\n #else\n float font_size = 16.0; // TODO fix this\n // smoothing gets smaller as the font size gets bigger\n // don't have fwidth we can approximate from font size, this doesn't account for scaling\n // so a big font scaled down will be wrong...\n float smoothing = clamp(font_pxrange / font_size, 0.0, smoothingMax);\n #endif\n\n float mapMin = 0.05;\n float mapMax = clamp(1.0 - font_sdfIntensity, mapMin, 1.0);\n\n // remap to a smaller range (used on smaller font sizes)\n float sigDistInner = map(mapMin, mapMax, sigDist);\n float sigDistOutline = map(mapMin, mapMax, sigDist + outline_thickness);\n sigDistShdw = map(mapMin, mapMax, sigDistShdw + outline_thickness);\n\n float center = 0.5;\n // calculate smoothing and use to generate opacity\n float inside = smoothstep(center-smoothing, center+smoothing, sigDistInner);\n float outline = smoothstep(center-smoothing, center+smoothing, sigDistOutline);\n float shadow = smoothstep(center-smoothing, center+smoothing, sigDistShdw);\n\n vec4 tcolor = (outline > inside) ? outline * vec4(outline_color.a * outline_color.rgb, outline_color.a) : vec4(0.0);\n tcolor = mix(tcolor, color, inside);\n\n vec4 scolor = (shadow > outline) ? shadow * vec4(shadow_color.a * shadow_color.rgb, shadow_color.a) : tcolor;\n tcolor = mix(scolor, tcolor, outline);\n \n return tcolor;\n}\n",msdfVS:"\nattribute vec3 vertex_outlineParameters;\nattribute vec3 vertex_shadowParameters;\n\nvarying vec4 outline_color;\nvarying float outline_thickness;\nvarying vec4 shadow_color;\nvarying vec2 shadow_offset;\n\nvoid unpackMsdfParams() {\n vec3 little = mod(vertex_outlineParameters, 256.);\n vec3 big = (vertex_outlineParameters - little) / 256.;\n\n outline_color.rb = little.xy / 255.;\n outline_color.ga = big.xy / 255.;\n\n // _outlineThicknessScale === 0.2\n outline_thickness = little.z / 255. * 0.2;\n\n little = mod(vertex_shadowParameters, 256.);\n big = (vertex_shadowParameters - little) / 256.;\n\n shadow_color.rb = little.xy / 255.;\n shadow_color.ga = big.xy / 255.;\n\n // vec2(little.z, big.z) / 127. - 1. remaps shadow offset from [0, 254] to [-1, 1]\n // _shadowOffsetScale === 0.005\n shadow_offset = (vec2(little.z, big.z) / 127. - 1.) * 0.005;\n}\n",normalVS:"\n#ifdef MORPHING_TEXTURE_BASED_NORMAL\nuniform highp sampler2D morphNormalTex;\n#endif\n\nvec3 getNormal() {\n #ifdef SKIN\n dNormalMatrix = mat3(dModelMatrix[0].xyz, dModelMatrix[1].xyz, dModelMatrix[2].xyz);\n #elif defined(INSTANCING)\n dNormalMatrix = mat3(instance_line1.xyz, instance_line2.xyz, instance_line3.xyz);\n #else\n dNormalMatrix = matrix_normal;\n #endif\n\n vec3 tempNormal = vertex_normal;\n\n #ifdef MORPHING\n #ifdef MORPHING_NRM03\n tempNormal += morph_weights_a[0] * morph_nrm0;\n tempNormal += morph_weights_a[1] * morph_nrm1;\n tempNormal += morph_weights_a[2] * morph_nrm2;\n tempNormal += morph_weights_a[3] * morph_nrm3;\n #endif\n #ifdef MORPHING_NRM47\n tempNormal += morph_weights_b[0] * morph_nrm4;\n tempNormal += morph_weights_b[1] * morph_nrm5;\n tempNormal += morph_weights_b[2] * morph_nrm6;\n tempNormal += morph_weights_b[3] * morph_nrm7;\n #endif\n #endif\n\n #ifdef MORPHING_TEXTURE_BASED_NORMAL\n\n #ifdef WEBGPU\n ivec2 morphUV = getTextureMorphCoords();\n vec3 morphNormal = texelFetch(morphNormalTex, ivec2(morphUV), 0).xyz;\n #else\n vec2 morphUV = getTextureMorphCoords();\n vec3 morphNormal = texture2D(morphNormalTex, morphUV).xyz;\n #endif\n\n // apply morph offset from texture\n tempNormal += morphNormal;\n #endif\n\n return normalize(dNormalMatrix * tempNormal);\n}\n",normalDetailMapPS:"\n#ifdef MAPTEXTURE\nuniform float material_normalDetailMapBumpiness;\n\nvec3 blendNormals(vec3 n1, vec3 n2) {\n // https://blog.selfshadow.com/publications/blending-in-detail/#detail-oriented\n n1 += vec3(0, 0, 1);\n n2 *= vec3(-1, -1, 1);\n return n1 * dot(n1, n2) / n1.z - n2;\n}\n#endif\n\nvec3 addNormalDetail(vec3 normalMap) {\n#ifdef MAPTEXTURE\n vec3 normalDetailMap = unpackNormal(texture2DBias($SAMPLER, $UV, textureBias));\n normalDetailMap = mix(vec3(0.0, 0.0, 1.0), normalDetailMap, material_normalDetailMapBumpiness);\n return blendNormals(normalMap, normalDetailMap);\n#else\n return normalMap;\n#endif\n}\n",normalInstancedVS:"\nvec3 getNormal() {\n dNormalMatrix = mat3(instance_line1.xyz, instance_line2.xyz, instance_line3.xyz);\n return normalize(dNormalMatrix * vertex_normal);\n}\n",normalMapPS:"\n#ifdef MAPTEXTURE\nuniform float material_bumpiness;\n#endif\n\nvoid getNormal() {\n#ifdef MAPTEXTURE\n vec3 normalMap = unpackNormal(texture2DBias($SAMPLER, $UV, textureBias));\n normalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, material_bumpiness);\n dNormalW = normalize(dTBN * addNormalDetail(normalMap));\n#else\n dNormalW = dVertexNormalW;\n#endif\n}\n",normalSkinnedVS:"\nvec3 getNormal() {\n dNormalMatrix = mat3(dModelMatrix[0].xyz, dModelMatrix[1].xyz, dModelMatrix[2].xyz);\n return normalize(dNormalMatrix * vertex_normal);\n}\n",normalXYPS:"\nvec3 unpackNormal(vec4 nmap) {\n vec3 normal;\n normal.xy = nmap.wy * 2.0 - 1.0;\n normal.z = sqrt(1.0 - saturate(dot(normal.xy, normal.xy)));\n return normal;\n}\n",normalXYZPS:"\nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\n",opacityPS:"\n#ifdef MAPFLOAT\nuniform float material_opacity;\n#endif\n\nvoid getOpacity() {\n dAlpha = 1.0;\n\n #ifdef MAPFLOAT\n dAlpha *= material_opacity;\n #endif\n\n #ifdef MAPTEXTURE\n dAlpha *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n dAlpha *= clamp(vVertexColor.$VC, 0.0, 1.0);\n #endif\n}\n",outputPS:"\n",outputAlphaPS:"\ngl_FragColor.a = litShaderArgs.opacity;\n",outputAlphaOpaquePS:"\n gl_FragColor.a = 1.0;\n",outputAlphaPremulPS:"\ngl_FragColor.rgb *= litShaderArgs.opacity;\ngl_FragColor.a = litShaderArgs.opacity;\n",outputTex2DPS:"\nvarying vec2 vUv0;\n\nuniform sampler2D source;\n\nvoid main(void) {\n gl_FragColor = texture2D(source, vUv0);\n}\n",packDepthPS:"\n// Packing a float in GLSL with multiplication and mod\n// http://blog.gradientstudios.com/2012/08/23/shadow-map-improvement\nvec4 packFloat(float depth) {\n const vec4 bit_shift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);\n\n // combination of mod and multiplication and division works better\n vec4 res = mod(depth * bit_shift * vec4(255), vec4(256) ) / vec4(255);\n res -= res.xxyz * bit_mask;\n return res;\n}\n",sheenPS:"\n\n#ifdef MAPCOLOR\nuniform vec3 material_sheen;\n#endif\n\nvoid getSheen() {\n vec3 sheenColor = vec3(1, 1, 1);\n\n #ifdef MAPCOLOR\n sheenColor *= material_sheen;\n #endif\n\n #ifdef MAPTEXTURE\n sheenColor *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n #endif\n\n #ifdef MAPVERTEX\n sheenColor *= saturate(vVertexColor.$VC);\n #endif\n\n sSpecularity = sheenColor;\n}\n",sheenGlossPS:"\n#ifdef MAPFLOAT\nuniform float material_sheenGloss;\n#endif\n\nvoid getSheenGlossiness() {\n float sheenGlossiness = 1.0;\n\n #ifdef MAPFLOAT\n sheenGlossiness *= material_sheenGloss;\n #endif\n\n #ifdef MAPTEXTURE\n sheenGlossiness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n sheenGlossiness *= saturate(vVertexColor.$VC);\n #endif\n\n #ifdef MAPINVERT\n sheenGlossiness = 1.0 - sheenGlossiness;\n #endif\n\n sheenGlossiness += 0.0000001;\n sGlossiness = sheenGlossiness;\n}\n",parallaxPS:"\nuniform float material_heightMapFactor;\n\nvoid getParallax() {\n float parallaxScale = material_heightMapFactor;\n\n float height = texture2DBias($SAMPLER, $UV, textureBias).$CH;\n height = height * parallaxScale - parallaxScale*0.5;\n vec3 viewDirT = dViewDirW * dTBN;\n\n viewDirT.z += 0.42;\n dUvOffset = height * (viewDirT.xy / viewDirT.z);\n}\n",particlePS:"\nvarying vec4 texCoordsAlphaLife;\n\nuniform sampler2D colorMap;\nuniform sampler2D colorParam;\nuniform float graphSampleSize;\nuniform float graphNumSamples;\n\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n#endif\n\nuniform float softening;\nuniform float colorMult;\n\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n const vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n float depth = dot(rgbaDepth, bitShift);\n return depth;\n}\n#endif\n\nvoid main(void) {\n vec4 tex = gammaCorrectInput(texture2D(colorMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y)));\n vec4 ramp = gammaCorrectInput(texture2D(colorParam, vec2(texCoordsAlphaLife.w, 0.0)));\n ramp.rgb *= colorMult;\n\n ramp.a += texCoordsAlphaLife.z;\n\n vec3 rgb = tex.rgb * ramp.rgb;\n float a = tex.a * ramp.a;\n",particleVS:"\nvec3 unpack3NFloats(float src) {\n float r = fract(src);\n float g = fract(src * 256.0);\n float b = fract(src * 65536.0);\n return vec3(r, g, b);\n}\n\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n\nvec4 tex1Dlod_lerp(highp sampler2D tex, vec2 tc) {\n return mix( texture2D(tex,tc), texture2D(tex,tc + graphSampleSize), fract(tc.x*graphNumSamples) );\n}\n\nvec4 tex1Dlod_lerp(highp sampler2D tex, vec2 tc, out vec3 w) {\n vec4 a = texture2D(tex,tc);\n vec4 b = texture2D(tex,tc + graphSampleSize);\n float c = fract(tc.x*graphNumSamples);\n\n vec3 unpackedA = unpack3NFloats(a.w);\n vec3 unpackedB = unpack3NFloats(b.w);\n w = mix(unpackedA, unpackedB, c);\n\n return mix(a, b, c);\n}\n\nvec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix) {\n float c = cos(pRotation);\n float s = sin(pRotation);\n\n mat2 m = mat2(c, -s, s, c);\n rotMatrix = m;\n\n return m * quadXY;\n}\n\nvec3 billboard(vec3 InstanceCoords, vec2 quadXY) {\n #ifdef SCREEN_SPACE\n vec3 pos = vec3(-1, 0, 0) * quadXY.x + vec3(0, -1, 0) * quadXY.y;\n #else\n vec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;\n #endif\n\n return pos;\n}\n\nvec3 customFace(vec3 InstanceCoords, vec2 quadXY) {\n vec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;\n return pos;\n}\n\nvec2 safeNormalize(vec2 v) {\n float l = length(v);\n return (l > 1e-06) ? v / l : v;\n}\n\nvoid main(void) {\n vec3 meshLocalPos = particle_vertexData.xyz;\n float id = floor(particle_vertexData.w);\n\n float rndFactor = fract(sin(id + 1.0 + seed));\n vec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));\n\n float uv = id / numParticlesPot;\n readInput(uv);\n\n#ifdef LOCAL_SPACE\n inVel = mat3(matrix_model) * inVel;\n#endif\n vec2 velocityV = safeNormalize((mat3(matrix_view) * inVel).xy); // should be removed by compiler if align/stretch is not used\n\n float particleLifetime = lifetime;\n\n if (inLife <= 0.0 || inLife > particleLifetime || !inShow) meshLocalPos = vec3(0.0);\n vec2 quadXY = meshLocalPos.xy;\n float nlife = clamp(inLife / particleLifetime, 0.0, 1.0);\n\n vec3 paramDiv;\n vec4 params = tex1Dlod_lerp(internalTex2, vec2(nlife, 0), paramDiv);\n float scale = params.y;\n float scaleDiv = paramDiv.x;\n float alphaDiv = paramDiv.z;\n\n scale += (scaleDiv * 2.0 - 1.0) * scaleDivMult * fract(rndFactor*10000.0);\n\n#ifndef USE_MESH\n texCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);\n#else\n texCoordsAlphaLife = vec4(particle_uv, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);\n#endif\n\n vec3 particlePos = inPos;\n vec3 particlePosMoved = vec3(0.0);\n\n mat2 rotMatrix;\n",particleAnimFrameClampVS:"\n float animFrame = min(floor(texCoordsAlphaLife.w * animTexParams.y) + animTexParams.x, animTexParams.z);\n",particleAnimFrameLoopVS:"\n float animFrame = floor(mod(texCoordsAlphaLife.w * animTexParams.y + animTexParams.x, animTexParams.z + 1.0));\n",particleAnimTexVS:"\n float animationIndex;\n\n if (animTexIndexParams.y == 1.0) {\n animationIndex = floor((animTexParams.w + 1.0) * rndFactor3.z) * (animTexParams.z + 1.0);\n } else {\n animationIndex = animTexIndexParams.x * (animTexParams.z + 1.0);\n }\n\n float atlasX = (animationIndex + animFrame) * animTexTilesParams.x;\n float atlasY = 1.0 - floor(atlasX + 1.0) * animTexTilesParams.y;\n atlasX = fract(atlasX);\n\n texCoordsAlphaLife.xy *= animTexTilesParams.xy;\n texCoordsAlphaLife.xy += vec2(atlasX, atlasY);\n",particleInputFloatPS:"\nvoid readInput(float uv) {\n vec4 tex = texture2D(particleTexIN, vec2(uv, 0.25));\n vec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.75));\n\n inPos = tex.xyz;\n inVel = tex2.xyz;\n inAngle = (tex.w < 0.0? -tex.w : tex.w) - 1000.0;\n inShow = tex.w >= 0.0;\n inLife = tex2.w;\n}\n",particleInputRgba8PS:"\n//RG=X, BA=Y\n//RG=Z, BA=A\n//RGB=V, A=visMode\n//RGBA=life\n\n#define PI2 6.283185307179586\n\nuniform vec3 inBoundsSize;\nuniform vec3 inBoundsCenter;\n\nuniform float maxVel;\n\nfloat decodeFloatRG(vec2 rg) {\n return rg.y*(1.0/255.0) + rg.x;\n}\n\nfloat decodeFloatRGBA( vec4 rgba ) {\n return dot( rgba, vec4(1.0, 1.0/255.0, 1.0/65025.0, 1.0/160581375.0) );\n}\n\nvoid readInput(float uv) {\n vec4 tex0 = texture2D(particleTexIN, vec2(uv, 0.125));\n vec4 tex1 = texture2D(particleTexIN, vec2(uv, 0.375));\n vec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.625));\n vec4 tex3 = texture2D(particleTexIN, vec2(uv, 0.875));\n\n inPos = vec3(decodeFloatRG(tex0.rg), decodeFloatRG(tex0.ba), decodeFloatRG(tex1.rg));\n inPos = (inPos - vec3(0.5)) * inBoundsSize + inBoundsCenter;\n\n inVel = tex2.xyz;\n inVel = (inVel - vec3(0.5)) * maxVel;\n\n inAngle = decodeFloatRG(tex1.ba) * PI2;\n inShow = tex2.a > 0.5;\n\n inLife = decodeFloatRGBA(tex3);\n float maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));\n float maxPosLife = lifetime+1.0;\n inLife = inLife * (maxNegLife + maxPosLife) - maxNegLife;\n}\n",particleOutputFloatPS:"\nvoid writeOutput() {\n if (gl_FragCoord.y<1.0) {\n gl_FragColor = vec4(outPos, (outAngle + 1000.0) * visMode);\n } else {\n gl_FragColor = vec4(outVel, outLife);\n }\n}\n",particleOutputRgba8PS:"\nuniform vec3 outBoundsMul;\nuniform vec3 outBoundsAdd;\n\nvec2 encodeFloatRG( float v ) {\n vec2 enc = vec2(1.0, 255.0) * v;\n enc = fract(enc);\n enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n return enc;\n}\n\nvec4 encodeFloatRGBA( float v ) {\n vec4 enc = vec4(1.0, 255.0, 65025.0, 160581375.0) * v;\n enc = fract(enc);\n enc -= enc.yzww * vec4(1.0/255.0,1.0/255.0,1.0/255.0,0.0);\n return enc;\n}\n\nvoid writeOutput() {\n outPos = outPos * outBoundsMul + outBoundsAdd;\n outAngle = fract(outAngle / PI2);\n\n outVel = (outVel / maxVel) + vec3(0.5); // TODO: mul\n\n float maxNegLife = max(lifetime, (numParticles - 1.0) * (rate+rateDiv));\n float maxPosLife = lifetime+1.0;\n outLife = (outLife + maxNegLife) / (maxNegLife + maxPosLife);\n\n if (gl_FragCoord.y < 1.0) {\n gl_FragColor = vec4(encodeFloatRG(outPos.x), encodeFloatRG(outPos.y));\n } else if (gl_FragCoord.y < 2.0) {\n gl_FragColor = vec4(encodeFloatRG(outPos.z), encodeFloatRG(outAngle));\n } else if (gl_FragCoord.y < 3.0) {\n gl_FragColor = vec4(outVel, visMode*0.5+0.5);\n } else {\n gl_FragColor = encodeFloatRGBA(outLife);\n }\n}\n",particleUpdaterAABBPS:"\nuniform mat3 spawnBounds;\nuniform vec3 spawnPosInnerRatio;\n\nvec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {\n vec3 pos = inBounds - vec3(0.5);\n\n vec3 posAbs = abs(pos);\n vec3 maxPos = vec3(max(posAbs.x, max(posAbs.y, posAbs.z)));\n\n vec3 edge = maxPos + (vec3(0.5) - maxPos) * spawnPosInnerRatio;\n\n pos.x = edge.x * (maxPos.x == posAbs.x ? sign(pos.x) : 2.0 * pos.x);\n pos.y = edge.y * (maxPos.y == posAbs.y ? sign(pos.y) : 2.0 * pos.y);\n pos.z = edge.z * (maxPos.z == posAbs.z ? sign(pos.z) : 2.0 * pos.z);\n\n#ifndef LOCAL_SPACE\n return emitterPos + spawnBounds * pos;\n#else\n return spawnBounds * pos;\n#endif\n}\n\nvoid addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {\n localVelocity -= vec3(0, 0, initialVelocity);\n}\n",particleUpdaterEndPS:"\n writeOutput();\n}\n",particleUpdaterInitPS:"\nvarying vec2 vUv0;\n\nuniform highp sampler2D particleTexIN;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\nuniform highp sampler2D internalTex3;\n\nuniform mat3 emitterMatrix, emitterMatrixInv;\nuniform vec3 emitterScale;\n\nuniform vec3 emitterPos, frameRandom, localVelocityDivMult, velocityDivMult;\nuniform float delta, rate, rateDiv, lifetime, numParticles, rotSpeedDivMult, radialSpeedDivMult, seed;\nuniform float startAngle, startAngle2;\nuniform float initialVelocity;\n\nuniform float graphSampleSize;\nuniform float graphNumSamples;\n\nvec3 inPos;\nvec3 inVel;\nfloat inAngle;\nbool inShow;\nfloat inLife;\nfloat visMode;\n\nvec3 outPos;\nvec3 outVel;\nfloat outAngle;\nbool outShow;\nfloat outLife;\n",particleUpdaterNoRespawnPS:"\n if (outLife >= lifetime) {\n outLife -= max(lifetime, (numParticles - 1.0) * particleRate);\n visMode = -1.0;\n }\n",particleUpdaterOnStopPS:"\n visMode = outLife < 0.0? -1.0: visMode;\n",particleUpdaterRespawnPS:"\n if (outLife >= lifetime) {\n outLife -= max(lifetime, (numParticles - 1.0) * particleRate);\n visMode = 1.0;\n }\n visMode = outLife < 0.0? 1.0: visMode;\n",particleUpdaterSpherePS:"\nuniform float spawnBoundsSphere;\nuniform float spawnBoundsSphereInnerRatio;\n\nvec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {\n float rnd4 = fract(rndFactor * 1000.0);\n vec3 norm = normalize(inBounds.xyz - vec3(0.5));\n float r = rnd4 * (1.0 - spawnBoundsSphereInnerRatio) + spawnBoundsSphereInnerRatio;\n#ifndef LOCAL_SPACE\n return emitterPos + norm * r * spawnBoundsSphere;\n#else\n return norm * r * spawnBoundsSphere;\n#endif\n}\n\nvoid addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {\n localVelocity += normalize(inBounds - vec3(0.5)) * initialVelocity;\n}\n",particleUpdaterStartPS:"\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n\nvec3 unpack3NFloats(float src) {\n float r = fract(src);\n float g = fract(src * 256.0);\n float b = fract(src * 65536.0);\n return vec3(r, g, b);\n}\n\nvec3 tex1Dlod_lerp(highp sampler2D tex, vec2 tc, out vec3 w) {\n vec4 a = texture2D(tex, tc);\n vec4 b = texture2D(tex, tc + graphSampleSize);\n float c = fract(tc.x * graphNumSamples);\n\n vec3 unpackedA = unpack3NFloats(a.w);\n vec3 unpackedB = unpack3NFloats(b.w);\n w = mix(unpackedA, unpackedB, c);\n\n return mix(a.xyz, b.xyz, c);\n}\n\n#define HASHSCALE4 vec4(1031, .1030, .0973, .1099)\nvec4 hash41(float p) {\n vec4 p4 = fract(vec4(p) * HASHSCALE4);\n p4 += dot(p4, p4.wzxy+19.19);\n return fract(vec4((p4.x + p4.y)*p4.z, (p4.x + p4.z)*p4.y, (p4.y + p4.z)*p4.w, (p4.z + p4.w)*p4.x));\n}\n\nvoid main(void) {\n if (gl_FragCoord.x > numParticles) discard;\n\n readInput(vUv0.x);\n visMode = inShow? 1.0 : -1.0;\n\n vec4 rndFactor = hash41(gl_FragCoord.x + seed);\n\n float particleRate = rate + rateDiv * rndFactor.x;\n\n outLife = inLife + delta;\n float nlife = clamp(outLife / lifetime, 0.0, 1.0);\n\n vec3 localVelocityDiv;\n vec3 velocityDiv;\n vec3 paramDiv;\n vec3 localVelocity = tex1Dlod_lerp(internalTex0, vec2(nlife, 0), localVelocityDiv);\n vec3 velocity = tex1Dlod_lerp(internalTex1, vec2(nlife, 0), velocityDiv);\n vec3 params = tex1Dlod_lerp(internalTex2, vec2(nlife, 0), paramDiv);\n float rotSpeed = params.x;\n float rotSpeedDiv = paramDiv.y;\n\n vec3 radialParams = tex1Dlod_lerp(internalTex3, vec2(nlife, 0), paramDiv);\n float radialSpeed = radialParams.x;\n float radialSpeedDiv = radialParams.y;\n\n bool respawn = inLife <= 0.0 || outLife >= lifetime;\n inPos = respawn ? calcSpawnPosition(rndFactor.xyz, rndFactor.x) : inPos;\n inAngle = respawn ? mix(startAngle, startAngle2, rndFactor.x) : inAngle;\n\n#ifndef LOCAL_SPACE\n vec3 radialVel = inPos - emitterPos;\n#else\n vec3 radialVel = inPos;\n#endif\n radialVel = (dot(radialVel, radialVel) > 1.0E-8) ? radialSpeed * normalize(radialVel) : vec3(0.0);\n radialVel += (radialSpeedDiv * vec3(2.0) - vec3(1.0)) * radialSpeedDivMult * rndFactor.xyz;\n\n localVelocity += (localVelocityDiv * vec3(2.0) - vec3(1.0)) * localVelocityDivMult * rndFactor.xyz;\n velocity += (velocityDiv * vec3(2.0) - vec3(1.0)) * velocityDivMult * rndFactor.xyz;\n rotSpeed += (rotSpeedDiv * 2.0 - 1.0) * rotSpeedDivMult * rndFactor.y;\n\n addInitialVelocity(localVelocity, rndFactor.xyz);\n\n#ifndef LOCAL_SPACE\n outVel = emitterMatrix * localVelocity + (radialVel + velocity) * emitterScale;\n#else\n outVel = (localVelocity + radialVel) / emitterScale + emitterMatrixInv * velocity;\n#endif\n\n outPos = inPos + outVel * delta;\n outAngle = inAngle + rotSpeed * delta;\n",particle_billboardVS:"\n quadXY = rotate(quadXY, inAngle, rotMatrix);\n vec3 localPos = billboard(particlePos, quadXY);\n",particle_blendAddPS:"\n dBlendModeFogFactor = 0.0;\n rgb *= saturate(gammaCorrectInput(max(a, 0.0)));\n if ((rgb.r + rgb.g + rgb.b) < 0.000001) discard;\n",particle_blendMultiplyPS:"\n rgb = mix(vec3(1.0), rgb, vec3(a));\n if (rgb.r + rgb.g + rgb.b > 2.99) discard;\n",particle_blendNormalPS:"\n if (a < 0.01) discard;\n",particle_cpuVS:"\nattribute vec4 particle_vertexData; // XYZ = world pos, W = life\nattribute vec4 particle_vertexData2; // X = angle, Y = scale, Z = alpha, W = velocity.x\nattribute vec4 particle_vertexData3; // XYZ = particle local pos, W = velocity.y\nattribute float particle_vertexData4; // particle id\n\n// type depends on useMesh property. Start with X = velocity.z, Y = particle ID and for mesh particles proceeds with Z = mesh UV.x, W = mesh UV.y\n#ifndef USE_MESH\nattribute vec2 particle_vertexData5;\n#else\nattribute vec4 particle_vertexData5;\n#endif\n\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\n\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n\nuniform mat3 matrix_normal;\nuniform mat4 matrix_viewInverse;\n\nuniform float numParticles;\nuniform float lifetime;\nuniform float stretch;\nuniform float seed;\nuniform vec3 wrapBounds;\nuniform vec3 emitterScale;\nuniform vec3 faceTangent;\nuniform vec3 faceBinorm;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\nuniform vec3 emitterPos;\n\nvarying vec4 texCoordsAlphaLife;\n\nvec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix)\n{\n float c = cos(pRotation);\n float s = sin(pRotation);\n //vec4 rotationMatrix = vec4(c, -s, s, c);\n\n mat2 m = mat2(c, -s, s, c);\n rotMatrix = m;\n\n return m * quadXY;\n}\n\nvec3 billboard(vec3 InstanceCoords, vec2 quadXY)\n{\n vec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;\n return pos;\n}\n\nvec3 customFace(vec3 InstanceCoords, vec2 quadXY)\n{\n vec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;\n return pos;\n}\n\nvoid main(void)\n{\n vec3 particlePos = particle_vertexData.xyz;\n vec3 inPos = particlePos;\n vec3 vertPos = particle_vertexData3.xyz;\n vec3 inVel = vec3(particle_vertexData2.w, particle_vertexData3.w, particle_vertexData5.x);\n\n float id = floor(particle_vertexData4);\n float rndFactor = fract(sin(id + 1.0 + seed));\n vec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));\n\n#ifdef LOCAL_SPACE\n inVel = mat3(matrix_model) * inVel;\n#endif\n vec2 velocityV = normalize((mat3(matrix_view) * inVel).xy); // should be removed by compiler if align/stretch is not used\n\n vec2 quadXY = vertPos.xy;\n\n#ifdef USE_MESH\n texCoordsAlphaLife = vec4(particle_vertexData5.zw, particle_vertexData2.z, particle_vertexData.w);\n#else\n texCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, particle_vertexData2.z, particle_vertexData.w);\n#endif\n mat2 rotMatrix;\n\n float inAngle = particle_vertexData2.x;\n vec3 particlePosMoved = vec3(0.0);\n vec3 meshLocalPos = particle_vertexData3.xyz;\n",particle_cpu_endVS:"\n localPos *= particle_vertexData2.y * emitterScale;\n localPos += particlePos;\n\n gl_Position = matrix_viewProjection * vec4(localPos, 1.0);\n",particle_customFaceVS:"\n quadXY = rotate(quadXY, inAngle, rotMatrix);\n vec3 localPos = customFace(particlePos, quadXY);\n",particle_endPS:"\n rgb = addFog(rgb);\n rgb = toneMap(rgb);\n rgb = gammaCorrectOutput(rgb);\n gl_FragColor = vec4(rgb, a);\n}\n",particle_endVS:"\n localPos *= scale * emitterScale;\n localPos += particlePos;\n\n #ifdef SCREEN_SPACE\n gl_Position = vec4(localPos.x, localPos.y, 0.0, 1.0);\n #else\n gl_Position = matrix_viewProjection * vec4(localPos.xyz, 1.0);\n #endif\n",particle_halflambertPS:"\n vec3 negNormal = normal*0.5+0.5;\n vec3 posNormal = -normal*0.5+0.5;\n negNormal *= negNormal;\n posNormal *= posNormal;\n",particle_initVS:"\nattribute vec4 particle_vertexData; // XYZ = particle position, W = particle ID + random factor\n#ifdef USE_MESH\nattribute vec2 particle_uv; // mesh UV\n#endif\n\nuniform mat4 matrix_viewProjection;\nuniform mat4 matrix_model;\nuniform mat3 matrix_normal;\nuniform mat4 matrix_viewInverse;\n\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n\nuniform float numParticles, numParticlesPot;\nuniform float graphSampleSize;\nuniform float graphNumSamples;\nuniform float stretch;\nuniform vec3 wrapBounds;\nuniform vec3 emitterScale, emitterPos, faceTangent, faceBinorm;\nuniform float rate, rateDiv, lifetime, deltaRandomnessStatic, scaleDivMult, alphaDivMult, seed, delta;\nuniform sampler2D particleTexOUT, particleTexIN;\nuniform highp sampler2D internalTex0;\nuniform highp sampler2D internalTex1;\nuniform highp sampler2D internalTex2;\n\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params;\n#endif\n\nvarying vec4 texCoordsAlphaLife;\n\nvec3 inPos;\nvec3 inVel;\nfloat inAngle;\nbool inShow;\nfloat inLife;\n",particle_lambertPS:"\n vec3 negNormal = max(normal, vec3(0.0));\n vec3 posNormal = max(-normal, vec3(0.0));\n",particle_lightingPS:"\n vec3 light = negNormal.x*lightCube[0] + posNormal.x*lightCube[1] +\n negNormal.y*lightCube[2] + posNormal.y*lightCube[3] +\n negNormal.z*lightCube[4] + posNormal.z*lightCube[5];\n\n rgb *= light;\n",particle_localShiftVS:"\n particlePos = (matrix_model * vec4(particlePos, 1.0)).xyz;\n",particle_meshVS:"\n vec3 localPos = meshLocalPos;\n localPos.xy = rotate(localPos.xy, inAngle, rotMatrix);\n localPos.yz = rotate(localPos.yz, inAngle, rotMatrix);\n\n billboard(particlePos, quadXY);\n",particle_normalVS:"\n Normal = normalize(localPos + matrix_viewInverse[2].xyz);\n",particle_normalMapPS:"\n vec3 normalMap = normalize(texture2D(normalMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y)).xyz * 2.0 - 1.0);\n vec3 normal = ParticleMat * normalMap;\n",particle_pointAlongVS:"\n inAngle = atan(velocityV.x, velocityV.y); // not the fastest way, but easier to plug in; TODO: create rot matrix right from vectors\n\n",particle_softPS:"\n float depth = getLinearScreenDepth();\n float particleDepth = vDepth;\n float depthDiff = saturate(abs(particleDepth - depth) * softening);\n a *= depthDiff;\n",particle_softVS:"\n vDepth = getLinearDepth(localPos);\n",particle_stretchVS:"\n vec3 moveDir = inVel * stretch;\n vec3 posPrev = particlePos - moveDir;\n posPrev += particlePosMoved;\n\n vec2 centerToVertexV = normalize((mat3(matrix_view) * localPos).xy);\n\n float interpolation = dot(-velocityV, centerToVertexV) * 0.5 + 0.5;\n\n particlePos = mix(particlePos, posPrev, interpolation);\n",particle_TBNVS:"\n mat3 rot3 = mat3(rotMatrix[0][0], rotMatrix[0][1], 0.0, rotMatrix[1][0], rotMatrix[1][1], 0.0, 0.0, 0.0, 1.0);\n ParticleMat = mat3(-matrix_viewInverse[0].xyz, -matrix_viewInverse[1].xyz, matrix_viewInverse[2].xyz) * rot3;\n",particle_wrapVS:"\n vec3 origParticlePos = particlePos;\n particlePos -= matrix_model[3].xyz;\n particlePos = mod(particlePos, wrapBounds) - wrapBounds * 0.5;\n particlePos += matrix_model[3].xyz;\n particlePosMoved = particlePos - origParticlePos;\n",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 float anisotropy = material_anisotropy * roughness;\n vec3 anisotropicDirection = anisotropy >= 0.0 ? tbn[1] : tbn[0];\n vec3 anisotropicTangent = cross(anisotropicDirection, viewDir);\n vec3 anisotropicNormal = cross(anisotropicTangent, anisotropicDirection);\n vec3 bentNormal = normalize(mix(normalize(worldNormal), normalize(anisotropicNormal), anisotropy));\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;\n\nvec3 calcReflection(vec3 reflDir, float gloss) {\n vec3 lookupVec = fixSeams(cubeMapProject(reflDir));\n lookupVec.x *= -1.0;\n return $DECODE(textureCube(texture_cubeMap, lookupVec));\n}\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\nuniform sampler2D texture_envAtlas;\n#endif\nuniform samplerCube texture_cubeMap;\nuniform float material_reflectivity;\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\n // calculate roughness level\n float level = saturate(1.0 - gloss) * 5.0;\n float ilevel = floor(level);\n float flevel = level - ilevel;\n\n vec3 sharp = $DECODE_CUBEMAP(textureCube(texture_cubeMap, fixSeams(dir)));\n vec3 roughA = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel)));\n vec3 roughB = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0)));\n\n return processEnvironment(mix(sharp, mix(roughA, roughB, flevel), min(level, 1.0)));\n}\n\nvoid addReflection(vec3 reflDir, float gloss) { \n dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);\n}\n",reflectionEnvPS:"\n#ifndef ENV_ATLAS\n#define ENV_ATLAS\nuniform sampler2D texture_envAtlas;\n#endif\nuniform float material_reflectivity;\n\n// calculate mip level for shiny reflection given equirect coords uv.\nfloat shinyMipLevel(vec2 uv) {\n vec2 dx = dFdx(uv);\n vec2 dy = dFdy(uv);\n\n // calculate second dF at 180 degrees\n vec2 uv2 = vec2(fract(uv.x + 0.5), uv.y);\n vec2 dx2 = dFdx(uv2);\n vec2 dy2 = dFdy(uv2);\n\n // calculate min of both sets of dF to handle discontinuity at the azim edge\n float maxd = min(max(dot(dx, dx), dot(dy, dy)), max(dot(dx2, dx2), dot(dy2, dy2)));\n\n return clamp(0.5 * log2(maxd) - 1.0 + textureBias, 0.0, 5.0);\n}\n\nvec3 calcReflection(vec3 reflDir, float gloss) {\n vec3 dir = cubeMapProject(reflDir) * vec3(-1.0, 1.0, 1.0);\n vec2 uv = toSphericalUv(dir);\n\n // calculate roughness level\n float level = saturate(1.0 - gloss) * 5.0;\n float ilevel = floor(level);\n\n // accessing the shiny (top level) reflection - perform manual mipmap lookup\n float level2 = shinyMipLevel(uv * atlasSize);\n float ilevel2 = floor(level2);\n\n vec2 uv0, uv1;\n float weight;\n if (ilevel == 0.0) {\n uv0 = mapShinyUv(uv, ilevel2);\n uv1 = mapShinyUv(uv, ilevel2 + 1.0);\n weight = level2 - ilevel2;\n } else {\n // accessing rough reflection - just sample the same part twice\n uv0 = uv1 = mapRoughnessUv(uv, ilevel);\n weight = 0.0;\n }\n\n vec3 linearA = $DECODE(texture2D(texture_envAtlas, uv0));\n vec3 linearB = $DECODE(texture2D(texture_envAtlas, uv1));\n vec3 linear0 = mix(linearA, linearB, weight);\n vec3 linear1 = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0)));\n\n return processEnvironment(mix(linear0, linear1, level - ilevel));\n}\n\nvoid addReflection(vec3 reflDir, float gloss) { \n dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);\n}\n",reflectionSpherePS:"\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\nuniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\n\nvec3 calcReflection(vec3 reflDir, float gloss) {\n vec3 reflDirV = (mat3(matrix_view) * reflDir).xyz;\n\n float m = 2.0 * sqrt( dot(reflDirV.xy, reflDirV.xy) + (reflDirV.z+1.0)*(reflDirV.z+1.0) );\n vec2 sphereMapUv = reflDirV.xy / m + 0.5;\n\n return $DECODE(texture2D(texture_sphereMap, sphereMapUv));\n}\n\nvoid addReflection(vec3 reflDir, float gloss) { \n dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);\n}\n",reflectionSphereLowPS:"\nuniform sampler2D texture_sphereMap;\nuniform float material_reflectivity;\n\nvec3 calcReflection(vec3 reflDir, float gloss) {\n vec3 reflDirV = vNormalV;\n\n vec2 sphereMapUv = reflDirV.xy * 0.5 + 0.5;\n return $DECODE(texture2D(texture_sphereMap, sphereMapUv));\n}\n\nvoid addReflection(vec3 reflDir, float gloss) { \n dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);\n}\n",reflectionSheenPS:"\n\nvoid addReflectionSheen(vec3 worldNormal, vec3 viewDir, float gloss) {\n float NoV = dot(worldNormal, viewDir);\n float alphaG = gloss * gloss;\n\n // Avoid using a LUT and approximate the values analytically\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:"\nuniform float material_refractionIndex;\n\nvec3 refract2(vec3 viewVec, vec3 normal, float IOR) {\n float vn = dot(viewVec, normal);\n float k = 1.0 - IOR * IOR * (1.0 - vn * vn);\n vec3 refrVec = IOR * viewVec - (IOR * vn + sqrt(k)) * normal;\n return refrVec;\n}\n\nvoid addRefraction(\n vec3 worldNormal, \n vec3 viewDir, \n float thickness, \n float gloss, \n vec3 specularity, \n vec3 albedo, \n float transmission\n#if defined(LIT_IRIDESCENCE)\n , vec3 iridescenceFresnel,\n IridescenceArgs iridescence\n#endif \n) {\n // use same reflection code with refraction vector\n vec4 tmpRefl = dReflection;\n vec3 reflectionDir = refract2(-viewDir, worldNormal, material_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_refractionIndex;\nuniform float material_invAttenuationDistance;\nuniform vec3 material_attenuation;\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#if defined(LIT_IRIDESCENCE)\n , vec3 iridescenceFresnel,\n IridescenceArgs iridescence\n#endif\n) {\n\n // Extract scale from the model transform\n vec3 modelScale;\n modelScale.x = length(vec3(matrix_model[0].xyz));\n modelScale.y = length(vec3(matrix_model[1].xyz));\n modelScale.z = length(vec3(matrix_model[2].xyz));\n\n // Calculate the refraction vector, scaled by the thickness and scale of the object\n vec3 refractionVector = normalize(refract(-viewDir, worldNormal, material_refractionIndex)) * thickness * modelScale;\n\n // The refraction point is the entry point + vector to exit point\n vec4 pointOfRefraction = vec4(vPositionW + refractionVector, 1.0);\n\n // Project to texture space so we can sample it\n vec4 projectionPoint = matrix_viewProjection * pointOfRefraction;\n\n // use built-in getGrabScreenPos function to convert screen position to grab texture uv coords\n vec2 uv = getGrabScreenPos(projectionPoint);\n\n #ifdef SUPPORTS_TEXLOD\n // Use IOR and roughness to select mip\n float iorToRoughness = (1.0 - gloss) * clamp((1.0 / material_refractionIndex) * 2.0 - 2.0, 0.0, 1.0);\n float refractionLod = log2(uScreenSize.x) * iorToRoughness;\n vec3 refraction = texture2DLodEXT(uSceneColorMap, uv, refractionLod).rgb;\n #else\n vec3 refraction = texture2D(uSceneColorMap, uv).rgb;\n #endif\n\n // Transmittance is our final refraction color\n vec3 transmittance;\n if (material_invAttenuationDistance != 0.0)\n {\n vec3 attenuation = -log(material_attenuation) * material_invAttenuationDistance;\n transmittance = exp(-attenuation * length(refractionVector));\n }\n else\n {\n transmittance = refraction;\n }\n\n // Apply fresnel effect on refraction\n vec3 fresnel = vec3(1.0) - \n getFresnel(\n dot(viewDir, worldNormal), \n gloss, \n specularity\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n iridescence\n #endif\n );\n dDiffuseLight = mix(dDiffuseLight, refraction * transmittance * fresnel, transmission);\n}\n",reprojectPS:"\n// This shader requires the following #DEFINEs:\n//\n// PROCESS_FUNC - must be one of reproject, prefilter\n// DECODE_FUNC - must be one of decodeRGBM, decodeRGBE, decodeGamma or decodeLinear\n// ENCODE_FUNC - must be one of encodeRGBM, encodeRGBE, encideGamma or encodeLinear\n// SOURCE_FUNC - must be one of sampleCubemap, sampleEquirect, sampleOctahedral\n// TARGET_FUNC - must be one of getDirectionCubemap, getDirectionEquirect, getDirectionOctahedral\n//\n// When filtering:\n// NUM_SAMPLES - number of samples\n// NUM_SAMPLES_SQRT - sqrt of number of samples\n\nvarying vec2 vUv0;\n\n// source\n#ifdef CUBEMAP_SOURCE\n uniform samplerCube sourceCube;\n#else\n uniform sampler2D sourceTex;\n#endif\n\n#ifdef USE_SAMPLES_TEX\n // samples\n uniform sampler2D samplesTex;\n uniform vec2 samplesTexInverseSize;\n#endif\n\n// params:\n// x - target cubemap face 0..6\n// y - specular power (when prefiltering)\n// z - source cubemap seam scale (0 to disable)\n// w - target cubemap size for seam calc (0 to disable)\nuniform vec4 params;\n\n// params2:\n// x - target image total pixels\n// y - source cubemap size\nuniform vec2 params2;\n\nfloat targetFace() { return params.x; }\nfloat specularPower() { return params.y; }\nfloat sourceCubeSeamScale() { return params.z; }\nfloat targetCubeSeamScale() { return params.w; }\n\nfloat targetTotalPixels() { return params2.x; }\nfloat sourceTotalPixels() { return params2.y; }\n\nfloat PI = 3.141592653589793;\n\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n\n"+ya+"\n"+xa+'\n\n//-- supported projections\n\nvec3 modifySeams(vec3 dir, float scale) {\n vec3 adir = abs(dir);\n float M = max(max(adir.x, adir.y), adir.z);\n return dir / M * vec3(\n adir.x == M ? 1.0 : scale,\n adir.y == M ? 1.0 : scale,\n adir.z == M ? 1.0 : scale\n );\n}\n\nvec2 toSpherical(vec3 dir) {\n return vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y));\n}\n\nvec3 fromSpherical(vec2 uv) {\n return vec3(cos(uv.y) * sin(uv.x),\n sin(uv.y),\n cos(uv.y) * cos(uv.x));\n}\n\nvec3 getDirectionEquirect() {\n return fromSpherical((vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0) * vec2(PI, PI * 0.5));\n}\n\n// octahedral code, based on http://jcgt.org/published/0003/02/01\n// "Survey of Efficient Representations for Independent Unit Vectors" by Cigolle, Donow, Evangelakos, Mara, McGuire, Meyer\n\nfloat signNotZero(float k){\n return(k >= 0.0) ? 1.0 : -1.0;\n}\n\nvec2 signNotZero(vec2 v) {\n return vec2(signNotZero(v.x), signNotZero(v.y));\n}\n\n// Returns a unit vector. Argument o is an octahedral vector packed via octEncode, on the [-1, +1] square\nvec3 octDecode(vec2 o) {\n vec3 v = vec3(o.x, 1.0 - abs(o.x) - abs(o.y), o.y);\n if (v.y < 0.0) {\n v.xz = (1.0 - abs(v.zx)) * signNotZero(v.xz);\n }\n return normalize(v);\n}\n\nvec3 getDirectionOctahedral() {\n return octDecode(vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0);\n}\n\n// Assumes that v is a unit vector. The result is an octahedral vector on the [-1, +1] square\nvec2 octEncode(in vec3 v) {\n float l1norm = abs(v.x) + abs(v.y) + abs(v.z);\n vec2 result = v.xz * (1.0 / l1norm);\n if (v.y < 0.0) {\n result = (1.0 - abs(result.yx)) * signNotZero(result.xy);\n }\n return result;\n}\n\n/////////////////////////////////////////////////////////////////////\n\n#ifdef CUBEMAP_SOURCE\n vec4 sampleCubemap(vec3 dir) {\n return textureCube(sourceCube, modifySeams(dir, 1.0 - sourceCubeSeamScale()));\n }\n\n vec4 sampleCubemap(vec2 sph) {\n return sampleCubemap(fromSpherical(sph));\n}\n\n vec4 sampleCubemap(vec3 dir, float mipLevel) {\n return textureCubeLodEXT(sourceCube, modifySeams(dir, 1.0 - exp2(mipLevel) * sourceCubeSeamScale()), mipLevel);\n }\n\n vec4 sampleCubemap(vec2 sph, float mipLevel) {\n return sampleCubemap(fromSpherical(sph), mipLevel);\n }\n#else\n\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\n vec4 sampleEquirect(vec3 dir) {\n return sampleEquirect(toSpherical(dir));\n }\n\n vec4 sampleEquirect(vec2 sph, float mipLevel) {\n vec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;\n return texture2DLodEXT(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);\n }\n\n vec4 sampleEquirect(vec3 dir, float mipLevel) {\n return sampleEquirect(toSpherical(dir), mipLevel);\n }\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\n vec4 sampleOctahedral(vec2 sph) {\n return sampleOctahedral(fromSpherical(sph));\n }\n\n vec4 sampleOctahedral(vec3 dir, float mipLevel) {\n vec2 uv = octEncode(dir) * 0.5 + 0.5;\n return texture2DLodEXT(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);\n }\n\n vec4 sampleOctahedral(vec2 sph, float mipLevel) {\n return sampleOctahedral(fromSpherical(sph), mipLevel);\n }\n\n#endif\n\nvec3 getDirectionCubemap() {\n vec2 st = vUv0 * 2.0 - 1.0;\n float face = targetFace();\n\n vec3 vec;\n if (face == 0.0) {\n vec = vec3(1, -st.y, -st.x);\n } else if (face == 1.0) {\n vec = vec3(-1, -st.y, st.x);\n } else if (face == 2.0) {\n vec = vec3(st.x, 1, st.y);\n } else if (face == 3.0) {\n vec = vec3(st.x, -1, -st.y);\n } else if (face == 4.0) {\n vec = vec3(st.x, -st.y, 1);\n } else {\n vec = vec3(-st.x, -st.y, -1);\n }\n\n return normalize(modifySeams(vec, 1.0 / (1.0 - targetCubeSeamScale())));\n}\n\nmat3 matrixFromVector(vec3 n) { // frisvad\n float a = 1.0 / (1.0 + n.z);\n float b = -n.x * n.y * a;\n vec3 b1 = vec3(1.0 - n.x * n.x * a, b, -n.x);\n vec3 b2 = vec3(b, 1.0 - n.y * n.y * a, -n.y);\n return mat3(b1, b2, n);\n}\n\nmat3 matrixFromVectorSlow(vec3 n) {\n vec3 up = (1.0 - abs(n.y) <= 0.0000001) ? vec3(0.0, 0.0, n.y > 0.0 ? 1.0 : -1.0) : vec3(0.0, 1.0, 0.0);\n vec3 x = normalize(cross(up, n));\n vec3 y = cross(n, x);\n return mat3(x, y, n);\n}\n\nvec4 reproject() {\n if (NUM_SAMPLES <= 1) {\n // single sample\n return ENCODE_FUNC(DECODE_FUNC(SOURCE_FUNC(TARGET_FUNC())));\n } else {\n // multi sample\n vec3 t = TARGET_FUNC();\n vec3 tu = dFdx(t);\n vec3 tv = dFdy(t);\n\n vec3 result = vec3(0.0);\n for (float u = 0.0; u < NUM_SAMPLES_SQRT; ++u) {\n for (float v = 0.0; v < NUM_SAMPLES_SQRT; ++v) {\n result += DECODE_FUNC(SOURCE_FUNC(normalize(t +\n tu * (u / NUM_SAMPLES_SQRT - 0.5) +\n tv * (v / NUM_SAMPLES_SQRT - 0.5))));\n }\n }\n return ENCODE_FUNC(result / (NUM_SAMPLES_SQRT * NUM_SAMPLES_SQRT));\n }\n}\n\nvec4 unpackFloat = vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0);\n\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\n vec4 raw;\n raw.x = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n raw.y = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n raw.z = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;\n raw.w = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat);\n\n L.xyz = raw.xyz * 2.0 - 1.0;\n mipLevel = raw.w * 8.0;\n }\n\n // convolve an environment given pre-generated samples\n vec4 prefilterSamples() {\n // construct vector space given target direction\n mat3 vecSpace = matrixFromVectorSlow(TARGET_FUNC());\n\n vec3 L;\n float mipLevel;\n\n vec3 result = vec3(0.0);\n float totalWeight = 0.0;\n for (int i = 0; i < NUM_SAMPLES; ++i) {\n unpackSample(i, L, mipLevel);\n result += DECODE_FUNC(SOURCE_FUNC(vecSpace * L, mipLevel)) * L.z;\n totalWeight += L.z;\n }\n\n return ENCODE_FUNC(result / totalWeight);\n }\n\n // unweighted version of prefilterSamples\n vec4 prefilterSamplesUnweighted() {\n // construct vector space given target direction\n mat3 vecSpace = matrixFromVectorSlow(TARGET_FUNC());\n\n vec3 L;\n float mipLevel;\n\n vec3 result = vec3(0.0);\n float totalWeight = 0.0;\n for (int i = 0; i < NUM_SAMPLES; ++i) {\n unpackSample(i, L, mipLevel);\n result += DECODE_FUNC(SOURCE_FUNC(vecSpace * L, mipLevel));\n }\n\n return ENCODE_FUNC(result / float(NUM_SAMPLES));\n }\n#endif\n\nvoid main(void) {\n gl_FragColor = PROCESS_FUNC();\n}\n',screenDepthPS:"\nuniform highp sampler2D uSceneDepthMap;\n\n#ifndef SCREENSIZE\n#define SCREENSIZE\nuniform vec4 uScreenSize;\n#endif\n\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n\n#ifndef LINEARIZE_DEPTH\n#ifndef CAMERAPLANES\n#define CAMERAPLANES\nuniform vec4 camera_params; // x: 1 / camera_far, y: camera_far, z: camera_near, w: is_ortho\n#endif\n\n#define LINEARIZE_DEPTH\n#ifdef GL2\nfloat linearizeDepth(float z) {\n if (camera_params.w == 0.0)\n return (camera_params.z * camera_params.y) / (camera_params.y + z * (camera_params.z - camera_params.y));\n else\n return camera_params.z + z * (camera_params.y - camera_params.z);\n}\n#else // GL2\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n const vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n return dot(rgbaDepth, bitShift);\n}\n#endif\n#endif\n#endif // LINEARIZE_DEPTH\n\n// Retrieves rendered linear camera depth by UV\nfloat getLinearScreenDepth(vec2 uv) {\n #ifdef GL2\n return linearizeDepth(texture2D(uSceneDepthMap, uv).r);\n #else\n return unpackFloat(texture2D(uSceneDepthMap, uv)) * camera_params.y;\n #endif\n}\n\n#ifndef VERTEXSHADER\n// Retrieves rendered linear camera depth under the current pixel\nfloat getLinearScreenDepth() {\n vec2 uv = gl_FragCoord.xy * uScreenSize.zw;\n return getLinearScreenDepth(uv);\n}\n#endif\n\n// Generates linear camera depth for the given world position\nfloat getLinearDepth(vec3 pos) {\n return -(matrix_view * vec4(pos, 1.0)).z;\n}\n",shadowCascadesPS:"\nconst float maxCascades = 4.0;\n\n// shadow matrix for selected cascade\nmat4 cascadeShadowMat;\n\n// function which selects a shadow projection matrix based on cascade distances \nvoid getShadowCascadeMatrix(mat4 shadowMatrixPalette[4], float shadowCascadeDistances[4], float shadowCascadeCount) {\n\n // depth in 0 .. far plane range\n float depth = 1.0 / gl_FragCoord.w;\n\n // find cascade index based on the depth (loop as there is no per component vec compare operator in webgl)\n float cascadeIndex = 0.0;\n for (float i = 0.0; i < maxCascades; i++) {\n if (depth < shadowCascadeDistances[int(i)]) {\n cascadeIndex = i;\n break;\n }\n }\n\n // limit to actual number of used cascades\n cascadeIndex = min(cascadeIndex, shadowCascadeCount - 1.0);\n\n // pick shadow matrix\n #ifdef GL2\n cascadeShadowMat = shadowMatrixPalette[int(cascadeIndex)];\n #else\n // webgl 1 does not allow non-cost index array lookup\n if (cascadeIndex == 0.0) {\n cascadeShadowMat = shadowMatrixPalette[0];\n }\n else if (cascadeIndex == 1.0) {\n cascadeShadowMat = shadowMatrixPalette[1];\n }\n else if (cascadeIndex == 2.0) {\n cascadeShadowMat = shadowMatrixPalette[2];\n }\n else {\n cascadeShadowMat = shadowMatrixPalette[3];\n }\n #endif\n}\n\nvoid fadeShadow(float shadowCascadeDistances[4]) { \n\n // if the pixel is past the shadow distance, remove shadow\n // this enforces straight line instead of corner of shadow which moves when camera rotates \n float depth = 1.0 / gl_FragCoord.w;\n if (depth > shadowCascadeDistances[int(maxCascades - 1.0)]) {\n dShadowCoord.z = -9999999.0;\n }\n}\n",shadowEVSMPS:"\nfloat VSM$(sampler2D tex, vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n vec3 moments = texture2D(tex, texCoords).xyz;\n return calculateEVSM(moments, Z, vsmBias, exponent);\n}\n\nfloat getShadowVSM$(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n return VSM$(shadowMap, shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);\n}\n\nfloat getShadowSpotVSM$(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n return VSM$(shadowMap, shadowCoord.xy, shadowParams.x, length(lightDir) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);\n}\n",shadowEVSMnPS:"\nfloat VSM$(sampler2D tex, vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n float pixelSize = 1.0 / resolution;\n texCoords -= vec2(pixelSize);\n vec3 s00 = texture2D(tex, texCoords).xyz;\n vec3 s10 = texture2D(tex, texCoords + vec2(pixelSize, 0)).xyz;\n vec3 s01 = texture2D(tex, texCoords + vec2(0, pixelSize)).xyz;\n vec3 s11 = texture2D(tex, texCoords + vec2(pixelSize)).xyz;\n vec2 fr = fract(texCoords * resolution);\n vec3 h0 = mix(s00, s10, fr.x);\n vec3 h1 = mix(s01, s11, fr.x);\n vec3 moments = mix(h0, h1, fr.y);\n return calculateEVSM(moments, Z, vsmBias, exponent);\n}\n\nfloat getShadowVSM$(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n return VSM$(shadowMap, shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);\n}\n\nfloat getShadowSpotVSM$(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n return VSM$(shadowMap, shadowCoord.xy, shadowParams.x, length(lightDir) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);\n}\n",shadowPCSSPS:"\n\n/**\n * PCSS is a shadow sampling method that provides contact hardening soft shadows. \n * Based on: \n * - https://www.gamedev.net/tutorials/programming/graphics/effect-area-light-shadows-part-1-pcss-r4971/\n * - https://github.com/pboechat/PCSS \n */\n\n\n#define PCSS_SAMPLE_COUNT 16\nuniform float pcssDiskSamples[PCSS_SAMPLE_COUNT];\nuniform float pcssSphereSamples[PCSS_SAMPLE_COUNT];\n\nvec2 vogelDisk(int sampleIndex, float count, float phi, float r) {\n const float GoldenAngle = 2.4;\n float theta = float(sampleIndex) * GoldenAngle + phi;\n\n float sine = sin(theta);\n float cosine = cos(theta);\n return vec2(r * cosine, r * sine);\n}\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\n float weight = float(sampleIndex) / count;\n return vec3(cos(theta) * r, weight, sin(theta) * r);\n}\n\nfloat gradientNoise(vec2 screenPos) {\n vec3 magic = vec3(0.06711056, 0.00583715, 52.9829189);\n return fract(magic.z * fract(dot(screenPos, magic.xy)));\n}\n\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\nfloat unpackFloat(vec4 rgbaDepth) {\n const vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n return dot(rgbaDepth, bitShift);\n}\n#endif\n\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}\n\n\nfloat PCSSBlockerDistance(TEXTURE_ACCEPT(shadowMap), vec2 sampleCoords[PCSS_SAMPLE_COUNT], vec2 shadowCoords, vec2 searchSize, float z) {\n\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\n #ifdef GL2\n float blocker = textureLod(shadowMap, sampleUV, 0.0).r;\n #else // GL1\n float blocker = unpackFloat(texture2D(shadowMap, sampleUV));\n #endif \n float isBlocking = step(blocker, z);\n blockers += isBlocking;\n averageBlocker += blocker * isBlocking;\n }\n\n if (blockers > 0.0)\n return averageBlocker /= blockers;\n return -1.0;\n}\n\nfloat PCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoords, vec4 cameraParams, vec2 shadowSearchArea) {\n float receiverDepth = linearizeDepth(shadowCoords.z, cameraParams);\n#ifndef GL2\n // If using packed depth on GL1, we need to normalize to get the correct receiver depth\n receiverDepth *= 1.0 / (cameraParams.y - cameraParams.z);\n#endif\n\n vec2 samplePoints[PCSS_SAMPLE_COUNT];\n float noise = gradientNoise( 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\n float averageBlocker = PCSSBlockerDistance(TEXTURE_PASS(shadowMap), samplePoints, shadowCoords.xy, shadowSearchArea, receiverDepth);\n if (averageBlocker == -1.0) {\n return 1.0;\n } else {\n\n vec2 filterRadius = ((receiverDepth - averageBlocker) / averageBlocker) * shadowSearchArea * cameraParams.x;\n\n float shadow = 0.0;\n\n for (int i = 0; i < PCSS_SAMPLE_COUNT; i ++)\n {\n vec2 sampleUV = samplePoints[i] * filterRadius;\n sampleUV = shadowCoords.xy + sampleUV;\n\n #ifdef GL2\n float depth = textureLod(shadowMap, sampleUV, 0.0).r;\n #else // GL1\n float depth = unpackFloat(texture2D(shadowMap, sampleUV));\n #endif\n shadow += step(receiverDepth, depth);\n }\n return shadow / float(PCSS_SAMPLE_COUNT);\n } \n}\n\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\n #ifdef GL2\n float blocker = textureCubeLodEXT(shadowMap, sampleDir, 0.0).r;\n #else // GL1\n float blocker = unpackFloat(textureCube(shadowMap, sampleDir));\n #endif\n float isBlocking = step(blocker, z);\n blockers += isBlocking;\n averageBlocker += blocker * isBlocking;\n }\n\n if (blockers > 0.0)\n return averageBlocker /= float(blockers);\n return -1.0;\n}\n\nfloat PCSSCube(samplerCube shadowMap, vec4 shadowParams, vec3 shadowCoords, vec4 cameraParams, float shadowSearchArea, vec3 lightDir) {\n \n vec3 samplePoints[PCSS_SAMPLE_COUNT];\n float noise = gradientNoise( 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\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\n float filterRadius = ((receiverDepth - averageBlocker) / averageBlocker) * shadowSearchArea;\n\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\n #ifdef GL2\n float depth = textureCubeLodEXT(shadowMap, sampleDir, 0.0).r;\n #else // GL1\n float depth = unpackFloat(textureCube(shadowMap, sampleDir));\n #endif\n shadow += step(receiverDepth, depth);\n }\n return shadow / float(PCSS_SAMPLE_COUNT);\n }\n}\n\nfloat getShadowPointPCSS(samplerCube shadowMap, vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec2 shadowSearchArea, vec3 lightDir) {\n return PCSSCube(shadowMap, shadowParams, shadowCoord, cameraParams, shadowSearchArea.x, lightDir);\n}\n\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\nfloat getShadowPCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec2 shadowSearchArea, vec3 lightDir) {\n return PCSS(TEXTURE_PASS(shadowMap), shadowCoord, cameraParams, shadowSearchArea);\n}\n\n",shadowSampleCoordPS:"\n\nvec3 getShadowSampleCoord$LIGHT(mat4 shadowTransform, vec4 shadowParams, vec3 worldPosition, vec3 lightPos, inout vec3 lightDir, vec3 lightDirNorm, vec3 normal) {\n\n vec3 surfacePosition = worldPosition;\n\n#ifdef SHADOW_SAMPLE_POINT\n #ifdef SHADOW_SAMPLE_NORMAL_OFFSET\n float distScale = length(lightDir);\n surfacePosition = worldPosition + 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 SHADOW_SAMPLE_SOURCE_ZBUFFER\n #ifdef SHADOW_SAMPLE_NORMAL_OFFSET\n surfacePosition = worldPosition + normal * shadowParams.y;\n #endif\n #else\n #ifdef SHADOW_SAMPLE_NORMAL_OFFSET\n #ifdef SHADOW_SAMPLE_ORTHO\n float distScale = 1.0;\n #else\n float distScale = abs(dot(vPositionW - lightPos, lightDirNorm));\n #endif\n surfacePosition = worldPosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;\n #endif\n #endif\n\n vec4 positionInShadowSpace = shadowTransform * vec4(surfacePosition, 1.0);\n #ifdef SHADOW_SAMPLE_ORTHO\n positionInShadowSpace.z = saturate(positionInShadowSpace.z) - 0.0001;\n #else\n #ifdef 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\n #ifdef SHADOW_SAMPLE_Z_BIAS\n positionInShadowSpace.z += getShadowBias(shadowParams.x, shadowParams.z);\n #endif\n surfacePosition = positionInShadowSpace.xyz;\n#endif\n\n return surfacePosition;\n}\n",shadowStandardPS:"\nvec3 lessThan2(vec3 a, vec3 b) {\n return clamp((b - a)*1000.0, 0.0, 1.0); // softer version\n}\n\n#ifndef UNPACKFLOAT\n#define UNPACKFLOAT\n float unpackFloat(vec4 rgbaDepth) {\n const vec4 bitShift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n return dot(rgbaDepth, bitShift);\n }\n#endif\n\n// ----- Direct/Spot Sampling -----\n\n#ifdef GL2\n\nfloat _getShadowPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec3 shadowParams) {\n float z = shadowCoord.z;\n vec2 uv = shadowCoord.xy * shadowParams.x; // 1 unit - 1 texel\n float shadowMapSizeInv = 1.0 / shadowParams.x;\n vec2 base_uv = floor(uv + 0.5);\n float s = (uv.x + 0.5 - base_uv.x);\n float t = (uv.y + 0.5 - base_uv.y);\n base_uv -= vec2(0.5);\n base_uv *= shadowMapSizeInv;\n\n float sum = 0.0;\n\n float uw0 = (3.0 - 2.0 * s);\n float uw1 = (1.0 + 2.0 * s);\n\n float u0 = (2.0 - s) / uw0 - 1.0;\n float u1 = s / uw1 + 1.0;\n\n float vw0 = (3.0 - 2.0 * t);\n float vw1 = (1.0 + 2.0 * t);\n\n float v0 = (2.0 - t) / vw0 - 1.0;\n float v1 = t / vw1 + 1.0;\n\n u0 = u0 * shadowMapSizeInv + base_uv.x;\n v0 = v0 * shadowMapSizeInv + base_uv.y;\n\n u1 = u1 * shadowMapSizeInv + base_uv.x;\n v1 = v1 * shadowMapSizeInv + base_uv.y;\n\n sum += uw0 * vw0 * 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\n sum *= 1.0f / 16.0;\n return sum;\n}\n\nfloat getShadowPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return _getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);\n}\n\nfloat getShadowSpotPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return _getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);\n}\n\nfloat getShadowPCF1x1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return textureShadow(shadowMap, shadowCoord);\n}\n\nfloat getShadowSpotPCF1x1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return textureShadow(shadowMap, shadowCoord);\n}\n\n#else // GL1\n\nfloat _xgetShadowPCF3x3(mat3 depthKernel, vec3 shadowCoord, sampler2D shadowMap, vec3 shadowParams) {\n mat3 shadowKernel;\n vec3 shadowZ = vec3(shadowCoord.z);\n shadowKernel[0] = vec3(greaterThan(depthKernel[0], shadowZ));\n shadowKernel[1] = vec3(greaterThan(depthKernel[1], shadowZ));\n shadowKernel[2] = vec3(greaterThan(depthKernel[2], shadowZ));\n\n vec2 fractionalCoord = fract( shadowCoord.xy * shadowParams.x );\n\n shadowKernel[0] = mix(shadowKernel[0], shadowKernel[1], fractionalCoord.x);\n shadowKernel[1] = mix(shadowKernel[1], shadowKernel[2], fractionalCoord.x);\n\n vec4 shadowValues;\n shadowValues.x = mix(shadowKernel[0][0], shadowKernel[0][1], fractionalCoord.y);\n shadowValues.y = mix(shadowKernel[0][1], shadowKernel[0][2], fractionalCoord.y);\n shadowValues.z = mix(shadowKernel[1][0], shadowKernel[1][1], fractionalCoord.y);\n shadowValues.w = mix(shadowKernel[1][1], shadowKernel[1][2], fractionalCoord.y);\n\n return dot( shadowValues, vec4( 1.0 ) ) * 0.25;\n}\n\nfloat _getShadowPCF3x3(sampler2D shadowMap, vec3 shadowCoord, vec3 shadowParams) {\n float xoffset = 1.0 / shadowParams.x; // 1/shadow map width\n float dx0 = -xoffset;\n float dx1 = xoffset;\n\n mat3 depthKernel;\n depthKernel[0][0] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx0, dx0)));\n depthKernel[0][1] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx0, 0.0)));\n depthKernel[0][2] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx0, dx1)));\n depthKernel[1][0] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(0.0, dx0)));\n depthKernel[1][1] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy));\n depthKernel[1][2] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(0.0, dx1)));\n depthKernel[2][0] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx1, dx0)));\n depthKernel[2][1] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx1, 0.0)));\n depthKernel[2][2] = unpackFloat(textureShadow(shadowMap, shadowCoord.xy + vec2(dx1, dx1)));\n\n return _xgetShadowPCF3x3(depthKernel, shadowCoord, shadowMap, shadowParams);\n}\n\nfloat getShadowPCF3x3(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n return _getShadowPCF3x3(shadowMap, shadowCoord, shadowParams.xyz);\n}\n\nfloat getShadowSpotPCF3x3(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n return _getShadowPCF3x3(shadowMap, shadowCoord, shadowParams.xyz);\n}\n\nfloat _getShadowPCF1x1(sampler2D shadowMap, vec3 shadowCoord) {\n float shadowSample = unpackFloat(textureShadow(shadowMap, shadowCoord.xy));\n return shadowSample > shadowCoord.z ? 1.0 : 0.0;\n}\n\nfloat getShadowPCF1x1(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n return _getShadowPCF1x1(shadowMap, shadowCoord);\n}\n\nfloat getShadowSpotPCF1x1(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams) {\n return _getShadowPCF1x1(shadowMap, shadowCoord);\n}\n#endif\n\n\n// ----- Omni Sampling -----\n\n#ifndef WEBGPU\n\nfloat _getShadowPoint(samplerCube shadowMap, vec4 shadowParams, vec3 dir) {\n\n vec3 tc = normalize(dir);\n vec3 tcAbs = abs(tc);\n\n vec4 dirX = vec4(1,0,0, tc.x);\n vec4 dirY = vec4(0,1,0, tc.y);\n float majorAxisLength = tc.z;\n if ((tcAbs.x > tcAbs.y) && (tcAbs.x > tcAbs.z)) {\n dirX = vec4(0,0,1, tc.z);\n dirY = vec4(0,1,0, tc.y);\n majorAxisLength = tc.x;\n } else if ((tcAbs.y > tcAbs.x) && (tcAbs.y > tcAbs.z)) {\n dirX = vec4(1,0,0, tc.x);\n dirY = vec4(0,0,1, tc.z);\n majorAxisLength = tc.y;\n }\n\n float shadowParamsInFaceSpace = ((1.0/shadowParams.x) * 2.0) * abs(majorAxisLength);\n\n vec3 xoffset = (dirX.xyz * shadowParamsInFaceSpace);\n vec3 yoffset = (dirY.xyz * shadowParamsInFaceSpace);\n vec3 dx0 = -xoffset;\n vec3 dy0 = -yoffset;\n vec3 dx1 = xoffset;\n vec3 dy1 = yoffset;\n\n mat3 shadowKernel;\n mat3 depthKernel;\n\n depthKernel[0][0] = unpackFloat(textureCube(shadowMap, tc + dx0 + dy0));\n depthKernel[0][1] = unpackFloat(textureCube(shadowMap, tc + dx0));\n depthKernel[0][2] = unpackFloat(textureCube(shadowMap, tc + dx0 + dy1));\n depthKernel[1][0] = unpackFloat(textureCube(shadowMap, tc + dy0));\n depthKernel[1][1] = unpackFloat(textureCube(shadowMap, tc));\n depthKernel[1][2] = unpackFloat(textureCube(shadowMap, tc + dy1));\n depthKernel[2][0] = unpackFloat(textureCube(shadowMap, tc + dx1 + dy0));\n depthKernel[2][1] = unpackFloat(textureCube(shadowMap, tc + dx1));\n depthKernel[2][2] = unpackFloat(textureCube(shadowMap, tc + dx1 + dy1));\n\n vec3 shadowZ = vec3(length(dir) * shadowParams.w + shadowParams.z);\n\n shadowKernel[0] = vec3(lessThan2(depthKernel[0], shadowZ));\n shadowKernel[1] = vec3(lessThan2(depthKernel[1], shadowZ));\n shadowKernel[2] = vec3(lessThan2(depthKernel[2], shadowZ));\n\n vec2 uv = (vec2(dirX.w, dirY.w) / abs(majorAxisLength)) * 0.5;\n\n vec2 fractionalCoord = fract( uv * shadowParams.x );\n\n shadowKernel[0] = mix(shadowKernel[0], shadowKernel[1], fractionalCoord.x);\n shadowKernel[1] = mix(shadowKernel[1], shadowKernel[2], fractionalCoord.x);\n\n vec4 shadowValues;\n shadowValues.x = mix(shadowKernel[0][0], shadowKernel[0][1], fractionalCoord.y);\n shadowValues.y = mix(shadowKernel[0][1], shadowKernel[0][2], fractionalCoord.y);\n shadowValues.z = mix(shadowKernel[1][0], shadowKernel[1][1], fractionalCoord.y);\n shadowValues.w = mix(shadowKernel[1][1], shadowKernel[1][2], fractionalCoord.y);\n\n return 1.0 - dot( shadowValues, vec4( 1.0 ) ) * 0.25;\n}\n\nfloat getShadowPointPCF3x3(samplerCube shadowMap, vec3 shadowCoord, vec4 shadowParams, vec3 lightDir) {\n return _getShadowPoint(shadowMap, shadowParams, lightDir);\n}\n\n#endif\n",shadowStandardGL2PS:"\nfloat _getShadowPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec3 shadowParams) {\n // http://the-witness.net/news/2013/09/shadow-mapping-summary-part-1/\n\n float z = shadowCoord.z;\n vec2 uv = shadowCoord.xy * shadowParams.x; // 1 unit - 1 texel\n float shadowMapSizeInv = 1.0 / shadowParams.x;\n vec2 base_uv = floor(uv + 0.5);\n float s = (uv.x + 0.5 - base_uv.x);\n float t = (uv.y + 0.5 - base_uv.y);\n base_uv -= vec2(0.5);\n base_uv *= shadowMapSizeInv;\n\n\n float uw0 = (4.0 - 3.0 * s);\n float uw1 = 7.0;\n float uw2 = (1.0 + 3.0 * s);\n\n float u0 = (3.0 - 2.0 * s) / uw0 - 2.0;\n float u1 = (3.0 + s) / uw1;\n float u2 = s / uw2 + 2.0;\n\n float vw0 = (4.0 - 3.0 * t);\n float vw1 = 7.0;\n float vw2 = (1.0 + 3.0 * t);\n\n float v0 = (3.0 - 2.0 * t) / vw0 - 2.0;\n float v1 = (3.0 + t) / vw1;\n float v2 = t / vw2 + 2.0;\n\n float sum = 0.0;\n\n u0 = u0 * shadowMapSizeInv + base_uv.x;\n v0 = v0 * shadowMapSizeInv + base_uv.y;\n\n u1 = u1 * shadowMapSizeInv + base_uv.x;\n v1 = v1 * shadowMapSizeInv + base_uv.y;\n\n u2 = u2 * shadowMapSizeInv + base_uv.x;\n v2 = v2 * shadowMapSizeInv + base_uv.y;\n\n sum += uw0 * vw0 * 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\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\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\n sum *= 1.0f / 144.0;\n\n sum = saturate(sum);\n\n return sum;\n}\n\nfloat getShadowPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return _getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);\n}\n\nfloat getShadowSpotPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {\n return _getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);\n}\n",shadowVSM8PS:"\nfloat calculateVSM8(vec3 moments, float Z, float vsmBias) {\n float VSMBias = vsmBias;//0.01 * 0.25;\n float depthScale = VSMBias * Z;\n float minVariance1 = depthScale * depthScale;\n return chebyshevUpperBound(moments.xy, Z, minVariance1, 0.1);\n}\n\nfloat decodeFloatRG(vec2 rg) {\n return rg.y*(1.0/255.0) + rg.x;\n}\n\nfloat VSM8(sampler2D tex, vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {\n vec4 c = texture2D(tex, texCoords);\n vec3 moments = vec3(decodeFloatRG(c.xy), decodeFloatRG(c.zw), 0.0);\n return calculateVSM8(moments, Z, vsmBias);\n}\n\nfloat getShadowVSM8(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n return VSM8(shadowMap, shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, 0.0);\n}\n\nfloat getShadowSpotVSM8(sampler2D shadowMap, vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {\n return VSM8(shadowMap, shadowCoord.xy, shadowParams.x, length(lightDir) * shadowParams.w + shadowParams.z, shadowParams.y, 0.0);\n}\n",shadowVSM_commonPS:"\nfloat linstep(float a, float b, float v) {\n return saturate((v - a) / (b - a));\n}\n\nfloat reduceLightBleeding(float pMax, float amount) {\n // Remove the [0, amount] tail and linearly rescale (amount, 1].\n return linstep(amount, 1.0, pMax);\n}\n\nfloat chebyshevUpperBound(vec2 moments, float mean, float minVariance, float lightBleedingReduction) {\n // Compute variance\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, minVariance);\n\n // Compute probabilistic upper bound\n float d = mean - moments.x;\n float pMax = variance / (variance + (d * d));\n\n pMax = reduceLightBleeding(pMax, lightBleedingReduction);\n\n // One-tailed Chebyshev\n return (mean <= moments.x ? 1.0 : pMax);\n}\n\nfloat calculateEVSM(vec3 moments, float Z, float vsmBias, float exponent) {\n Z = 2.0 * Z - 1.0;\n float warpedDepth = exp(exponent * Z);\n\n moments.xy += vec2(warpedDepth, warpedDepth*warpedDepth) * (1.0 - moments.z);\n\n float VSMBias = vsmBias;//0.01 * 0.25;\n float depthScale = VSMBias * exponent * warpedDepth;\n float minVariance1 = depthScale * depthScale;\n return chebyshevUpperBound(moments.xy, warpedDepth, minVariance1, 0.1);\n}\n",skinBatchConstVS:"\nattribute float vertex_boneIndices;\n\nuniform vec4 matrix_pose[BONE_LIMIT * 3];\n\nmat4 getBoneMatrix(const in float i) {\n // read 4x3 matrix\n vec4 v1 = matrix_pose[int(3.0 * i)];\n vec4 v2 = matrix_pose[int(3.0 * i + 1.0)];\n vec4 v3 = matrix_pose[int(3.0 * i + 2.0)];\n\n // transpose to 4x4 matrix\n return mat4(\n v1.x, v2.x, v3.x, 0,\n v1.y, v2.y, v3.y, 0,\n v1.z, v2.z, v3.z, 0,\n v1.w, v2.w, v3.w, 1\n );\n}\n",skinBatchTexVS:"\nattribute float vertex_boneIndices;\n\nuniform highp sampler2D texture_poseMap;\nuniform vec4 texture_poseMapSize;\n\nmat4 getBoneMatrix(const in float i) {\n float j = i * 3.0;\n float dx = texture_poseMapSize.z;\n float dy = texture_poseMapSize.w;\n\n float y = floor(j * dx);\n float x = j - (y * texture_poseMapSize.x);\n y = dy * (y + 0.5);\n\n // read elements of 4x3 matrix\n vec4 v1 = texture2D(texture_poseMap, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(texture_poseMap, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(texture_poseMap, vec2(dx * (x + 2.5), y));\n\n // transpose to 4x4 matrix\n return mat4(\n v1.x, v2.x, v3.x, 0,\n v1.y, v2.y, v3.y, 0,\n v1.z, v2.z, v3.z, 0,\n v1.w, v2.w, v3.w, 1\n );\n}\n",skinConstVS:"\nattribute vec4 vertex_boneWeights;\nattribute vec4 vertex_boneIndices;\n\nuniform vec4 matrix_pose[BONE_LIMIT * 3];\n\nvoid getBoneMatrix(const in float i, out vec4 v1, out vec4 v2, out vec4 v3) {\n // read 4x3 matrix\n v1 = matrix_pose[int(3.0 * i)];\n v2 = matrix_pose[int(3.0 * i + 1.0)];\n v3 = matrix_pose[int(3.0 * i + 2.0)];\n}\n\nmat4 getSkinMatrix(const in vec4 indices, const in vec4 weights) {\n // get 4 bone matrices\n vec4 a1, a2, a3;\n getBoneMatrix(indices.x, a1, a2, a3);\n\n vec4 b1, b2, b3;\n getBoneMatrix(indices.y, b1, b2, b3);\n\n vec4 c1, c2, c3;\n getBoneMatrix(indices.z, c1, c2, c3);\n\n vec4 d1, d2, d3;\n getBoneMatrix(indices.w, d1, d2, d3);\n\n // multiply them by weights and add up to get final 4x3 matrix\n vec4 v1 = a1 * weights.x + b1 * weights.y + c1 * weights.z + d1 * weights.w;\n vec4 v2 = a2 * weights.x + b2 * weights.y + c2 * weights.z + d2 * weights.w;\n vec4 v3 = a3 * weights.x + b3 * weights.y + c3 * weights.z + d3 * weights.w;\n\n // add up weights\n float one = dot(weights, vec4(1.0));\n\n // transpose to 4x4 matrix\n return mat4(\n v1.x, v2.x, v3.x, 0,\n v1.y, v2.y, v3.y, 0,\n v1.z, v2.z, v3.z, 0,\n v1.w, v2.w, v3.w, one\n );\n}\n",skinTexVS:"\n\nattribute vec4 vertex_boneWeights;\nattribute vec4 vertex_boneIndices;\n\nuniform highp sampler2D texture_poseMap;\nuniform vec4 texture_poseMapSize;\n\nvoid getBoneMatrix(const in float index, out vec4 v1, out vec4 v2, out vec4 v3) {\n\n float i = float(index);\n float j = i * 3.0;\n float dx = texture_poseMapSize.z;\n float dy = texture_poseMapSize.w;\n \n float y = floor(j * dx);\n float x = j - (y * texture_poseMapSize.x);\n y = dy * (y + 0.5);\n\n // read elements of 4x3 matrix\n v1 = texture2D(texture_poseMap, vec2(dx * (x + 0.5), y));\n v2 = texture2D(texture_poseMap, vec2(dx * (x + 1.5), y));\n v3 = texture2D(texture_poseMap, vec2(dx * (x + 2.5), y));\n}\n\nmat4 getSkinMatrix(const in vec4 indices, const in vec4 weights) {\n // get 4 bone matrices\n vec4 a1, a2, a3;\n getBoneMatrix(indices.x, a1, a2, a3);\n\n vec4 b1, b2, b3;\n getBoneMatrix(indices.y, b1, b2, b3);\n\n vec4 c1, c2, c3;\n getBoneMatrix(indices.z, c1, c2, c3);\n\n vec4 d1, d2, d3;\n getBoneMatrix(indices.w, d1, d2, d3);\n\n // multiply them by weights and add up to get final 4x3 matrix\n vec4 v1 = a1 * weights.x + b1 * weights.y + c1 * weights.z + d1 * weights.w;\n vec4 v2 = a2 * weights.x + b2 * weights.y + c2 * weights.z + d2 * weights.w;\n vec4 v3 = a3 * weights.x + b3 * weights.y + c3 * weights.z + d3 * weights.w;\n\n // add up weights\n float one = dot(weights, vec4(1.0));\n\n // transpose to 4x4 matrix\n return mat4(\n v1.x, v2.x, v3.x, 0,\n v1.y, v2.y, v3.y, 0,\n v1.z, v2.z, v3.z, 0,\n v1.w, v2.w, v3.w, one\n );\n}\n",skyboxEnvPS:"\nvarying vec3 vViewDir;\n\nuniform sampler2D texture_envAtlas;\nuniform float mipLevel;\n\nvoid main(void) {\n vec3 dir = vViewDir * vec3(-1.0, 1.0, 1.0);\n vec2 uv = toSphericalUv(normalize(dir));\n\n vec3 linear = $DECODE(texture2D(texture_envAtlas, mapRoughnessUv(uv, mipLevel)));\n\n gl_FragColor = vec4(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0);\n}\n",skyboxHDRPS:"\nvarying vec3 vViewDir;\n\nuniform samplerCube texture_cubeMap;\n\nvoid main(void) {\n vec3 dir=vViewDir;\n dir.x *= -1.0;\n\n vec3 linear = $DECODE(textureCube(texture_cubeMap, fixSeamsStatic(dir, $FIXCONST)));\n\n gl_FragColor = vec4(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0);\n}\n",skyboxVS:"\nattribute vec3 aPosition;\n\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n\nuniform mat4 matrix_projectionSkybox;\nuniform mat3 cubeMapRotationMatrix;\n\nvarying vec3 vViewDir;\n\nvoid main(void) {\n mat4 view = matrix_view;\n view[3][0] = view[3][1] = view[3][2] = 0.0;\n gl_Position = matrix_projectionSkybox * view * vec4(aPosition, 1.0);\n\n // Force skybox to far Z, regardless of the clip planes on the camera\n // Subtract a tiny fudge factor to ensure floating point errors don't\n // still push pixels beyond far Z. See:\n // http://www.opengl.org/discussion_boards/showthread.php/171867-skybox-problem\n\n gl_Position.z = gl_Position.w - 0.00001;\n vViewDir = aPosition * cubeMapRotationMatrix;\n}\n",specularPS:"\n\n#ifdef MAPCOLOR\nuniform vec3 material_specular;\n#endif\n\nvoid getSpecularity() {\n vec3 specularColor = vec3(1,1,1);\n\n #ifdef MAPCOLOR\n specularColor *= material_specular;\n #endif\n\n #ifdef MAPTEXTURE\n specularColor *= $DECODE(texture2DBias($SAMPLER, $UV, textureBias)).$CH;\n #endif\n\n #ifdef MAPVERTEX\n specularColor *= saturate(vVertexColor.$VC);\n #endif\n\n dSpecularity = specularColor;\n}\n",sphericalPS:"\n// equirectangular helper functions\nconst float PI = 3.141592653589793;\n\nvec2 toSpherical(vec3 dir) {\n return vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y));\n}\n\nvec2 toSphericalUv(vec3 dir) {\n vec2 uv = toSpherical(dir) / vec2(PI * 2.0, PI) + 0.5;\n return vec2(uv.x, 1.0 - uv.y);\n}\n",specularityFactorPS:"\n\n#ifdef MAPFLOAT\nuniform float material_specularityFactor;\n#endif\n\nvoid getSpecularityFactor() {\n float specularityFactor = 1.0;\n\n #ifdef MAPFLOAT\n specularityFactor *= material_specularityFactor;\n #endif\n\n #ifdef MAPTEXTURE\n specularityFactor *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n specularityFactor *= saturate(vVertexColor.$VC);\n #endif\n\n dSpecularityFactor = specularityFactor;\n}\n",spotPS:"\nfloat getSpotEffect(vec3 lightSpotDir, float lightInnerConeAngle, float lightOuterConeAngle, vec3 lightDirNorm) {\n float cosAngle = dot(lightDirNorm, lightSpotDir);\n return smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle);\n}\n",startPS:"\nvoid main(void) {\n dReflection = vec4(0);\n\n #ifdef LIT_CLEARCOAT\n ccSpecularLight = vec3(0);\n ccReflection = vec3(0);\n #endif\n",startVS:"\nvoid main(void) {\n gl_Position = getPosition();\n",startNineSlicedPS:"\n nineSlicedUv = vUv0;\n nineSlicedUv.y = 1.0 - nineSlicedUv.y;\n\n",startNineSlicedTiledPS:"\n vec2 tileMask = step(vMask, vec2(0.99999));\n vec2 tileSize = 0.5 * (innerOffset.xy + innerOffset.zw);\n vec2 tileScale = vec2(1.0) / (vec2(1.0) - tileSize);\n vec2 clampedUv = mix(innerOffset.xy * 0.5, vec2(1.0) - innerOffset.zw * 0.5, fract((vTiledUv - tileSize) * tileScale));\n clampedUv = clampedUv * atlasRect.zw + atlasRect.xy;\n nineSlicedUv = vUv0 * tileMask + clampedUv * (vec2(1.0) - tileMask);\n nineSlicedUv.y = 1.0 - nineSlicedUv.y;\n \n",storeEVSMPS:"\nfloat exponent = VSM_EXPONENT;\n\ndepth = 2.0 * depth - 1.0;\ndepth = exp(exponent * depth);\ngl_FragColor = vec4(depth, depth*depth, 1.0, 1.0);\n",tangentBinormalVS:"\nvec3 getTangent() {\n return normalize(dNormalMatrix * vertex_tangent.xyz);\n}\n\nvec3 getBinormal() {\n return cross(vNormalW, vTangentW) * vertex_tangent.w;\n}\n",TBNPS:"\nvoid getTBN(vec3 tangent, vec3 binormal, vec3 normal) {\n dTBN = mat3(normalize(tangent), normalize(binormal), normalize(normal));\n}\n",TBNderivativePS:"\nuniform float tbnBasis;\n\n// http://www.thetenthplanet.de/archives/1180\nvoid getTBN(vec3 tangent, vec3 binormal, vec3 normal) {\n vec2 uv = $UV;\n\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx( vPositionW );\n vec3 dp2 = dFdy( vPositionW );\n vec2 duv1 = dFdx( uv );\n vec2 duv2 = dFdy( uv );\n\n // solve the linear system\n vec3 dp2perp = cross( dp2, 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\n // construct a scale-invariant frame\n float denom = max( dot(T,T), dot(B,B) );\n float invmax = (denom == 0.0) ? 0.0 : tbnBasis / sqrt( denom );\n dTBN = mat3(T * invmax, -B * invmax, normal );\n}\n",TBNfastPS:"\nvoid getTBN(vec3 tangent, vec3 binormal, vec3 normal) {\n dTBN = mat3(tangent, binormal, normal);\n}\n",TBNObjectSpacePS:"\nvoid getTBN(vec3 tangent, vec3 binormal, vec3 normal) {\n\n vec3 B = cross(normal, vObjectSpaceUpW);\n vec3 T = cross(normal, B);\n\n if (dot(B,B)==0.0) // deal with case when vObjectSpaceUpW normal are parallel\n {\n float major=max(max(normal.x, normal.y), normal.z);\n\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\n dTBN = mat3(normalize(T), normalize(B), normalize(normal));\n}\n",textureSamplePS:"\nvec4 texture2DSRGB(sampler2D tex, vec2 uv) {\n return gammaCorrectInput(texture2D(tex, uv));\n}\n\nvec4 texture2DSRGB(sampler2D tex, vec2 uv, float bias) {\n return gammaCorrectInput(texture2D(tex, uv, bias));\n}\n\nvec3 texture2DRGBM(sampler2D tex, vec2 uv) {\n return decodeRGBM(texture2D(tex, uv));\n}\n\nvec3 texture2DRGBM(sampler2D tex, vec2 uv, float bias) {\n return decodeRGBM(texture2D(tex, uv, bias));\n}\n\nvec3 texture2DRGBE(sampler2D tex, vec2 uv) {\n return decodeRGBM(texture2D(tex, uv));\n}\n\nvec3 texture2DRGBE(sampler2D tex, vec2 uv, float bias) {\n return decodeRGBM(texture2D(tex, uv, bias));\n}\n",thicknessPS:"\n#ifdef MAPFLOAT\nuniform float material_thickness;\n#endif\n\nvoid getThickness() {\n dThickness = 1.0;\n\n #ifdef MAPFLOAT\n dThickness *= material_thickness;\n #endif\n\n #ifdef MAPTEXTURE\n dThickness *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n dThickness *= saturate(vVertexColor.$VC);\n #endif\n}\n",tonemappingAcesPS:"\nuniform float exposure;\n\nvec3 toneMap(vec3 color) {\n float tA = 2.51;\n float tB = 0.03;\n float tC = 2.43;\n float tD = 0.59;\n float tE = 0.14;\n vec3 x = color * exposure;\n return (x*(tA*x+tB))/(x*(tC*x+tD)+tE);\n}\n",tonemappingAces2PS:"\nuniform float exposure;\n\n// ACES approximation by Stephen Hill\n\n// sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT\nconst mat3 ACESInputMat = mat3(\n 0.59719, 0.35458, 0.04823,\n 0.07600, 0.90834, 0.01566,\n 0.02840, 0.13383, 0.83777\n);\n\n// ODT_SAT => XYZ => D60_2_D65 => sRGB\nconst mat3 ACESOutputMat = mat3(\n 1.60475, -0.53108, -0.07367,\n -0.10208, 1.10813, -0.00605,\n -0.00327, -0.07276, 1.07602\n);\n\nvec3 RRTAndODTFit(vec3 v) {\n vec3 a = v * (v + 0.0245786) - 0.000090537;\n vec3 b = v * (0.983729 * v + 0.4329510) + 0.238081;\n return a / b;\n}\n\nvec3 toneMap(vec3 color) {\n color *= exposure / 0.6;\n color = color * ACESInputMat;\n\n // Apply RRT and ODT\n color = RRTAndODTFit(color);\n color = color * ACESOutputMat;\n\n // Clamp to [0, 1]\n color = clamp(color, 0.0, 1.0);\n\n return color;\n}\n",tonemappingFilmicPS:"\nconst float A = 0.15;\nconst float B = 0.50;\nconst float C = 0.10;\nconst float D = 0.20;\nconst float E = 0.02;\nconst float F = 0.30;\nconst float W = 11.2;\n\nuniform float exposure;\n\nvec3 uncharted2Tonemap(vec3 x) {\n return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\n}\n\nvec3 toneMap(vec3 color) {\n color = uncharted2Tonemap(color * exposure);\n vec3 whiteScale = 1.0 / uncharted2Tonemap(vec3(W,W,W));\n color = color * whiteScale;\n\n return color;\n}\n",tonemappingHejlPS:"\nuniform float exposure;\n\nvec3 toneMap(vec3 color) {\n color *= exposure;\n const float A = 0.22, B = 0.3, C = .1, D = 0.2, E = .01, F = 0.3;\n const float Scl = 1.25;\n\n vec3 h = max( vec3(0.0), color - vec3(0.004) );\n return (h*((Scl*A)*h+Scl*vec3(C*B,C*B,C*B))+Scl*vec3(D*E,D*E,D*E)) / (h*(A*h+vec3(B,B,B))+vec3(D*F,D*F,D*F)) - Scl*vec3(E/F,E/F,E/F);\n}\n",tonemappingLinearPS:"\nuniform float exposure;\n\nvec3 toneMap(vec3 color) {\n return color * exposure;\n}\n",tonemappingNonePS:"\nvec3 toneMap(vec3 color) {\n return color;\n}\n",transformVS:"\n#ifdef PIXELSNAP\nuniform vec4 uScreenSize;\n#endif\n\n#ifdef SCREENSPACE\nuniform float projectionFlipY;\n#endif\n\n#ifdef MORPHING\nuniform vec4 morph_weights_a;\nuniform vec4 morph_weights_b;\n#endif\n\n#ifdef MORPHING_TEXTURE_BASED\n uniform vec4 morph_tex_params;\n\n #ifdef WEBGPU\n ivec2 getTextureMorphCoords() {\n\n // turn morph_vertex_id into int grid coordinates\n ivec2 textureSize = ivec2(morph_tex_params.xy);\n int morphGridV = int(morph_vertex_id / textureSize.x);\n int morphGridU = int(morph_vertex_id - (morphGridV * textureSize.x));\n morphGridV = textureSize.y - morphGridV - 1;\n return ivec2(morphGridU, morphGridV);\n }\n #else\n vec2 getTextureMorphCoords() {\n vec2 textureSize = morph_tex_params.xy;\n vec2 invTextureSize = morph_tex_params.zw;\n\n // turn morph_vertex_id into int grid coordinates\n float morphGridV = floor(morph_vertex_id * invTextureSize.x);\n float morphGridU = morph_vertex_id - (morphGridV * textureSize.x);\n\n // convert grid coordinates to uv coordinates with half pixel offset\n return vec2(morphGridU, morphGridV) * invTextureSize + (0.5 * invTextureSize);\n }\n #endif\n\n#endif\n\n#ifdef MORPHING_TEXTURE_BASED_POSITION\nuniform highp sampler2D morphPositionTex;\n#endif\n\nmat4 getModelMatrix() {\n #ifdef DYNAMICBATCH\n return getBoneMatrix(vertex_boneIndices);\n #elif defined(SKIN)\n return matrix_model * getSkinMatrix(vertex_boneIndices, vertex_boneWeights);\n #elif defined(INSTANCING)\n return mat4(instance_line1, instance_line2, instance_line3, instance_line4);\n #else\n return matrix_model;\n #endif\n}\n\nvec4 getPosition() {\n dModelMatrix = getModelMatrix();\n vec3 localPos = vertex_position;\n\n #ifdef NINESLICED\n // outer and inner vertices are at the same position, scale both\n localPos.xz *= outerScale;\n\n // offset inner vertices inside\n // (original vertices must be in [-1;1] range)\n vec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0));\n vec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0));\n localPos.xz += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;\n\n vTiledUv = (localPos.xz - outerScale + innerOffset.xy) * -0.5 + 1.0; // uv = local pos - inner corner\n\n localPos.xz *= -0.5; // move from -1;1 to -0.5;0.5\n localPos = localPos.xzy;\n #endif\n\n #ifdef MORPHING\n #ifdef MORPHING_POS03\n localPos.xyz += morph_weights_a[0] * morph_pos0;\n localPos.xyz += morph_weights_a[1] * morph_pos1;\n localPos.xyz += morph_weights_a[2] * morph_pos2;\n localPos.xyz += morph_weights_a[3] * morph_pos3;\n #endif // MORPHING_POS03\n #ifdef MORPHING_POS47\n localPos.xyz += morph_weights_b[0] * morph_pos4;\n localPos.xyz += morph_weights_b[1] * morph_pos5;\n localPos.xyz += morph_weights_b[2] * morph_pos6;\n localPos.xyz += morph_weights_b[3] * morph_pos7;\n #endif // MORPHING_POS47\n #endif // MORPHING\n\n #ifdef MORPHING_TEXTURE_BASED_POSITION\n\n #ifdef WEBGPU\n ivec2 morphUV = getTextureMorphCoords();\n vec3 morphPos = texelFetch(morphPositionTex, ivec2(morphUV), 0).xyz;\n #else\n vec2 morphUV = getTextureMorphCoords();\n vec3 morphPos = texture2D(morphPositionTex, morphUV).xyz;\n #endif\n\n localPos += morphPos;\n\n #endif\n\n vec4 posW = dModelMatrix * vec4(localPos, 1.0);\n #ifdef SCREENSPACE\n posW.zw = vec2(0.0, 1.0);\n #endif\n dPositionW = posW.xyz;\n\n vec4 screenPos;\n #ifdef UV1LAYOUT\n screenPos = vec4(vertex_texCoord1.xy * 2.0 - 1.0, 0.5, 1);\n #else\n #ifdef SCREENSPACE\n screenPos = posW;\n screenPos.y *= projectionFlipY;\n #else\n screenPos = matrix_viewProjection * posW;\n #endif\n\n #ifdef PIXELSNAP\n // snap vertex to a pixel boundary\n screenPos.xy = (screenPos.xy * 0.5) + 0.5;\n screenPos.xy *= uScreenSize.xy;\n screenPos.xy = floor(screenPos.xy);\n screenPos.xy *= uScreenSize.zw;\n screenPos.xy = (screenPos.xy * 2.0) - 1.0;\n #endif\n #endif\n\n return screenPos;\n}\n\nvec3 getWorldPosition() {\n return dPositionW;\n}\n",transformDeclVS:"\nattribute vec3 vertex_position;\n\nuniform mat4 matrix_model;\nuniform mat4 matrix_viewProjection;\n\nvec3 dPositionW;\nmat4 dModelMatrix;\n",transmissionPS:"\n\n#ifdef MAPFLOAT\nuniform float material_refraction;\n#endif\n\nvoid getRefraction() {\n float refraction = 1.0;\n\n #ifdef MAPFLOAT\n refraction = material_refraction;\n #endif\n\n #ifdef MAPTEXTURE\n refraction *= texture2DBias($SAMPLER, $UV, textureBias).$CH;\n #endif\n\n #ifdef MAPVERTEX\n refraction *= saturate(vVertexColor.$VC);\n #endif\n\n dTransmission = refraction;\n}\n",uv0VS:"\n#ifdef NINESLICED\nvec2 getUv0() {\n vec2 uv = vertex_position.xz;\n\n // offset inner vertices inside\n // (original vertices must be in [-1;1] range)\n vec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0));\n vec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0));\n uv += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;\n\n uv = uv * -0.5 + 0.5;\n uv = uv * atlasRect.zw + atlasRect.xy;\n\n vMask = vertex_texCoord0.xy;\n\n return uv;\n}\n#else\nvec2 getUv0() {\n return vertex_texCoord0;\n}\n#endif\n",uv1VS:"\nvec2 getUv1() {\n return vertex_texCoord1;\n}\n",viewDirPS:"\nvoid getViewDir() {\n dViewDirW = normalize(view_position - vPositionW);\n}\n",viewNormalVS:"\n#ifndef VIEWMATRIX\n#define VIEWMATRIX\nuniform mat4 matrix_view;\n#endif\n\nvec3 getViewNormal() {\n return mat3(matrix_view) * vNormalW;\n}\n",webgpuPS:ps,webgpuVS:ms},ba=new Jn;function wa(e){return ba.get(e)}function Ta(e,t){ba.get(e,(function(){return t}))}function Aa(e,t,i,n){return void 0===n&&(n=!1),new Nn(e,vs.createDefinition(e,{name:t+"_"+i,vertexCode:Sa[t],fragmentCode:Sa[i],useTransformFeedback:n}))}function Ca(e,t,i,n,s,r){void 0===r&&(r=!1);var a=wa(e),o=a.getCachedShader(n);return o||(o=new Nn(e,vs.createDefinition(e,{name:n,vertexCode:t,fragmentCode:i,attributes:s,useTransformFeedback:r})),a.setCachedShader(n,o)),o}function Ea(e,t){var i,n=e.definition,s=(null!=(i=n.name)?i:"shader")+"-id-"+e.id,r={generateKey:function(e){return s},createShaderDefinition:function(e,t){return n}},a="shader",o=wa(e.device);o.register(a,r);var h=o.getProgram(a,{},t);return o.unregister(a),h}Sa.createShader=Aa,Sa.createShaderFromCode=Ca;var Ma={type:5,base:0,count:4,indexed:!1},Pa=new ve,Ra=new ve,Ia=function(){function e(e){this.uniformBuffer=void 0,this.bindGroup=void 0;var t=e.device;if(this.shader=e,t.supportsUniformBuffers){var i=new va;this.shader=Ea(e,i);var n=this.shader.meshUniformBufferFormat;n&&(this.uniformBuffer=new Gn(t,n));var s=this.shader.meshBindGroupFormat;this.bindGroup=new zn(t,s,this.uniformBuffer)}}var t=e.prototype;return t.destroy=function(){var e,t;null==(e=this.uniformBuffer)||e.destroy(),this.uniformBuffer=null,null==(t=this.bindGroup)||t.destroy(),this.bindGroup=null},t.render=function(e,t){var i,n=this.shader.device;e&&(Pa.set(n.vx,n.vy,n.vw,n.vh),Ra.set(n.sx,n.sy,n.sw,n.sh),t=null!=(i=t)?i:e,n.setViewport(e.x,e.y,e.z,e.w),n.setScissor(t.x,t.y,t.z,t.w));n.setVertexBuffer(n.quadVertexBuffer,0);var s=this.shader;if(n.setShader(s),n.supportsUniformBuffers){var r=this.bindGroup;r.defaultUniformBuffer&&r.defaultUniformBuffer.update(),r.update(),n.setBindGroup(0,r)}n.draw(Ma),e&&(n.setViewport(Pa.x,Pa.y,Pa.z,Pa.w),n.setScissor(Ra.x,Ra.y,Ra.z,Ra.w))},e}(),La=new ve;function Da(e,t,i,n,s){e.setCullMode(0),e.setDepthState(xi.NODEPTH),e.setStencilState(null,null);var r=new Ia(i);n||((n=La).x=0,n.y=0,n.z=t?t.width:e.width,n.w=t?t.height:e.height);var a,o=new ga(e,(function(){r.render(n,s)}));(o.init(t),o.colorOps.clear=!1,o.depthStencilOps.clearDepth=!1,e.isWebGPU&&null===t)&&((null!=(a=null==t?void 0:t.samples)?a:e.samples)>1&&(o.colorOps.store=!0));o.render(),r.destroy()}var Oa=new Jn,ka=function(){function e(e,t,i){void 0===i&&(i={}),this.index=void 0,this.name=void 0,this.shaderDefine=void 0,this.name=e,this.index=t,Object.assign(this,i),this.initShaderDefines()}return e.prototype.initShaderDefines=function(){var e;this.isShadow?e="SHADOW":this.isForward?e="FORWARD":2===this.index?e="DEPTH":3===this.index&&(e="PICK");var t=e?"#define "+e+"_PASS\n":"",i="#define "+this.name.toUpperCase()+"_PASS\n";this.shaderDefines=t+i},e}(),Fa=function(){function e(){var e=this;this.passesNamed=new Map,this.passesIndexed=[],this.nextIndex=0;var t=function(t,i,n){e.allocate(t,n)};t("forward",0,{isForward:!0}),t("forward_hdr",0,{isForward:!0}),t("depth"),t("pick"),t("shadow")}e.get=function(t){return Oa.get(t,(function(){return new e}))};var t=e.prototype;return t.allocate=function(e,t){var i=this.passesNamed.get(e);return void 0===i&&(i=new ka(e,this.nextIndex,t),this.passesNamed.set(i.name,i),this.passesIndexed[i.index]=i,this.nextIndex++),i},t.getByIndex=function(e){return this.passesIndexed[e]},t.getByName=function(e){return this.passesNamed.get(e)},e}();function Ba(e,t){return t||(t=Sa),1===e||2===e?t.gamma2_2PS?t.gamma2_2PS:Sa.gamma2_2PS:3===e?"#define HDR\n"+(t.gamma2_2PS?t.gamma2_2PS:Sa.gamma2_2PS):t.gamma1_0PS?t.gamma1_0PS:Sa.gamma1_0PS}function Na(e,t){return t||(t=Sa),1===e?t.tonemappingFilmicPS?t.tonemappingFilmicPS:Sa.tonemappingFilmicPS:0===e?t.tonemappingLinearPS?t.tonemappingLinearPS:Sa.tonemappingLinearPS:2===e?t.tonemappingHejlPS?t.tonemappingHejlPS:Sa.tonemappingHejlPS:3===e?t.tonemappingAcesPS?t.tonemappingAcesPS:Sa.tonemappingAcesPS:4===e?t.tonemappingAces2PS?t.tonemappingAces2PS:Sa.tonemappingAces2PS:t.tonemapingNonePS?t.tonemapingNonePS:Sa.tonemappingNonePS}function Ua(e,t){return t||(t=Sa),"linear"===e?t.fogLinearPS?t.fogLinearPS:Sa.fogLinearPS:"exp"===e?t.fogExpPS?t.fogExpPS:Sa.fogExpPS:"exp2"===e?t.fogExp2PS?t.fogExp2PS:Sa.fogExp2PS:t.fogNonePS?t.fogNonePS:Sa.fogNonePS}function za(e,t){return t||(t=Sa),e.supportsBoneTextures?t.skinTexVS:"#define BONE_LIMIT "+e.getBoneLimit()+"\n"+t.skinConstVS}function Va(){return"void main(void)\n{\n"}function Ga(){return"}\n"}var Ha={generateKey:function(e){var t="basic";return e.fog&&(t+="_fog"),e.alphaTest&&(t+="_atst"),e.vertexColors&&(t+="_vcol"),e.diffuseMap&&(t+="_diff"),e.skin&&(t+="_skin"),e.screenSpace&&(t+="_ss"),e.useInstancing&&(t+="_inst"),e.useMorphPosition&&(t+="_morphp"),e.useMorphNormal&&(t+="_morphn"),e.useMorphTextureBased&&(t+="_morpht"),t+="_"+e.pass},createShaderDefinition:function(e,t){var i={vertex_position:lt};t.skin&&(i.vertex_boneWeights=dt,i.vertex_boneIndices=ft),t.vertexColors&&(i.vertex_color=pt),t.diffuseMap&&(i.vertex_texCoord0=_t);var n=Fa.get(e).getByIndex(t.pass).shaderDefines,s=n;s+=Sa.transformDeclVS,t.skin?(s+=za(e),s+=Sa.transformSkinnedVS):s+=Sa.transformVS,t.vertexColors&&(s+="attribute vec4 vertex_color;\n",s+="varying vec4 vColor;\n"),t.diffuseMap&&(s+="attribute vec2 vertex_texCoord0;\n",s+="varying vec2 vUv0;\n"),2===t.pass&&(s+="varying float vDepth;\n",s+="#ifndef VIEWMATRIX\n",s+="#define VIEWMATRIX\n",s+="uniform mat4 matrix_view;\n",s+="#endif\n",s+="#ifndef CAMERAPLANES\n",s+="#define CAMERAPLANES\n",s+="uniform vec4 camera_params;\n\n",s+="#endif\n"),s+="void main(void)\n{\n",s+=" gl_Position = getPosition();\n",2===t.pass&&(s+=" vDepth = -(matrix_view * vec4(getWorldPosition(),1.0)).z * camera_params.x;\n"),t.vertexColors&&(s+=" vColor = vertex_color;\n"),t.diffuseMap&&(s+=" vUv0 = vertex_texCoord0;\n"),s+="}\n";var r=n;return t.vertexColors?r+="varying vec4 vColor;\n":r+="uniform vec4 uColor;\n",t.diffuseMap&&(r+="varying vec2 vUv0;\n",r+="uniform sampler2D texture_diffuseMap;\n"),t.fog&&(r+=Ua(t.fog)),t.alphaTest&&(r+=Sa.alphaTestPS),2===t.pass&&(r+="varying float vDepth;\n",r+=Sa.packDepthPS),r+="void main(void)\n{\n",t.vertexColors?r+=" gl_FragColor = vColor;\n":r+=" gl_FragColor = uColor;\n",t.diffuseMap&&(r+=" gl_FragColor *= texture2D(texture_diffuseMap, vUv0);\n"),t.alphaTest&&(r+=" alphaTest(gl_FragColor.a);\n"),3!==t.pass&&(2===t.pass?r+=" gl_FragColor = packFloat(vDepth);\n":t.fog&&(r+=" glFragColor.rgb = addFog(gl_FragColor.rgb);\n")),r+="}\n",vs.createDefinition(e,{name:"BasicShader",attributes:i,vertexCode:s,fragmentCode:r})}},Wa=new Jn;function Xa(e){return Wa.get(e)}var ja=[];ja[0]={src:1,dst:1,op:2},ja[3]={src:1,dst:0,op:0},ja[2]={src:6,dst:8,op:0},ja[4]={src:1,dst:8,op:0},ja[1]={src:1,dst:1,op:0},ja[6]={src:6,dst:1,op:0},ja[7]={src:4,dst:2,op:0},ja[8]={src:5,dst:1,op:0},ja[5]={src:4,dst:0,op:0},ja[9]={src:1,dst:1,op:3},ja[10]={src:1,dst:1,op:4};var qa=0,Ya=function(){function e(){this._shader=null,this.meshInstances=[],this.name="Untitled",this.id=qa++,this.variants={},this.parameters={},this.alphaTest=0,this.alphaToCoverage=!1,this._blendState=new yi,this._depthState=new xi,this.cull=1,this.stencilFront=null,this.stencilBack=null,this.depthBias=0,this.slopeDepthBias=0,this._shaderVersion=0,this._scene=null,this._dirtyBlend=!1,this.dirty=!0}var t=e.prototype;return t._markBlendDirty=function(){this._scene?this._scene.layers._dirtyBlend=!0:this._dirtyBlend=!0},t.copy=function(e){var t;return this.name=e.name,this._shader=e._shader,this.alphaTest=e.alphaTest,this.alphaToCoverage=e.alphaToCoverage,this._blendState.copy(e._blendState),this._depthState.copy(e._depthState),this.cull=e.cull,this.depthBias=e.depthBias,this.slopeDepthBias=e.slopeDepthBias,this.stencilFront=null==(t=e.stencilFront)?void 0:t.clone(),e.stencilBack&&(this.stencilBack=e.stencilFront===e.stencilBack?this.stencilFront:e.stencilBack.clone()),this},t.clone=function(){var e=new this.constructor;return e.copy(this)},t._updateMeshInstanceKeys=function(){for(var e=this.meshInstances,t=0;t<e.length;t++)e[t].updateKey()},t.updateUniforms=function(e,t){},t.getShaderVariant=function(e,t,i,n,s,r,a,o,h){var l=new va(a,o,h);return Ea(this._shader,l)},t.update=function(){this.dirty=!0,this._shader&&(this._shader.failed=!1)},t.clearParameters=function(){this.parameters={}},t.getParameters=function(){return this.parameters},t.clearVariants=function(){this.variants={};for(var e=this.meshInstances,t=e.length,i=0;i<t;i++)e[i].clearShaders()},t.getParameter=function(e){return this.parameters[e]},t.setParameter=function(e,t){if(void 0===t&&"object"==typeof e){var i=e;if(i.length){for(var n=0;n<i.length;n++)this.setParameter(i[n]);return}e=i.name,t=i.value}var s=this.parameters[e];s?s.data=t:this.parameters[e]={scopeId:null,data:t}},t.deleteParameter=function(e){this.parameters[e]&&delete this.parameters[e]},t.setParameters=function(e,t){var i=this.parameters;for(var n in void 0===t&&(t=i),t){var s=i[n];s&&(s.scopeId||(s.scopeId=e.scope.resolve(n)),s.scopeId.setValue(s.data))}},t.destroy=function(){this.variants={},this._shader=null;for(var e=0;e<this.meshInstances.length;e++){var t=this.meshInstances[e];if(t.clearShaders(),t._material=null,t.mesh){var i=Xa(t.mesh.device);this!==i&&(t.material=i)}}this.meshInstances.length=0},t.addMeshInstanceRef=function(e){this.meshInstances.push(e)},t.removeMeshInstanceRef=function(e){var t=this.meshInstances,i=t.indexOf(e);-1!==i&&t.splice(i,1)},Z(e,[{key:"redWrite",get:function(){return this._blendState.redWrite},set:function(e){this._blendState.redWrite=e}},{key:"greenWrite",get:function(){return this._blendState.greenWrite},set:function(e){this._blendState.greenWrite=e}},{key:"blueWrite",get:function(){return this._blendState.blueWrite},set:function(e){this._blendState.blueWrite=e}},{key:"alphaWrite",get:function(){return this._blendState.alphaWrite},set:function(e){this._blendState.alphaWrite=e}},{key:"shader",get:function(){return this._shader},set:function(e){this._shader=e}},{key:"transparent",get:function(){return this._blendState.blend}},{key:"blendState",get:function(){return this._blendState},set:function(e){this._blendState.blend!==e.blend&&this._markBlendDirty(),this._blendState.copy(e)}},{key:"blendType",get:function(){if(!this.transparent)return 3;for(var e=this._blendState,t=e.colorOp,i=e.colorSrcFactor,n=e.colorDstFactor,s=e.alphaOp,r=e.alphaSrcFactor,a=e.alphaDstFactor,o=0;o<ja.length;o++){var h=ja[o];if(h.src===i&&h.dst===n&&h.op===t&&h.src===r&&h.dst===a&&h.op===s)return o}return 2},set:function(e){var t=ja[e];this._blendState.setColorBlend(t.op,t.src,t.dst),this._blendState.setAlphaBlend(t.op,t.src,t.dst);var i=3!==e;this._blendState.blend!==i&&(this._blendState.blend=i,this._markBlendDirty()),this._updateMeshInstanceKeys()}},{key:"depthState",get:function(){return this._depthState},set:function(e){this._depthState.copy(e)}},{key:"depthTest",get:function(){return this._depthState.test},set:function(e){this._depthState.test=e}},{key:"depthFunc",get:function(){return this._depthState.func},set:function(e){this._depthState.func=e}},{key:"depthWrite",get:function(){return this._depthState.write},set:function(e){this._depthState.write=e}}]),e}(),Ka=function(e){function t(){var t;return(t=e.call(this)||this).color=new ue(1,1,1,1),t.colorUniform=new Float32Array(4),t.colorMap=null,t.vertexColors=!1,t}Q(t,e);var i=t.prototype;return i.copy=function(t){return e.prototype.copy.call(this,t),this.color.copy(t.color),this.colorMap=t.colorMap,this.vertexColors=t.vertexColors,this},i.updateUniforms=function(e,t){this.clearParameters(),this.colorUniform[0]=this.color.r,this.colorUniform[1]=this.color.g,this.colorUniform[2]=this.color.b,this.colorUniform[3]=this.color.a,this.setParameter("uColor",this.colorUniform),this.colorMap&&this.setParameter("texture_diffuseMap",this.colorMap)},i.getShaderVariant=function(e,t,i,n,s,r,a,o,h){if(this.updateShader)return this.updateShader(e,t,i,n,s,r),this.shader;var l={skin:i&&0!=(2&i),screenSpace:i&&0!=(i&Hr),useInstancing:i&&0!=(32&i),useMorphPosition:i&&0!=(i&Wr),useMorphNormal:i&&0!=(i&Xr),useMorphTextureBased:i&&0!=(i&jr),alphaTest:this.alphaTest>0,vertexColors:this.vertexColors,diffuseMap:!!this.colorMap,pass:s},c=new va(a,o,h),u=wa(e);return u.register("basic",Ha),u.getProgram("basic",l,c)},t}(Ya),Za=function(){function e(e,t,i){this._aabb=new Ie,this.origMeshInstances=void 0,this.meshInstance=null,this.dynamic=void 0,this.batchGroupId=void 0,this.origMeshInstances=e,this.dynamic=t,this.batchGroupId=i}var t=e.prototype;return t.destroy=function(e,t){this.meshInstance&&(this.removeFromLayers(e,t),this.meshInstance.destroy(),this.meshInstance=null)},t.addToLayers=function(e,t){for(var i=0;i<t.length;i++){var n=e.layers.getLayerById(t[i]);n&&n.addMeshInstances([this.meshInstance])}},t.removeFromLayers=function(e,t){for(var i=0;i<t.length;i++){var n=e.layers.getLayerById(t[i]);n&&n.removeMeshInstances([this.meshInstance])}},t.updateBoundingBox=function(){this._aabb.copy(this.origMeshInstances[0].aabb);for(var e=1;e<this.origMeshInstances.length;e++)this._aabb.add(this.origMeshInstances[e].aabb);this.meshInstance.aabb=this._aabb,this.meshInstance._aabbVer=0},e}(),$a=function(e,t,i,n,s){void 0===s&&(s=[0]),this._ui=!1,this._sprite=!1,this._obj={model:[],element:[],sprite:[],render:[]},this.id=void 0,this.name=void 0,this.dynamic=void 0,this.maxAabbSize=void 0,this.layers=void 0,this.id=e,this.name=t,this.dynamic=i,this.maxAabbSize=n,this.layers=s};$a.MODEL="model",$a.ELEMENT="element",$a.SPRITE="sprite",$a.RENDER="render";var Qa=new Te,Ja=function(){function e(e){this.bones=void 0,this._dirty=!0,this._rootBone=null,this._skinUpdateIndex=-1,this._updateBeforeCull=!0,e&&this.initSkin(e)}var t=e.prototype;return t.init=function(e,t){if(e.supportsBoneTextures){var i=3*t,n=Math.ceil(Math.sqrt(i));n=ce.roundUp(n,3);var s=Math.ceil(i/n);this.boneTexture=new Yn(e,{width:n,height:s,format:Ze,mipmaps:!1,minFilter:0,magFilter:0,name:"skin"}),this.matrixPalette=this.boneTexture.lock()}else this.matrixPalette=new Float32Array(12*t)},t.destroy=function(){this.boneTexture&&(this.boneTexture.destroy(),this.boneTexture=null)},t.resolve=function(e,t){this.rootBone=e;for(var i=this.skin,n=[],s=0;s<i.boneNames.length;s++){var r=i.boneNames[s],a=e.findByName(r);a||(a=t),n.push(a)}this.bones=n},t.initSkin=function(e){this.skin=e,this.bones=[];var t=e.inverseBindPose.length;this.init(e.device,t),this.matrices=[];for(var i=0;i<t;i++)this.matrices[i]=new Te},t.uploadBones=function(e){e.supportsBoneTextures&&(this.boneTexture.lock(),this.boneTexture.unlock())},t._updateMatrices=function(e,t){if(this._skinUpdateIndex!==t){this._skinUpdateIndex=t,Qa.copy(e.getWorldTransform()).invert();for(var i=this.bones.length-1;i>=0;i--)this.matrices[i].mulAffine2(Qa,this.bones[i].getWorldTransform()),this.matrices[i].mulAffine2(this.matrices[i],this.skin.inverseBindPose[i])}},t.updateMatrices=function(e,t){this._updateBeforeCull&&this._updateMatrices(e,t)},t.updateMatrixPalette=function(e,t){this._updateMatrices(e,t);for(var i=this.matrixPalette,n=this.bones.length,s=0;s<n;s++){var r=this.matrices[s].data,a=12*s;i[a]=r[0],i[a+1]=r[4],i[a+2]=r[8],i[a+3]=r[12],i[a+4]=r[1],i[a+5]=r[5],i[a+6]=r[9],i[a+7]=r[13],i[a+8]=r[2],i[a+9]=r[6],i[a+10]=r[10],i[a+11]=r[14]}this.uploadBones(this.skin.device)},Z(e,[{key:"rootBone",get:function(){return this._rootBone},set:function(e){this._rootBone=e}}]),e}(),eo=function(e){function t(t,i,n){var s;s=e.call(this)||this;var r=i.length;return s.init(t,r),s.device=t,s.rootNode=n,s.bones=i,s}Q(t,e);var i=t.prototype;return i.updateMatrices=function(e,t){},i.updateMatrixPalette=function(e,t){for(var i=this.matrixPalette,n=this.bones.length,s=0;s<n;s++){var r=this.bones[s].getWorldTransform().data,a=12*s;i[a]=r[0],i[a+1]=r[4],i[a+2]=r[8],i[a+3]=r[12],i[a+4]=r[1],i[a+5]=r[5],i[a+6]=r[9],i[a+7]=r[13],i[a+8]=r[2],i[a+9]=r[6],i[a+10]=r[10],i[a+11]=r[14]}this.uploadBones(this.device)},t}(Ja),to=new Te,io=new me,no=new Ae,so=new Ae,ro=new me,ao=new me,oo=new Te,ho=new Ae,lo=new me,co=new Te,uo=new Ae,fo=new Ae,po=new Te,mo=new me,_o=new me,go=function(e){function t(t){var i;return void 0===t&&(t="Untitled"),(i=e.call(this)||this).name=void 0,i.tags=new ae(ee(i)),i._labels={},i.localPosition=new me,i.localRotation=new Ae,i.localScale=new me(1,1,1),i.localEulerAngles=new me,i.position=new me,i.rotation=new Ae,i.eulerAngles=new me,i._scale=null,i.localTransform=new Te,i._dirtyLocal=!1,i._aabbVer=0,i._frozen=!1,i.worldTransform=new Te,i._dirtyWorld=!1,i._worldScaleSign=0,i._normalMatrix=new _e,i._dirtyNormal=!0,i._right=null,i._up=null,i._forward=null,i._parent=null,i._children=[],i._graphDepth=0,i._enabled=!0,i._enabledInHierarchy=!1,i.scaleCompensation=!1,i.name=t,i}Q(t,e);var i=t.prototype;return i._notifyHierarchyStateChanged=function(e,t){e._onHierarchyStateChanged(t);for(var i=e._children,n=0,s=i.length;n<s;n++)i[n]._enabled&&this._notifyHierarchyStateChanged(i[n],t)},i._onHierarchyStateChanged=function(e){this._enabledInHierarchy=e,e&&!this._frozen&&this._unfreezeParentToRoot()},i._cloneInternal=function(e){e.name=this.name;var t=this.tags._list;e.tags.clear();for(var i=0;i<t.length;i++)e.tags.add(t[i]);e._labels=Object.assign({},this._labels),e.localPosition.copy(this.localPosition),e.localRotation.copy(this.localRotation),e.localScale.copy(this.localScale),e.localEulerAngles.copy(this.localEulerAngles),e.position.copy(this.position),e.rotation.copy(this.rotation),e.eulerAngles.copy(this.eulerAngles),e.localTransform.copy(this.localTransform),e._dirtyLocal=this._dirtyLocal,e.worldTransform.copy(this.worldTransform),e._dirtyWorld=this._dirtyWorld,e._dirtyNormal=this._dirtyNormal,e._aabbVer=this._aabbVer+1,e._enabled=this._enabled,e.scaleCompensation=this.scaleCompensation,e._enabledInHierarchy=!1},i.clone=function(){var e=new this.constructor;return this._cloneInternal(e),e},i.copy=function(e){return e._cloneInternal(this),this},i.find=function(e,t){var i=[],n=this._children.length;if(e instanceof Function){var s=e;s(this)&&i.push(this);for(var r=0;r<n;r++){var a=this._children[r].find(s);a.length&&(i=i.concat(a))}}else{this[e]&&(this[e]instanceof Function?this[e]():this[e])===t&&i.push(this);for(var o=0;o<n;++o){var h=this._children[o].find(e,t);h.length&&(i=i.concat(h))}}return i},i.findOne=function(e,t){var i=this._children.length,n=null;if(e instanceof Function){var s=e;if(n=s(this))return this;for(var r=0;r<i;r++)if(n=this._children[r].findOne(s))return n}else{if(this[e]&&(this[e]instanceof Function?this[e]():this[e])===t)return this;for(var a=0;a<i;a++)if(null!==(n=this._children[a].findOne(e,t)))return n}return null},i.findByTag=function(){var e=arguments,t=[],i=function i(n,s){var r;s&&(r=n.tags).has.apply(r,e)&&t.push(n);for(var a=0;a<n._children.length;a++)i(n._children[a],!0)};return i(this,!1),t},i.findByName=function(e){if(this.name===e)return this;for(var t=0;t<this._children.length;t++){var i=this._children[t].findByName(e);if(null!==i)return i}return null},i.findByPath=function(e){for(var t=Array.isArray(e)?e:e.split("/"),i=this,n=function(e){if(i=i.children.find((function(i){return i.name===t[e]})),!i)return{v:null}},s=0,r=t.length;s<r;++s){var a=n(s);if("object"==typeof a)return a.v}return i},i.forEach=function(e,t){e.call(t,this);for(var i=this._children,n=0;n<i.length;n++)i[n].forEach(e,t)},i.isDescendantOf=function(e){for(var t=this._parent;t;){if(t===e)return!0;t=t._parent}return!1},i.isAncestorOf=function(e){return e.isDescendantOf(this)},i.getEulerAngles=function(){return this.getWorldTransform().getEulerAngles(this.eulerAngles),this.eulerAngles},i.getLocalEulerAngles=function(){return this.localRotation.getEulerAngles(this.localEulerAngles),this.localEulerAngles},i.getLocalPosition=function(){return this.localPosition},i.getLocalRotation=function(){return this.localRotation},i.getLocalScale=function(){return this.localScale},i.getLocalTransform=function(){return this._dirtyLocal&&(this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale),this._dirtyLocal=!1),this.localTransform},i.getPosition=function(){return this.getWorldTransform().getTranslation(this.position),this.position},i.getRotation=function(){return this.rotation.setFromMat4(this.getWorldTransform()),this.rotation},i.getScale=function(){return this._scale||(this._scale=new me),this.getWorldTransform().getScale(this._scale)},i.getWorldTransform=function(){return this._dirtyLocal||this._dirtyWorld?(this._parent&&this._parent.getWorldTransform(),this._sync(),this.worldTransform):this.worldTransform},i.reparent=function(e,t){var i=this._parent;i&&i.removeChild(this),e&&(t>=0?e.insertChild(this,t):e.addChild(this))},i.setLocalEulerAngles=function(e,t,i){this.localRotation.setFromEulerAngles(e,t,i),this._dirtyLocal||this._dirtifyLocal()},i.setLocalPosition=function(e,t,i){e instanceof me?this.localPosition.copy(e):this.localPosition.set(e,t,i),this._dirtyLocal||this._dirtifyLocal()},i.setLocalRotation=function(e,t,i,n){e instanceof Ae?this.localRotation.copy(e):this.localRotation.set(e,t,i,n),this._dirtyLocal||this._dirtifyLocal()},i.setLocalScale=function(e,t,i){e instanceof me?this.localScale.copy(e):this.localScale.set(e,t,i),this._dirtyLocal||this._dirtifyLocal()},i._dirtifyLocal=function(){this._dirtyLocal||(this._dirtyLocal=!0,this._dirtyWorld||this._dirtifyWorld())},i._unfreezeParentToRoot=function(){for(var e=this._parent;e;)e._frozen=!1,e=e._parent},i._dirtifyWorld=function(){this._dirtyWorld||this._unfreezeParentToRoot(),this._dirtifyWorldInternal()},i._dirtifyWorldInternal=function(){if(!this._dirtyWorld){this._frozen=!1,this._dirtyWorld=!0;for(var e=0;e<this._children.length;e++)this._children[e]._dirtyWorld||this._children[e]._dirtifyWorldInternal()}this._dirtyNormal=!0,this._worldScaleSign=0,this._aabbVer++},i.setPosition=function(e,t,i){e instanceof me?lo.copy(e):lo.set(e,t,i),null===this._parent?this.localPosition.copy(lo):(co.copy(this._parent.getWorldTransform()).invert(),co.transformPoint(lo,this.localPosition)),this._dirtyLocal||this._dirtifyLocal()},i.setRotation=function(e,t,i,n){if(e instanceof Ae?uo.copy(e):uo.set(e,t,i,n),null===this._parent)this.localRotation.copy(uo);else{var s=this._parent.getRotation();fo.copy(s).invert(),this.localRotation.copy(fo).mul(uo)}this._dirtyLocal||this._dirtifyLocal()},i.setEulerAngles=function(e,t,i){if(this.localRotation.setFromEulerAngles(e,t,i),null!==this._parent){var n=this._parent.getRotation();fo.copy(n).invert(),this.localRotation.mul2(fo,this.localRotation)}this._dirtyLocal||this._dirtifyLocal()},i.addChild=function(e){this._prepareInsertChild(e),this._children.push(e),this._onInsertChild(e)},i.addChildAndSaveTransform=function(e){var t=e.getPosition(),i=e.getRotation();this._prepareInsertChild(e),e.setPosition(oo.copy(this.worldTransform).invert().transformPoint(t)),e.setRotation(ho.copy(this.getRotation()).invert().mul(i)),this._children.push(e),this._onInsertChild(e)},i.insertChild=function(e,t){this._prepareInsertChild(e),this._children.splice(t,0,e),this._onInsertChild(e)},i._prepareInsertChild=function(e){e._parent&&e._parent.removeChild(e)},i._fireOnHierarchy=function(e,t,i){this.fire(e,i);for(var n=0;n<this._children.length;n++)this._children[n]._fireOnHierarchy(t,t,i)},i._onInsertChild=function(e){e._parent=this;var t=e._enabled&&this.enabled;e._enabledInHierarchy!==t&&(e._enabledInHierarchy=t,e._notifyHierarchyStateChanged(e,t)),e._updateGraphDepth(),e._dirtifyWorld(),this._frozen&&e._unfreezeParentToRoot(),e._fireOnHierarchy("insert","inserthierarchy",this),this.fire&&this.fire("childinsert",e)},i._updateGraphDepth=function(){this._graphDepth=this._parent?this._parent._graphDepth+1:0;for(var e=0,t=this._children.length;e<t;e++)this._children[e]._updateGraphDepth()},i.removeChild=function(e){var t=this._children.indexOf(e);-1!==t&&(this._children.splice(t,1),e._parent=null,e._fireOnHierarchy("remove","removehierarchy",this),this.fire("childremove",e))},i._sync=function(){if(this._dirtyLocal&&(this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale),this._dirtyLocal=!1),this._dirtyWorld){if(null===this._parent)this.worldTransform.copy(this.localTransform);else if(this.scaleCompensation){var e,t=this._parent,i=this.localScale,n=t;if(n){for(;n&&n.scaleCompensation;)n=n._parent;n&&(n=n._parent)&&(e=n.worldTransform.getScale(),ro.mul2(e,this.localScale),i=ro)}so.setFromMat4(t.worldTransform),no.mul2(so,this.localRotation);var s=t.worldTransform;t.scaleCompensation&&(ao.mul2(e,t.getLocalScale()),to.setTRS(t.worldTransform.getTranslation(io),so,ao),s=to),s.transformPoint(this.localPosition,io),this.worldTransform.setTRS(io,no,i)}else this.worldTransform.mulAffine2(this._parent.worldTransform,this.localTransform);this._dirtyWorld=!1}},i.syncHierarchy=function(){if(this._enabled&&!this._frozen){this._frozen=!0,(this._dirtyLocal||this._dirtyWorld)&&this._sync();for(var e=this._children,t=0,i=e.length;t<i;t++)e[t].syncHierarchy()}},i.lookAt=function(e,t,i,n,s,r){if(void 0===n&&(n=0),void 0===s&&(s=1),void 0===r&&(r=0),e instanceof me)mo.copy(e),t instanceof me?_o.copy(t):_o.copy(me.UP);else{if(void 0===i)return;mo.set(e,t,i),_o.set(n,s,r)}po.setLookAt(this.getPosition(),mo,_o),uo.setFromMat4(po),this.setRotation(uo)},i.translate=function(e,t,i){e instanceof me?lo.copy(e):lo.set(e,t,i),lo.add(this.getPosition()),this.setPosition(lo)},i.translateLocal=function(e,t,i){e instanceof me?lo.copy(e):lo.set(e,t,i),this.localRotation.transformVector(lo,lo),this.localPosition.add(lo),this._dirtyLocal||this._dirtifyLocal()},i.rotate=function(e,t,i){if(uo.setFromEulerAngles(e,t,i),null===this._parent)this.localRotation.mul2(uo,this.localRotation);else{var n=this.getRotation(),s=this._parent.getRotation();fo.copy(s).invert(),uo.mul2(fo,uo),this.localRotation.mul2(uo,n)}this._dirtyLocal||this._dirtifyLocal()},i.rotateLocal=function(e,t,i){uo.setFromEulerAngles(e,t,i),this.localRotation.mul(uo),this._dirtyLocal||this._dirtifyLocal()},Z(t,[{key:"right",get:function(){return this._right||(this._right=new me),this.getWorldTransform().getX(this._right).normalize()}},{key:"up",get:function(){return this._up||(this._up=new me),this.getWorldTransform().getY(this._up).normalize()}},{key:"forward",get:function(){return this._forward||(this._forward=new me),this.getWorldTransform().getZ(this._forward).normalize().mulScalar(-1)}},{key:"normalMatrix",get:function(){var e=this._normalMatrix;return this._dirtyNormal&&(this.getWorldTransform().invertTo3x3(e),e.transpose(),this._dirtyNormal=!1),e}},{key:"enabled",get:function(){return this._enabled&&this._enabledInHierarchy},set:function(e){var t;this._enabled!==e&&(this._enabled=e,(e&&null!=(t=this._parent)&&t.enabled||!e)&&this._notifyHierarchyStateChanged(this,e))}},{key:"parent",get:function(){return this._parent}},{key:"path",get:function(){var e=this._parent;if(!e)return"";for(var t=this.name;e&&e._parent;)t=e.name+"/"+t,e=e._parent;return t}},{key:"root",get:function(){for(var e=this;e._parent;)e=e._parent;return e}},{key:"children",get:function(){return this._children}},{key:"graphDepth",get:function(){return this._graphDepth}},{key:"worldScaleSign",get:function(){return 0===this._worldScaleSign&&(this._worldScaleSign=this.getWorldTransform().scaleSign),this._worldScaleSign}}]),t}(p),vo=function(){function e(){this.cache=new Map}var t=e.prototype;return t.destroy=function(){this.cache.forEach((function(e,t){t.destroy()})),this.cache.clear()},t.incRef=function(e){var t=(this.cache.get(e)||0)+1;this.cache.set(e,t)},t.decRef=function(e){if(e){var t=this.cache.get(e);t&&(0===--t?(this.cache.delete(e),e.destroy()):this.cache.set(e,t))}},e}(),yo=function(){function e(){}return e.incRef=function(e){this.cache.incRef(e)},e.decRef=function(e){this.cache.decRef(e)},e.destroy=function(){this.cache.destroy()},e}();yo.cache=new vo;var xo=new Ie,So=new Ie,bo=new Oe,wo=new Set,To=function(e){this.vertexBuffer=null,this.count=e},Ao=function(){function e(e,t,i){this._key=[],this._key[0]=Eo(e,t,!0,0),this.command=i}return Z(e,[{key:"key",get:function(){return this._key[0]},set:function(e){this._key[0]=e}}]),e}(),Co=function(){function e(e,t,i){if(void 0===i&&(i=null),this.visible=!0,this.castShadow=!1,this._material=void 0,this._shader=[],this._bindGroups=[],e instanceof go){var n=e;e=t,t=i,i=n}this._key=[0,0],this.isStatic=!1,this._staticLightList=null,this._staticSource=null,this.node=i,this._mesh=e,e.incRefCount(),this.material=t,this._shaderDefs=65536,this._shaderDefs|=e.vertexBuffer.format.hasUv0?4:0,this._shaderDefs|=e.vertexBuffer.format.hasUv1?8:0,this._shaderDefs|=e.vertexBuffer.format.hasColor?16:0,this._shaderDefs|=e.vertexBuffer.format.hasTangents?512:0,this._lightHash=0,this.layer=15,this._renderStyle=0,this._receiveShadow=!0,this._screenSpace=!1,this._noDepthDrawGl1=!1,this.cull=!0,this.pick=!0,this._updateAabb=!0,this._updateAabbFunc=null,this._calculateSortDistance=null,this.updateKey(),this._skinInstance=null,this._morphInstance=null,this.instancingData=null,this._customAabb=null,this.aabb=new Ie,this._aabbVer=-1,this.drawOrder=0,this.visibleThisFrame=!1,this.isVisibleFunc=null,this.parameters={},this.stencilFront=null,this.stencilBack=null,this.flipFacesFactor=1}var t=e.prototype;return t.clearShaders=function(){for(var e=this._shader,t=0;t<e.length;t++)e[t]=null;this.destroyBindGroups()},t.destroyBindGroups=function(){for(var e=this._bindGroups,t=0;t<e.length;t++){var i=e[t];if(i){var n=i.defaultUniformBuffer;n&&n.destroy(),i.destroy()}}e.length=0},t.getBindGroup=function(e,t){var i=this._bindGroups[t];if(!i){var n=this._shader[t],s=n.meshUniformBufferFormat,r=new Gn(e,s),a=n.meshBindGroupFormat;i=new zn(e,a,r),this._bindGroups[t]=i}return i},t.destroy=function(){var t,i,n=this.mesh;n&&(this.mesh=null,n.refCount<1&&n.destroy()),this.setRealtimeLightmap(e.lightmapParamNames[0],null),this.setRealtimeLightmap(e.lightmapParamNames[1],null),null==(t=this._skinInstance)||t.destroy(),this._skinInstance=null,null==(i=this.morphInstance)||i.destroy(),this.morphInstance=null,this.clearShaders(),this.material=null},e._prepareRenderStyleForArray=function(e,t){if(e){for(var i=0;i<e.length;i++){e[i]._renderStyle=t;var n=e[i].mesh;wo.has(n)||(wo.add(n),n.prepareRenderState(t))}wo.clear()}},t._isVisible=function(e){return!!this.visible&&(this.isVisibleFunc?this.isVisibleFunc(e):(bo.center=this.aabb.center,bo.radius=this._aabb.halfExtents.length(),e.frustum.containsSphere(bo)))},t.updateKey=function(){var e=this.material;this._key[0]=Eo(this.layer,e.alphaToCoverage||e.alphaTest?2:e.blendType,!1,e.id)},t.setInstancing=function(e){e?(this.instancingData=new To(e.numVertices),this.instancingData.vertexBuffer=e,e.format.instancing=!0,this.cull=!1):(this.instancingData=null,this.cull=!0)},t.updatePassShader=function(e,t,i,n,s,r){this._shader[t]=this.material.getShaderVariant(this.mesh.device,e,this._shaderDefs,i,t,n,s,r,this._mesh.vertexBuffer.format)},t.ensureMaterial=function(e){this.material||(this.material=Xa(e))},t.clearParameters=function(){this.parameters={}},t.getParameters=function(){return this.parameters},t.getParameter=function(e){return this.parameters[e]},t.setParameter=function(e,t,i){if(void 0===i&&(i=-262141),void 0===t&&"object"==typeof e){var n=e;if(n.length){for(var s=0;s<n.length;s++)this.setParameter(n[s]);return}e=n.name,t=n.value}var r=this.parameters[e];r?(r.data=t,r.passFlags=i):this.parameters[e]={scopeId:null,data:t,passFlags:i}},t.setRealtimeLightmap=function(e,t){var i=this.getParameter(e);i!==t&&(i&&yo.decRef(i.data),t?(yo.incRef(t),this.setParameter(e,t)):this.deleteParameter(e))},t.deleteParameter=function(e){this.parameters[e]&&delete this.parameters[e]},t.setParameters=function(e,t){var i=this.parameters;for(var n in i){var s=i[n];s.passFlags&t&&(s.scopeId||(s.scopeId=e.scope.resolve(n)),s.scopeId.setValue(s.data))}},t.setLightmapped=function(t){t?this.mask=-6&(2|this.mask):(this.setRealtimeLightmap(e.lightmapParamNames[0],null),this.setRealtimeLightmap(e.lightmapParamNames[1],null),this._shaderDefs&=-8385,this.mask=-7&(1|this.mask))},t.setCustomAabb=function(e){e?this._customAabb?this._customAabb.copy(e):this._customAabb=e.clone():(this._customAabb=null,this._aabbVer=-1),this._setupSkinUpdate()},t._setupSkinUpdate=function(){this._skinInstance&&(this._skinInstance._updateBeforeCull=!this._customAabb)},Z(e,[{key:"renderStyle",get:function(){return this._renderStyle},set:function(e){this._renderStyle=e,this.mesh.prepareRenderState(e)}},{key:"mesh",get:function(){return this._mesh},set:function(e){e!==this._mesh&&(this._mesh&&this._mesh.decRefCount(),this._mesh=e,e&&e.incRefCount())}},{key:"aabb",get:function(){if(!this._updateAabb)return this._aabb;if(this._updateAabbFunc)return this._updateAabbFunc(this._aabb);var e=this._customAabb,t=!!e;if(!e)if(e=xo,this.skinInstance){if(!this.mesh.boneAabb){var i=this._morphInstance?this._morphInstance.morph._targets:null;this.mesh._initBoneAabbs(i)}for(var n=this.mesh.boneUsed,s=!0,r=0;r<this.mesh.boneAabb.length;r++)n[r]&&(So.setFromTransformedAabb(this.mesh.boneAabb[r],this.skinInstance.matrices[r]),s?(s=!1,e.center.copy(So.center),e.halfExtents.copy(So.halfExtents)):e.add(So));t=!0}else if(this.node._aabbVer!==this._aabbVer){if(this.mesh?(e.center.copy(this.mesh.aabb.center),e.halfExtents.copy(this.mesh.aabb.halfExtents)):(e.center.set(0,0,0),e.halfExtents.set(0,0,0)),this.mesh&&this.mesh.morph){var a=this.mesh.morph.aabb;e._expand(a.getMin(),a.getMax())}t=!0,this._aabbVer=this.node._aabbVer}return t&&this._aabb.setFromTransformedAabb(e,this.node.getWorldTransform()),this._aabb},set:function(e){this._aabb=e}},{key:"material",get:function(){return this._material},set:function(e){this.clearShaders();var t=this._material;if(t&&t.removeMeshInstanceRef(this),this._material=e,e){e.addMeshInstanceRef(this),this.updateKey();var i=t&&t.transparent;if(e.transparent!==i){var n=this._material._scene||(null==t?void 0:t._scene);n?n.layers._dirtyBlend=!0:e._dirtyBlend=!0}}}},{key:"layer",get:function(){return this._layer},set:function(e){this._layer=e,this.updateKey()}},{key:"calculateSortDistance",get:function(){return this._calculateSortDistance},set:function(e){this._calculateSortDistance=e}},{key:"receiveShadow",get:function(){return this._receiveShadow},set:function(e){this._receiveShadow=e,this._shaderDefs=e?-2&this._shaderDefs:1|this._shaderDefs,this._shader[0]=null,this._shader[1]=null}},{key:"skinInstance",get:function(){return this._skinInstance},set:function(e){this._skinInstance=e;var t=this._shaderDefs;(t=e?2|t:-3&t)!==this._shaderDefs&&(this._shaderDefs=t,this.clearShaders()),this._setupSkinUpdate()}},{key:"morphInstance",get:function(){return this._morphInstance},set:function(e){var t;null==(t=this._morphInstance)||t.destroy(),this._morphInstance=e;var i=this._shaderDefs;i=e&&e.morph.useTextureMorph?i|jr:-4097&i,i=e&&e.morph.morphPositions?i|Wr:-1025&i,(i=e&&e.morph.morphNormals?i|Xr:-2049&i)!==this._shaderDefs&&(this._shaderDefs=i,this.clearShaders())}},{key:"screenSpace",get:function(){return this._screenSpace},set:function(e){this._screenSpace=e,this._shaderDefs=e?this._shaderDefs|Hr:-257&this._shaderDefs,this._shader[0]=null}},{key:"key",get:function(){return this._key[0]},set:function(e){this._key[0]=e}},{key:"mask",get:function(){return this._shaderDefs>>16},set:function(e){var t=65535&this._shaderDefs;this._shaderDefs=t|e<<16,this._shader[0]=null,this._shader[1]=null}},{key:"instancingCount",get:function(){return this.instancingData?this.instancingData.count:0},set:function(e){this.instancingData&&(this.instancingData.count=e)}}]),e}();function Eo(e,t,i,n){return(15&e)<<27|(3===t?1:0)<<26|(i?1:0)<<25|(33554431&n)<<0}function Mo(e,t){if(e&&!t)return!1;if(!e&&t)return!1;if((e=e.data)===(t=t.data))return!0;if(e instanceof Float32Array&&t instanceof Float32Array){if(e.length!==t.length)return!1;for(var i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}return!1}function Po(e,t){for(var i in e)if(e.hasOwnProperty(i)&&!Mo(e[i],t[i]))return!1;for(var n in t)if(t.hasOwnProperty(n)&&!Mo(t[n],e[n]))return!1;return!0}function Ro(e,t){for(var i=0;i<e.length;i++)if(t.indexOf(e[i])<0)return!1;for(var n=0;n<t.length;n++)if(e.indexOf(t[n])<0)return!1;return!0}Co.lightmapParamNames=["texture_lightMap","texture_dirLightMap"];var Io=[0,1,3,2,3,1],Lo=[0,1,3,0,3,2],Do=new _e;function Oo(e){return e.node.worldTransform.scaleSign}var ko=function(){function e(e,t,i){this.device=e,this.rootNode=t,this.scene=i,this._init=!1,this._batchGroups={},this._batchGroupCounter=0,this._batchList=[],this._dirtyGroups=[]}var t=e.prototype;return t.destroy=function(){this.device=null,this.rootNode=null,this.scene=null,this._batchGroups={},this._batchList=[],this._dirtyGroups=[]},t.addGroup=function(e,t,i,n,s){if(void 0===n&&(n=this._batchGroupCounter,this._batchGroupCounter++),!this._batchGroups[n]){var r=new $a(n,e,t,i,s);return this._batchGroups[n]=r,r}},t.removeGroup=function(e){if(this._batchGroups[e]){for(var t=[],i=0;i<this._batchList.length;i++)this._batchList[i].batchGroupId===e?this.destroyBatch(this._batchList[i]):t.push(this._batchList[i]);this._batchList=t,this._removeModelsFromBatchGroup(this.rootNode,e),delete this._batchGroups[e]}},t.markGroupDirty=function(e){this._dirtyGroups.indexOf(e)<0&&this._dirtyGroups.push(e)},t.getGroupByName=function(e){var t=this._batchGroups;for(var i in t)if(t.hasOwnProperty(i)&&t[i].name===e)return t[i];return null},t.getBatches=function(e){for(var t=[],i=this._batchList.length,n=0;n<i;n++){var s=this._batchList[n];s.batchGroupId===e&&t.push(s)}return t},t._removeModelsFromBatchGroup=function(e,t){if(e.enabled){e.model&&e.model.batchGroupId===t&&(e.model.batchGroupId=-1),e.render&&e.render.batchGroupId===t&&(e.render.batchGroupId=-1),e.element&&e.element.batchGroupId===t&&(e.element.batchGroupId=-1),e.sprite&&e.sprite.batchGroupId===t&&(e.sprite.batchGroupId=-1);for(var i=0;i<e._children.length;i++)this._removeModelsFromBatchGroup(e._children[i],t)}},t.insert=function(e,t,i){var n=this._batchGroups[t];n&&n._obj[e].indexOf(i)<0&&(n._obj[e].push(i),this.markGroupDirty(t))},t.remove=function(e,t,i){var n=this._batchGroups[t];if(n){var s=n._obj[e].indexOf(i);s>=0&&(n._obj[e].splice(s,1),this.markGroupDirty(t))}},t._extractRender=function(e,t,i,n){if(e.render){if(e.render.isStatic){for(var s=this.scene.drawCalls,r=e.render.meshInstances,a=0;a<s.length;a++)s[a]._staticSource&&(r.indexOf(s[a]._staticSource)<0||t.push(s[a]));for(var o=0;o<r.length;o++)s.indexOf(r[o])>=0&&t.push(r[o])}else t=n[e.render.batchGroupId]=t.concat(e.render.meshInstances);e.render.removeFromLayers()}return t},t._extractModel=function(e,t,i,n){if(e.model&&e.model.model){if(e.model.isStatic){for(var s=this.scene.drawCalls,r=e.model.meshInstances,a=0;a<s.length;a++)s[a]._staticSource&&(r.indexOf(s[a]._staticSource)<0||t.push(s[a]));for(var o=0;o<r.length;o++)s.indexOf(r[o])>=0&&t.push(r[o])}else t=n[e.model.batchGroupId]=t.concat(e.model.meshInstances);e.model.removeModelFromLayers()}return t},t._extractElement=function(e,t,i){if(e.element){var n=!1;e.element._text&&e.element._text._model.meshInstances.length>0?(t.push(e.element._text._model.meshInstances[0]),e.element.removeModelFromLayers(e.element._text._model),n=!0):e.element._image&&(t.push(e.element._image._renderable.meshInstance),e.element.removeModelFromLayers(e.element._image._renderable.model),e.element._image._renderable.unmaskMeshInstance&&(t.push(e.element._image._renderable.unmaskMeshInstance),e.element._image._renderable.unmaskMeshInstance.stencilFront&&e.element._image._renderable.unmaskMeshInstance.stencilBack||(e.element._dirtifyMask(),e.element._onPrerender())),n=!0),n&&(i._ui=!0)}},t._collectAndRemoveMeshInstances=function(e,t){for(var i=0;i<t.length;i++){var n=t[i],s=this._batchGroups[n];if(s){var r=e[n];r||(r=e[n]=[]);for(var a=0;a<s._obj.model.length;a++)r=this._extractModel(s._obj.model[a],r,s,e);for(var o=0;o<s._obj.render.length;o++)r=this._extractRender(s._obj.render[o],r,s,e);for(var h=0;h<s._obj.element.length;h++)this._extractElement(s._obj.element[h],r,s);for(var l=0;l<s._obj.sprite.length;l++){var c=s._obj.sprite[l];c.sprite&&c.sprite._meshInstance&&(s.dynamic||0===c.sprite.sprite._renderMode)&&(r.push(c.sprite._meshInstance),c.sprite.removeModelFromLayers(),s._sprite=!0,c.sprite._batchGroup=s)}}}},t.generate=function(e){var t={};e||(e=Object.keys(this._batchGroups));for(var i,n,s,r,a=[],o=0;o<this._batchList.length;o++)e.indexOf(this._batchList[o].batchGroupId)<0?a.push(this._batchList[o]):this.destroyBatch(this._batchList[o]);if(this._batchList=a,this._collectAndRemoveMeshInstances(t,e),e===this._dirtyGroups)this._dirtyGroups.length=0;else{for(var h=[],l=0;l<this._dirtyGroups.length;l++)e.indexOf(this._dirtyGroups[l])<0&&h.push(this._dirtyGroups[l]);this._dirtyGroups=h}for(var c in t)if(t.hasOwnProperty(c)&&(i=t[c],s=this._batchGroups[c])){n=this.prepare(i,s.dynamic,s.maxAabbSize,s._ui||s._sprite);for(var u=0;u<n.length;u++)(r=this.create(n[u],s.dynamic,parseInt(c,10)))&&r.addToLayers(this.scene,s.layers)}},t.prepare=function(e,t,i,n){if(void 0===i&&(i=Number.POSITIVE_INFINITY),0===e.length)return[];var s,r=.5*i,a=this.device.supportsBoneTextures?1024:this.device.boneLimit,o=this.device.extUintElement?4294967295:65535,h=new Ie,l=new Ie,c=null,u=[],d=0;n&&e.sort((function(e,t){return e.drawOrder-t.drawOrder}));for(var f,p=e,m=n?function(e){c?c.add(e.aabb):c=e.aabb.clone(),f.push(e)}:function(e){f.push(e)};p.length>0;){u[d]=[p[0]],f=[];var _=p[0].material,g=p[0].layer,v=p[0]._shaderDefs,y=p[0].parameters,x=p[0].stencilFront,S=p[0]._staticLightList,b=p[0].mesh.vertexBuffer.getNumVertices(),w=p[0].drawOrder;h.copy(p[0].aabb);var T=Oo(p[0]),A=p[0].mesh.vertexBuffer.format.batchingHash,C=p[0].mesh.primitive[0].indexed;c=null;for(var E=1;E<p.length;E++){var M=p[E];if(t&&u[d].length>=a){f=f.concat(p.slice(E));break}if(_!==M.material||g!==M.layer||A!==M.mesh.vertexBuffer.format.batchingHash||C!==M.mesh.primitive[0].indexed||v!==M._shaderDefs||b+M.mesh.vertexBuffer.getNumVertices()>o)m(M);else if(l.copy(h),l.add(M.aabb),l.halfExtents.x>r||l.halfExtents.y>r||l.halfExtents.z>r)m(M);else if(!x||(s=M.stencilFront)&&x.func===s.func&&x.zpass===s.zpass)if(T===Oo(M))if(Po(y,M.parameters)){var P=M._staticLightList;if(S&&P){if(!Ro(S,P)){m(M);continue}}else if(S||P){m(M);continue}n&&c&&c.intersects(M.aabb)&&M.drawOrder!==w?m(M):(h.add(M.aabb),b+=M.mesh.vertexBuffer.getNumVertices(),u[d].push(M))}else m(M);else m(M);else m(M)}d++,p=f}return u},t.collectBatchedMeshData=function(e,t){for(var i=null,n=0,s=0,r=null,a=0;a<e.length;a++)if(e[a].visible){var o=e[a].mesh;if(n+=o.vertexBuffer.numVertices,o.primitive[0].indexed)s+=o.primitive[0].count;else{var h=o.primitive[0].type;6!==h&&5!==h||4===o.primitive[0].count&&(s+=6)}if(!i){r=e[a].material,i={};for(var l=o.vertexBuffer.format.elements,c=0;c<l.length;c++){i[l[c].name]={numComponents:l[c].numComponents,dataType:l[c].dataType,normalize:l[c].normalize,count:0}}t&&(i[ft]={numComponents:1,dataType:6,normalize:!1,count:0})}}return{streams:i,batchNumVerts:n,batchNumIndices:s,material:r}},t.create=function(e,t,i){if(!this._init){var n="#define BONE_LIMIT "+this.device.getBoneLimit()+"\n";this.transformVS=n+"#define DYNAMICBATCH\n"+Sa.transformVS,this.skinTexVS=Sa.skinBatchTexVS,this.skinConstVS=Sa.skinBatchConstVS,this.vertexFormats={},this._init=!0}var s,r,a,o=null,h=null,l=this.collectBatchedMeshData(e,t);if(l.streams){var c,u,d,f=l.streams,p=l.material,m=l.batchNumVerts,_=l.batchNumIndices;h=new Za(e,t,i),this._batchList.push(h);var g,v=0,y=0,x=new me,S=new(m<=65535?Uint16Array:Uint32Array)(_);for(s in f)(o=f[s]).typeArrayType=hi[o.dataType],o.elementByteSize=li[o.dataType],o.buffer=new o.typeArrayType(m*o.numComponents);for(var b=0;b<e.length;b++)if(e[b].visible){for(s in a=(r=e[b].mesh).vertexBuffer.numVertices,t||(g=e[b].node.getWorldTransform()),f)if(s!==ft){var w=new(o=f[s]).typeArrayType(o.buffer.buffer,o.elementByteSize*o.count),T=r.getVertexStream(s,w)*o.numComponents;if(o.count+=T,!t&&o.numComponents>=3)if(s===lt)for(var A=0;A<T;A+=o.numComponents)x.set(w[A],w[A+1],w[A+2]),g.transformPoint(x,x),w[A]=x.x,w[A+1]=x.y,w[A+2]=x.z;else if(s===ct||s===ut){g.invertTo3x3(Do),Do.transpose();for(var C=0;C<T;C+=o.numComponents)x.set(w[C],w[C+1],w[C+2]),Do.transformVector(x,x),w[C]=x.x,w[C+1]=x.y,w[C+2]=x.z}}if(t){o=f[ft];for(var E=0;E<a;E++)o.buffer[o.count++]=b}if(r.primitive[0].indexed){c=r.primitive[0].base,u=r.primitive[0].count;var M=r.indexBuffer[0].getFormat();d=new ui[M](r.indexBuffer[0].storage)}else{var P=r.primitive[0].type;if(6===P||5===P){if(4!==r.primitive[0].count){u=0;continue}c=0,u=6,d=6===P?Io:Lo}}for(var R=0;R<u;R++)S[R+y]=d[c+R]+v;y+=u,v+=a}for(s in r=new Jr(this.device),f)o=f[s],r.setVertexStream(s,o.buffer,o.numComponents,void 0,o.dataType,o.normalize);S.length>0&&r.setIndices(S),r.update(4,!1),t&&((p=p.clone()).chunks.transformVS=this.transformVS,p.chunks.skinTexVS=this.skinTexVS,p.chunks.skinConstVS=this.skinConstVS,p.update());var I=new Co(r,p,this.rootNode);I.castShadow=h.origMeshInstances[0].castShadow,I.parameters=h.origMeshInstances[0].parameters,I.isStatic=h.origMeshInstances[0].isStatic,I.layer=h.origMeshInstances[0].layer,I._staticLightList=h.origMeshInstances[0]._staticLightList,I._shaderDefs=h.origMeshInstances[0]._shaderDefs,I.cull=h.origMeshInstances[0].cull;var L=this._batchGroups[i];if(L&&L._ui&&(I.cull=!1),t){for(var D=[],O=0;O<h.origMeshInstances.length;O++)D.push(h.origMeshInstances[O].node);I.skinInstance=new eo(this.device,D,this.rootNode)}I._updateAabb=!1,I.drawOrder=h.origMeshInstances[0].drawOrder,I.stencilFront=h.origMeshInstances[0].stencilFront,I.stencilBack=h.origMeshInstances[0].stencilBack,I.flipFacesFactor=Oo(h.origMeshInstances[0]),I.castShadow=h.origMeshInstances[0].castShadow,h.meshInstance=I,h.updateBoundingBox()}return h},t.updateAll=function(){this._dirtyGroups.length>0&&this.generate(this._dirtyGroups);for(var e=0;e<this._batchList.length;e++)this._batchList[e].dynamic&&this._batchList[e].updateBoundingBox()},t.clone=function(e,t){var i=new Za(t,e.dynamic,e.batchGroupId);this._batchList.push(i);for(var n=[],s=0;s<t.length;s++)n.push(t[s].node);return i.meshInstance=new Co(e.meshInstance.mesh,e.meshInstance.material,e.meshInstance.node),i.meshInstance._updateAabb=!1,i.meshInstance.parameters=t[0].parameters,i.meshInstance.isStatic=t[0].isStatic,i.meshInstance.cull=t[0].cull,i.meshInstance.layer=t[0].layer,i.meshInstance._staticLightList=t[0]._staticLightList,e.dynamic&&(i.meshInstance.skinInstance=new eo(this.device,n,this.rootNode)),i.meshInstance.castShadow=e.meshInstance.castShadow,i.meshInstance._shader=e.meshInstance._shader.slice(),i.meshInstance.castShadow=e.meshInstance.castShadow,i},t.destroyBatch=function(e){e.destroy(this.scene,this._batchGroups[e.batchGroupId].layers)},e}(),Fo=new me,Bo=new me,No=new me,Uo=new Te,zo=[new me,new me,new me,new me,new me,new me,new me,new me],Vo=function(){function e(){this.shaderPassInfo=void 0,this._aspectRatio=16/9,this._aspectRatioMode=0,this._calculateProjection=null,this._calculateTransform=null,this._clearColor=new ue(.75,.75,.75,1),this._clearColorBuffer=!0,this._clearDepth=1,this._clearDepthBuffer=!0,this._clearStencil=0,this._clearStencilBuffer=!0,this._cullingMask=4294967295,this._cullFaces=!0,this._farClip=1e3,this._flipFaces=!1,this._fov=45,this._frustumCulling=!0,this._horizontalFov=!1,this._layers=[0,1,2,4,3],this._layersSet=new Set(this._layers),this._nearClip=.1,this._node=null,this._orthoHeight=10,this._projection=0,this._rect=new ve(0,0,1,1),this._renderTarget=null,this._scissorRect=new ve(0,0,1,1),this._scissorRectClear=!1,this._aperture=16,this._shutter=.001,this._sensitivity=1e3,this._projMat=new Te,this._projMatDirty=!0,this._projMatSkybox=new Te,this._viewMat=new Te,this._viewMatDirty=!0,this._viewProjMat=new Te,this._viewProjMatDirty=!0,this.frustum=new ke,this._xr=null,this._xrProperties={horizontalFov:this._horizontalFov,fov:this._fov,aspectRatio:this._aspectRatio,farClip:this._farClip,nearClip:this._nearClip}}var t=e.prototype;return t.clone=function(){return(new e).copy(this)},t.copy=function(e){return this._aspectRatio=e._aspectRatio,this._farClip=e._farClip,this._fov=e._fov,this._horizontalFov=e._horizontalFov,this._nearClip=e._nearClip,this._xrProperties.aspectRatio=e._xrProperties.aspectRatio,this._xrProperties.farClip=e._xrProperties.farClip,this._xrProperties.fov=e._xrProperties.fov,this._xrProperties.horizontalFov=e._xrProperties.horizontalFov,this._xrProperties.nearClip=e._xrProperties.nearClip,this.aspectRatioMode=e.aspectRatioMode,this.calculateProjection=e.calculateProjection,this.calculateTransform=e.calculateTransform,this.clearColor=e.clearColor,this.clearColorBuffer=e.clearColorBuffer,this.clearDepth=e.clearDepth,this.clearDepthBuffer=e.clearDepthBuffer,this.clearStencil=e.clearStencil,this.clearStencilBuffer=e.clearStencilBuffer,this.cullFaces=e.cullFaces,this.cullingMask=e.cullingMask,this.flipFaces=e.flipFaces,this.frustumCulling=e.frustumCulling,this.layers=e.layers,this.orthoHeight=e.orthoHeight,this.projection=e.projection,this.rect=e.rect,this.renderTarget=e.renderTarget,this.scissorRect=e.scissorRect,this.aperture=e.aperture,this.shutter=e.shutter,this.sensitivity=e.sensitivity,this.shaderPassInfo=e.shaderPassInfo,this._projMatDirty=!0,this},t._updateViewProjMat=function(){(this._projMatDirty||this._viewMatDirty||this._viewProjMatDirty)&&(this._viewProjMat.mul2(this.projectionMatrix,this.viewMatrix),this._viewProjMatDirty=!1)},t.worldToScreen=function(e,t,i,n){void 0===n&&(n=new me),this._updateViewProjMat(),this._viewProjMat.transformPoint(e,n);var s=this._viewProjMat.data,r=e.x*s[3]+e.y*s[7]+e.z*s[11]+1*s[15];return n.x=.5*(n.x/r+1)*t,n.y=.5*(1-n.y/r)*i,n},t.screenToWorld=function(e,t,i,n,s,r){void 0===r&&(r=new me);var a=this.farClip-this.nearClip;if(Fo.set(e/n,(s-t)/s,i/a),Fo.mulScalar(2),Fo.sub(me.ONE),0===this._projection){Te._getPerspectiveHalfSize(Bo,this.fov,this.aspectRatio,this.nearClip,this.horizontalFov),Bo.x*=Fo.x,Bo.y*=Fo.y;var o=this._node.getWorldTransform();Bo.z=-this.nearClip,o.transformPoint(Bo,No);var h=this._node.getPosition();r.sub2(No,h),r.normalize(),r.mulScalar(i),r.add(h)}else this._updateViewProjMat(),Uo.copy(this._viewProjMat).invert(),Uo.transformPoint(Fo,r);return r},t._evaluateProjectionMatrix=function(){if(this._projMatDirty){if(0===this._projection)this._projMat.setPerspective(this.fov,this.aspectRatio,this.nearClip,this.farClip,this.horizontalFov),this._projMatSkybox.copy(this._projMat);else{var e=this._orthoHeight,t=e*this.aspectRatio;this._projMat.setOrtho(-t,t,-e,e,this.nearClip,this.farClip),this._projMatSkybox.setPerspective(this.fov,this.aspectRatio,this.nearClip,this.farClip)}this._projMatDirty=!1}},t.getProjectionMatrixSkybox=function(){return this._evaluateProjectionMatrix(),this._projMatSkybox},t.getExposure=function(){var e=Math.log2(this._aperture*this._aperture/this._shutter*100/this._sensitivity);return 1/(1.2*Math.pow(2,e))},t.getScreenSize=function(e){if(0===this._projection){var t=this._node.getPosition().distance(e.center);if(t<e.radius)return 1;var i=Math.asin(e.radius/t),n=Math.tan(i),s=Math.tan(this.fov/2*ce.DEG_TO_RAD);return Math.min(n/s,1)}return ce.clamp(e.radius/this._orthoHeight,0,1)},t.getFrustumCorners=function(e,t){void 0===e&&(e=this.nearClip),void 0===t&&(t=this.farClip);var i=this.fov*Math.PI/180,n=0===this._projection?Math.tan(i/2)*e:this._orthoHeight,s=n*this.aspectRatio,r=zo;return r[0].x=s,r[0].y=-n,r[0].z=-e,r[1].x=s,r[1].y=n,r[1].z=-e,r[2].x=-s,r[2].y=n,r[2].z=-e,r[3].x=-s,r[3].y=-n,r[3].z=-e,0===this._projection&&(s=(n=Math.tan(i/2)*t)*this.aspectRatio),r[4].x=s,r[4].y=-n,r[4].z=-t,r[5].x=s,r[5].y=n,r[5].z=-t,r[6].x=-s,r[6].y=n,r[6].z=-t,r[7].x=-s,r[7].y=-n,r[7].z=-t,r},t.setXrProperties=function(e){Object.assign(this._xrProperties,e),this._projMatDirty=!0},Z(e,[{key:"fullSizeClearRect",get:function(){var e=this._scissorRectClear?this.scissorRect:this._rect;return 0===e.x&&0===e.y&&1===e.z&&1===e.w}},{key:"aspectRatio",get:function(){var e;return null!=(e=this.xr)&&e.active?this._xrProperties.aspectRatio:this._aspectRatio},set:function(e){this._aspectRatio!==e&&(this._aspectRatio=e,this._projMatDirty=!0)}},{key:"aspectRatioMode",get:function(){return this._aspectRatioMode},set:function(e){this._aspectRatioMode!==e&&(this._aspectRatioMode=e,this._projMatDirty=!0)}},{key:"calculateProjection",get:function(){return this._calculateProjection},set:function(e){this._calculateProjection=e,this._projMatDirty=!0}},{key:"calculateTransform",get:function(){return this._calculateTransform},set:function(e){this._calculateTransform=e}},{key:"clearColor",get:function(){return this._clearColor},set:function(e){this._clearColor.copy(e)}},{key:"clearColorBuffer",get:function(){return this._clearColorBuffer},set:function(e){this._clearColorBuffer=e}},{key:"clearDepth",get:function(){return this._clearDepth},set:function(e){this._clearDepth=e}},{key:"clearDepthBuffer",get:function(){return this._clearDepthBuffer},set:function(e){this._clearDepthBuffer=e}},{key:"clearStencil",get:function(){return this._clearStencil},set:function(e){this._clearStencil=e}},{key:"clearStencilBuffer",get:function(){return this._clearStencilBuffer},set:function(e){this._clearStencilBuffer=e}},{key:"cullingMask",get:function(){return this._cullingMask},set:function(e){this._cullingMask=e}},{key:"cullFaces",get:function(){return this._cullFaces},set:function(e){this._cullFaces=e}},{key:"farClip",get:function(){var e;return null!=(e=this.xr)&&e.active?this._xrProperties.farClip:this._farClip},set:function(e){this._farClip!==e&&(this._farClip=e,this._projMatDirty=!0)}},{key:"flipFaces",get:function(){return this._flipFaces},set:function(e){this._flipFaces=e}},{key:"fov",get:function(){var e;return null!=(e=this.xr)&&e.active?this._xrProperties.fov:this._fov},set:function(e){this._fov!==e&&(this._fov=e,this._projMatDirty=!0)}},{key:"frustumCulling",get:function(){return this._frustumCulling},set:function(e){this._frustumCulling=e}},{key:"horizontalFov",get:function(){var e;return null!=(e=this.xr)&&e.active?this._xrProperties.horizontalFov:this._horizontalFov},set:function(e){this._horizontalFov!==e&&(this._horizontalFov=e,this._projMatDirty=!0)}},{key:"layers",get:function(){return this._layers},set:function(e){this._layers=e.slice(0),this._layersSet=new Set(this._layers)}},{key:"layersSet",get:function(){return this._layersSet}},{key:"nearClip",get:function(){var e;return null!=(e=this.xr)&&e.active?this._xrProperties.nearClip:this._nearClip},set:function(e){this._nearClip!==e&&(this._nearClip=e,this._projMatDirty=!0)}},{key:"node",get:function(){return this._node},set:function(e){this._node=e}},{key:"orthoHeight",get:function(){return this._orthoHeight},set:function(e){this._orthoHeight!==e&&(this._orthoHeight=e,this._projMatDirty=!0)}},{key:"projection",get:function(){return this._projection},set:function(e){this._projection!==e&&(this._projection=e,this._projMatDirty=!0)}},{key:"projectionMatrix",get:function(){return this._evaluateProjectionMatrix(),this._projMat}},{key:"rect",get:function(){return this._rect},set:function(e){this._rect.copy(e)}},{key:"renderTarget",get:function(){return this._renderTarget},set:function(e){this._renderTarget=e}},{key:"scissorRect",get:function(){return this._scissorRect},set:function(e){this._scissorRect.copy(e)}},{key:"viewMatrix",get:function(){if(this._viewMatDirty){var e=this._node.getWorldTransform();this._viewMat.copy(e).invert(),this._viewMatDirty=!1}return this._viewMat}},{key:"aperture",get:function(){return this._aperture},set:function(e){this._aperture=e}},{key:"sensitivity",get:function(){return this._sensitivity},set:function(e){this._sensitivity=e}},{key:"shutter",get:function(){return this._shutter},set:function(e){this._shutter=e}},{key:"xr",get:function(){return this._xr},set:function(e){this._xr!==e&&(this._xr=e,this._projMatDirty=!0)}}]),e}(),Go=1/255,Ho=new Float32Array(1),Wo=new Int32Array(Ho.buffer),Xo=function(){function e(){}return e.float2Half=function(e){Ho[0]=e;var t=Wo[0],i=t>>16&32768,n=t>>12&2047,s=t>>23&255;return s<103?i:s>142?(i|=31744,i|=(255===s?0:1)&&8388607&t):s<113?i|=((n|=2048)>>114-s)+(n>>113-s&1):(i|=s-112<<10|n>>1,i+=1&n)},e.float2Bytes=function(e,t,i,n){var s=255*e%1;if(t[i+0]=Math.round(255*(e%1-Go*s)),n>1){var r=65025*e%1;if(t[i+1]=Math.round(255*(s-Go*r)),n>2){var a=16581375*e%1;t[i+2]=Math.round(255*(r-Go*a)),n>3&&(t[i+3]=Math.round(255*a))}}},e.float2BytesRange=function(t,i,n,s,r,a){t=ce.clamp((t-s)/(r-s),0,1),e.float2Bytes(t,i,n,a)},e.float2MantissaExponent=function(t,i,n,s){var r=Math.floor(Math.log2(Math.abs(t)))+1;t/=Math.pow(2,r),e.float2BytesRange(t,i,n,-1,1,s-1),i[n+s-1]=Math.round(r+127)},e}(),jo=new Te,qo=new Te,Yo=new Te,Ko=function(){function e(){}return e.create=function(t,i,n){var s=new Vo;switch(s.node=new go(t),s.aspectRatio=1,s.aspectRatioMode=1,s._scissorRectClear=!0,i){case 1:s.node.setRotation(e.pointLightRotations[n]),s.fov=90,s.projection=0;break;case 2:s.projection=0;break;case 0:s.projection=1}return s},e.evalSpotCookieMatrix=function(t){var i=e._spotCookieCamera;i||(i=e.create("SpotCookieCamera",2),e._spotCookieCamera=i),i.fov=2*t._outerConeAngle;var n=i._node;n.setPosition(t._node.getPosition()),n.setRotation(t._node.getRotation()),n.rotateLocal(-90,0,0),jo.setTRS(n.getPosition(),n.getRotation(),me.ONE).invert(),qo.mul2(i.projectionMatrix,jo);var s=t.cookieMatrix,r=t.atlasViewport;return Yo.setViewport(r.x,r.y,r.z,r.w),s.mul2(Yo,qo),s},e}();Ko.pointLightRotations=[(new Ae).setFromEulerAngles(0,90,180),(new Ae).setFromEulerAngles(0,-90,180),(new Ae).setFromEulerAngles(90,0,0),(new Ae).setFromEulerAngles(-90,0,0),(new Ae).setFromEulerAngles(0,180,180),(new Ae).setFromEulerAngles(0,0,180)],Ko._spotCookieCamera=null;var Zo=new me,$o=new Float32Array(6),Qo=new me(-.5,0,0),Jo=new me(0,0,.5),eh={FLAGS:0,COLOR_A:1,COLOR_B:2,SPOT_ANGLES:3,SHADOW_BIAS:4,COOKIE_A:5,COOKIE_B:6,COUNT_ALWAYS:7,POSITION_X:7,POSITION_Y:8,POSITION_Z:9,RANGE:10,SPOT_DIRECTION_X:11,SPOT_DIRECTION_Y:12,SPOT_DIRECTION_Z:13,PROJ_MAT_00:14,ATLAS_VIEWPORT_A:14,PROJ_MAT_01:15,ATLAS_VIEWPORT_B:15,PROJ_MAT_02:16,PROJ_MAT_03:17,PROJ_MAT_10:18,PROJ_MAT_11:19,PROJ_MAT_12:20,PROJ_MAT_13:21,PROJ_MAT_20:22,PROJ_MAT_21:23,PROJ_MAT_22:24,PROJ_MAT_23:25,PROJ_MAT_30:26,PROJ_MAT_31:27,PROJ_MAT_32:28,PROJ_MAT_33:29,AREA_DATA_WIDTH_X:30,AREA_DATA_WIDTH_Y:31,AREA_DATA_WIDTH_Z:32,AREA_DATA_HEIGHT_X:33,AREA_DATA_HEIGHT_Y:34,AREA_DATA_HEIGHT_Z:35,COUNT:36},th={POSITION_RANGE:0,SPOT_DIRECTION:1,PROJ_MAT_0:2,ATLAS_VIEWPORT:2,PROJ_MAT_1:3,PROJ_MAT_2:4,PROJ_MAT_3:5,AREA_DATA_WIDTH:6,AREA_DATA_HEIGHT:7,COUNT:8},ih=function(){function e(t){this.device=t,this.cookiesEnabled=!1,this.shadowsEnabled=!1,this.areaLightsEnabled=!1,this.maxLights=255;var i=eh.COUNT_ALWAYS,n=0;e.lightTextureFormat===e.FORMAT_FLOAT?n=th.COUNT:i=eh.COUNT,this.lights8=new Uint8ClampedArray(4*i*this.maxLights),this.lightsTexture8=e.createTexture(this.device,i,this.maxLights,7,"LightsTexture8"),this._lightsTexture8Id=this.device.scope.resolve("lightsTexture8"),n?(this.lightsFloat=new Float32Array(4*n*this.maxLights),this.lightsTextureFloat=e.createTexture(this.device,n,this.maxLights,Ze,"LightsTextureFloat"),this._lightsTextureFloatId=this.device.scope.resolve("lightsTextureFloat")):(this.lightsFloat=null,this.lightsTextureFloat=null,this._lightsTextureFloatId=void 0),this._lightsTextureInvSizeId=this.device.scope.resolve("lightsTextureInvSize"),this._lightsTextureInvSizeData=new Float32Array(4),this._lightsTextureInvSizeData[0]=n?1/this.lightsTextureFloat.width:0,this._lightsTextureInvSizeData[1]=n?1/this.lightsTextureFloat.height:0,this._lightsTextureInvSizeData[2]=1/this.lightsTexture8.width,this._lightsTextureInvSizeData[3]=1/this.lightsTexture8.height,this.invMaxColorValue=0,this.invMaxAttenuation=0,this.boundsMin=new me,this.boundsDelta=new me}e.initShaderDefines=function(){var t=e.lightTextureFormat===e.FORMAT_FLOAT?"FLOAT":"8BIT";e.shaderDefines="\n \n#define CLUSTER_TEXTURE_"+t+"\n "+e.buildShaderDefines(eh,"CLUSTER_TEXTURE_8_")+"\n "+e.buildShaderDefines(th,"CLUSTER_TEXTURE_F_")+"\n "},e.buildShaderDefines=function(t,i){var n="",s=e.useTexelFetch?"":".5";return Object.keys(t).forEach((function(e){n+="\n#define "+i+e+" "+t[e]+s})),n},e.init=function(t){e.lightTextureFormat=t.extTextureFloat&&t.maxTextures>8?e.FORMAT_FLOAT:e.FORMAT_8BIT,e.useTexelFetch=t.supportsTextureFetch,e.initShaderDefines()},e.createTexture=function(e,t,i,n,s){return new Yn(e,{name:s,width:t,height:i,mipmaps:!1,format:n,addressU:1,addressV:1,type:Vt,magFilter:0,minFilter:0,anisotropy:1})};var t=e.prototype;return t.destroy=function(){this.lightsTexture8&&(this.lightsTexture8.destroy(),this.lightsTexture8=null),this.lightsTextureFloat&&(this.lightsTextureFloat.destroy(),this.lightsTextureFloat=null)},t.setCompressionRanges=function(e,t){this.invMaxColorValue=1/t,this.invMaxAttenuation=1/e},t.setBounds=function(e,t){this.boundsMin.copy(e),this.boundsDelta.copy(t)},t.uploadTextures=function(){this.lightsTextureFloat&&(this.lightsTextureFloat.lock().set(this.lightsFloat),this.lightsTextureFloat.unlock()),this.lightsTexture8.lock().set(this.lights8),this.lightsTexture8.unlock()},t.updateUniforms=function(){this._lightsTexture8Id.setValue(this.lightsTexture8),e.lightTextureFormat===e.FORMAT_FLOAT&&this._lightsTextureFloatId.setValue(this.lightsTextureFloat),this._lightsTextureInvSizeId.setValue(this._lightsTextureInvSizeData)},t.getSpotDirection=function(e,t){t._node.getWorldTransform().getY(e).mulScalar(-1),e.normalize()},t.getLightAreaSizes=function(e){var t=e._node.getWorldTransform();return t.transformVector(Qo,Zo),$o[0]=Zo.x,$o[1]=Zo.y,$o[2]=Zo.z,t.transformVector(Jo,Zo),$o[3]=Zo.x,$o[4]=Zo.y,$o[5]=Zo.z,$o},t.addLightDataFlags=function(e,t,i,n,s,r){e[t+0]=n?255:0,e[t+1]=64*i._shape,e[t+2]=255*i._falloffMode,e[t+3]=s?255*r:0},t.addLightDataColor=function(e,t,i,n,s){var r=this.invMaxColorValue,a=n?i._linearFinalColor:i._finalColor;Xo.float2Bytes(a[0]*r,e,t+0,2),Xo.float2Bytes(a[1]*r,e,t+2,2),Xo.float2Bytes(a[2]*r,e,t+4,2),e[t+6]=s?255:0;var o=!!(1&i.mask),h=!!(2&i.mask);e[t+7]=o&&h?127:h?255:0},t.addLightDataSpotAngles=function(e,t,i){Xo.float2Bytes(.499999*i._innerConeAngleCos+.5,e,t+0,2),Xo.float2Bytes(.499999*i._outerConeAngleCos+.5,e,t+2,2)},t.addLightDataShadowBias=function(e,t,i){var n=i.getRenderData(null,0),s=i._getUniformBiasValues(n);Xo.float2BytesRange(s.bias,e,t,-1,20,2),Xo.float2Bytes(s.normalBias,e,t+2,2)},t.addLightDataPositionRange=function(e,t,i,n){var s=Zo.sub2(n,this.boundsMin).div(this.boundsDelta);Xo.float2Bytes(s.x,e,t+0,4),Xo.float2Bytes(s.y,e,t+4,4),Xo.float2Bytes(s.z,e,t+8,4),Xo.float2Bytes(i.attenuationEnd*this.invMaxAttenuation,e,t+12,4)},t.addLightDataSpotDirection=function(e,t,i){this.getSpotDirection(Zo,i),Xo.float2Bytes(.499999*Zo.x+.5,e,t+0,4),Xo.float2Bytes(.499999*Zo.y+.5,e,t+4,4),Xo.float2Bytes(.499999*Zo.z+.5,e,t+8,4)},t.addLightDataLightProjMatrix=function(e,t,i){for(var n=i.data,s=0;s<12;s++)Xo.float2BytesRange(n[s],e,t+4*s,-2,2,4);for(var r=12;r<16;r++)Xo.float2MantissaExponent(n[r],e,t+4*r,4)},t.addLightDataCookies=function(e,t,i){var n="rgb"===i._cookieChannel;if(e[t+0]=Math.floor(255*i.cookieIntensity),e[t+1]=n?255:0,!n){var s=i._cookieChannel;e[t+4]="rrr"===s?255:0,e[t+5]="ggg"===s?255:0,e[t+6]="bbb"===s?255:0,e[t+7]="aaa"===s?255:0}},t.addLightAtlasViewport=function(e,t,i){Xo.float2Bytes(i.x,e,t+0,2),Xo.float2Bytes(i.y,e,t+2,2),Xo.float2Bytes(i.z/3,e,t+4,2)},t.addLightAreaSizes=function(e,t,i){for(var n=this.getLightAreaSizes(i),s=0;s<6;s++)Xo.float2MantissaExponent(n[s],e,t+4*s,4)},t.addLightData=function(t,i,n){var s=2===t._type,r=t.atlasViewportAllocated,a=this.cookiesEnabled&&!!t._cookie&&r,o=this.areaLightsEnabled&&0!==t.shape,h=this.shadowsEnabled&&t.castShadows&&r,l=t._node.getPosition(),c=null,u=null;s?h?c=t.getRenderData(null,0).shadowMatrix:a&&(c=Ko.evalSpotCookieMatrix(t)):(h||a)&&(u=t.atlasViewport);var d=this.lights8,f=i*this.lightsTexture8.width*4;if(this.addLightDataFlags(d,f+4*eh.FLAGS,t,s,h,t.shadowIntensity),this.addLightDataColor(d,f+4*eh.COLOR_A,t,n,a),s&&this.addLightDataSpotAngles(d,f+4*eh.SPOT_ANGLES,t),t.castShadows&&this.addLightDataShadowBias(d,f+4*eh.SHADOW_BIAS,t),a&&this.addLightDataCookies(d,f+4*eh.COOKIE_A,t),e.lightTextureFormat===e.FORMAT_FLOAT){var p=this.lightsFloat,m=i*this.lightsTextureFloat.width*4;if(p[m+4*th.POSITION_RANGE+0]=l.x,p[m+4*th.POSITION_RANGE+1]=l.y,p[m+4*th.POSITION_RANGE+2]=l.z,p[m+4*th.POSITION_RANGE+3]=t.attenuationEnd,s&&(this.getSpotDirection(Zo,t),p[m+4*th.SPOT_DIRECTION+0]=Zo.x,p[m+4*th.SPOT_DIRECTION+1]=Zo.y,p[m+4*th.SPOT_DIRECTION+2]=Zo.z),c)for(var _=c.data,g=0;g<16;g++)p[m+4*th.PROJ_MAT_0+g]=_[g];if(u&&(p[m+4*th.ATLAS_VIEWPORT+0]=u.x,p[m+4*th.ATLAS_VIEWPORT+1]=u.y,p[m+4*th.ATLAS_VIEWPORT+2]=u.z/3),o){var v=this.getLightAreaSizes(t);p[m+4*th.AREA_DATA_WIDTH+0]=v[0],p[m+4*th.AREA_DATA_WIDTH+1]=v[1],p[m+4*th.AREA_DATA_WIDTH+2]=v[2],p[m+4*th.AREA_DATA_HEIGHT+0]=v[3],p[m+4*th.AREA_DATA_HEIGHT+1]=v[4],p[m+4*th.AREA_DATA_HEIGHT+2]=v[5]}}else this.addLightDataPositionRange(d,f+4*eh.POSITION_X,t,l),s&&this.addLightDataSpotDirection(d,f+4*eh.SPOT_DIRECTION_X,t),c&&this.addLightDataLightProjMatrix(d,f+4*eh.PROJ_MAT_00,c),u&&this.addLightAtlasViewport(d,f+4*eh.ATLAS_VIEWPORT_A,u),o&&this.addLightAreaSizes(d,f+4*eh.AREA_DATA_WIDTH_X,t)},e}();ih.FORMAT_FLOAT=0,ih.FORMAT_8BIT=1,ih.lightTextureFormat=ih.FORMAT_8BIT,ih.useTexelFetch=!1,ih.shaderDefines="";var nh=new me,sh=new me,rh=new me,ah=new Ie,oh=1e-6,hh=function(){this.light=null,this.min=new me,this.max=new me},lh=function(){function e(e){this.clusterTexture=void 0,this.device=e,this.name="Untitled",this.reportCount=0,this.boundsMin=new me,this.boundsMax=new me,this.boundsDelta=new me,this._cells=new me(1,1,1),this._cellsLimit=new me,this.cells=this._cells,this.maxCellLightCount=4,this._maxAttenuation=0,this._maxColorValue=0,this._usedLights=[],this._usedLights.push(new hh),this.lightsBuffer=new ih(e),this.registerUniforms(e)}var t=e.prototype;return t.destroy=function(){this.lightsBuffer.destroy(),this.releaseClusterTexture()},t.releaseClusterTexture=function(){this.clusterTexture&&(this.clusterTexture.destroy(),this.clusterTexture=null)},t.registerUniforms=function(e){this._clusterSkipId=e.scope.resolve("clusterSkip"),this._clusterMaxCellsId=e.scope.resolve("clusterMaxCells"),this._clusterWorldTextureId=e.scope.resolve("clusterWorldTexture"),this._clusterTextureSizeId=e.scope.resolve("clusterTextureSize"),this._clusterTextureSizeData=new Float32Array(3),this._clusterBoundsMinId=e.scope.resolve("clusterBoundsMin"),this._clusterBoundsMinData=new Float32Array(3),this._clusterBoundsDeltaId=e.scope.resolve("clusterBoundsDelta"),this._clusterBoundsDeltaData=new Float32Array(3),this._clusterCellsCountByBoundsSizeId=e.scope.resolve("clusterCellsCountByBoundsSize"),this._clusterCellsCountByBoundsSizeData=new Float32Array(3),this._clusterCellsDotId=e.scope.resolve("clusterCellsDot"),this._clusterCellsDotData=new Float32Array(3),this._clusterCellsMaxId=e.scope.resolve("clusterCellsMax"),this._clusterCellsMaxData=new Float32Array(3),this._clusterCompressionLimit0Id=e.scope.resolve("clusterCompressionLimit0"),this._clusterCompressionLimit0Data=new Float32Array(2)},t.updateParams=function(e){e&&(this.cells=e.cells,this.maxCellLightCount=e.maxLightsPerCell,this.lightsBuffer.cookiesEnabled=e.cookiesEnabled,this.lightsBuffer.shadowsEnabled=e.shadowsEnabled,this.lightsBuffer.areaLightsEnabled=e.areaLightsEnabled)},t.updateCells=function(){if(this._cellsDirty){this._cellsDirty=!1;var e=this._cells.x,t=this._cells.y,i=this._cells.z,n=e*t*i,s=this.maxCellLightCount*n,r=Math.ceil(Math.sqrt(s));r=ce.roundUp(r,this.maxCellLightCount);var a=Math.ceil(s/r);this._clusterCellsMaxData[0]=e,this._clusterCellsMaxData[1]=t,this._clusterCellsMaxData[2]=i,this._clusterCellsDotData[0]=this.maxCellLightCount,this._clusterCellsDotData[1]=e*i*this.maxCellLightCount,this._clusterCellsDotData[2]=e*this.maxCellLightCount,this.clusters=new Uint8ClampedArray(s),this.counts=new Int32Array(n),this._clusterTextureSizeData[0]=r,this._clusterTextureSizeData[1]=1/r,this._clusterTextureSizeData[2]=1/a,this.releaseClusterTexture(),this.clusterTexture=ih.createTexture(this.device,r,a,1,"ClusterTexture")}},t.uploadTextures=function(){this.clusterTexture.lock().set(this.clusters),this.clusterTexture.unlock(),this.lightsBuffer.uploadTextures()},t.updateUniforms=function(){this._clusterSkipId.setValue(this._usedLights.length>1?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._clusterCompressionLimit0Data[0]=this._maxAttenuation,this._clusterCompressionLimit0Data[1]=this._maxColorValue,this._clusterTextureSizeId.setValue(this._clusterTextureSizeData),this._clusterBoundsMinId.setValue(this._clusterBoundsMinData),this._clusterBoundsDeltaId.setValue(this._clusterBoundsDeltaData),this._clusterCellsDotId.setValue(this._clusterCellsDotData),this._clusterCellsMaxId.setValue(this._clusterCellsMaxData),this._clusterCompressionLimit0Id.setValue(this._clusterCompressionLimit0Data)},t.evalLightCellMinMax=function(e,t,i){t.copy(e.min),t.sub(this.boundsMin),t.div(this.boundsDelta),t.mul2(t,this.cells),t.floor(),i.copy(e.max),i.sub(this.boundsMin),i.div(this.boundsDelta),i.mul2(i,this.cells),i.ceil(),t.max(me.ZERO),i.min(this._cellsLimit)},t.collectLights=function(e){var t=this.lightsBuffer.maxLights,i=this._usedLights,n=1;e.forEach((function(e){var s,r=!!(3&e.mask),a=2===e.type&&0===e._outerConeAngle;e.enabled&&0!==e.type&&e.visibleThisFrame&&e.intensity>0&&r&&!a&&(n<t&&(n<i.length?s=i[n]:(s=new hh,i.push(s)),s.light=e,e.getBoundingBox(ah),s.min.copy(ah.getMin()),s.max.copy(ah.getMax()),n++))})),i.length=n},t.evaluateBounds=function(){var e=this._usedLights,t=this.boundsMin,i=this.boundsMax;if(e.length>1){t.copy(e[1].min),i.copy(e[1].max);for(var n=2;n<e.length;n++)t.min(e[n].min),i.max(e[n].max)}else t.set(0,0,0),i.set(1,1,1);this.boundsDelta.sub2(i,t),this.lightsBuffer.setBounds(t,this.boundsDelta)},t.evaluateCompressionLimits=function(e){for(var t=0,i=0,n=this._usedLights,s=1;s<n.length;s++){var r=n[s].light;t=Math.max(r.attenuationEnd,t);var a=e?r._linearFinalColor:r._finalColor;i=Math.max(a[0],i),i=Math.max(a[1],i),i=Math.max(a[2],i)}this._maxAttenuation=t+oh,this._maxColorValue=i+oh,this.lightsBuffer.setCompressionRanges(this._maxAttenuation,this._maxColorValue)},t.updateClusters=function(e){this.counts.fill(0),this.clusters.fill(0);for(var t=this._cells.x,i=this._cells.z,n=this.counts,s=this._maxCellLightCount,r=this.clusters,a=this.maxCellLightCount,o=this._usedLights,h=1;h<o.length;h++){var l=o[h],c=l.light;this.lightsBuffer.addLightData(c,h,e),this.evalLightCellMinMax(l,sh,rh);for(var u=sh.x,d=rh.x,f=sh.y,p=rh.y,m=sh.z,_=rh.z,g=u;g<=d;g++)for(var v=m;v<=_;v++)for(var y=f;y<=p;y++){var x=g+t*(v+y*i),S=n[x];S<s&&(r[a*x+S]=h,n[x]=S+1)}}},t.update=function(e,t,i){this.updateParams(i),this.updateCells(),this.collectLights(e),this.evaluateBounds(),this.evaluateCompressionLimits(t),this.updateClusters(t),this.uploadTextures()},t.activate=function(){this.updateUniforms()},Z(e,[{key:"maxCellLightCount",get:function(){return this._maxCellLightCount},set:function(e){e!==this._maxCellLightCount&&(this._maxCellLightCount=e,this._cellsDirty=!0)}},{key:"cells",get:function(){return this._cells},set:function(e){nh.copy(e).floor(),this._cells.equals(nh)||(this._cells.copy(nh),this._cellsLimit.copy(nh).sub(me.ONE),this._cellsDirty=!0)}}]),e}(),ch=new ve,uh=function(){function e(e,t){this.device=e,this.lightTextureAtlas=t,this.blitShader2d=null,this.blitShaderCube=null,this.blitTextureId=null,this.invViewProjId=null}var t=e.prototype;return t.destroy=function(){},t.getShader=function(e,t){return this[e]||(this[e]=Ca(this.device,"\n attribute vec2 vertex_position;\n varying vec2 uv0;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.5, 1.0);\n uv0 = vertex_position.xy * 0.5 + 0.5;\n }",t,"cookie_renderer_"+e)),this.blitTextureId||(this.blitTextureId=this.device.scope.resolve("blitTexture")),this.invViewProjId||(this.invViewProjId=this.device.scope.resolve("invViewProj")),this[e]},e.createTexture=function(e,t){return new Yn(e,{name:"CookieAtlas",width:t,height:t,format:7,cubemap:!1,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1})},t.initInvViewProjMatrices=function(){if(!e._invViewProjMatrices){e._invViewProjMatrices=[];for(var t=0;t<6;t++){var i=Ko.create(null,1,t),n=i.projectionMatrix,s=i.node.getLocalTransform().clone().invert();e._invViewProjMatrices[t]=(new Te).mul2(n,s).invert()}}},t.render=function(t,i){if(t.enabled&&t.cookie&&t.visibleThisFrame){var n=t.numShadowFaces,s=n>1?this.shaderCube:this.shader2d,r=this.device;n>1&&this.initInvViewProjMatrices(),this.blitTextureId.setValue(t.cookie),r.setBlendState(yi.NOBLEND);for(var a=0;a<n;a++){if(ch.copy(t.atlasViewport),n>1){var o=ch.z/3,h=this.lightTextureAtlas.cubeSlotsOffsets[a];ch.x+=o*h.x,ch.y+=o*h.y,ch.z=o,ch.w=o,this.invViewProjId.setValue(e._invViewProjMatrices[a].data)}ch.mulScalar(i.colorBuffer.width),Da(r,i,s,ch)}}},Z(e,[{key:"shader2d",get:function(){return this.getShader("blitShader2d","\n varying vec2 uv0;\n uniform sampler2D blitTexture;\n void main(void) {\n gl_FragColor = texture2D(blitTexture, uv0);\n }")}},{key:"shaderCube",get:function(){return this.getShader("blitShaderCube","\n varying vec2 uv0;\n uniform samplerCube blitTexture;\n uniform mat4 invViewProj;\n void main(void) {\n vec4 projPos = vec4(uv0 * 2.0 - 1.0, 0.5, 1.0);\n vec4 worldPos = invViewProj * projPos;\n gl_FragColor = textureCube(blitTexture, worldPos.xyz);\n }")}}]),e}();uh._invViewProjMatrices=null;var dh=function(){function e(e,t){this.texture=e,this.cached=!1,this.renderTargets=t}return e.prototype.destroy=function(){this.texture&&(this.texture.destroy(),this.texture=null);for(var e=this.renderTargets,t=0;t<e.length;t++)e[t].destroy();this.renderTargets.length=0},e.getShadowFormat=function(e,t){return 3===t?Ze:2===t?Ye:4===t?Qe:5!==t&&0!==t||!e.supportsDepthShadow?6===t&&(e.webgl2||e.isWebGPU)?$e:7:Qe},e.getShadowFiltering=function(e,t){return 5!==t&&0!==t&&6!==t||e.supportsDepthShadow?3===t?e.extTextureFloatLinear?1:0:2===t?e.extTextureHalfFloatLinear?1:0:1:0},e.create=function(e,t){return 1===t._type?this.createCubemap(e,t._shadowResolution,t._shadowType):this.create2dMap(e,t._shadowResolution,t._shadowType)},e.createAtlas=function(e,t,i){for(var n=this.create2dMap(e,t,i),s=n.renderTargets,r=s[0],a=0;a<5;a++)s.push(r);return n},e.create2dMap=function(t,i,n){var s=this.getShadowFormat(t,n),r=this.getShadowFiltering(t,n),a=new Yn(t,{format:s,width:i,height:i,mipmaps:!1,minFilter:r,magFilter:r,addressU:1,addressV:1,name:"ShadowMap2D"}),o=null;return 4===n||(5===n||0===n)&&t.supportsDepthShadow?(a.compareOnRead=!0,a.compareFunc=1,o=new Di({depthBuffer:a})):o=new Di({colorBuffer:a,depth:!0}),t.isWebGPU&&(o.flipY=!0),new e(a,[o])},e.createCubemap=function(t,i,n){for(var s=6===n&&(t.webgl2||t.isWebGPU)?$e:7,r=new Yn(t,{format:s,width:i,height:i,cubemap:!0,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1,name:"ShadowMapCube"}),a=[],o=0;o<6;o++){var h=new Di({colorBuffer:r,face:o,depth:!0});a.push(h)}return new e(r,a)},e}(),fh=[],ph=[],mh=new ve,_h=new ve,gh=function(e){this.size=Math.floor(1024*e.w),this.used=!1,this.lightId=-1,this.rect=e},vh=function(){function e(e){this.device=e,this.version=1,this.shadowAtlasResolution=2048,this.shadowAtlas=null,this.shadowEdgePixels=3,this.cookieAtlasResolution=2048,this.cookieAtlas=null,this.cookieRenderTarget=null,this.slots=[],this.atlasSplit=[],this.cubeSlotsOffsets=[new ge(0,0),new ge(0,1),new ge(1,0),new ge(1,1),new ge(2,0),new ge(2,1)],this.scissorVec=new ve,this.allocateShadowAtlas(1),this.allocateCookieAtlas(1),this.allocateUniforms()}var t=e.prototype;return t.destroy=function(){this.destroyShadowAtlas(),this.destroyCookieAtlas()},t.destroyShadowAtlas=function(){this.shadowAtlas&&(this.shadowAtlas.destroy(),this.shadowAtlas=null)},t.destroyCookieAtlas=function(){this.cookieAtlas&&(this.cookieAtlas.destroy(),this.cookieAtlas=null),this.cookieRenderTarget&&(this.cookieRenderTarget.destroy(),this.cookieRenderTarget=null)},t.allocateShadowAtlas=function(e){if(!this.shadowAtlas||this.shadowAtlas.texture.width!==e){this.version++,this.destroyShadowAtlas(),this.shadowAtlas=dh.createAtlas(this.device,e,0),this.shadowAtlas.cached=!0;var t=4/this.shadowAtlasResolution;this.scissorVec.set(t,t,-2*t,-2*t)}},t.allocateCookieAtlas=function(e){this.cookieAtlas&&this.cookieAtlas.width===e||(this.version++,this.destroyCookieAtlas(),this.cookieAtlas=uh.createTexture(this.device,e),this.cookieRenderTarget=new Di({colorBuffer:this.cookieAtlas,depth:!1,flipY:!0}))},t.allocateUniforms=function(){this._shadowAtlasTextureId=this.device.scope.resolve("shadowAtlasTexture"),this._shadowAtlasParamsId=this.device.scope.resolve("shadowAtlasParams"),this._shadowAtlasParams=new Float32Array(2),this._cookieAtlasTextureId=this.device.scope.resolve("cookieAtlasTexture")},t.updateUniforms=function(){var e=this.shadowAtlas.renderTargets[0],t=(this.device.isWebGPU||this.device.webgl2)&&!0?e.depthBuffer:e.colorBuffer;this._shadowAtlasTextureId.setValue(t),this._shadowAtlasParams[0]=this.shadowAtlasResolution,this._shadowAtlasParams[1]=this.shadowEdgePixels,this._shadowAtlasParamsId.setValue(this._shadowAtlasParams),this._cookieAtlasTextureId.setValue(this.cookieAtlas)},t.subdivide=function(e,t){var i=t.atlasSplit;if(!i){var n=Math.ceil(Math.sqrt(e));(i=ph)[0]=n,i.length=1}var s,r;if(s=i,r=this.atlasSplit,s.length!==r.length||!s.every((function(e,t){return e===r[t]}))){var a;this.version++,this.slots.length=0,this.atlasSplit.length=0,(a=this.atlasSplit).push.apply(a,i);var o=this.atlasSplit[0];if(o>1)for(var h=1/o,l=0;l<o;l++)for(var c=0;c<o;c++){var u=new ve(l*h,c*h,h,h),d=this.atlasSplit[1+l*o+c];if(d>1)for(var f=0;f<d;f++)for(var p=0;p<d;p++){var m=h/d,_=new ve(u.x+f*m,u.y+p*m,m,m);this.slots.push(new gh(_))}else this.slots.push(new gh(u))}else this.slots.push(new gh(new ve(0,0,1,1)));this.slots.sort((function(e,t){return t.size-e.size}))}},t.collectLights=function(e,t,i){var n=i.cookiesEnabled,s=i.shadowsEnabled,r=!1,a=!1,o=fh;o.length=0;var h=function(e){for(var t=0;t<e.length;t++){var i=e[t];if(i.visibleThisFrame){var h=s&&i.castShadows,l=n&&!!i.cookie;r||(r=h),a||(a=l),(h||l)&&o.push(i)}}};return(n||s)&&(h(e),h(t)),o.sort((function(e,t){return t.maxScreenSize-e.maxScreenSize})),r&&this.allocateShadowAtlas(this.shadowAtlasResolution),a&&this.allocateCookieAtlas(this.cookieAtlasResolution),(r||a)&&this.subdivide(o.length,i),o},t.setupSlot=function(e,t){e.atlasViewport.copy(t);for(var i=e.numShadowFaces,n=0;n<i;n++)if(e.castShadows||e._cookie){if(mh.copy(t),_h.copy(t),2===e._type&&mh.add(this.scissorVec),1===e._type){var s=mh.z/3,r=this.cubeSlotsOffsets[n];mh.x+=s*r.x,mh.y+=s*r.y,mh.z=s,mh.w=s,_h.copy(mh)}if(e.castShadows){var a=e.getRenderData(null,n);a.shadowViewport.copy(mh),a.shadowScissor.copy(_h)}}},t.assignSlot=function(e,t,i){e.atlasViewportAllocated=!0;var n=this.slots[t];n.lightId=e.id,n.used=!0,i&&(e.atlasSlotUpdated=!0,e.atlasVersion=this.version,e.atlasSlotIndex=t)},t.update=function(e,t,i){this.shadowAtlasResolution=i.shadowAtlasResolution,this.cookieAtlasResolution=i.cookieAtlasResolution;var n=this.collectLights(e,t,i);if(n.length>0){for(var s=this.slots,r=0;r<s.length;r++)s[r].used=!1;for(var a=Math.min(n.length,s.length),o=0;o<a;o++){var h=n[o];h.castShadows&&(h._shadowMap=this.shadowAtlas);var l=s[h.atlasSlotIndex];if(h.atlasVersion===this.version&&h.id===(null==l?void 0:l.lightId)){var c=s[h.atlasSlotIndex];c.size!==s[o].size||c.used||this.assignSlot(h,h.atlasSlotIndex,!1)}}for(var u=0,d=0;d<a;d++){for(;u<s.length&&s[u].used;)u++;var f=n[d];f.atlasViewportAllocated||this.assignSlot(f,u,!0);var p=s[f.atlasSlotIndex];this.setupSlot(f,p.rect)}}this.updateUniforms()},e}(),yh=function(){function e(){this.cache=new Map}var t=e.prototype;return t.destroy=function(){this.clear(),this.cache=null},t.clear=function(){this.cache.forEach((function(e){e.forEach((function(e){e.destroy()}))})),this.cache.clear()},t.getKey=function(e){return(1===e._type)+"-"+e._shadowType+"-"+e._shadowResolution},t.get=function(e,t){var i=this.getKey(t),n=this.cache.get(i);if(n&&n.length)return n.pop();var s=dh.create(e,t);return s.cached=!0,s},t.add=function(e,t){var i=this.getKey(e),n=this.cache.get(i);n?n.push(t):this.cache.set(i,[t])},e}(),xh=function(){function e(e,t){this.shadowLights=[],this.renderer=void 0,this.shadowRenderer=void 0,this.device=void 0,this.renderer=e,this.shadowRenderer=t,this.device=e.device}var t=e.prototype;return t.cull=function(e,t){var i=this.renderer.scene.clusteredLightingEnabled;e.visibleThisFrame=!0,i||e._shadowMap||(e._shadowMap=dh.create(this.device,e));for(var n=e._type,s=2===n?1:6,r=0;r<s;r++){var a=e.getRenderData(null,r),o=a.shadowCamera;o.nearClip=e.attenuationEnd/1e3,o.farClip=e.attenuationEnd;var h=o._node,l=e._node;if(h.setPosition(l.getPosition()),2===n)o.fov=2*e._outerConeAngle,h.setRotation(l.getRotation()),h.rotateLocal(-90,0,0);else if(1===n)if(i){var c=2/(this.shadowRenderer.lightTextureAtlas.shadowAtlasResolution*e.atlasViewport.z/3)*this.shadowRenderer.lightTextureAtlas.shadowEdgePixels;o.fov=Math.atan(1+c)*ce.RAD_TO_DEG*2}else o.fov=90;this.renderer.updateCameraFrustum(o),this.shadowRenderer.cullShadowCasters(t,a.visibleCasters,o)}},t.prepareLights=function(e,t){for(var i,n=0;n<t.length;n++){var s=t[n];if(this.shadowRenderer.needsShadowRendering(s)&&s.atlasViewportAllocated){e.push(s);for(var r=0;r<s.numShadowFaces;r++)i=this.shadowRenderer.prepareFace(s,null,r)}}return i},t.prepareClusteredRenderPass=function(e,t,i){var n=this,s=this.shadowLights,r=this.prepareLights(s,t),a=this.prepareLights(s,i),o=null!=r?r:a,h=s.length;h&&(this.shadowRenderer.setupRenderPass(e,o,!1),e.execute=function(){for(var e=0;e<h;e++)for(var t=s[e],i=0;i<t.numShadowFaces;i++)n.shadowRenderer.renderFace(t,null,i,!0);s.length=0})},t.setupNonClusteredFaceRenderPass=function(e,t,i,n){var s=this,r=this.shadowRenderer.prepareFace(t,null,i),a=new ga(this.device,(function(){s.shadowRenderer.renderFace(t,null,i,!1)}));this.shadowRenderer.setupRenderPass(a,r,!0),n&&(a.after=function(){s.shadowRenderer.renderVsm(t,r)}),e.addRenderPass(a)},t.buildNonClusteredRenderPasses=function(e,t,i){for(var n=0;n<t.length;n++){var s=t[n];this.shadowRenderer.needsShadowRendering(s)&&this.setupNonClusteredFaceRenderPass(e,s,0,!0)}for(var r=0;r<i.length;r++){var a=i[r];if(this.shadowRenderer.needsShadowRendering(a))for(var o=a.numShadowFaces,h=0;h<o;h++)this.setupNonClusteredFaceRenderPass(e,a,h,!1)}},e}(),Sh=new Ie,bh=new me,wh=new Te,Th=[new me,new me,new me,new me,new me,new me,new me,new me],Ah={min:0,max:0};function Ch(e,t,i){Th[0].x=Th[1].x=Th[2].x=Th[3].x=t.x,Th[1].y=Th[3].y=Th[7].y=Th[5].y=t.y,Th[2].z=Th[3].z=Th[6].z=Th[7].z=t.z,Th[4].x=Th[5].x=Th[6].x=Th[7].x=i.x,Th[0].y=Th[2].y=Th[4].y=Th[6].y=i.y,Th[0].z=Th[1].z=Th[4].z=Th[5].z=i.z;for(var n=9999999999,s=-9999999999,r=0;r<8;++r){e.transformPoint(Th[r],Th[r]);var a=Th[r].z;a<n&&(n=a),a>s&&(s=a)}return Ah.min=n,Ah.max=s,Ah}var Eh=function(){function e(e,t){this.renderer=void 0,this.shadowRenderer=void 0,this.device=void 0,this.renderer=e,this.shadowRenderer=t,this.device=e.device}var t=e.prototype;return t.cull=function(e,t,i){e.visibleThisFrame=!0,e._shadowMap||(e._shadowMap=dh.create(this.device,e));var n=i._nearClip;this.generateSplitDistances(e,n,Math.min(i._farClip,e.shadowDistance));for(var s=e.shadowUpdateOverrides,r=0;r<e.numCascades&&0!==(null==s?void 0:s[r]);r++){var a=e.getRenderData(i,r),o=a.shadowCamera;o.renderTarget=e._shadowMap.renderTargets[0],a.shadowViewport.copy(e.cascades[r]),a.shadowScissor.copy(e.cascades[r]);var h=o._node,l=e._node;h.setPosition(l.getPosition()),h.setRotation(l.getRotation()),h.rotateLocal(-90,0,0);var c=0===r?n:e._shadowCascadeDistances[r-1],u=e._shadowCascadeDistances[r],d=i.getFrustumCorners(c,u);bh.set(0,0,0);for(var f=i.node.getWorldTransform(),p=0;p<8;p++)f.transformPoint(d[p],d[p]),bh.add(d[p]);bh.mulScalar(1/8);for(var m=0,_=0;_<8;_++){var g=d[_].sub(bh).length();g>m&&(m=g)}var v=h.right,y=h.up,x=h.forward,S=.25*e._shadowResolution/m,b=Math.ceil(bh.dot(y)*S)/S,w=Math.ceil(bh.dot(v)*S)/S,T=y.mulScalar(b),A=v.mulScalar(w),C=bh.dot(x),E=x.mulScalar(C);bh.add2(T,A).add(E),h.setPosition(bh),h.translateLocal(0,0,1e6),o.nearClip=.01,o.farClip=2e6,o.orthoHeight=m,this.renderer.updateCameraFrustum(o),this.shadowRenderer.cullShadowCasters(t,a.visibleCasters,o);for(var M=!0,P=a.visibleCasters,R=0;R<P.length;R++){var I=P[R];M?(M=!1,Sh.copy(I.aabb)):Sh.add(I.aabb)}wh.copy(h.getWorldTransform()).invert();var L=Ch(wh,Sh.getMin(),Sh.getMax());a.depthRangeCompensation=(L.max-L.min)/e.shadowDistance,h.translateLocal(0,0,L.max+.1),o.farClip=L.max-L.min+.2}},t.generateSplitDistances=function(e,t,i){e._shadowCascadeDistances.fill(i);for(var n=1;n<e.numCascades;n++){var s=n/e.numCascades,r=t+(i-t)*s,a=t*Math.pow(i/t,s),o=ce.lerp(r,a,e.cascadeDistribution);e._shadowCascadeDistances[n-1]=o}},t.addLightRenderPasses=function(e,t,i){for(var n,s=this,r=t.numShadowFaces,a=t.shadowUpdateOverrides,o=!0,h=0;h<r;h++)0===(null==a?void 0:a[h])&&(o=!1),n=this.shadowRenderer.prepareFace(t,i,h);var l=new ga(this.device,(function(){for(var e=0;e<r;e++)0!==(null==a?void 0:a[e])&&s.shadowRenderer.renderFace(t,i,e,!o),1===(null==a?void 0:a[e])&&(a[e]=0)}));l.after=function(){s.shadowRenderer.renderVsm(t,i)},this.shadowRenderer.setupRenderPass(l,n,o),e.addRenderPass(l)},t.buildFrameGraph=function(e,t,i){for(var n=t.directionalLights,s=0;s<n.length;s++){var r=n[s];this.shadowRenderer.needsShadowRendering(r)&&this.addLightRenderPasses(e,r,i.camera)}},e}(),Mh=new Oe,Ph=function(){function e(){}return e.lightCompare=function(e,t){return e.key-t.key},e.prepare=function(t,i,n,s){for(var r=n,a=r.length,o=[],h=new me,l=new me,c=new Ie,u=new Te,d=[],f=[],p=[],m=[],_=0;_<a;_++){var g=r[_];if(g.isStatic){var v=g.aabb;m.length=0;for(var y=1;y<=2;y++)for(var x=0;x<s.length;x++){var S=s[x];if(S._type===y&&(S.enabled&&S.mask&g.mask&&S.isStatic)){if(f[x]||(f[x]=new Ie,S._node.getWorldTransform(),S.getBoundingSphere(Mh),f[x].center.copy(Mh.center),f[x].halfExtents.set(Mh.radius,Mh.radius,Mh.radius)),!f[x].intersects(v))continue;m.push(x)}}if(0===m.length){o.push(g);continue}for(var b=g.mesh,w=b.vertexBuffer,T=b.indexBuffer[g.renderStyle],A=2===T.bytesPerIndex?new Uint16Array(T.lock()):new Uint32Array(T.lock()),C=b.primitive[g.renderStyle].count/3,E=b.primitive[g.renderStyle].base,M=w.format.elements,P=w.format.size/4,R=new Float32Array(w.storage),I=void 0,L=0;L<M.length;L++)M[L].name===lt&&(I=M[L].offset/4);d.length=C;for(var D=0;D<C;D++)d[D]=0;var O=!1;p.length=6*C;for(var k=0;k<C;k++){for(var F=Number.MAX_VALUE,B=Number.MAX_VALUE,N=Number.MAX_VALUE,U=-Number.MAX_VALUE,z=-Number.MAX_VALUE,V=-Number.MAX_VALUE,G=0;G<3;G++){var H=A[3*k+G+E],W=R[H=H*P+I],X=R[H+1],j=R[H+2];W<F&&(F=W),X<B&&(B=X),j<N&&(N=j),W>U&&(U=W),X>z&&(z=X),j>V&&(V=j)}var q=6*k;p[q]=F,p[q+1]=B,p[q+2]=N,p[q+3]=U,p[q+4]=z,p[q+5]=V}for(var Y=0;Y<m.length;Y++){var K=m[Y];u.copy(g.node.worldTransform).invert(),c.setFromTransformedAabb(f[K],u);for(var Z=c.getMin(),$=c.getMax(),Q=1<<Y,J=0;J<C;J++){var ee=6*J;p[ee]<=$.x&&p[ee+3]>=Z.x&&p[ee+1]<=$.y&&p[ee+4]>=Z.y&&p[ee+2]<=$.z&&p[ee+5]>=Z.z&&(d[J]|=Q,O=!0)}}if(O){for(var te={},ie=0;ie<C;ie++){var ne=3*ie+E,se=d[ie];te[se]||(te[se]=[]);var re=te[se];re.push(A[ne]),re.push(A[ne+1]),re.push(A[ne+2])}for(var ae in te){var oe=te[ae],he=new As(t,T.format,oe.length,T.usage);(2===he.bytesPerIndex?new Uint16Array(he.lock()):new Uint32Array(he.lock())).set(oe),he.unlock();for(var le=Number.MAX_VALUE,ce=Number.MAX_VALUE,ue=Number.MAX_VALUE,de=-Number.MAX_VALUE,fe=-Number.MAX_VALUE,pe=-Number.MAX_VALUE,_e=0;_e<oe.length;_e++){var ge=oe[_e],ve=R[ge*P+I],ye=R[ge*P+I+1],xe=R[ge*P+I+2];ve<le&&(le=ve),ye<ce&&(ce=ye),xe<ue&&(ue=xe),ve>de&&(de=ve),ye>fe&&(fe=ye),xe>pe&&(pe=xe)}h.set(le,ce,ue),l.set(de,fe,pe);var Se=new Ie;Se.setMinMax(h,l);var be=new Jr(t);be.vertexBuffer=w,be.indexBuffer[0]=he,be.primitive[0].type=4,be.primitive[0].base=0,be.primitive[0].count=oe.length,be.primitive[0].indexed=!0,be.aabb=Se;var we=new Co(be,g.material,g.node);we.isStatic=g.isStatic,we.visible=g.visible,we.layer=g.layer,we.castShadow=g.castShadow,we._receiveShadow=g._receiveShadow,we.cull=g.cull,we.pick=g.pick,we.mask=g.mask,we.parameters=g.parameters,we._shaderDefs=g._shaderDefs,we._staticSource=g,g._staticLightList?we._staticLightList=g._staticLightList:we._staticLightList=[];for(var Ae=0;Ae<m.length;Ae++){if(ae&1<<Ae){var Ce=s[m[Ae]];we._staticLightList.indexOf(Ce)<0&&we._staticLightList.push(Ce)}}we._staticLightList.sort(e.lightCompare),o.push(we)}}else o.push(g)}else o.push(g)}n.length=o.length;for(var Ee=0;Ee<o.length;Ee++)n[Ee]=o[Ee]},e.revert=function(e){for(var t,i=e,n=i.length,s=[],r=0;r<n;r++){var a=i[r];a._staticSource?a._staticSource!==t&&(s.push(a._staticSource),t=a._staticSource):s.push(a)}e.length=s.length;for(var o=0;o<s.length;o++)e[o]=s[o]},e}();function Rh(e,t){return Math.exp(-e*e/(2*t*t))}var Ih=new Te,Lh=new Te,Dh=new Float32Array(2),Oh=new ve(1,1,0,0),kh={r:1,g:2,b:3,a:4},Fh=new Te;function Bh(e){var t=e.material,i=e.skinInstance?10:0,n=0;if(t.opacityMap){var s=t.opacityMapChannel;s&&(n=kh[s])}return i+n}var Nh=function(){function e(e,t){this.shadowPassCache=[],this.device=e.device,this.renderer=e,this.lightTextureAtlas=t;var i=this.device.scope;this.polygonOffsetId=i.resolve("polygonOffset"),this.polygonOffset=new Float32Array(2),this.sourceId=i.resolve("source"),this.pixelOffsetId=i.resolve("pixelOffset"),this.weightId=i.resolve("weight[0]"),this.blurVsmShaderCode=[Sa.blurVSMPS,"#define GAUSS\n"+Sa.blurVSMPS];var n="#define PACKED\n";this.blurPackedVsmShaderCode=[n+this.blurVsmShaderCode[0],n+this.blurVsmShaderCode[1]],this.blurVsmShader=[{},{}],this.blurPackedVsmShader=[{},{}],this.blurVsmWeights={},this.shadowMapLightRadiusId=i.resolve("light_radius"),this.viewUniformFormat=null,this.viewBindGroupFormat=null,this.blendStateWrite=new yi,this.blendStateNoWrite=new yi,this.blendStateNoWrite.setColorWrite(!1,!1,!1,!1)}e.createShadowCamera=function(e,t,i,n){var s=Ko.create("ShadowCamera",i,n);return s.clearColor=t>=1&&t<=3?new ue(0,0,0,0):new ue(1,1,1,1),s.clearDepthBuffer=!0,s.clearStencilBuffer=!1,s},e.setShadowCameraSettings=function(e,t,i,n,s){var r=4===i||(5===i||0===i)&&t.supportsDepthShadow;1!==n||s||(r=!1),e.clearColorBuffer=!r};var t=e.prototype;return t.cullShadowCasters=function(e,t,i){for(var n=0,s=e.length,r=0;r<s;r++){var a=e[r];a.castShadow&&(a.cull&&!a._isVisible(i)||(a.visibleThisFrame=!0,t[n]=a,n++))}t.length=n,t.sort(this.renderer.sortCompareDepth)},t.setupRenderState=function(e,t){var i=this.renderer.scene.clusteredLightingEnabled;e.webgl2||e.isWebGPU?1!==t._type||i?(e.setDepthBias(!0),e.setDepthBiasValues(-1e3*t.shadowBias,-1e3*t.shadowBias)):e.setDepthBias(!1):e.extStandardDerivatives&&(1===t._type?(this.polygonOffset[0]=0,this.polygonOffset[1]=0,this.polygonOffsetId.setValue(this.polygonOffset)):(this.polygonOffset[0]=-1e3*t.shadowBias,this.polygonOffset[1]=-1e3*t.shadowBias,this.polygonOffsetId.setValue(this.polygonOffset)));var n=e.webgl2||e.isWebGPU,s=i?t._isPcf&&n:t._isPcf&&n&&1!==t._type;e.setBlendState(s?this.blendStateNoWrite:this.blendStateWrite),e.setDepthState(xi.DEFAULT),e.setStencilState(null,null)},t.restoreRenderState=function(e){e.webgl2||e.isWebGPU?e.setDepthBias(!1):e.extStandardDerivatives&&(this.polygonOffset[0]=0,this.polygonOffset[1]=0,this.polygonOffsetId.setValue(this.polygonOffset))},t.dispatchUniforms=function(e,t,i,n){var s=t._node;0!==e._type&&(this.renderer.dispatchViewPos(s.getPosition()),this.shadowMapLightRadiusId.setValue(e.attenuationEnd)),Ih.setTRS(s.getPosition(),s.getRotation(),me.ONE).invert(),Lh.mul2(t.projectionMatrix,Ih);var r=i.shadowViewport;t.rect=r,t.scissorRect=i.shadowScissor,Fh.setViewport(r.x,r.y,r.z,r.w),i.shadowMatrix.mul2(Fh,Lh),0===e._type&&e._shadowMatrixPalette.set(i.shadowMatrix.data,16*n)},t.getShadowPass=function(e){var t,i=e._type,n=e._shadowType,s=null==(t=this.shadowPassCache[i])?void 0:t[n];if(!s){var r="ShadowPass_"+i+"_"+n;s=Fa.get(this.device).allocate(r,{isShadow:!0,lightType:i,shadowType:n}),this.shadowPassCache[i]||(this.shadowPassCache[i]=[]),this.shadowPassCache[i][n]=s}return s.index},t.submitCasters=function(e,t){for(var i=this.device,n=this.renderer,s=n.scene,r=this.getShadowPass(t),a=e.length,o=0;o<a;o++){var h=e[o],l=h.mesh;h.ensureMaterial(i);var c=h.material;n.setBaseConstants(i,c),n.setSkinning(i,h),c.dirty&&(c.updateUniforms(i,s),c.dirty=!1),c.chunks&&(n.setupCullMode(!0,1,h),c.setParameters(i),h.setParameters(i,16));var u=h._shader[r];u||(h.updatePassShader(s,r,null,null,this.viewUniformFormat,this.viewBindGroupFormat),u=h._shader[r],h._key[1]=Bh(h)),!u.failed&&i.setShader(u),n.setVertexBuffers(i,l),n.setMorphing(i,h.morphInstance),this.renderer.setupMeshUniformBuffers(h,r);var d=h.renderStyle;i.setIndexBuffer(l.indexBuffer[d]),n.drawInstance(i,h,l,d),n._shadowDrawCalls++}},t.needsShadowRendering=function(e){var t=e.enabled&&e.castShadows&&0!==e.shadowUpdateMode&&e.visibleThisFrame;return 1===e.shadowUpdateMode&&(e.shadowUpdateMode=0),t&&(this.renderer._shadowMapUpdates+=e.numShadowFaces),t},t.getLightRenderData=function(e,t,i){return e.getRenderData(0===e._type?t:null,i)},t.setupRenderPass=function(e,t,i){var n=t.renderTarget;e.init(n),e.depthStencilOps.clearDepthValue=1,e.depthStencilOps.clearDepth=i,n.depthBuffer?e.depthStencilOps.storeDepth=!0:(e.colorOps.clearValue.copy(t.clearColor),e.colorOps.clear=i,e.depthStencilOps.storeDepth=!1),e.requiresCubemaps=!1},t.prepareFace=function(t,i,n){var s=t._type,r=t._shadowType,a=this.renderer.scene.clusteredLightingEnabled,o=this.getLightRenderData(t,i,n).shadowCamera;e.setShadowCameraSettings(o,this.device,r,s,a);var h=0===s?0:n;return o.renderTarget=t._shadowMap.renderTargets[h],o},t.renderFace=function(e,t,i,n,s){void 0===s&&(s=!0);var r=this.device,a=this.getLightRenderData(e,t,i),o=a.shadowCamera;this.dispatchUniforms(e,o,a,i);var h=o.renderTarget,l=this.renderer;l.setCameraUniforms(o,h),r.supportsUniformBuffers&&l.setupViewUniformBuffers(a.viewBindGroups,this.viewUniformFormat,this.viewBindGroupFormat,1),s?(l.setupViewport(o,h),n&&l.clear(o)):l.clearView(o,h,!0,!1),this.setupRenderState(r,e),this.submitCasters(a.visibleCasters,e),this.restoreRenderState(r)},t.render=function(e,t,i){if(void 0===i&&(i=!0),this.needsShadowRendering(e)){for(var n=e.numShadowFaces,s=0;s<n;s++)this.prepareFace(e,t,s),this.renderFace(e,t,s,!0,i);this.renderVsm(e,t)}},t.renderVsm=function(e,t){e._isVsm&&e._vsmBlurSize>1&&(this.renderer.scene.clusteredLightingEnabled&&0!==e._type||this.applyVsmBlur(e,t))},t.getVsmBlurShader=function(e,t,i){var n=(e?this.blurPackedVsmShader:this.blurVsmShader)[t][i];if(!n){this.blurVsmWeights[i]=function(e){for(var t=(e-1)/6,i=.5*(e-1),n=new Array(e),s=0,r=0;r<e;++r)n[r]=Rh(r-i,t),s+=n[r];for(var a=0;a<e;++a)n[a]/=s;return n}(i);var s=Sa.fullscreenQuadVS,r="#define SAMPLES "+i+"\n";r+=e?this.blurPackedVsmShaderCode[t]:this.blurVsmShaderCode[t];var a="blurVsm"+t+i+e;n=Ca(this.device,s,r,a),e?this.blurPackedVsmShader[t][i]=n:this.blurVsmShader[t][i]=n}return n},t.applyVsmBlur=function(e,t){var i=this.device;i.setBlendState(yi.NOBLEND);var n=e.getRenderData(0===e._type?t:null,0).shadowCamera.renderTarget,s=this.renderer.shadowMapCache.get(i,e),r=s.renderTargets[0],a=1===e._shadowType,o=e.vsmBlurMode,h=e._vsmBlurSize,l=this.getVsmBlurShader(a,o,h);Oh.z=e._shadowResolution-2,Oh.w=Oh.z,this.sourceId.setValue(n.colorBuffer),Dh[0]=1/e._shadowResolution,Dh[1]=0,this.pixelOffsetId.setValue(Dh),1===o&&this.weightId.setValue(this.blurVsmWeights[h]),Da(i,r,l,null,Oh),this.sourceId.setValue(r.colorBuffer),Dh[1]=Dh[0],Dh[0]=0,this.pixelOffsetId.setValue(Dh),Da(i,n,l,null,Oh),this.renderer.shadowMapCache.add(e,s)},t.initViewBindGroupFormat=function(){this.device.supportsUniformBuffers&&!this.viewUniformFormat&&(this.viewUniformFormat=new sn(this.device,[new nn("matrix_viewProjection",ti)]),this.viewBindGroupFormat=new ln(this.device,[new on(ai,3)],[]))},t.frameUpdate=function(){this.initViewBindGroupFormat()},e}(),Uh=0,zh=[0,0,0,0],Vh=new Te,Gh=new Te,Hh=new Te,Wh=new _e,Xh=new Oe,jh=(new Te).setScale(1,-1,1),qh=(new Te).set([1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1]),Yh=new Te,Kh=new Te,Zh=new Te,$h=new Te,Qh=new Set,Jh=function(){function e(e){this.clustersDebugRendered=!1,this.device=e,this.scene=null,this.lightTextureAtlas=new vh(e),this.shadowMapCache=new yh,this.shadowRenderer=new Nh(this,this.lightTextureAtlas),this._shadowRendererLocal=new xh(this,this.shadowRenderer),this._shadowRendererDirectional=new Eh(this,this.shadowRenderer),this._cookieRenderer=new uh(e,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.boneTextureSizeId=t.resolve("texture_poseMapSize"),this.poseMatrixId=t.resolve("matrix_pose[0]"),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.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.morphWeightsA=t.resolve("morph_weights_a"),this.morphWeightsB=t.resolve("morph_weights_b"),this.morphPositionTex=t.resolve("morphPositionTex"),this.morphNormalTex=t.resolve("morphNormalTex"),this.morphTexParams=t.resolve("morph_tex_params")}var t=e.prototype;return t.destroy=function(){this.shadowRenderer=null,this._shadowRendererLocal=null,this._shadowRendererDirectional=null,this.shadowMapCache.destroy(),this.shadowMapCache=null,this._cookieRenderer.destroy(),this._cookieRenderer=null,this.lightTextureAtlas.destroy(),this.lightTextureAtlas=null},t.sortCompare=function(e,t){if(e.layer===t.layer){if(e.drawOrder&&t.drawOrder)return e.drawOrder-t.drawOrder;if(e.zdist&&t.zdist)return t.zdist-e.zdist;if(e.zdist2&&t.zdist2)return e.zdist2-t.zdist2}return t._key[0]-e._key[0]},t.sortCompareMesh=function(e,t){if(e.layer===t.layer){if(e.drawOrder&&t.drawOrder)return e.drawOrder-t.drawOrder;if(e.zdist&&t.zdist)return t.zdist-e.zdist}var i=e._key[0],n=t._key[0];return i===n&&e.mesh&&t.mesh?t.mesh.id-e.mesh.id:n-i},t.sortCompareDepth=function(e,t){var i=e._key[1],n=t._key[1];return i===n&&e.mesh&&t.mesh?t.mesh.id-e.mesh.id:n-i},t.setupViewport=function(e,t){var i=this.device,n=t?t.width:i.width,s=t?t.height:i.height,r=e.rect,a=Math.floor(r.x*n),o=Math.floor(r.y*s),h=Math.floor(r.z*n),l=Math.floor(r.w*s);if(i.setViewport(a,o,h,l),e._scissorRectClear){var c=e.scissorRect;a=Math.floor(c.x*n),o=Math.floor(c.y*s),h=Math.floor(c.z*n),l=Math.floor(c.w*s)}i.setScissor(a,o,h,l)},t.setCameraUniforms=function(e,t){var i=null==t?void 0:t.flipY,n=1;if(e.xr&&e.xr.session){var s,r=e._node.parent;r&&(s=r.getWorldTransform());var a=e.xr.views;n=a.length;for(var o=0;o<n;o++){var h=a[o];r?(h.viewInvOffMat.mul2(s,h.viewInvMat),h.viewOffMat.copy(h.viewInvOffMat).invert()):(h.viewInvOffMat.copy(h.viewInvMat),h.viewOffMat.copy(h.viewMat)),h.viewMat3.setFromMat4(h.viewOffMat),h.projViewOffMat.mul2(h.projMat,h.viewOffMat),h.position[0]=h.viewInvOffMat.data[12],h.position[1]=h.viewInvOffMat.data[13],h.position[2]=h.viewInvOffMat.data[14],e.frustum.setFromMat4(h.projViewOffMat)}}else{var l=e.projectionMatrix;e.calculateProjection&&e.calculateProjection(l,0);var c=e.getProjectionMatrixSkybox();if(i&&(l=Yh.mul2(jh,l),c=Kh.mul2(jh,c)),this.device.isWebGPU&&(l=Zh.mul2(qh,l),c=$h.mul2(qh,c)),this.projId.setValue(l.data),this.projSkyboxId.setValue(c.data),e.calculateTransform)e.calculateTransform(Gh,0);else{var u=e._node.getPosition(),d=e._node.getRotation();Gh.setTRS(u,d,me.ONE)}this.viewInvId.setValue(Gh.data),Hh.copy(Gh).invert(),this.viewId.setValue(Hh.data),Wh.setFromMat4(Hh),this.viewId3.setValue(Wh.data),Vh.mul2(l,Hh),this.viewProjId.setValue(Vh.data),this.flipYId.setValue(i?-1:1),this.dispatchViewPos(e._node.getPosition()),e.frustum.setFromMat4(Vh)}this.tbnBasis.setValue(i?-1:1);var f=e._nearClip,p=e._farClip;return this.nearClipId.setValue(f),this.farClipId.setValue(p),this.cameraParams[0]=1/p,this.cameraParams[1]=p,this.cameraParams[2]=f,this.cameraParams[3]=1===e.projection?1:0,this.cameraParamsId.setValue(this.cameraParams),this.exposureId.setValue(this.scene.physicalUnits?e.getExposure():this.scene.exposure),n},t.clear=function(e,t,i,n){var s=((null!=t?t:e._clearColorBuffer)?1:0)|((null!=i?i:e._clearDepthBuffer)?2:0)|((null!=n?n:e._clearStencilBuffer)?4:0);s&&this.device.clear({color:[e._clearColor.r,e._clearColor.g,e._clearColor.b,e._clearColor.a],depth:e._clearDepth,stencil:e._clearStencil,flags:s})},t.setCamera=function(e,t,i,n){this.setCameraUniforms(e,t),this.clearView(e,t,i,!1)},t.clearView=function(e,t,i,n){var s=this.device;if(s.setRenderTarget(t),s.updateBegin(),n&&(s.setColorWrite(!0,!0,!0,!0),s.setDepthWrite(!0)),this.setupViewport(e,t),i){var r=e._clearOptions;s.clear(r||{color:[e._clearColor.r,e._clearColor.g,e._clearColor.b,e._clearColor.a],depth:e._clearDepth,flags:(e._clearColorBuffer?1:0)|(e._clearDepthBuffer?2:0)|(e._clearStencilBuffer?4:0),stencil:e._clearStencil})}},t.setupCullMode=function(e,t,i){var n=i.material,s=0;if(e){var r=1;2!==n.cull&&1!==n.cull||(r=t*i.flipFacesFactor*i.node.worldScaleSign),s=r<0?2===n.cull?1:2:n.cull}this.device.setCullMode(s),0===s&&0===n.cull&&this.twoSidedLightingNegScaleFactorId.setValue(i.node.worldScaleSign)},t.updateCameraFrustum=function(e){if(e.xr&&e.xr.views.length){var t=e.xr.views[0];return Vh.mul2(t.projMat,t.viewOffMat),void e.frustum.setFromMat4(Vh)}var i=e.projectionMatrix;if(e.calculateProjection&&e.calculateProjection(i,0),e.calculateTransform)e.calculateTransform(Gh,0);else{var n=e._node.getPosition(),s=e._node.getRotation();Gh.setTRS(n,s,me.ONE),this.viewInvId.setValue(Gh.data)}Hh.copy(Gh).invert(),Vh.mul2(i,Hh),e.frustum.setFromMat4(Vh)},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){Uh++;var t=e.length;if(0!==t)for(var i=0;i<t;i++){var n=e[i].skinInstance;n&&(n.updateMatrices(e[i].node,Uh),n._dirty=!0)}},t.updateGpuSkinMatrices=function(e){for(var t=e.length,i=0;i<t;i++){var n=e[i];if(n.visibleThisFrame){var s=n.skinInstance;s&&s._dirty&&(s.updateMatrixPalette(n.node,Uh),s._dirty=!1)}}},t.updateMorphing=function(e){for(var t=e.length,i=0;i<t;i++){var n=e[i],s=n.morphInstance;s&&s._dirty&&n.visibleThisFrame&&s.update()}},t.gpuUpdate=function(e){this.updateGpuSkinMatrices(e),this.updateMorphing(e)},t.setVertexBuffers=function(e,t){e.setVertexBuffer(t.vertexBuffer)},t.setMorphing=function(e,t){if(t)if(t.morph.useTextureMorph)e.setVertexBuffer(t.morph.vertexBufferIds),this.morphPositionTex.setValue(t.texturePositions),this.morphNormalTex.setValue(t.textureNormals),this.morphTexParams.setValue(t._textureParams);else{for(var i=0;i<t._activeVertexBuffers.length;i++){var n=t._activeVertexBuffers[i];if(n){var s=Tt+(i+8);n.format.elements[0].name=s,n.format.elements[0].scopeId=e.scope.resolve(s),n.format.update(),e.setVertexBuffer(n)}}this.morphWeightsA.setValue(t._shaderMorphWeightsA),this.morphWeightsB.setValue(t._shaderMorphWeightsB)}},t.setSkinning=function(e,t){if(t.skinInstance)if(this._skinDrawCalls++,e.supportsBoneTextures){var i=t.skinInstance.boneTexture;this.boneTextureId.setValue(i),zh[0]=i.width,zh[1]=i.height,zh[2]=1/i.width,zh[3]=1/i.height,this.boneTextureSizeId.setValue(zh)}else this.poseMatrixId.setValue(t.skinInstance.matrixPalette)},t.dispatchViewPos=function(e){var t=this.viewPos;t[0]=e.x,t[1]=e.y,t[2]=e.z,this.viewPosId.setValue(t)},t.initViewBindGroupFormat=function(){this.device.supportsUniformBuffers&&!this.viewUniformFormat&&(this.viewUniformFormat=new sn(this.device,[new nn("matrix_viewProjection",ti)]),this.viewBindGroupFormat=new ln(this.device,[new on(ai,3)],[new hn("lightsTextureFloat",2,jt,1),new hn("lightsTexture8",2,jt,1)]))},t.setupViewUniformBuffers=function(e,t,i,n){for(var s=this.device;e.length<n;){var r=new Gn(s,t),a=new zn(s,i,r);e.push(a)}var o=e[0];o.defaultUniformBuffer.update(),o.update(),s.setBindGroup(1,o)},t.setupMeshUniformBuffers=function(e,t){var i=this.device;if(i.supportsUniformBuffers){this.modelMatrixId.setValue(e.node.worldTransform.data),this.normalMatrixId.setValue(e.node.normalMatrix.data);var n=e.getBindGroup(i,t);n.defaultUniformBuffer.update(),n.update(),i.setBindGroup(0,n)}},t.drawInstance=function(e,t,i,n,s){var r=t.instancingData;if(r)r.count>0&&(this._instancedDrawCalls++,e.setVertexBuffer(r.vertexBuffer),e.draw(i.primitive[n],r.count));else{var a=t.node.worldTransform;this.modelMatrixId.setValue(a.data),s&&this.normalMatrixId.setValue(t.node.normalMatrix.data),e.draw(i.primitive[n])}},t.drawInstance2=function(e,t,i,n){var s=t.instancingData;s?s.count>0&&(this._instancedDrawCalls++,e.draw(i.primitive[n],s.count,!0)):e.draw(i.primitive[n],void 0,!0)},t.cull=function(e,t,i){var n=0,s=t.length,r=e.cullingMask||4294967295;if(!e.frustumCulling){for(var a=0;a<s;a++){var o=t[a];(o.visible||o.command)&&(o.mask&&0==(o.mask&r)||(i[n]=o,n++,o.visibleThisFrame=!0))}return n}for(var h=0;h<s;h++){var l=t[h];if(l.command)i[n]=l,n++,l.visibleThisFrame=!0;else{if(!l.visible)continue;var c=!0;if(l.mask&&0==(l.mask&r))continue;l.cull&&(c=l._isVisible(e)),c&&(i[n]=l,n++,l.visibleThisFrame=!0)}}return n},t.cullLights=function(e,t){for(var i=this.scene.clusteredLightingEnabled,n=this.scene.physicalUnits,s=0;s<t.length;s++){var r=t[s];if(r.enabled)if(0!==r._type)if(r.getBoundingSphere(Xh),e.frustum.containsSphere(Xh)){r.visibleThisFrame=!0,r.usePhysicalUnits=n;var a=e.getScreenSize(Xh);r.maxScreenSize=Math.max(r.maxScreenSize,a)}else i||r.castShadows&&!r.shadowMap&&(r.visibleThisFrame=!0);else r.usePhysicalUnits=this.scene.physicalUnits}},t.cullShadowmaps=function(e){for(var t=this.scene.clusteredLightingEnabled,i=0;i<e._lights.length;i++){var n=e._lights[i];if(0!==n._type&&(t&&n.atlasSlotUpdated&&0===n.shadowUpdateMode&&(n.shadowUpdateMode=1),n.visibleThisFrame&&n.castShadows&&0!==n.shadowUpdateMode)){var s=e._lightCompositionData[i].shadowCastersList;this._shadowRendererLocal.cull(n,s)}}for(var r=e._renderActions,a=0;a<r.length;a++)for(var o=r[a],h=o.directionalLightsIndices.length,l=0;l<h;l++){var c=o.directionalLightsIndices[l],u=e._lights[c],d=e._lightCompositionData[c].shadowCastersList;this._shadowRendererDirectional.cull(u,d,o.camera.camera)}},t.cullComposition=function(e){for(var t=e._renderActions,i=0;i<t.length;i++){var n=t[i],s=n.layerIndex,r=e.layerList[s];if(r.enabled&&e.subLayerEnabled[s]){var a=e.subLayerList[s],o=n.cameraIndex,h=r.cameras[o];if(h){h.frameUpdate(n.renderTarget),n.firstCameraUse&&(this.updateCameraFrustum(h.camera),this._camerasRendered++),this.cullLights(h.camera,r._lights);var l=r.instances,c=a?l.visibleTransparent[o]:l.visibleOpaque[o];if(!c.done){r.onPreCull&&r.onPreCull(o);var u=a?r.transparentMeshInstances:r.opaqueMeshInstances;c.length=this.cull(h.camera,u,c.list),c.done=!0,r.onPostCull&&r.onPostCull(o)}}}}this.scene.clusteredLightingEnabled&&this.updateLightTextureAtlas(e),this.cullShadowmaps(e)},t.updateShaders=function(e,t){for(var i=e.length,n=0;n<i;n++){var s=e[n].material;if(s&&!Qh.has(s)&&(Qh.add(s),s.getShaderVariant!==Ya.prototype.getShaderVariant)){if(t&&(!s.useLighting||s.emitter&&!s.emitter.lighting))continue;s.clearVariants()}}Qh.clear()},t.renderCookies=function(e){for(var t=this.lightTextureAtlas.cookieRenderTarget,i=0;i<e.length;i++){var n=e[i];n.atlasViewportAllocated&&(n.atlasSlotUpdated&&this._cookieRenderer.render(n,t))}},t.beginFrame=function(e,t){var i=e._meshInstances,n=this.scene;if(n.updateShaders||t){var s=!n.updateShaders&&t;this.updateShaders(i,s),n.updateShaders=!1,n._shaderVersion++}this.updateCpuSkinMatrices(i);for(var r=i.length,a=0;a<r;a++)i[a].visibleThisFrame=!1;for(var o=e._lights,h=o.length,l=0;l<h;l++)o[l].beginFrame()},t.updateLightTextureAtlas=function(e){this.lightTextureAtlas.update(e._splitLights[2],e._splitLights[1],this.scene.lighting)},t.updateClusters=function(e){for(var t=e.getEmptyWorldClusters(this.device),i=e._renderActions,n=0;n<i.length;n++){var s=i[n],r=s.lightClusters;if(r&&r!==t&&!Qh.has(r)){Qh.add(r);var a=e.layerList[s.layerIndex];r.update(a.clusteredLightsSet,this.scene.gammaCorrection,this.scene.lighting)}}Qh.clear()},t.updateLayerComposition=function(e,t){for(var i=e.layerList.length,n=0;n<i;n++)e.layerList[n]._postRenderCounter=0;for(var s=this.scene,r=s._shaderVersion,a=0;a<i;a++){var o=e.layerList[a];o._shaderVersion=r,o._preRenderCalledForCameras=0,o._postRenderCalledForCameras=0;var h=e.subLayerList[a];o._postRenderCounter|=h?2:1,o._postRenderCounterMax=o._postRenderCounter;for(var l=0;l<o.cameras.length;l++)o.instances.prepare(l);o._needsStaticPrepare&&o._staticLightHash&&!this.scene.clusteredLightingEnabled&&(o._staticPrepareDone&&(Ph.revert(o.opaqueMeshInstances),Ph.revert(o.transparentMeshInstances)),Ph.prepare(this.device,s,o.opaqueMeshInstances,o._lights),Ph.prepare(this.device,s,o.transparentMeshInstances,o._lights),e._dirty=!0,s.updateShaders=!0,o._needsStaticPrepare=!1,o._staticPrepareDone=!0)}return e._update(this.device,t)},t.frameUpdate=function(){this.clustersDebugRendered=!1,this.initViewBindGroupFormat()},e}(),el=2.399963229728653,tl=function(e,t,i){var n=t*el,s=Math.sqrt(t)/Math.sqrt(i);e.x=s*Math.cos(n),e.y=s*Math.sin(n)},il=function(e,t,i,n,s){void 0===n&&(n=0),void 0===s&&(s=1),n=1-2*n,s=1-2*s;var r=ce.lerp(n,s,t/i),a=Math.sqrt(1-r*r),o=el*t;e.x=Math.cos(o)*a,e.y=r,e.z=Math.sin(o)*a},nl=function(e){var t=(e<<16|e>>>16)>>>0;return 2.3283064365386963e-10*(t=((16711935&(t=((252645135&(t=((858993459&(t=((1431655765&t)<<1|(2863311530&t)>>>1)>>>0))<<2|(3435973836&t)>>>2)>>>0))<<4|(4042322160&t)>>>4)>>>0))<<8|(4278255360&t)>>>8)>>>0)},sl={linear:"decodeLinear",srgb:"decodeGamma",rgbm:"decodeRGBM",rgbe:"decodeRGBE",rgbp:"decodeRGBP"},rl={linear:"encodeLinear",srgb:"encodeGamma",rgbm:"encodeRGBM",rgbe:"encodeRGBE",rgbp:"encodeRGBP"},al=function(){function e(){}return e.decodeFunc=function(e){return sl[e]||"decodeGamma"},e.encodeFunc=function(e){return rl[e]||"encodeGamma"},e}(),ol=function(e){switch(e){case $t:return"Cubemap";case Jt:return"Octahedral";default:return"Equirect"}},hl=function(e,t,i){if(e<=0)t[i+0]=0,t[i+1]=0,t[i+2]=0,t[i+3]=0;else if(e>=1)t[i+0]=255,t[i+1]=0,t[i+2]=0,t[i+3]=0;else{var n=1*e%1,s=255*e%1,r=65025*e%1,a=16581375*e%1;n-=s/255,s-=r/255,r-=a/255,t[i+0]=Math.min(255,Math.floor(256*n)),t[i+1]=Math.min(255,Math.floor(256*s)),t[i+2]=Math.min(255,Math.floor(256*r)),t[i+3]=Math.min(255,Math.floor(256*a))}},ll=function(e,t,i,n){var s=2*i*Math.PI,r=Math.pow(1-t,1/(n+1)),a=Math.sqrt(1-r*r);e.set(Math.cos(s)*a,Math.sin(s)*a,r).normalize()},cl=function(e,t,i){var n=2*i*Math.PI,s=Math.sqrt(1-t),r=Math.sqrt(t);e.set(Math.cos(n)*r,Math.sin(n)*r,s).normalize()},ul=function(e,t,i,n){var s=2*i*Math.PI,r=Math.sqrt((1-t)/(1+(n*n-1)*t)),a=Math.sqrt(1-r*r);e.set(Math.cos(s)*a,Math.sin(s)*a,r).normalize()},dl=function(e,t){var i=e*t,n=t/(1-e*e+i*i);return n*n*(1/Math.PI)},fl={16:{2:26,8:20,32:17,128:16,512:16},32:{2:53,8:40,32:34,128:32,512:32},128:{2:214,8:163,32:139,128:130,512:128},1024:{2:1722,8:1310,32:1114,128:1041,512:1025}},pl=function(e,t,i){for(var n=i/e,s=1-Math.log2(t)/11,r=s*s,a=new me,o=new me,h=new me(0,0,1),l=[],c=function(e,t){var i=fl[e];return i&&i[t]||e}(e,t),u=0;u<c;++u){ul(a,u/c,nl(u),r);var d=a.z;if(o.set(a.x,a.y,a.z).mulScalar(2*d).sub(h),o.z>0){var f=dl(Math.min(1,d),r)/4+.001,p=.5*Math.log2(n/f);l.push(o.x,o.y,o.z,p)}}for(;l.length<4*e;)l.push(0,0,0,0);return l},ml=function(e,t,i){var n=function(e){for(var t=e.length,i=Math.min(t,512),n=Math.ceil(t/i),s=new Uint8Array(i*n*4),r=0,a=0;a<t;a+=4)hl(.5*e[a+0]+.5,s,r+0),hl(.5*e[a+1]+.5,s,r+4),hl(.5*e[a+2]+.5,s,r+8),hl(e[a+3]/8,s,r+12),r+=16;return{width:i,height:n,data:s}}(i);return new Yn(e,{name:t,width:n.width,height:n.height,mipmaps:!1,minFilter:0,magFilter:0,levels:[n.data]})},_l=function(){function e(e){void 0===e&&(e=!0),this.map=new Map,this.destroyContent=e}var t=e.prototype;return t.destroy=function(){this.destroyContent&&this.map.forEach((function(e,t){e.destroy()}))},t.get=function(e,t){if(!this.map.has(e)){var i=t();return this.map.set(e,i),i}return this.map.get(e)},e}(),gl=new _l(!1),vl=new Jn,yl=function(e,t,i){return vl.get(e,(function(){return new _l})).get(t,(function(){return ml(e,t,gl.get(t,i))}))},xl=function(e,t,i){return yl(e,"lambert-samples-"+t+"-"+i,(function(){return function(e,t){for(var i=t/e,n=new me,s=[],r=0;r<e;++r){cl(n,r/e,nl(r));var a=n.z/Math.PI,o=.5*Math.log2(i/a);s.push(n.x,n.y,n.z,o)}return s}(t,i)}))},Sl=function(e,t,i){return yl(e,"phong-samples-"+t+"-"+i,(function(){return function(e,t){for(var i=new me,n=[],s=0;s<e;++s)ll(i,s/e,nl(s),t),n.push(i.x,i.y,i.z,0);return n}(t,i)}))},bl=function(e,t,i,n){return yl(e,"ggx-samples-"+t+"-"+i+"-"+n,(function(){return pl(t,i,n)}))},wl="\nattribute vec2 vertex_position;\n\nuniform vec4 uvMod;\n\nvarying vec2 vUv0;\n\nvoid main(void) {\n gl_Position = vec4(vertex_position, 0.5, 1.0);\n vUv0 = getImageEffectUV((vertex_position.xy * 0.5 + 0.5) * uvMod.xy + uvMod.zw);\n}\n";function Tl(e,t,i){var n;void 0===i&&(i={}),e instanceof Ii&&(e=arguments[1],t=arguments[2],i={},void 0!==arguments[3]&&(i.specularPower=arguments[3]),void 0!==arguments[4]&&(i.numSamples=arguments[4]));var s={none:"reproject",lambert:"prefilterSamplesUnweighted",phong:"prefilterSamplesUnweighted",ggx:"prefilterSamples"},r=i.hasOwnProperty("specularPower")?i.specularPower:1,a=i.hasOwnProperty("face")?i.face:null,o=i.hasOwnProperty("distribution")?i.distribution:1===r?"none":"phong",h=s[o]||"reproject",l=h.startsWith("prefilterSamples"),c=al.decodeFunc(e.encoding),u=al.encodeFunc(t.encoding),d="sample"+ol(e.projection),f="getDirection"+ol(t.projection),p=i.hasOwnProperty("numSamples")?i.numSamples:1024,m=h+"_"+c+"_"+u+"_"+d+"_"+f+"_"+p,_=e.device,g=wa(_).getCachedShader(m);if(!g){var v="#define PROCESS_FUNC "+h+"\n"+(l?"#define USE_SAMPLES_TEX\n":"")+(e.cubemap?"#define CUBEMAP_SOURCE\n":"")+"#define DECODE_FUNC "+c+"\n#define ENCODE_FUNC "+u+"\n#define SOURCE_FUNC "+d+"\n#define TARGET_FUNC "+f+"\n#define NUM_SAMPLES "+p+"\n#define NUM_SAMPLES_SQRT "+Math.round(Math.sqrt(p)).toFixed(1)+"\n";g=Ca(_,wl,v+"\n"+Sa.reprojectPS,m)}_.setBlendState(yi.NOBLEND);var y=_.scope.resolve(e.cubemap?"sourceCube":"sourceTex");y.setValue(e);var x=_.scope.resolve("params"),S=_.scope.resolve("params2"),b=_.scope.resolve("uvMod");if(null!=(n=i)&&n.seamPixels){var w=i.seamPixels,T=i.rect?i.rect.z:t.width,A=i.rect?i.rect.w:t.height,C=T-2*w,E=A-2*w;b.setValue([(C+2*w)/C,(E+2*w)/E,-w/C,-w/E])}else b.setValue([1,1,0,0]);var M=[0,r,e.fixCubemapSeams?1/e.width:0,t.fixCubemapSeams?1/t.width:0],P=[t.width*t.height*(t.cubemap?6:1),e.width*e.height*(e.cubemap?6:1)];if(l){var R=e.width*e.height*(e.cubemap?6:1),I="ggx"===o?bl(_,p,r,R):"lambert"===o?xl(_,p,R):Sl(_,p,r);_.scope.resolve("samplesTex").setValue(I),_.scope.resolve("samplesTexInverseSize").setValue([1/I.width,1/I.height])}for(var L=0;L<(t.cubemap?6:1);L++)if(null===a||L===a){var D,O=new Di({colorBuffer:t,face:L,depth:!1});M[0]=L,x.setValue(M),S.setValue(P),Da(_,O,g,null==(D=i)?void 0:D.rect),O.destroy()}}var Al=function(e,t){return void 0===t&&(t=0),1+Math.floor(Math.log2(Math.max(e,t)))},Cl=function(){function e(){}return e.generateSkyboxCubemap=function(e,t){var i=function(e,t,i,n){return new Yn(e,{name:"lighting-"+t,cubemap:!0,width:t,height:t,format:i,type:7===i?Wt:Vt,addressU:1,addressV:1,fixCubemapSeams:!0,mipmaps:!!n})}(e.device,t||(e.cubemap?e.width:e.width/4),7,!1);return Tl(e,i,{numSamples:1024}),i},e.generateLightingSource=function(e,t){var i=e.device,n=function(e){return function(e){return e.extTextureHalfFloat&&e.textureHalfFloatRenderable}(e)?Ye:function(e){return e.extTextureFloat&&e.textureFloatRenderable}(e)?Ze:7}(i),s=(null==t?void 0:t.target)||new Yn(i,{name:"lighting-source",cubemap:!0,width:(null==t?void 0:t.size)||128,height:(null==t?void 0:t.size)||128,format:n,type:7===n?Wt:Vt,addressU:1,addressV:1,fixCubemapSeams:!1,mipmaps:!0});return Tl(e,s,{numSamples:e.mipmaps?1:1024}),s},e.generateAtlas=function(e,t){for(var i=e.device,n=(null==t?void 0:t.target)||new Yn(i,{name:"envAtlas",width:(null==t?void 0:t.size)||512,height:(null==t?void 0:t.size)||512,format:7,type:Wt,projection:Qt,addressU:1,addressV:1,mipmaps:!1}),s=n.width/512,r=new ve(0,0,512*s,256*s),a=Al(256)-Al(4),o=0;o<a;++o)Tl(e,n,{numSamples:1,rect:r,seamPixels:s}),r.x+=r.w,r.y+=r.w,r.z=Math.max(1,Math.floor(.5*r.z)),r.w=Math.max(1,Math.floor(.5*r.w));r.set(0,256*s,256*s,128*s);for(var h=1;h<7;++h)Tl(e,n,{numSamples:(null==t?void 0:t.numReflectionSamples)||1024,distribution:(null==t?void 0:t.distribution)||"ggx",specularPower:Math.max(1,2048>>2*h),rect:r,seamPixels:s}),r.y+=r.w,r.z=Math.max(1,Math.floor(.5*r.z)),r.w=Math.max(1,Math.floor(.5*r.w));return r.set(128*s,384*s,64*s,32*s),Tl(e,n,{numSamples:(null==t?void 0:t.numAmbientSamples)||2048,distribution:"lambert",rect:r,seamPixels:s}),n},e.generatePrefilteredAtlas=function(e,t){for(var i=e[0].device,n=e[0].format,s=e[0].type,r=(null==t?void 0:t.target)||new Yn(i,{name:"envPrefilteredAtlas",width:(null==t?void 0:t.size)||512,height:(null==t?void 0:t.size)||512,format:n,type:s,projection:Qt,addressU:1,addressV:1,mipmaps:!1}),a=r.width/512,o=new ve(0,0,512*a,256*a),h=Al(512),l=0;l<h;++l)Tl(e[0],r,{numSamples:1,rect:o,seamPixels:a}),o.x+=o.w,o.y+=o.w,o.z=Math.max(1,Math.floor(.5*o.z)),o.w=Math.max(1,Math.floor(.5*o.w));o.set(0,256*a,256*a,128*a);for(var c=1;c<e.length;++c)Tl(e[c],r,{numSamples:1,rect:o,seamPixels:a}),o.y+=o.w,o.z=Math.max(1,Math.floor(.5*o.z)),o.w=Math.max(1,Math.floor(.5*o.w));return o.set(128*a,384*a,64*a,32*a),null!=t&&t.legacyAmbient?Tl(e[5],r,{numSamples:1,rect:o,seamPixels:a}):Tl(e[0],r,{numSamples:(null==t?void 0:t.numSamples)||2048,distribution:"lambert",rect:o,seamPixels:a}),r},e}(),El=function(){function e(){this.code=""}var t=e.prototype;return t.append=function(){for(var e=this,t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];i.forEach((function(t){t.endsWith("\n")?e.code+=t:e.code+=t+"\n"}))},t.prepend=function(){for(var e=this,t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];i.forEach((function(t){t.endsWith("\n")?e.code=t+e.code:e.code=t+"\n"+e.code}))},e}(),Ml={vertex_normal:ct,vertex_tangent:ut,vertex_texCoord0:_t,vertex_texCoord1:gt,vertex_color:pt,vertex_boneWeights:dt,vertex_boneIndices:ft},Pl={vVertexColor:"vec4",vPositionW:"vec3",vNormalV:"vec3",vNormalW:"vec3",vTangentW:"vec3",vBinormalW:"vec3",vObjectSpaceUpW:"vec3",vUv0:"vec2",vUv1:"vec2"},Rl=function(){function e(e,t){if(this.device=e,this.options=t,this.attributes={vertex_position:lt},t.chunks){this.chunks={};var i=t.chunks;for(var n in Sa)if(i.hasOwnProperty(n)){var s=i[n];for(var r in Ml)Ml.hasOwnProperty(r)&&s.indexOf(r)>=0&&(this.attributes[r]=Ml[r]);this.chunks[n]=s}else this.chunks[n]=Sa[n]}else this.chunks=Sa;this.shaderPassInfo=Fa.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,this.needsNormal=this.lighting||this.reflections||t.useSpecular||t.ambientSH||t.heightMapEnabled||t.enableGGXSpecular||t.clusteredLightingEnabled&&!this.shadowPass||t.clearCoatNormalMapEnabled,this.needsNormal=this.needsNormal&&!this.shadowPass,this.needsSceneColor=t.useDynamicRefraction,this.needsScreenSize=t.useDynamicRefraction,this.needsTransforms=t.useDynamicRefraction,this.varyings="",this.varyingDefines="",this.vshader=null,this.frontendDecl=null,this.frontendCode=null,this.frontendFunc=null,this.lightingUv=null,this.defines=[],this.fshader=null}var t=e.prototype;return t._vsAddBaseCode=function(e,t,i){return e+=t.baseVS,1!==i.nineSlicedMode&&2!==i.nineSlicedMode||(e+=t.baseNineSlicedVS),e},t._vsAddTransformCode=function(e,t,i,n){return e+=this.chunks.transformVS},t._setMapTransform=function(e,t,i,n){var s=i+100*n;if(!e[3][s]){var r="texture_"+t+"MapTransform";e[0]+="uniform vec3 "+r+"0;\n",e[0]+="uniform vec3 "+r+"1;\n",e[1]+="varying vec2 vUV"+n+"_"+i+";\n",e[2]+=" vUV"+n+"_"+i+" = vec2(dot(vec3(uv"+n+", 1), "+r+"0), dot(vec3(uv"+n+", 1), "+r+"1));\n",e[3][s]=!0}return e},t._fsGetBaseCode=function(){var e=this.options,t=this.chunks,i=this.chunks.basePS;return 1===e.nineSlicedMode?i+=t.baseNineSlicedPS:2===e.nineSlicedMode&&(i+=t.baseNineSlicedTiledPS),i},t._fsGetStartCode=function(e,t,i,n){var s=i.startPS;return 1===n.nineSlicedMode?s+=i.startNineSlicedPS:2===n.nineSlicedMode&&(s+=i.startNineSlicedTiledPS),s},t._getLightSourceShapeString=function(e){switch(e){case 1:return"Rect";case 2:return"Disk";case 3:return"Sphere";default:return""}},t.generateVertexShader=function(e,t,i){var n=this,s=this.device,r=this.options,a=this.chunks,o="",h="";o=this._vsAddBaseCode(o,a,r),h+=" vPositionW = getWorldPosition();\n",2===this.options.pass&&(o+="varying float vDepth;\n",o+="#ifndef VIEWMATRIX\n",o+="#define VIEWMATRIX\n",o+="uniform mat4 matrix_view;\n",o+="#endif\n",o+="#ifndef CAMERAPLANES\n",o+="#define CAMERAPLANES\n",o+="uniform vec4 camera_params;\n\n",o+="#endif\n",h+=" vDepth = -(matrix_view * vec4(vPositionW,1.0)).z * camera_params.x;\n"),this.options.useInstancing&&(this.attributes.instance_line1=Bt,this.attributes.instance_line2=Nt,this.attributes.instance_line3=Ut,this.attributes.instance_line4=zt,o+=a.instancingVS),this.needsNormal&&(this.attributes.vertex_normal=ct,h+=" vNormalW = getNormal();\n","sphereMap"===r.reflectionSource&&s.fragmentUniformsCount<=16&&(o+=a.viewNormalVS,h+=" vNormalV = getViewNormal();\n"),r.hasTangents&&(r.heightMapEnabled||r.normalMapEnabled||r.enableGGXSpecular)?(this.attributes.vertex_tangent=ut,o+=a.tangentBinormalVS,h+=" vTangentW = getTangent();\n",h+=" vBinormalW = getBinormal();\n"):!r.enableGGXSpecular&&s.extStandardDerivatives||(h+=" vObjectSpaceUpW = normalize(dNormalMatrix * vec3(0, 1, 0));\n"));for(var l=0;l<2;l++)e[l]&&(this.attributes["vertex_texCoord"+l]="TEXCOORD"+l,o+=a["uv"+l+"VS"],h+=" vec2 uv"+l+" = getUv"+l+"();\n"),t[l]&&(h+=" vUv"+l+" = uv"+l+";\n");var c=[o,this.varyings,h,[]];if(i.forEach((function(e){n._setMapTransform(c,e.name,e.id,e.uv)})),o=c[0],this.varyings=c[1],h=c[2],r.vertexColors&&(this.attributes.vertex_color=pt,h+=" vVertexColor = vertex_color;\n"),r.useMsdf&&r.msdfTextAttribute&&(this.attributes.vertex_outlineParameters=Dt,this.attributes.vertex_shadowParameters=Ot,h+=" unpackMsdfParams();\n",o+=a.msdfVS),r.useMorphPosition||r.useMorphNormal)if(r.useMorphTextureBased){o+="#define MORPHING_TEXTURE_BASED\n",r.useMorphPosition&&(o+="#define MORPHING_TEXTURE_BASED_POSITION\n"),r.useMorphNormal&&(o+="#define MORPHING_TEXTURE_BASED_NORMAL\n"),this.attributes.morph_vertex_id=zt;var u=s.isWebGPU?"uint":"float";o+="attribute "+u+" morph_vertex_id;\n"}else o+="#define MORPHING\n",r.useMorphPosition?(this.attributes.morph_pos0=Dt,this.attributes.morph_pos1=Ot,this.attributes.morph_pos2=kt,this.attributes.morph_pos3=Ft,o+="#define MORPHING_POS03\n",o+="attribute vec3 morph_pos0;\n",o+="attribute vec3 morph_pos1;\n",o+="attribute vec3 morph_pos2;\n",o+="attribute vec3 morph_pos3;\n"):r.useMorphNormal&&(this.attributes.morph_nrm0=Dt,this.attributes.morph_nrm1=Ot,this.attributes.morph_nrm2=kt,this.attributes.morph_nrm3=Ft,o+="#define MORPHING_NRM03\n",o+="attribute vec3 morph_nrm0;\n",o+="attribute vec3 morph_nrm1;\n",o+="attribute vec3 morph_nrm2;\n",o+="attribute vec3 morph_nrm3;\n"),r.useMorphNormal?(this.attributes.morph_nrm4=Bt,this.attributes.morph_nrm5=Nt,this.attributes.morph_nrm6=Ut,this.attributes.morph_nrm7=zt,o+="#define MORPHING_NRM47\n",o+="attribute vec3 morph_nrm4;\n",o+="attribute vec3 morph_nrm5;\n",o+="attribute vec3 morph_nrm6;\n",o+="attribute vec3 morph_nrm7;\n"):(this.attributes.morph_pos4=Bt,this.attributes.morph_pos5=Nt,this.attributes.morph_pos6=Ut,this.attributes.morph_pos7=zt,o+="#define MORPHING_POS47\n",o+="attribute vec3 morph_pos4;\n",o+="attribute vec3 morph_pos5;\n",o+="attribute vec3 morph_pos6;\n",o+="attribute vec3 morph_pos7;\n");r.skin?(this.attributes.vertex_boneWeights=dt,this.attributes.vertex_boneIndices=ft,o+=za(s,a),o+="#define SKIN\n"):r.useInstancing&&(o+="#define INSTANCING\n"),r.screenSpace&&(o+="#define SCREENSPACE\n"),r.pixelSnap&&(o+="#define PIXELSNAP\n"),o=this._vsAddTransformCode(o,s,a,r),this.needsNormal&&(o+=a.normalVS),o+="\n",o+=a.startVS,o+=h,o+=a.endVS,o+="}",Object.keys(Pl).forEach((function(e){o.indexOf(e)>=0&&(n.varyings+="varying "+Pl[e]+" "+e+";\n",n.varyingDefines+="#define VARYING_"+e.toUpperCase()+"\n")}));var d=this.shaderPassInfo.shaderDefines;this.vshader=d+this.varyings+o},t._fsGetBeginCode=function(){for(var e=this.shaderPassInfo.shaderDefines,t=0;t<this.defines.length;t++)e+="#define "+this.defines[t]+"\n";return e},t._fsGetPickPassCode=function(){var e=this._fsGetBeginCode();return e+="uniform vec4 uColor;\n",e+=this.varyings,e+=this.varyingDefines,e+=this.frontendDecl,e+=this.frontendCode,e+="void main(void)\n{\n",e+=this.frontendFunc,e+=" gl_FragColor = uColor;\n",e+="}\n"},t._fsGetDepthPassCode=function(){var e=this.chunks,t=this._fsGetBeginCode();return t+="varying float vDepth;\n",t+=this.varyings,t+=this.varyingDefines,t+=e.packDepthPS,t+=this.frontendDecl,t+=this.frontendCode,t+="void main(void)\n{\n",t+=this.frontendFunc,t+=" gl_FragColor = packFloat(vDepth);\n",t+="}\n"},t._fsGetShadowPassCode=function(){var e=this.device,t=this.options,i=this.chunks,n=this.varyings,s=this.shaderPassInfo.lightType,r=this.shaderPassInfo.shadowType;0!==s&&t.clusteredLightingEnabled&&(1!==r&&2!==r&&3!==r&&6!==r||(r=0));var a=this._fsGetBeginCode();!e.extStandardDerivatives||e.webgl2||e.isWebGPU||(a+="uniform vec2 polygonOffset;\n"),3===r?e.textureFloatHighPrecision?a+="#define VSM_EXPONENT 15.0\n\n":a+="#define VSM_EXPONENT 5.54\n\n":2===r&&(a+="#define VSM_EXPONENT 5.54\n\n"),0!==s&&(a+="uniform vec3 view_position;\n",a+="uniform float light_radius;\n"),a+=n,a+=this.varyingDefines,a+=this.frontendDecl,a+=this.frontendCode;var o=5===r||0===r||4===r||6===r,h=1===s&&6!==r&&!t.clusteredLightingEnabled,l=o&&!e.supportsDepthShadow||h;l?a+=i.packDepthPS:1===r&&(a+="vec2 encodeFloatRG( float v ) {\n",a+=" vec2 enc = vec2(1.0, 255.0) * v;\n",a+=" enc = fract(enc);\n",a+=" enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);\n",a+=" return enc;\n",a+="}\n\n"),6===r&&(a+=Sa.linearizeDepthPS),a+="void main(void)\n{\n",a+=this.frontendFunc;var c=1===r||2===r||3===r,u=6===r,d=0===s||!c&&2===s,f=!1;if(d?u?(a+=" float depth = linearizeDepth(gl_FragCoord.z, camera_params);\n",f=!0):a+=" float depth = gl_FragCoord.z;\n":(a+=" float depth = min(distance(view_position, vPositionW) / light_radius, 0.99999);\n",f=!0),!e.webgl2&&e.extStandardDerivatives&&!e.isWebGPU&&(a+=" float minValue = 2.3374370500153186e-10; //(1.0 / 255.0) / (256.0 * 256.0 * 256.0);\n",a+=" depth += polygonOffset.x * max(abs(dFdx(depth)), abs(dFdy(depth))) + minValue * polygonOffset.y;\n",f=!0),d&&u&&l&&(a+=" depth *= 1.0 / (camera_params.y - camera_params.z);\n",f=!0),l)a+=" gl_FragColor = packFloat(depth);\n";else if(c)a+=1===r?" gl_FragColor = vec4(encodeFloatRG(depth), encodeFloatRG(depth*depth));\n":i.storeEVSMPS;else{6===r?a+=" gl_FragColor.r = depth;\n":(f&&(a+=" gl_FragDepth = depth;\n"),a+=" gl_FragColor = vec4(1.0);\n")}return a+="}\n"},t._fsGetLitPassCode=function(){var e=this.device,t=this.options,i=this.chunks,n=new El,s=new El,r=new El,a=new El;!1===t.opacityFadesSpecular&&n.append("uniform float material_alphaFade;"),t.useSpecular&&(this.defines.push("LIT_SPECULAR"),this.reflections&&this.defines.push("LIT_REFLECTIONS"),t.useClearCoat&&this.defines.push("LIT_CLEARCOAT"),t.fresnelModel>0&&this.defines.push("LIT_SPECULAR_FRESNEL"),t.conserveEnergy&&this.defines.push("LIT_CONSERVE_ENERGY"),t.useSheen&&this.defines.push("LIT_SHEEN"),t.useIridescence&&this.defines.push("LIT_IRIDESCENCE"));var o=[],h=0,l=!1,c=!1,u=!1,d=t.lights.some((function(e){return e._shape&&0!==e._shape}));t.clusteredLightingEnabled&&t.clusteredLightingAreaLightsEnabled&&(d=!0);var f="highp";7===e.areaLightLutFormat&&(n.append("#define AREA_R8_G8_B8_A8_LUTS"),f="lowp"),(d||t.clusteredLightingEnabled)&&(n.append("#define AREA_LIGHTS"),n.append("uniform "+f+" sampler2D areaLightsLutTex1;"),n.append("uniform "+f+" sampler2D areaLightsLutTex2;"));for(var p=0;p<t.lights.length;p++){var m=t.lights[p],_=m._type;if(!t.clusteredLightingEnabled||0===_){var g=d&&m._shape?m._shape:0;n.append("uniform vec3 light"+p+"_color;"),6===m._shadowType&&m.castShadows&&!t.noShadow&&(n.append("uniform float light"+p+"_shadowSearchArea;"),n.append("uniform vec4 light"+p+"_cameraParams;")),0===_?n.append("uniform vec3 light"+p+"_direction;"):(n.append("uniform vec3 light"+p+"_position;"),n.append("uniform float light"+p+"_radius;"),2===_&&(n.append("uniform vec3 light"+p+"_direction;"),n.append("uniform float light"+p+"_innerConeAngle;"),n.append("uniform float light"+p+"_outerConeAngle;"))),0!==g&&(0===_&&n.append("uniform vec3 light"+p+"_position;"),n.append("uniform vec3 light"+p+"_halfWidth;"),n.append("uniform vec3 light"+p+"_halfHeight;")),m.castShadows&&!t.noShadow&&(n.append("uniform mat4 light"+p+"_shadowMatrix;"),n.append("uniform float light"+p+"_shadowIntensity;"),0===_&&(n.append("uniform mat4 light"+p+"_shadowMatrixPalette[4];"),n.append("uniform float light"+p+"_shadowCascadeDistances[4];"),n.append("uniform float light"+p+"_shadowCascadeCount;")),n.append("uniform vec4 light"+p+"_shadowParams;"),0===_&&(l=!0),1===_?n.append("uniform samplerCube light"+p+"_shadowMap;"):m._isPcf&&e.supportsDepthShadow?n.append("uniform sampler2DShadow light"+p+"_shadowMap;"):n.append("uniform sampler2D light"+p+"_shadowMap;"),h++,o[m._shadowType]=!0,m._isVsm&&(c=!0),6===m._shadowType&&(u=!0)),m._cookie&&(m._cookie._cubemap?1===_&&(n.append("uniform samplerCube light"+p+"_cookie;"),n.append("uniform float light"+p+"_cookieIntensity;"),m.castShadows&&!t.noShadow||n.append("uniform mat4 light"+p+"_shadowMatrix;")):2===_&&(n.append("uniform sampler2D light"+p+"_cookie;"),n.append("uniform float light"+p+"_cookieIntensity;"),m.castShadows&&!t.noShadow||n.append("uniform mat4 light"+p+"_shadowMatrix;"),m._cookieTransform&&(n.append("uniform vec4 light"+p+"_cookieMatrix;"),n.append("uniform vec2 light"+p+"_cookieOffset;"))))}}var v=this.needsNormal&&(t.normalMapEnabled||t.clearCoatNormalMapEnabled||t.enableGGXSpecular&&!t.heightMapEnabled);v&&(t.hasTangents?s.append(t.fastTbn?i.TBNfastPS:i.TBNPS):e.extStandardDerivatives&&(t.normalMapEnabled||t.clearCoatNormalMapEnabled)?s.append(i.TBNderivativePS.replace(/\$UV/g,this.lightingUv)):s.append(i.TBNObjectSpacePS)),s.append(i.sphericalPS),s.append(i.decodePS),s.append(Ba(t.gamma,i)),s.append(Na(t.toneMap,i)),s.append(Ua(t.fog,i)),s.append(this.frontendCode),t.useCubeMapRotation&&n.append("#define CUBEMAP_ROTATION"),this.needsNormal&&(s.append(i.cubeMapRotatePS),s.append(t.cubeMapProjection>0?i.cubeMapProjectBoxPS:i.cubeMapProjectNonePS),s.append(t.skyboxIntensity?i.envMultiplyPS:i.envConstPS)),(this.lighting&&t.useSpecular||this.reflections)&&(t.useMetalness&&s.append(i.metalnessModulatePS),2===t.fresnelModel&&s.append(i.fresnelSchlickPS),t.useIridescence&&s.append(i.iridescenceDiffractionPS));var y=t.aoMapEnabled||t.useAoVertexColors;if(y)switch(s.append(i.aoDiffuseOccPS),t.occludeSpecular){case 1:s.append(t.occludeSpecularFloat?i.aoSpecOccSimplePS:i.aoSpecOccConstSimplePS);break;case 2:s.append(t.occludeSpecularFloat?i.aoSpecOccPS:i.aoSpecOccConstPS)}if("envAtlasHQ"===t.reflectionSource)s.append(t.fixSeams?i.fixCubemapSeamsStretchPS:i.fixCubemapSeamsNonePS),s.append(i.envAtlasPS),s.append(i.reflectionEnvHQPS.replace(/\$DECODE_CUBEMAP/g,al.decodeFunc(t.reflectionCubemapEncoding)).replace(/\$DECODE/g,al.decodeFunc(t.reflectionEncoding)));else if("envAtlas"===t.reflectionSource)s.append(i.envAtlasPS),s.append(i.reflectionEnvPS.replace(/\$DECODE/g,al.decodeFunc(t.reflectionEncoding)));else if("cubeMap"===t.reflectionSource)s.append(t.fixSeams?i.fixCubemapSeamsStretchPS:i.fixCubemapSeamsNonePS),s.append(i.reflectionCubePS.replace(/\$DECODE/g,al.decodeFunc(t.reflectionEncoding)));else if("sphereMap"===t.reflectionSource){var x=e.fragmentUniformsCount>16?i.reflectionSpherePS:i.reflectionSphereLowPS;s.append(x.replace(/\$DECODE/g,al.decodeFunc(t.reflectionEncoding)))}this.reflections&&(t.useClearCoat&&s.append(i.reflectionCCPS),t.useSheen&&s.append(i.reflectionSheenPS)),t.useRefraction&&(t.useDynamicRefraction?s.append(i.refractionDynamicPS):this.reflections&&s.append(i.refractionCubePS)),t.useSheen&&s.append(i.lightSheenPS),t.clusteredLightingEnabled&&(s.append(i.clusteredLightUtilsPS),t.clusteredLightingCookiesEnabled&&s.append(i.clusteredLightCookiesPS),t.clusteredLightingShadowsEnabled&&!t.noShadow&&(o[0]=!0,o[4]=!0,o[6]=!0)),(h>0||t.clusteredLightingEnabled)&&(l&&s.append(i.shadowCascadesPS),(o[5]||o[0])&&s.append(i.shadowStandardPS),o[4]&&(e.webgl2||e.isWebGPU)&&s.append(i.shadowStandardGL2PS),c&&(s.append(i.shadowVSM_commonPS),o[1]&&s.append(i.shadowVSM8PS),o[2]&&s.append(e.extTextureHalfFloatLinear?i.shadowEVSMPS.replace(/\$/g,"16"):i.shadowEVSMnPS.replace(/\$/g,"16")),o[3]&&s.append(e.extTextureFloatLinear?i.shadowEVSMPS.replace(/\$/g,"32"):i.shadowEVSMnPS.replace(/\$/g,"32"))),u&&(s.append(i.linearizeDepthPS),s.append(i.shadowPCSSPS)),e.webgl2||e.extStandardDerivatives||e.isWebGPU||s.append(i.biasConstPS)),t.enableGGXSpecular&&s.append("uniform float material_anisotropy;"),this.lighting&&(s.append(i.lightDiffuseLambertPS),(d||t.clusteredLightingAreaLightsEnabled)&&s.append(i.ltcPS));var S=!1;t.useSpecular&&(this.lighting&&s.append(0===t.shadingModel?i.lightSpecularPhongPS:t.enableGGXSpecular?i.lightSpecularAnisoGGXPS:i.lightSpecularBlinnPS),t.fresnelModel||this.reflections||t.diffuseMapEnabled||(n.append("uniform vec3 material_ambient;"),n.append("#define LIT_OLD_AMBIENT"),S=!0)),s.append(i.combinePS),(t.lightMapEnabled||t.useLightMapVertexColors)&&s.append(t.useSpecular&&t.dirLightMapEnabled?i.lightmapDirAddPS:i.lightmapAddPS);var b=!t.lightMapEnabled&&!t.useLightMapVertexColors||t.lightMapWithoutAmbient;b&&("ambientSH"===t.ambientSource?s.append(i.ambientSHPS):"envAtlas"===t.ambientSource?("envAtlas"!==t.reflectionSource&&"envAtlasHQ"!==t.reflectionSource&&s.append(i.envAtlasPS),s.append(i.ambientEnvPS.replace(/\$DECODE/g,al.decodeFunc(t.ambientEncoding)))):s.append(i.ambientConstantPS)),t.useAmbientTint&&!S&&n.append("uniform vec3 material_ambient;"),t.useMsdf&&(t.msdfTextAttribute||n.append("#define UNIFORM_TEXT_PARAMETERS"),s.append(i.msdfPS)),this.needsNormal&&(s.append(i.viewDirPS),t.useSpecular&&s.append(t.enableGGXSpecular?i.reflDirAnisoPS:i.reflDirPS));var w,T=!1,A=!1,C=!1,E=!1,M=!1;if(t.clusteredLightingEnabled&&this.lighting&&(E=!0,T=!0,A=!0,M=!0,s.append(i.floatUnpackingPS),t.lightMaskDynamic&&n.append("#define CLUSTER_MESH_DYNAMIC_LIGHTS"),t.clusteredLightingCookiesEnabled&&n.append("#define CLUSTER_COOKIES"),t.clusteredLightingShadowsEnabled&&!t.noShadow&&(n.append("#define CLUSTER_SHADOWS"),n.append("#define CLUSTER_SHADOW_TYPE_"+zr[t.clusteredLightingShadowType])),t.clusteredLightingAreaLightsEnabled&&n.append("#define CLUSTER_AREALIGHTS"),n.append(ih.shaderDefines),t.clusteredLightingShadowsEnabled&&!t.noShadow&&s.append(i.clusteredLightShadowsPS),s.append(i.clusteredLightPS)),t.twoSidedLighting&&n.append("uniform float twoSidedLightingNegScaleFactor;"),a.append(this._fsGetStartCode(a,e,i,t)),this.needsNormal&&(t.twoSidedLighting?a.append(" dVertexNormalW = normalize(gl_FrontFacing ? vNormalW * twoSidedLightingNegScaleFactor : -vNormalW * twoSidedLightingNegScaleFactor);"):a.append(" dVertexNormalW = normalize(vNormalW);"),(t.heightMapEnabled||t.normalMapEnabled)&&t.hasTangents&&(t.twoSidedLighting?(a.append(" dTangentW = gl_FrontFacing ? vTangentW * twoSidedLightingNegScaleFactor : -vTangentW * twoSidedLightingNegScaleFactor;"),a.append(" dBinormalW = gl_FrontFacing ? vBinormalW * twoSidedLightingNegScaleFactor : -vBinormalW * twoSidedLightingNegScaleFactor;")):(a.append(" dTangentW = vTangentW;"),a.append(" dBinormalW = vBinormalW;"))),a.append(" getViewDir();"),v&&a.append(" getTBN(dTangentW, dBinormalW, dVertexNormalW);")),a.append(this.frontendFunc),this.needsNormal&&(t.useSpecular&&r.append(" getReflDir(litShaderArgs.worldNormal, dViewDirW, litShaderArgs.gloss, dTBN);"),t.useClearCoat&&r.append(" ccReflDirW = normalize(-reflect(dViewDirW, litShaderArgs.clearcoat.worldNormal));")),(this.lighting&&t.useSpecular||this.reflections)&&(t.useMetalness&&r.append(" getMetalnessModulate(litShaderArgs);"),t.useIridescence&&r.append(" vec3 iridescenceFresnel = getIridescence(saturate(dot(dViewDirW, litShaderArgs.worldNormal)), litShaderArgs.specularity, litShaderArgs.iridescence);")),b&&(r.append(" addAmbient(litShaderArgs.worldNormal);"),t.conserveEnergy&&t.useSpecular&&r.append(" dDiffuseLight = dDiffuseLight * (1.0 - litShaderArgs.specularity);"),t.separateAmbient&&r.append("\n vec3 dAmbientLight = dDiffuseLight;\n dDiffuseLight = vec3(0);\n ")),t.useAmbientTint&&!S&&r.append(" dDiffuseLight *= material_ambient;"),y&&!t.occludeDirect&&r.append(" occludeDiffuse(litShaderArgs.ao);"),(t.lightMapEnabled||t.useLightMapVertexColors)&&r.append(" addLightMap(\n litShaderArgs.lightmap, \n litShaderArgs.lightmapDir, \n litShaderArgs.worldNormal, \n dViewDirW, \n dReflDirW, \n litShaderArgs.gloss, \n litShaderArgs.specularity, \n dVertexNormalW,\n dTBN\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n litShaderArgs.iridescence\n #endif\n );"),this.lighting||this.reflections){this.reflections&&(t.useClearCoat&&(r.append(" addReflectionCC(ccReflDirW, litShaderArgs.clearcoat.gloss);"),t.fresnelModel>0?(r.append(" ccFresnel = getFresnelCC(dot(dViewDirW, litShaderArgs.clearcoat.worldNormal));"),r.append(" ccReflection.rgb *= ccFresnel;")):r.append(" ccFresnel = 0.0;")),t.useSpecularityFactor&&r.append(" ccReflection.rgb *= litShaderArgs.specularityFactor;"),t.useSheen&&r.append(" addReflectionSheen(litShaderArgs.worldNormal, dViewDirW, litShaderArgs.sheen.gloss);"),r.append(" addReflection(dReflDirW, litShaderArgs.gloss);"),t.fresnelModel>0?r.append(" dReflection.rgb *= \n getFresnel(\n dot(dViewDirW, litShaderArgs.worldNormal), \n litShaderArgs.gloss, \n litShaderArgs.specularity\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel,\n litShaderArgs.iridescence\n #endif\n );"):r.append(" dReflection.rgb *= litShaderArgs.specularity;"),t.useSpecularityFactor&&r.append(" dReflection.rgb *= litShaderArgs.specularityFactor;")),d&&(r.append(" dSpecularLight *= litShaderArgs.specularity;"),t.useSpecular&&r.append(" calcLTCLightValues(litShaderArgs.gloss, litShaderArgs.worldNormal, dViewDirW, litShaderArgs.specularity, litShaderArgs.clearcoat.gloss, litShaderArgs.clearcoat.worldNormal, litShaderArgs.clearcoat.specularity);"));for(var P=0;P<t.lights.length;P++){var R=t.lights[P],I=R._type;if(!t.clusteredLightingEnabled||0===I){w=!1;var L=d&&R._shape?R.shape:0,D=d&&R._shape?this._getLightSourceShapeString(L):"";if(0!==L&&r.append(" calc"+D+"LightValues(light"+P+"_position, light"+P+"_halfWidth, light"+P+"_halfHeight);"),0===I?(r.append(" dLightDirNormW = light"+P+"_direction;"),r.append(" dAtten = 1.0;")):(R._cookie&&(2!==I||R._cookie._cubemap?1===I&&R._cookie._cubemap&&(M=!0,w=!0):(M=!0,w=!0)),r.append(" getLightDirPoint(light"+P+"_position);"),T=!0,w&&(2===I?r.append(" dAtten3 = getCookie2D"+(R._cookieFalloff?"":"Clip")+(R._cookieTransform?"Xform":"")+"(light"+P+"_cookie, light"+P+"_shadowMatrix, light"+P+"_cookieIntensity"+(R._cookieTransform?", light"+P+"_cookieMatrix, light"+P+"_cookieOffset":"")+")."+R._cookieChannel+";"):r.append(" dAtten3 = getCookieCube(light"+P+"_cookie, light"+P+"_shadowMatrix, light"+P+"_cookieIntensity)."+R._cookieChannel+";")),0===L?0===R._falloffMode?(r.append(" dAtten = getFalloffLinear(light"+P+"_radius, dLightDirW);"),A=!0):(r.append(" dAtten = getFalloffInvSquared(light"+P+"_radius, dLightDirW);"),C=!0):(r.append(" dAtten = getFalloffWindow(light"+P+"_radius, dLightDirW);"),C=!0),r.append(" if (dAtten > 0.00001) {"),2===I&&(w&&!R._cookieFalloff||(r.append(" dAtten *= getSpotEffect(light"+P+"_direction, light"+P+"_innerConeAngle, light"+P+"_outerConeAngle, dLightDirNormW);"),E=!0))),0!==L?0===I?r.append(" dAttenD = getLightDiffuse(litShaderArgs.worldNormal, dViewDirW, dLightDirW, dLightDirNormW);"):r.append(" dAttenD = get"+D+"LightDiffuse(litShaderArgs.worldNormal, dViewDirW, dLightDirW, dLightDirNormW) * 16.0;"):r.append(" dAtten *= getLightDiffuse(litShaderArgs.worldNormal, dViewDirW, dLightDirW, dLightDirNormW);"),R.castShadows&&!t.noShadow){var O=6===R._shadowType,k=1===R._shadowType||2===R._shadowType||3===R._shadowType,F=5===R._shadowType||0===R._shadowType||4===R._shadowType,B=null,N=void 0;switch(R._shadowType){case 1:B="VSM8",N="0.0";break;case 2:B="VSM16",N="5.54";break;case 3:B="VSM32",N=e.textureFloatHighPrecision?"15.0":"5.54";break;case 5:B="PCF1x1";break;case 4:B="PCF5x5";break;case 6:B="PCSS";break;default:B="PCF3x3"}if(null!==B){R._normalOffsetBias&&!R._isVsm&&s.append("#define SHADOW_SAMPLE_NORMAL_OFFSET"),0===I&&s.append("#define SHADOW_SAMPLE_ORTHO"),((F||O)&&e.webgl2||e.extStandardDerivatives||e.isWebGPU)&&s.append("#define SHADOW_SAMPLE_SOURCE_ZBUFFER"),1===I&&s.append("#define SHADOW_SAMPLE_POINT");var U=i.shadowSampleCoordPS;s.append(U.replace("$LIGHT",P)),s.append("#undef SHADOW_SAMPLE_NORMAL_OFFSET"),s.append("#undef SHADOW_SAMPLE_ORTHO"),s.append("#undef SHADOW_SAMPLE_SOURCE_ZBUFFER"),s.append("#undef SHADOW_SAMPLE_POINT");var z="light"+P+"_shadowMatrix";0===I&&R.numCascades>1&&(r.append(" getShadowCascadeMatrix(light"+P+"_shadowMatrixPalette, light"+P+"_shadowCascadeDistances, light"+P+"_shadowCascadeCount);"),z="cascadeShadowMat"),r.append(" dShadowCoord = getShadowSampleCoord"+P+"("+z+", light"+P+"_shadowParams, vPositionW, dLightPosW, dLightDirW, dLightDirNormW, dVertexNormalW);"),0===I&&r.append(" fadeShadow(light"+P+"_shadowCascadeDistances);");var V="SHADOWMAP_PASS(light"+P+"_shadowMap), dShadowCoord, light"+P+"_shadowParams";if(k)V=V+", "+N+", dLightDirW";else if(O){var G="vec2(light"+P+"_shadowSearchArea)";0!==L&&(G="vec2(length(light"+P+"_halfWidth), length(light"+P+"_halfHeight)) * light"+P+"_shadowSearchArea"),V=V+", light"+P+"_cameraParams, "+G+", dLightDirW"}1===I?(B="Point"+B,O||(V+=", dLightDirW")):2===I&&(B="Spot"+B),r.append(" float shadow"+P+" = getShadow"+B+"("+V+");"),r.append(" dAtten *= mix(1.0, shadow"+P+", light"+P+"_shadowIntensity);")}}if(0!==L?t.conserveEnergy&&t.useSpecular?r.append(" dDiffuseLight += ((dAttenD * dAtten) * light"+P+"_color"+(w?" * dAtten3":"")+") * (1.0 - dLTCSpecFres);"):r.append(" dDiffuseLight += (dAttenD * dAtten) * light"+P+"_color"+(w?" * dAtten3":"")+";"):d&&t.conserveEnergy&&t.useSpecular?r.append(" dDiffuseLight += (dAtten * light"+P+"_color"+(w?" * dAtten3":"")+") * (1.0 - litShaderArgs.specularity);"):r.append(" dDiffuseLight += dAtten * light"+P+"_color"+(w?" * dAtten3":"")+";"),t.useSpecular&&r.append(" dHalfDirW = normalize(-dLightDirNormW + dViewDirW);"),R.affectSpecularity)if(0!==L)t.useClearCoat&&r.append(" ccSpecularLight += ccLTCSpecFres * get"+D+"LightSpecular(litShaderArgs.clearcoat.worldNormal, dViewDirW) * dAtten * light"+P+"_color"+(w?" * dAtten3":"")+";"),t.useSpecular&&r.append(" dSpecularLight += dLTCSpecFres * get"+D+"LightSpecular(litShaderArgs.worldNormal, dViewDirW) * dAtten * light"+P+"_color"+(w?" * dAtten3":"")+";");else{var H=!1;0===I&&t.fresnelModel>0&&(H=!0),t.useClearCoat&&r.append(" ccSpecularLight += getLightSpecular(dHalfDirW, ccReflDirW, litShaderArgs.clearcoat.worldNormal, dViewDirW, dLightDirNormW, litShaderArgs.clearcoat.gloss, dTBN) * dAtten * light"+P+"_color"+(w?" * dAtten3":"")+(H?" * getFresnelCC(dot(dViewDirW, dHalfDirW));":";")),t.useSheen&&r.append(" sSpecularLight += getLightSpecularSheen(dHalfDirW, litShaderArgs.worldNormal, dViewDirW, dLightDirNormW, litShaderArgs.sheen.gloss) * dAtten * light"+P+"_color"+(w?" * dAtten3;":";")),t.useSpecular&&r.append(" dSpecularLight += getLightSpecular(dHalfDirW, dReflDirW, litShaderArgs.worldNormal, dViewDirW, dLightDirNormW, litShaderArgs.gloss, dTBN) * dAtten * light"+P+"_color"+(w?" * dAtten3":"")+(H?" \n * getFresnel(\n dot(dViewDirW, dHalfDirW), \n litShaderArgs.gloss, \n litShaderArgs.specularity\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel, \n litShaderArgs.iridescence\n #endif\n );":"* litShaderArgs.specularity;"))}0!==I&&r.append(" }")}}t.clusteredLightingEnabled&&this.lighting&&(A=!0,C=!0,T=!0,r.append(" addClusteredLights(\n litShaderArgs.worldNormal, \n dViewDirW, \n dReflDirW,\n #if defined(LIT_CLEARCOAT)\n ccReflDirW,\n #endif\n litShaderArgs.gloss, \n litShaderArgs.specularity, \n dVertexNormalW, \n dTBN, \n #if defined(LIT_IRIDESCENCE)\n iridescenceFresnel,\n #endif\n litShaderArgs.clearcoat, \n litShaderArgs.sheen, \n litShaderArgs.iridescence\n );")),d&&(t.useClearCoat&&r.append(" litShaderArgs.clearcoat.specularity = 1.0;"),t.useSpecular&&r.append(" litShaderArgs.specularity = vec3(1);")),t.useRefraction&&r.append(" addRefraction(\n litShaderArgs.worldNormal, \n dViewDirW, \n litShaderArgs.thickness, \n litShaderArgs.gloss, \n litShaderArgs.specularity, \n litShaderArgs.albedo, \n litShaderArgs.transmission\n #if defined(LIT_IRIDESCENCE)\n , iridescenceFresnel, \n litShaderArgs.iridescence\n #endif\n );")}y&&(t.occludeDirect&&r.append(" occludeDiffuse(litShaderArgs.ao);"),1!==t.occludeSpecular&&2!==t.occludeSpecular||r.append(" occludeSpecular(litShaderArgs.gloss, litShaderArgs.ao, litShaderArgs.worldNormal, dViewDirW);")),t.useSpecularityFactor&&r.append(" dSpecularLight *= litShaderArgs.specularityFactor;"),!1===t.opacityFadesSpecular&&(2!==t.blendType&&4!==t.blendType||(r.append("float specLum = dot((dSpecularLight + dReflection.rgb * dReflection.a), vec3( 0.2126, 0.7152, 0.0722 ));"),r.append("#ifdef LIT_CLEARCOAT\n specLum += dot(ccSpecularLight * litShaderArgs.clearcoat.specularity + ccReflection.rgb * litShaderArgs.clearcoat.specularity, vec3( 0.2126, 0.7152, 0.0722 ));\n#endif"),r.append("litShaderArgs.opacity = clamp(litShaderArgs.opacity + gammaCorrectInput(specLum), 0.0, 1.0);")),r.append("litShaderArgs.opacity *= material_alphaFade;")),r.append(i.endPS),2===t.blendType||6===t.blendType||t.alphaToCoverage?r.append(i.outputAlphaPS):4===t.blendType?r.append(i.outputAlphaPremulPS):r.append(i.outputAlphaOpaquePS),t.useMsdf&&r.append(" gl_FragColor = applyMsdf(gl_FragColor);"),r.append(i.outputPS),r.append(i.debugOutputPS),T&&s.prepend(i.lightDirPointPS),A&&s.prepend(i.falloffLinearPS),C&&s.prepend(i.falloffInvSquaredPS),E&&s.prepend(i.spotPS),M&&!t.clusteredLightingEnabled&&s.prepend(i.cookiePS);var W="",X="void evaluateBackend(LitShaderArguments litShaderArgs) {\n"+r.code+"\n}";s.append(X),a.append(i.debugProcessFrontendPS),a.append(" evaluateBackend(litShaderArgs);"),a.append("}\n");var j=n.code+s.code+a.code;return j.includes("dTBN")&&(W+="mat3 dTBN;\n"),j.includes("dVertexNormalW")&&(W+="vec3 dVertexNormalW;\n"),j.includes("dTangentW")&&(W+="vec3 dTangentW;\n"),j.includes("dBinormalW")&&(W+="vec3 dBinormalW;\n"),j.includes("dViewDirW")&&(W+="vec3 dViewDirW;\n"),j.includes("dReflDirW")&&(W+="vec3 dReflDirW;\n"),j.includes("dHalfDirW")&&(W+="vec3 dHalfDirW;\n"),j.includes("ccReflDirW")&&(W+="vec3 ccReflDirW;\n"),j.includes("dLightDirNormW")&&(W+="vec3 dLightDirNormW;\n"),j.includes("dLightDirW")&&(W+="vec3 dLightDirW;\n"),j.includes("dLightPosW")&&(W+="vec3 dLightPosW;\n"),j.includes("dShadowCoord")&&(W+="vec3 dShadowCoord;\n"),j.includes("dReflection")&&(W+="vec4 dReflection;\n"),j.includes("dDiffuseLight")&&(W+="vec3 dDiffuseLight;\n"),j.includes("dSpecularLight")&&(W+="vec3 dSpecularLight;\n"),j.includes("dAtten")&&(W+="float dAtten;\n"),j.includes("dAttenD")&&(W+="float dAttenD;\n"),j.includes("dAtten3")&&(W+="vec3 dAtten3;\n"),j.includes("dMsdf")&&(W+="vec4 dMsdf;\n"),j.includes("ccFresnel")&&(W+="float ccFresnel;\n"),j.includes("ccReflection")&&(W+="vec3 ccReflection;\n"),j.includes("ccSpecularLight")&&(W+="vec3 ccSpecularLight;\n"),j.includes("ccSpecularityNoFres")&&(W+="float ccSpecularityNoFres;\n"),j.includes("sSpecularLight")&&(W+="vec3 sSpecularLight;\n"),j.includes("sReflection")&&(W+="vec3 sReflection;\n"),this._fsGetBeginCode()+this.varyings+this.varyingDefines+this._fsGetBaseCode()+(t.detailModes?i.detailModesPS:"")+W+this.frontendDecl+j},t.generateFragmentShader=function(e,t,i,n){var s=this.options;this.frontendDecl=e,this.frontendCode=t,this.frontendFunc=i,this.lightingUv=n,3===s.pass?this.fshader=this._fsGetPickPassCode():2===s.pass?this.fshader=this._fsGetDepthPassCode():this.shadowPass?this.fshader=this._fsGetShadowPassCode():s.customFragmentShader?this.fshader=this._fsGetBeginCode()+s.customFragmentShader:this.fshader=this._fsGetLitPassCode()},t.getDefinition=function(){var e=vs.createDefinition(this.device,{name:"LitShader",attributes:this.attributes,vertexCode:this.vshader,fragmentCode:this.fshader});return this.options.isForwardPass&&(e.tag=1),e},e}(),Il=function(){function e(){this.hasTangents=!1,this.chunks={},this._pass=0,this._isForwardPass=!1,this.alphaTest=!1,this.forceFragmentPrecision=null,this.blendType=3,this.separateAmbient=!1,this.screenSpace=!1,this.skin=!1,this.useInstancing=!1,this.useMorphPosition=!1,this.useMorphNormal=!1,this.useMorphTextureBased=!1,this.nineSlicedMode=0,this.clusteredLightingEnabled=!0,this.clusteredLightingCookiesEnabled=!1,this.clusteredLightingShadowsEnabled=!1,this.clusteredLightingShadowType=0,this.clusteredLightingAreaLightsEnabled=!1,this.vertexColors=!1,this.lightMapEnabled=!1,this.useLightMapVertexColors=!1,this.dirLightMapEnabled=!1,this.heightMapEnabled=!1,this.normalMapEnabled=!1,this.clearCoatNormalMapEnabled=!1,this.aoMapEnabled=!1,this.useAoVertexColors=!1,this.diffuseMapEnabled=!1,this.useAmbientTint=!1,this.customFragmentShader=null,this.pixelSnap=!1,this.useClearCoatNormalMap=!1,this.useDiffuseMap=!1,this.useAoMap=!1,this.detailModes=0,this.shadingModel=0,this.ambientSH=!1,this.fastTbn=!1,this.twoSidedLighting=!1,this.occludeSpecular=0,this.occludeSpecularFloat=!1,this.useMsdf=!1,this.msdfTextAttribute=0,this.alphaToCoverage=!1,this.opacityFadesSpecular=!1,this.cubeMapProjection=0,this.occludeDirect=!1,this.conserveEnergy=!1,this.useSpecular=!1,this.useSpecularityFactor=!1,this.useSpecularColor=!1,this.enableGGXSpecular=!1,this.fresnelModel=0,this.useRefraction=!1,this.useClearCoat=!1,this.useSheen=!1,this.useIridescence=!1,this.useMetalness=!1,this.useDynamicRefraction=!1,this.fog=Nr,this.gamma=0,this.toneMap=-1,this.fixSeams=!1,this.reflectionSource=null,this.reflectionEncoding=null,this.reflectionCubemapEncoding=null,this.ambientSource="constant",this.ambientEncoding=null,this.skyboxIntensity=1,this.useCubeMapRotation=!1,this.lightMapWithoutAmbient=!1,this.lights=[],this.noShadow=!1,this.lightMaskDynamic=0}return Z(e,[{key:"pass",get:function(){return this._pass},set:function(e){}},{key:"isForwardPass",get:function(){return this._isForwardPass},set:function(e){}}]),e}(),Ll=function(){function e(){this._pass=0,this._isForwardPass=!1,this.chunks=[],this.forceUv1=!1,this.ambientTint=!1,this.diffuseTint=!1,this.specularTint=!1,this.metalnessTint=!1,this.glossTint=!1,this.emissiveTint=!1,this.opacityTint=!1,this.emissiveEncoding="linear",this.lightMapEncoding="linear",this.packedNormal=!1,this.glossInvert=!1,this.sheenGlossInvert=!1,this.clearCoatGlossInvert=!1,this.litOptions=new Il}return Z(e,[{key:"pass",get:function(){return this._pass},set:function(e){this._pass=e,this.litOptions._pass=e}},{key:"isForwardPass",get:function(){return this._isForwardPass},set:function(e){this._isForwardPass=e,this.litOptions._isForwardPass=e}}]),e}(),Dl=[],Ol={optionsContext:new Ll,optionsContextMin:new Ll,generateKey:function(e){var t,i=function(e){var t=[];for(var i in e)e.hasOwnProperty(i)&&"chunks"!==i&&"lights"!==i&&t.push(i);return t.sort()};e===this.optionsContextMin?(this.propsMin||(this.propsMin=i(e)),t=this.propsMin):e===this.optionsContext?(this.props||(this.props=i(e)),t=this.props):t=i(e);for(var n="standard",s=0;s<t.length;s++)e[t[s]]&&(n+=t[s]+e[t[s]]);if(e.chunks){var r=[];for(var a in e.chunks)e.chunks.hasOwnProperty(a)&&r.push(a+e.chunks[a]);r.sort(),n+=r}if(e.litOptions)for(var o in e.litOptions)if("lights"===o)for(var h=e.litOptions.clusteredLightingEnabled,l=0;l<e.litOptions.lights.length;l++){var c=e.litOptions.lights[l];h&&0!==c._type||(n+=c.key)}else n+=o+e.litOptions[o];return Mi(n)},_getUvSourceExpression:function(e,t,i){var n,s=i[e],r=i[t],a=i.isForwardPass;return a&&1===i.litOptions.nineSlicedMode||a&&2===i.litOptions.nineSlicedMode?n="nineSlicedUv":(n=0===s?"vUv"+r:"vUV"+r+"_"+s,i.heightMap&&"heightMapTransform"!==e&&(n+=" + dUvOffset")),n},_addMapDef:function(e,t){return t?"#define "+e+"\n":"#undef "+e+"\n"},_addMapDefs:function(e,t,i,n,s){return this._addMapDef("MAPFLOAT",e)+this._addMapDef("MAPCOLOR",t)+this._addMapDef("MAPVERTEX",i)+this._addMapDef("MAPTEXTURE",n)+this._addMapDef("MAPINVERT",s)},_addMap:function(e,t,i,n,s,r){void 0===r&&(r=null);var a=e+"Map",o=a+"Uv",h=a+"Identifier",l=a+"Transform",c=a+"Channel",u=e+"VertexColorChannel",d=e+"VertexColor",f=e+"Mode",p=e+"Invert",m=i[e+"Tint"],_=i[d],g=i[a],v=i[h],y=i[f],x=n[t];if(g){var S=this._getUvSourceExpression(l,o,i);if(x=x.replace(/\$UV/g,S).replace(/\$CH/g,i[c]),s&&-1!==x.search(/\$SAMPLER/g)){var b="texture_"+a,w=s[v];w?b=w:s[v]=b,x=x.replace(/\$SAMPLER/g,b)}if(r&&(x="aaa"===i[c]?x.replace(/\$DECODE/g,"passThrough"):x.replace(/\$DECODE/g,al.decodeFunc(i.litOptions.gamma||"srgb"!==r?r:"linear"))).indexOf("$texture2DSAMPLE")){x=x.replace(/\$texture2DSAMPLE/g,{linear:"texture2D",srgb:"texture2DSRGB",rgbm:"texture2DRGBM",rgbe:"texture2DRGBE"}[r]||"texture2D")}}_&&(x=x.replace(/\$VC/g,i[u])),y&&(x=x.replace(/\$DETAILMODE/g,y));var T=!!(1&m),A=!!(2&m),C=!!i[p];return(x=this._addMapDefs(T,A,_,g,C)+x).replace(/\$/g,"")},_correctChannel:function(e,t,i){if(i[e]>0){if(i[e]<t.length)return t.substring(0,i[e]);if(i[e]>t.length){for(var n=t,s=n.charAt(n.length-1),r=i[e]-n.length,a=0;a<r;a++)n+=s;return n}return t}},createShaderDefinition:function(e,t){var i=Fa.get(e).getByIndex(t.pass).isForward;t.isForwardPass=i;var n=new Rl(e,t.litOptions),s=[],r=[],a=[],o={};for(var h in Dl){var l=h+"Map";if(t[h+"VertexColor"]){var c=h+"VertexColorChannel";t[c]=this._correctChannel(h,t[c],Dl)}if(t[l]){var u=l+"Channel",d=l+"Transform",f=l+"Uv";t[f]=Math.min(t[f],1),t[u]=this._correctChannel(h,t[u],Dl);var p=t[f];s[p]=!0,r[p]=r[p]||t[l]&&!t[d],t[d]&&a.push({name:h,id:t[d],uv:t[f]})}}t.forceUv1&&(s[1]=!0,r[1]=void 0===r[1]||r[1]),n.generateVertexShader(s,r,a),0===t.litOptions.shadingModel?(t.litOptions.fresnelModel=0,t.litOptions.ambientSH=!1):t.litOptions.fresnelModel=0===t.litOptions.fresnelModel?2:t.litOptions.fresnelModel;var m=new El,_=new El,g=new El,v=new El,y="";if(2===t.litOptions.nineSlicedMode?m.append("const float textureBias = -1000.0;"):m.append("uniform float textureBias;"),i){if(t.heightMap&&(m.append("vec2 dUvOffset;"),_.append(this._addMap("height","parallaxPS",t,n.chunks,o)),g.append("getParallax();")),3!==t.litOptions.blendType||t.litOptions.alphaTest||t.litOptions.alphaToCoverage?(m.append("float dAlpha;"),_.append(this._addMap("opacity","opacityPS",t,n.chunks,o)),g.append("getOpacity();"),v.append("_litShaderArgs.opacity = dAlpha;"),t.litOptions.alphaTest&&(_.append(n.chunks.alphaTestPS),g.append("alphaTest(dAlpha);"))):m.append("float dAlpha = 1.0;"),n.needsNormal){if((t.normalMap||t.clearCoatNormalMap)&&(_.append(t.packedNormal?n.chunks.normalXYPS:n.chunks.normalXYZPS),!t.litOptions.hasTangents)){var x=t.normalMap?"normalMap":"clearCoatNormalMap";y=this._getUvSourceExpression(x+"Transform",x+"Uv",t)}m.append("vec3 dNormalW;"),_.append(this._addMap("normalDetail","normalDetailMapPS",t,n.chunks,o)),_.append(this._addMap("normal","normalMapPS",t,n.chunks,o)),g.append("getNormal();"),v.append("_litShaderArgs.worldNormal = dNormalW;")}if(n.needsSceneColor&&m.append("uniform sampler2D uSceneColorMap;"),n.needsScreenSize&&m.append("uniform vec4 uScreenSize;"),n.needsTransforms&&(m.append("uniform mat4 matrix_viewProjection;"),m.append("uniform mat4 matrix_model;")),m.append("vec3 dAlbedo;"),t.diffuseDetail&&_.append(this._addMap("diffuseDetail","diffuseDetailMapPS",t,n.chunks,o,t.diffuseDetailEncoding)),_.append(this._addMap("diffuse","diffusePS",t,n.chunks,o,t.diffuseEncoding)),g.append("getAlbedo();"),v.append("_litShaderArgs.albedo = dAlbedo;"),t.litOptions.useRefraction&&(m.append("float dTransmission;"),_.append(this._addMap("refraction","transmissionPS",t,n.chunks,o)),g.append("getRefraction();"),v.append("_litShaderArgs.transmission = dTransmission;"),m.append("float dThickness;"),_.append(this._addMap("thickness","thicknessPS",t,n.chunks,o)),g.append("getThickness();"),v.append("_litShaderArgs.thickness = dThickness;")),t.litOptions.useIridescence&&(m.append("float dIridescence;"),_.append(this._addMap("iridescence","iridescencePS",t,n.chunks,o)),g.append("getIridescence();"),v.append("_litShaderArgs.iridescence.intensity = dIridescence;"),m.append("float dIridescenceThickness;"),_.append(this._addMap("iridescenceThickness","iridescenceThicknessPS",t,n.chunks,o)),g.append("getIridescenceThickness();"),v.append("_litShaderArgs.iridescence.thickness = dIridescenceThickness;")),n.lighting&&t.litOptions.useSpecular||n.reflections?(m.append("vec3 dSpecularity;"),m.append("float dGlossiness;"),t.litOptions.useSheen&&(m.append("vec3 sSpecularity;"),_.append(this._addMap("sheen","sheenPS",t,n.chunks,o,t.sheenEncoding)),g.append("getSheen();"),v.append("_litShaderArgs.sheen.specularity = sSpecularity;"),m.append("float sGlossiness;"),_.append(this._addMap("sheenGloss","sheenGlossPS",t,n.chunks,o)),g.append("getSheenGlossiness();"),v.append("_litShaderArgs.sheen.gloss = sGlossiness;")),t.litOptions.useMetalness&&(m.append("float dMetalness;"),_.append(this._addMap("metalness","metalnessPS",t,n.chunks,o)),g.append("getMetalness();"),v.append("_litShaderArgs.metalness = dMetalness;")),t.litOptions.useSpecularityFactor&&(m.append("float dSpecularityFactor;"),_.append(this._addMap("specularityFactor","specularityFactorPS",t,n.chunks,o)),g.append("getSpecularityFactor();"),v.append("_litShaderArgs.specularityFactor = dSpecularityFactor;")),t.litOptions.useSpecularColor?_.append(this._addMap("specular","specularPS",t,n.chunks,o,t.specularEncoding)):_.append("void getSpecularity() { dSpecularity = vec3(1); }"),_.append(this._addMap("gloss","glossPS",t,n.chunks,o)),g.append("getGlossiness();"),g.append("getSpecularity();"),v.append("_litShaderArgs.specularity = dSpecularity;"),v.append("_litShaderArgs.gloss = dGlossiness;")):(m.append("vec3 dSpecularity = vec3(0.0);"),m.append("float dGlossiness = 0.0;")),t.aoDetail&&_.append(this._addMap("aoDetail","aoDetailMapPS",t,n.chunks,o)),(t.aoMap||t.aoVertexColor)&&(m.append("float dAo;"),_.append(this._addMap("ao","aoPS",t,n.chunks,o)),g.append("getAO();"),v.append("_litShaderArgs.ao = dAo;")),m.append("vec3 dEmission;"),_.append(this._addMap("emissive","emissivePS",t,n.chunks,o,t.emissiveEncoding)),g.append("getEmission();"),v.append("_litShaderArgs.emission = dEmission;"),t.litOptions.useClearCoat&&(m.append("float ccSpecularity;"),m.append("float ccGlossiness;"),m.append("vec3 ccNormalW;"),_.append(this._addMap("clearCoat","clearCoatPS",t,n.chunks,o)),_.append(this._addMap("clearCoatGloss","clearCoatGlossPS",t,n.chunks,o)),_.append(this._addMap("clearCoatNormal","clearCoatNormalPS",t,n.chunks,o)),g.append("getClearCoat();"),g.append("getClearCoatGlossiness();"),g.append("getClearCoatNormal();"),v.append("_litShaderArgs.clearcoat.specularity = ccSpecularity;"),v.append("_litShaderArgs.clearcoat.gloss = ccGlossiness;"),v.append("_litShaderArgs.clearcoat.worldNormal = ccNormalW;")),t.lightMap||t.lightVertexColor){var S=t.dirLightMap&&t.litOptions.useSpecular,b=S?"lightmapDirPS":"lightmapSinglePS";m.append("vec3 dLightmap;"),S&&m.append("vec3 dLightmapDir;"),_.append(this._addMap("light",b,t,n.chunks,o,t.lightMapEncoding)),g.append("getLightMap();"),v.append("_litShaderArgs.lightmap = dLightmap;"),S&&v.append("_litShaderArgs.lightmapDir = dLightmapDir;")}-1===_.code.indexOf("texture2DSRGB")&&-1===_.code.indexOf("texture2DRGBM")&&-1===_.code.indexOf("texture2DRGBE")||_.prepend(n.chunks.textureSamplePS)}else t.litOptions.alphaTest&&(m.append("float dAlpha;"),_.append(this._addMap("opacity","opacityPS",t,n.chunks,o)),_.append(n.chunks.alphaTestPS),g.append("getOpacity();"),g.append("alphaTest(dAlpha);"),v.append("_litShaderArgs.opacity = dAlpha;"));for(var w in m.append(n.chunks.litShaderArgsPS),_.append("LitShaderArguments evaluateFrontend() { LitShaderArguments _litShaderArgs; \n"+g.code+"\n"+v.code+"\n return _litShaderArgs;\n }\n"),g.code="LitShaderArguments litShaderArgs = evaluateFrontend();",o)m.append("uniform sampler2D "+o[w]+";");return g.code="\n"+g.code.split("\n").map((function(e){return" "+e})).join("\n")+"\n\n",n.generateFragmentShader(m.code,_.code,g.code,y),n.getDefinition()}},kl=function(e,t){if(e.length!==t.length)return!1;for(var i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0},Fl=function(e){return 1!==e.r||1!==e.g||1!==e.b},Bl=function(){function e(){this._mapXForms=null}var t=e.prototype;return t.updateMinRef=function(e,t,i,n,s,r,a){this._updateSharedOptions(e,t,i,n,r),this._updateMinOptions(e,i),this._updateUVOptions(e,i,n,!0),e.litOptions.chunks=e.chunks},t.updateRef=function(e,t,i,n,s,r,a){this._updateSharedOptions(e,t,i,n,r),this._updateEnvOptions(e,i,t),this._updateMaterialOptions(e,i),1===r&&(e.litOptions.gamma&&(e.litOptions.gamma=3),e.litOptions.toneMap=0),e.litOptions.hasTangents=n&&0!=(512&n),this._updateLightOptions(e,t,i,n,a,s),this._updateUVOptions(e,i,n,!1),e.litOptions.chunks=e.chunks},t._updateSharedOptions=function(e,t,i,n,s){e.forceUv1=i.forceUv1,e.chunks=i.chunks||"",e.pass=s,e.litOptions.alphaTest=i.alphaTest>0,e.litOptions.forceFragmentPrecision=i.forceFragmentPrecision||"",e.litOptions.blendType=i.blendType,e.litOptions.separateAmbient=!1,e.litOptions.screenSpace=n&&0!=(n&Hr),e.litOptions.skin=n&&0!=(2&n),e.litOptions.useInstancing=n&&0!=(32&n),e.litOptions.useMorphPosition=n&&0!=(n&Wr),e.litOptions.useMorphNormal=n&&0!=(n&Xr),e.litOptions.useMorphTextureBased=n&&0!=(n&jr),e.litOptions.nineSlicedMode=i.nineSlicedMode||0,t.clusteredLightingEnabled&&i.useLighting?(e.litOptions.clusteredLightingEnabled=!0,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=!1,e.litOptions.clusteredLightingCookiesEnabled=!1,e.litOptions.clusteredLightingShadowsEnabled=!1,e.litOptions.clusteredLightingAreaLightsEnabled=!1)},t._updateUVOptions=function(e,t,i,n){var s=!1,r=!1,a=!1;i&&(s=0!=(4&i),r=0!=(8&i),a=0!=(16&i)),e.litOptions.vertexColors=!1,this._mapXForms=[];var o={};for(var h in Dl)this._updateTexOptions(e,t,h,s,r,a,n,o);this._mapXForms=null,e.litOptions.lightMapEnabled=e.lightMap,e.litOptions.useLightMapVertexColors=e.lightVertexColor,e.litOptions.dirLightMapEnabled=e.dirLightMap,e.litOptions.heightMapEnabled=e.heightMap,e.litOptions.normalMapEnabled=e.normalMap,e.litOptions.clearCoatNormalMapEnabled=e.clearCoatNormalMap,e.litOptions.aoMapEnabled=e.aoMap,e.litOptions.useAoVertexColors=e.aoVertexColor,e.litOptions.diffuseMapEnabled=e.diffuseMap},t._updateTexOptions=function(e,t,i,n,s,r,a,o){var h=i+"Map",l=i+"VertexColor",c=i+"VertexColorChannel",u=h+"Channel",d=h+"Transform",f=h+"Uv",p=h+"Identifier";"light"!==i&&(e[h]=!1,e[p]=void 0,e[u]="",e[d]=0,e[f]=0),e[l]=!1,e[c]="";var m="opacity"===i;if((!m||3!==t.blendType||0!==t.alphaTest||t.alphaToCoverage)&&(!a||m)&&("height"!==i&&t[l]&&r&&(e[l]=t[l],e[c]=t[c],e.litOptions.vertexColors=!0),t[h])){var _=!0;if(0!==t[f]||n||(_=!1),1!==t[f]||s||(_=!1),_){var g=t[h].id,v=o[g];void 0===v&&(o[g]=i,v=i),e[h]=!!t[h],e[p]=v,e[d]=this._getMapTransformID(t.getUniform(d),t[f]),e[u]=t[u],e[f]=t[f]}}},t._updateMinOptions=function(e,t){e.opacityTint=1!==t.opacity&&3!==t.blendType,e.litOptions.lights=[]},t._updateMaterialOptions=function(e,t){var i,n,s,r,a,o=(t.diffuseTint||!t.diffuseMap&&!t.diffuseVertexColor)&&Fl(t.diffuse),h=!!(t.useMetalness||t.specularMap||t.sphereMap||t.cubeMap||(a=t.specular,0!==a.r||0!==a.g||0!==a.b)||t.specularityFactor>0&&t.useMetalness||t.enableGGXSpecular||t.clearCoat>0),l=!t.useMetalness||t.useMetalnessSpecularColor,c=h&&(t.specularTint||!t.specularMap&&!t.specularVertexColor)&&Fl(t.specular),u=h&&t.useMetalnessSpecularColor&&(t.specularityFactorTint||t.specularityFactor<1&&!t.specularityFactorMap),d=!t.emissiveMap||Fl(t.emissive)&&t.emissiveTint,f=1!==t.emissiveIntensity,p=!!t.normalMap&&(t.normalMap.format===je||t.normalMap.type===Xt);e.opacityTint=1!==t.opacity&&3!==t.blendType?1:0,e.ambientTint=t.ambientTint,e.diffuseTint=o?2:0,e.specularTint=c?2:0,e.specularityFactorTint=u?1:0,e.metalnessTint=t.useMetalness&&t.metalness<1?1:0,e.glossTint=1,e.emissiveTint=(d?2:0)+(f?1:0),e.diffuseEncoding=null==(i=t.diffuseMap)?void 0:i.encoding,e.diffuseDetailEncoding=null==(n=t.diffuseDetailMap)?void 0:n.encoding,e.emissiveEncoding=null==(s=t.emissiveMap)?void 0:s.encoding,e.lightMapEncoding=null==(r=t.lightMap)?void 0:r.encoding,e.packedNormal=p,e.refractionTint=1!==t.refraction?1:0,e.refractionIndexTint=t.refractionIndex!==1/1.5?1:0,e.thicknessTint=t.useDynamicRefraction&&1!==t.thickness?1:0,e.specularEncoding=t.specularEncoding||"linear",e.sheenEncoding=t.sheenEncoding||"linear",e.aoMapUv=t.aoUvSet,e.aoDetail=!!t.aoMap,e.diffuseDetail=!!t.diffuseMap,e.normalDetail=!!t.normalMap,e.diffuseDetailMode=t.diffuseDetailMode,e.aoDetailMode=t.aoDetailMode,e.clearCoatTint=1!==t.clearCoat?1:0,e.clearCoatGloss=!!t.clearCoatGloss,e.clearCoatGlossTint=1!==t.clearCoatGloss?1:0,e.iridescenceTint=1!==t.iridescence?1:0,e.sheenTint=t.useSheen&&Fl(t.sheen)?2:0,e.sheenGlossTint=1,e.glossInvert=t.glossInvert,e.sheenGlossInvert=t.sheenGlossInvert,e.clearCoatGlossInvert=t.clearCoatGlossInvert,e.litOptions.useAmbientTint=e.ambientTint,e.litOptions.customFragmentShader=t.customFragmentShader,e.litOptions.pixelSnap=t.pixelSnap,e.litOptions.useClearCoatNormalMap=!!t.clearCoatNormalMap,e.litOptions.useDiffuseMap=!!t.diffuseMap,e.litOptions.useAoMap=!!t.aoMap,e.litOptions.detailModes=!!e.diffuseDetail||!!e.aoDetail,e.litOptions.shadingModel=t.shadingModel,e.litOptions.ambientSH=!!t.ambientSH,e.litOptions.fastTbn=t.fastTbn,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.cubeMapProjection=t.cubeMapProjection,e.litOptions.occludeDirect=t.occludeDirect,e.litOptions.conserveEnergy=t.conserveEnergy&&0!==t.shadingModel,e.litOptions.useSpecular=h,e.litOptions.useSpecularityFactor=(u||!!t.specularityFactorMap)&&t.useMetalnessSpecularColor,e.litOptions.useSpecularColor=l,e.litOptions.enableGGXSpecular=t.enableGGXSpecular,e.litOptions.fresnelModel=t.fresnelModel,e.litOptions.useRefraction=(t.refraction||!!t.refractionMap)&&(t.useDynamicRefraction||!!e.litOptions.reflectionSource),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},t._updateEnvOptions=function(e,t,i){e.litOptions.fog=t.useFog?i.fog:"none",e.litOptions.gamma=t.useGammaTonemap?i.gammaCorrection:0,e.litOptions.toneMap=t.useGammaTonemap?i.toneMapping:-1,e.litOptions.fixSeams=!!t.cubeMap&&t.cubeMap.fixCubemapSeams;var n=0===t.shadingModel,s=!1;if(t.envAtlas&&t.cubeMap&&!n?(e.litOptions.reflectionSource="envAtlasHQ",e.litOptions.reflectionEncoding=t.envAtlas.encoding,e.litOptions.reflectionCubemapEncoding=t.cubeMap.encoding):t.envAtlas&&!n?(e.litOptions.reflectionSource="envAtlas",e.litOptions.reflectionEncoding=t.envAtlas.encoding):t.cubeMap?(e.litOptions.reflectionSource="cubeMap",e.litOptions.reflectionEncoding=t.cubeMap.encoding):t.sphereMap?(e.litOptions.reflectionSource="sphereMap",e.litOptions.reflectionEncoding=t.sphereMap.encoding):t.useSkybox&&i.envAtlas&&i.skybox&&!n?(e.litOptions.reflectionSource="envAtlasHQ",e.litOptions.reflectionEncoding=i.envAtlas.encoding,e.litOptions.reflectionCubemapEncoding=i.skybox.encoding,s=!0):t.useSkybox&&i.envAtlas&&!n?(e.litOptions.reflectionSource="envAtlas",e.litOptions.reflectionEncoding=i.envAtlas.encoding,s=!0):t.useSkybox&&i.skybox?(e.litOptions.reflectionSource="cubeMap",e.litOptions.reflectionEncoding=i.skybox.encoding,s=!0):(e.litOptions.reflectionSource=null,e.litOptions.reflectionEncoding=null),t.ambientSH&&!n)e.litOptions.ambientSource="ambientSH",e.litOptions.ambientEncoding=null;else{var r=t.envAtlas||(t.useSkybox&&i.envAtlas?i.envAtlas:null);r&&!n?(e.litOptions.ambientSource="envAtlas",e.litOptions.ambientEncoding=r.encoding):(e.litOptions.ambientSource="constant",e.litOptions.ambientEncoding=null)}e.litOptions.skyboxIntensity=s&&(1!==i.skyboxIntensity||i.physicalUnits),e.litOptions.useCubeMapRotation=s&&i._skyboxRotationShaderInclude},t._updateLightOptions=function(e,t,i,n,s,r){if(e.lightMap=!1,e.lightMapChannel="",e.lightMapUv=0,e.lightMapTransform=0,e.litOptions.lightMapWithoutAmbient=!1,e.dirLightMap=!1,n&&(e.litOptions.noShadow=0!=(1&n),0!=(64&n)&&(e.lightMapEncoding=7===t.lightmapPixelFormat?"rgbm":"linear",e.lightMap=!0,e.lightMapChannel="rgb",e.lightMapUv=1,e.lightMapTransform=0,e.litOptions.lightMapWithoutAmbient=!i.lightMap,0!=(n&Gr)&&(e.dirLightMap=!0),0!=(n&qr)&&(e.litOptions.lightMapWithoutAmbient=!1))),i.useLighting){var a=[],o=n?n>>16:1;e.litOptions.lightMaskDynamic=!!(1&o),s&&(this._collectLights(0,s[0],a,o),this._collectLights(1,s[1],a,o,r),this._collectLights(2,s[2],a,o,r)),e.litOptions.lights=a}else e.litOptions.lights=[];0===e.litOptions.lights.length&&(e.litOptions.noShadow=!0)},t._collectLights=function(e,t,i,n,s){for(var r=0;r<t.length;r++){var a=t[r];if(a.enabled&&a.mask&n){if(0!==e&&a.isStatic)continue;i.push(a)}}if(s)for(var o=0;o<s.length;o++){var h=s[o];h._type===e&&i.push(h)}},t._getMapTransformID=function(e,t){if(!e)return 0;var i=this._mapXForms[t];i||(i=[],this._mapXForms[t]=i);for(var n=0;n<i.length;n++)if(kl(i[n][0].value,e[0].value)&&kl(i[n][1].value,e[1].value))return n+1;return i.push(e)},e}();function Nl(e,t,i){void 0===t&&(t=!0),void 0===i&&(i=!0);var n={};return n[e+"Map"]="texture",n[e+"MapTiling"]="vec2",n[e+"MapOffset"]="vec2",n[e+"MapRotation"]="number",n[e+"MapUv"]="number",t&&(n[e+"MapChannel"]="string",i&&(n[e+"VertexColor"]="boolean",n[e+"VertexColorChannel"]="string")),n}var Ul=$({name:"string",chunks:"chunks",mappingFormat:"string",_engine:"boolean",ambient:"rgb",ambientTint:"boolean"},Nl("ao"),Nl("aoDetail",!0,!1),{aoDetailMode:"string",diffuse:"rgb",diffuseTint:"boolean"},Nl("diffuse"),Nl("diffuseDetail",!0,!1),{diffuseDetailMode:"string",specular:"rgb",specularTint:"boolean"},Nl("specular"),{occludeSpecular:"enum:occludeSpecular",specularityFactor:"number",specularityFactorTint:"boolean"},Nl("specularityFactor"),{useMetalness:"boolean",metalness:"number",enableGGXSpecular:"boolean",anisotropy:"number",metalnessTint:"boolean"},Nl("metalness"),{useMetalnessSpecularColor:"boolean",conserveEnergy:"boolean",shininess:"number",gloss:"number",glossInvert:"boolean"},Nl("gloss"),{clearCoat:"number"},Nl("clearCoat"),{clearCoatGloss:"number",clearCoatGlossInvert:"boolean"},Nl("clearCoatGloss"),{clearCoatBumpiness:"number"},Nl("clearCoatNormal",!1),{useSheen:"boolean",sheen:"rgb",sheenTint:"boolean"},Nl("sheen"),{sheenGloss:"number",sheenGlossTint:"boolean",sheenGlossInvert:"boolean"},Nl("sheenGloss"),{fresnelModel:"number",emissive:"rgb",emissiveTint:"boolean"},Nl("emissive"),{emissiveIntensity:"number"},Nl("normal",!1),{bumpiness:"number"},Nl("normalDetail",!1),{normalDetailMapBumpiness:"number"},Nl("height",!0,!1),{heightMapFactor:"number",alphaToCoverage:"boolean",alphaTest:"number",alphaFade:"number",opacity:"number"},Nl("opacity"),{opacityFadesSpecular:"boolean",reflectivity:"number",refraction:"number",refractionTint:"boolean"},Nl("refraction"),{refractionIndex:"number",thickness:"number",thicknessTint:"boolean"},Nl("thickness"),{attenuation:"rgb",attenuationDistance:"number",useDynamicRefraction:"boolean",sphereMap:"texture",cubeMap:"cubemap",cubeMapProjection:"number",cubeMapProjectionBox:"boundingbox",useIridescence:"boolean",iridescence:"number",iridescenceTint:"boolean"},Nl("iridescence"),{iridescenceThicknessTint:"boolean",iridescenceThicknessMin:"number",iridescenceThicknessMax:"number",iridescenceRefractionIndex:"number"},Nl("iridescenceThickness"),Nl("light"),{depthTest:"boolean",depthFunc:"enum:depthFunc",depthWrite:"boolean",depthBias:"number",slopeDepthBias:"number",cull:"enum:cull",blendType:"enum:blendType",shadingModel:"enum:shadingModel",useFog:"boolean",useLighting:"boolean",useSkybox:"boolean",useGammaTonemap:"boolean",envAtlas:"texture",twoSidedLighting:"boolean"}),zl=[];for(var Vl in Ul){"texture"===Ul[Vl]&&zl.push(Vl)}var Gl=[];for(var Hl in Ul){"cubemap"===Ul[Hl]&&Gl.push(Hl)}var Wl={aoMapVertexColor:"boolean",diffuseMapTint:"boolean",diffuseMapVertexColor:"boolean",emissiveMapTint:"boolean",emissiveMapVertexColor:"boolean",glossMapVertexColor:"boolean",metalnessMapVertexColor:"boolean",opacityMapVertexColor:"boolean",specularAntialias:"boolean",specularMapTint:"boolean",specularMapVertexColor:"boolean"},Xl={},jl={},ql=new Set,Yl=function(e){function t(){var t;return(t=e.call(this)||this)._dirtyShader=!0,t._assetReferences={},t._activeParams=new Set,t._activeLightingParams=new Set,t.shaderOptBuilder=new Bl,t.reset(),t}Q(t,e);var i=t.prototype;return i.reset=function(){var e=this;Object.keys(Xl).forEach((function(t){e["_"+t]=Xl[t].value()})),this._chunks={},this._uniformCache={}},i.copy=function(t){var i=this;for(var n in e.prototype.copy.call(this,t),Object.keys(Xl).forEach((function(e){i[e]=t[e]})),t._chunks)t._chunks.hasOwnProperty(n)&&(this._chunks[n]=t._chunks[n]);return this},i._setParameter=function(e,t){ql.add(e),this.setParameter(e,t)},i._setParameters=function(e){var t=this;e.forEach((function(e){t._setParameter(e.name,e.value)}))},i._processParameters=function(e){var t=this,i=this[e];i.forEach((function(e){ql.has(e)||delete t.parameters[e]})),this[e]=ql,(ql=i).clear()},i._updateMap=function(e){var t=e+"Map",i=this[t];if(i){this._setParameter("texture_"+t,i);var n=t+"Transform",s=this.getUniform(n);s&&this._setParameters(s)}},i._allocUniform=function(e,t){var i=this._uniformCache[e];return i||(i=t(),this._uniformCache[e]=i),i},i.getUniform=function(e,t,i){return jl[e](this,t,i)},i.updateUniforms=function(e,t){var i=this,n=function(n){return i.getUniform(n,e,t)};if(this._setParameter("material_ambient",n("ambient")),this.diffuseMap&&!this.diffuseTint||this._setParameter("material_diffuse",n("diffuse")),this.useMetalness)if((!this.metalnessMap||this.metalness<1)&&this._setParameter("material_metalness",this.metalness),this.specularMap&&!this.specularTint||this._setParameter("material_specular",n("specular")),this.specularityFactorMap&&!this.specularityFactorTint||this._setParameter("material_specularityFactor",this.specularityFactor),this.sheenMap&&!this.sheenTint||this._setParameter("material_sheen",n("sheen")),this.sheenGlossMap&&!this.sheenGlossTint||this._setParameter("material_sheenGloss",this.sheenGloss),0===this.refractionIndex)this._setParameter("material_f0",1);else if(this.refractionIndex!==1/1.5){var s=1/this.refractionIndex,r=(s-1)/(s+1);this._setParameter("material_f0",r*r)}else this._setParameter("material_f0",.04);else this.specularMap&&!this.specularTint||this._setParameter("material_specular",n("specular"));for(var a in this.enableGGXSpecular&&this._setParameter("material_anisotropy",this.anisotropy),this.clearCoat>0&&(this._setParameter("material_clearCoat",this.clearCoat),this._setParameter("material_clearCoatGloss",this.clearCoatGloss),this._setParameter("material_clearCoatBumpiness",this.clearCoatBumpiness)),this._setParameter("material_gloss",n("gloss")),this.emissiveMap&&!this.emissiveTint||this._setParameter("material_emissive",n("emissive")),1!==this.emissiveIntensity&&this._setParameter("material_emissiveIntensity",this.emissiveIntensity),this.refraction>0&&(this._setParameter("material_refraction",this.refraction),this._setParameter("material_refractionIndex",this.refractionIndex)),this.useDynamicRefraction&&(this._setParameter("material_thickness",this.thickness),this._setParameter("material_attenuation",n("attenuation")),this._setParameter("material_invAttenuationDistance",0===this.attenuationDistance?0:1/this.attenuationDistance)),this.useIridescence&&(this._setParameter("material_iridescence",this.iridescence),this._setParameter("material_iridescenceRefractionIndex",this.iridescenceRefractionIndex),this._setParameter("material_iridescenceThicknessMin",this.iridescenceThicknessMin),this._setParameter("material_iridescenceThicknessMax",this.iridescenceThicknessMax)),this._setParameter("material_opacity",this.opacity),!1===this.opacityFadesSpecular&&this._setParameter("material_alphaFade",this.alphaFade),this.occludeSpecular&&this._setParameter("material_occludeSpecularIntensity",this.occludeSpecularIntensity),1===this.cubeMapProjection&&this._setParameter(n("cubeMapProjectionBox")),Dl)this._updateMap(a);this.ambientSH&&this._setParameter("ambientSH[0]",this.ambientSH),this.normalMap&&this._setParameter("material_bumpiness",this.bumpiness),this.normalMap&&this.normalDetailMap&&this._setParameter("material_normalDetailMapBumpiness",this.normalDetailMapBumpiness),this.heightMap&&this._setParameter("material_heightMapFactor",n("heightMapFactor"));var o=0===this.shadingModel;this.envAtlas&&this.cubeMap&&!o?(this._setParameter("texture_envAtlas",this.envAtlas),this._setParameter("texture_cubeMap",this.cubeMap)):this.envAtlas&&!o?this._setParameter("texture_envAtlas",this.envAtlas):this.cubeMap?this._setParameter("texture_cubeMap",this.cubeMap):this.sphereMap&&this._setParameter("texture_sphereMap",this.sphereMap),this._setParameter("material_reflectivity",this.reflectivity),this._processParameters("_activeParams"),this._dirtyShader&&this.clearVariants()},i.updateEnvUniforms=function(e,t){var i=0===this.shadingModel;!(this.envAtlas&&!i||this.cubeMap||this.sphereMap)&&this.useSkybox&&(t.envAtlas&&t.skybox&&!i?(this._setParameter("texture_envAtlas",t.envAtlas),this._setParameter("texture_cubeMap",t.skybox)):t.envAtlas&&!i?this._setParameter("texture_envAtlas",t.envAtlas):t.skybox&&this._setParameter("texture_cubeMap",t.skybox)),this._processParameters("_activeLightingParams")},i.getShaderVariant=function(e,t,i,n,s,r,a,o,h){this.updateEnvUniforms(e,t);var l=Fa.get(e).getByIndex(s),c=2===s||3===s||l.isShadowPass,u=c?Ol.optionsContextMin:Ol.optionsContext;c?this.shaderOptBuilder.updateMinRef(u,t,this,i,n,s,r):this.shaderOptBuilder.updateRef(u,t,this,i,n,s,r),this.onUpdateShader&&(u=this.onUpdateShader(u));var d=new va(a,o,h),f=wa(e);f.register("standard",Ol);var p=f.getProgram("standard",u,d);return this._dirtyShader=!1,p},i.destroy=function(){for(var t in this._assetReferences)this._assetReferences[t]._unbind();this._assetReferences=null,e.prototype.destroy.call(this)},Z(t,[{key:"shader",get:function(){return null},set:function(e){}},{key:"chunks",get:function(){return this._dirtyShader=!0,this._chunks},set:function(e){this._dirtyShader=!0,this._chunks=e}}]),t}(Ya);Yl.TEXTURE_PARAMETERS=zl,Yl.CUBEMAP_PARAMETERS=Gl;var Kl,Zl,$l,Ql,Jl=function(e,t){jl[e]=t},ec=function(e,t,i,n){Object.defineProperty(Yl.prototype,e,{get:n||function(){return this["_"+e]},set:i}),Xl[e]={value:t}},tc=function(e){return e.defaultValue&&e.defaultValue.clone?function(e){var t="_"+e.name,i=e.dirtyShaderFunc||function(){return!0};ec(e.name,(function(){return e.defaultValue.clone()}),(function(e){var n=this[t];n.equals(e)||(this._dirtyShader=this._dirtyShader||i(n,e),this[t]=n.copy(e))}),e.getterFunc)}(e):function(e){var t="_"+e.name,i=e.dirtyShaderFunc||function(){return!0};ec(e.name,(function(){return e.defaultValue}),(function(e){var n=this[t];n!==e&&(this._dirtyShader=this._dirtyShader||i(n,e),this[t]=e)}),e.getterFunc)}(e)};function ic(e,t,i,n){void 0===t&&(t="rgb"),void 0===i&&(i=!0),void 0===n&&(n=0),Dl[e]=t.length||-1,tc({name:e+"Map",defaultValue:null,dirtyShaderFunc:function(e,t){return!!e!=!!t||e&&(e.type!==t.type||e.fixCubemapSeams!==t.fixCubemapSeams||e.format!==t.format)}}),tc({name:e+"MapTiling",defaultValue:new ge(1,1)}),tc({name:e+"MapOffset",defaultValue:new ge(0,0)}),tc({name:e+"MapRotation",defaultValue:0}),tc({name:e+"MapUv",defaultValue:n}),t&&(tc({name:e+"MapChannel",defaultValue:t}),i&&(tc({name:e+"VertexColor",defaultValue:!1}),tc({name:e+"VertexColorChannel",defaultValue:t})));var s=e+"MapTiling",r=e+"MapOffset",a=e+"MapRotation",o=e+"MapTransform";Jl(o,(function(e,t,i){var n=e[s],h=e[r],l=e[a];if(1===n.x&&1===n.y&&0===h.x&&0===h.y&&0===l)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)}]})),u=Math.cos(l*ce.DEG_TO_RAD),d=Math.sin(l*ce.DEG_TO_RAD),f=c[0].value;f[0]=u*n.x,f[1]=-d*n.y,f[2]=h.x;var p=c[1].value;return p[0]=d*n.x,p[1]=u*n.y,p[2]=1-n.y-h.y,c}))}function nc(e,t){tc({name:e,defaultValue:t,getterFunc:function(){return this._dirtyShader=!0,this["_"+e]}}),Jl(e,(function(t,i,n){var s=t._allocUniform(e,(function(){return new Float32Array(3)})),r=t[e];return t.useGammaTonemap&&n.gammaCorrection?(s[0]=Math.pow(r.r,2.2),s[1]=Math.pow(r.g,2.2),s[2]=Math.pow(r.b,2.2)):(s[0]=r.r,s[1]=r.g,s[2]=r.b),s}))}function sc(e,t,i){tc({name:e,defaultValue:t,dirtyShaderFunc:function(e,t){return(0===e||1===e)!=(0===t||1===t)}}),Jl(e,i)}function rc(e,t){tc({name:e,defaultValue:null,dirtyShaderFunc:function(e,t){return!!e==!!t}}),Jl(e,t)}function ac(e,t){tc({name:e,defaultValue:t})}!function(){nc("ambient",new ue(.7,.7,.7)),nc("diffuse",new ue(1,1,1)),nc("specular",new ue(0,0,0)),nc("emissive",new ue(0,0,0)),nc("sheen",new ue(1,1,1)),nc("attenuation",new ue(1,1,1)),sc("emissiveIntensity",1),sc("specularityFactor",1),sc("sheenGloss",0),sc("gloss",.25,(function(e,t,i){return 0===e.shadingModel?Math.pow(2,11*e.gloss):e.gloss})),sc("heightMapFactor",1,(function(e,t,i){return.025*e.heightMapFactor})),sc("opacity",1),sc("alphaFade",1),sc("alphaTest",0),sc("bumpiness",1),sc("normalDetailMapBumpiness",1),sc("reflectivity",1),sc("occludeSpecularIntensity",1),sc("refraction",0),sc("refractionIndex",1/1.5),sc("thickness",0),sc("attenuationDistance",0),sc("metalness",1),sc("anisotropy",0),sc("clearCoat",0),sc("clearCoatGloss",1),sc("clearCoatBumpiness",1),sc("aoUvSet",0,null),sc("iridescence",0),sc("iridescenceRefractionIndex",1/1.5),sc("iridescenceThicknessMin",0),sc("iridescenceThicknessMax",0),rc("ambientSH"),rc("cubeMapProjectionBox",(function(e,t,i){var n=e._allocUniform("cubeMapProjectionBox",(function(){return[{name:"envBoxMin",value:new Float32Array(3)},{name:"envBoxMax",value:new Float32Array(3)}]})),s=e.cubeMapProjectionBox.getMin(),r=n[0].value;r[0]=s.x,r[1]=s.y,r[2]=s.z;var a=e.cubeMapProjectionBox.getMax(),o=n[1].value;return o[0]=a.x,o[1]=a.y,o[2]=a.z,n})),ac("ambientTint",!1),ac("diffuseTint",!1),ac("specularTint",!1),ac("specularityFactorTint",!1),ac("emissiveTint",!1),ac("fastTbn",!1),ac("useMetalness",!1),ac("useMetalnessSpecularColor",!1),ac("useSheen",!1),ac("enableGGXSpecular",!1),ac("occludeDirect",!1),ac("normalizeNormalMap",!0),ac("conserveEnergy",!0),ac("opacityFadesSpecular",!0),ac("occludeSpecular",1),ac("shadingModel",1),ac("fresnelModel",2),ac("useDynamicRefraction",!1),ac("cubeMapProjection",0),ac("customFragmentShader",null),ac("forceFragmentPrecision",null),ac("useFog",!0),ac("useLighting",!0),ac("useGammaTonemap",!0),ac("useSkybox",!0),ac("forceUv1",!1),ac("pixelSnap",!1),ac("twoSidedLighting",!1),ac("nineSlicedMode",void 0),ac("msdfTextAttribute",!1),ac("useIridescence",!1),ac("glossInvert",!1),ac("sheenGlossInvert",!1),ac("clearCoatGlossInvert",!1),ic("diffuse"),ic("specular"),ic("emissive"),ic("thickness","g"),ic("specularityFactor","g"),ic("normal",""),ic("metalness","g"),ic("gloss","g"),ic("opacity","a"),ic("refraction","g"),ic("height","g",!1),ic("ao","g"),ic("light","rgb",!0,1),ic("msdf",""),ic("diffuseDetail","rgb",!1),ic("normalDetail",""),ic("aoDetail","g",!1),ic("clearCoat","g"),ic("clearCoatGloss","g"),ic("clearCoatNormal",""),ic("sheen","rgb"),ic("sheenGloss","g"),ic("iridescence","g"),ic("iridescenceThickness","g"),ac("diffuseDetailMode",Vr),ac("aoDetailMode",Vr),rc("cubeMap"),rc("sphereMap"),rc("envAtlas");var e=[null,null,null,null,null,null];ec("prefilteredCubemaps",(function(){return e.slice()}),(function(e){var t=this._prefilteredCubemaps;e=e||[];for(var i=!1,n=!0,s=0;s<6;++s){var r=e[s]||null;t[s]!==r&&(t[s]=r,i=!0),n=n&&!!t[s]}i&&(n?this.envAtlas=Cl.generatePrefilteredAtlas(t,{target:this.envAtlas}):this.envAtlas&&(this.envAtlas.destroy(),this.envAtlas=null),this._dirtyShader=!0)}),(function(){return this._prefilteredCubemaps}))}(),new me(1,1,1),new me(40,0,0);var oc=[null,function(e,t){return e.drawOrder-t.drawOrder},function(e,t){return Kl=e._key[0],Zl=t._key[0],Kl===Zl&&e.mesh&&t.mesh?t.mesh.id-e.mesh.id:Zl-Kl},function(e,t){return t.zdist-e.zdist},function(e,t){return e.zdist-t.zdist}];function hc(e,t){return t.key-e.key}var lc=0,cc=function(){this.list=[],this.length=0,this.done=!1},uc=function(){function e(){this.opaqueMeshInstances=[],this.transparentMeshInstances=[],this.shadowCasters=[],this.visibleOpaque=[],this.visibleTransparent=[]}var t=e.prototype;return t.prepare=function(e){this.visibleOpaque[e]||(this.visibleOpaque[e]=new cc),this.visibleTransparent[e]||(this.visibleTransparent[e]=new cc),this.visibleOpaque[e].done=!1,this.visibleTransparent[e].done=!1},t.delete=function(e){e<this.visibleOpaque.length&&this.visibleOpaque.splice(e,1),e<this.visibleTransparent.length&&this.visibleTransparent.splice(e,1)},e}(),dc=function(){function e(e){var t,i,n,s,r;void 0===e&&(e={}),void 0!==e.id?(this.id=e.id,lc=Math.max(this.id+1,lc)):this.id=lc++,this.name=e.name,this._enabled=null==(t=e.enabled)||t,this._refCounter=this._enabled?1:0,this.opaqueSortMode=null!=(i=e.opaqueSortMode)?i:2,this.transparentSortMode=null!=(n=e.transparentSortMode)?n:3,e.renderTarget&&(this.renderTarget=e.renderTarget),this.shaderPass=null!=(s=e.shaderPass)?s:0,this.passThrough=null!=(r=e.passThrough)&&r,this._clearColorBuffer=!!e.clearColorBuffer,this._clearDepthBuffer=!!e.clearDepthBuffer,this._clearStencilBuffer=!!e.clearStencilBuffer,this.onPreCull=e.onPreCull,this.onPreRender=e.onPreRender,this.onPreRenderOpaque=e.onPreRenderOpaque,this.onPreRenderTransparent=e.onPreRenderTransparent,this.onPostCull=e.onPostCull,this.onPostRender=e.onPostRender,this.onPostRenderOpaque=e.onPostRenderOpaque,this.onPostRenderTransparent=e.onPostRenderTransparent,this.onDrawCall=e.onDrawCall,this.onEnable=e.onEnable,this.onDisable=e.onDisable,this._enabled&&this.onEnable&&this.onEnable(),this.layerReference=e.layerReference,this.instances=e.layerReference?e.layerReference.instances:new uc,this.cullingMask=e.cullingMask?e.cullingMask:4294967295,this.opaqueMeshInstances=this.instances.opaqueMeshInstances,this.transparentMeshInstances=this.instances.transparentMeshInstances,this.shadowCasters=this.instances.shadowCasters,this.customSortCallback=null,this.customCalculateSortValues=null,this._lights=[],this._lightsSet=new Set,this._clusteredLightsSet=new Set,this._splitLights=[[],[],[]],this.cameras=[],this._dirty=!1,this._dirtyLights=!1,this._dirtyCameras=!1,this._lightHash=0,this._staticLightHash=0,this._needsStaticPrepare=!0,this._staticPrepareDone=!1,this._shaderVersion=-1,this._lightCube=null}var t=e.prototype;return t.incrementCounter=function(){0===this._refCounter&&(this._enabled=!0,this.onEnable&&this.onEnable()),this._refCounter++},t.decrementCounter=function(){if(1===this._refCounter)this._enabled=!1,this.onDisable&&this.onDisable();else if(0===this._refCounter)return;this._refCounter--},t.addMeshInstances=function(e,t){for(var i=this._shaderVersion,n=this.shadowCasters,s=0;s<e.length;s++){var r=e[s],a=r.material,o=3===a.blendType?this.opaqueMeshInstances:this.transparentMeshInstances;this.opaqueMeshInstances.indexOf(r)<0&&this.transparentMeshInstances.indexOf(r)<0&&o.push(r),!t&&r.castShadow&&n.indexOf(r)<0&&n.push(r),!this.passThrough&&i>=0&&a._shaderVersion!==i&&(a.getShaderVariant!==Ya.prototype.getShaderVariant&&a.clearVariants(),a._shaderVersion=i)}this.passThrough||(this._dirty=!0)},t.removeMeshInstanceFromArray=function(e,t){for(var i=-1,n=0,s=t.length,r=0;r<s;r++){var a=t[r];if(a===e){i=r,n=1;break}if(a._staticSource===e)i<0&&(i=r),n++;else if(i>=0)break}i>=0&&t.splice(i,n)},t.removeMeshInstances=function(e,t){for(var i=this.opaqueMeshInstances,n=this.transparentMeshInstances,s=this.shadowCasters,r=0;r<e.length;r++){var a=e[r];if(this.removeMeshInstanceFromArray(a,i),this.removeMeshInstanceFromArray(a,n),!t){var o=s.indexOf(a);o>=0&&s.splice(o,1)}}this._dirty=!0},t.clearMeshInstances=function(e){(0!==this.opaqueMeshInstances.length||0!==this.transparentMeshInstances.length||!e&&0!==this.shadowCasters.length)&&(this.opaqueMeshInstances.length=0,this.transparentMeshInstances.length=0,e||(this.shadowCasters.length=0),this.passThrough||(this._dirty=!0))},t.addLight=function(e){var t=e.light;this._lightsSet.has(t)||(this._lightsSet.add(t),this._lights.push(t),this._dirtyLights=!0,this._generateLightHash()),0!==t.type&&this._clusteredLightsSet.add(t)},t.removeLight=function(e){var t=e.light;this._lightsSet.has(t)&&(this._lightsSet.delete(t),this._lights.splice(this._lights.indexOf(t),1),this._dirtyLights=!0,this._generateLightHash()),0!==t.type&&this._clusteredLightsSet.delete(t)},t.clearLights=function(){this._lightsSet.clear(),this._clusteredLightsSet.clear(),this._lights.length=0,this._dirtyLights=!0},t.addShadowCasters=function(e){for(var t=this.shadowCasters,i=0;i<e.length;i++){var n=e[i];n.castShadow&&(t.indexOf(n)<0&&t.push(n))}this._dirtyLights=!0},t.removeShadowCasters=function(e){for(var t=this.shadowCasters,i=0;i<e.length;i++){var n=t.indexOf(e[i]);n>=0&&t.splice(n,1)}this._dirtyLights=!0},t._generateLightHash=function(){if(this._lights.length>0){this._lights.sort(hc);for(var e="",t="",i=0;i<this._lights.length;i++)this._lights[i].isStatic?t+=this._lights[i].key:e+=this._lights[i].key;0===e.length?this._lightHash=0:this._lightHash=Mi(e),0===t.length?this._staticLightHash=0:this._staticLightHash=Mi(t)}else this._lightHash=0,this._staticLightHash=0},t.addCamera=function(e){this.cameras.indexOf(e)>=0||(this.cameras.push(e),this._dirtyCameras=!0)},t.removeCamera=function(e){var t=this.cameras.indexOf(e);t>=0&&(this.cameras.splice(t,1),this._dirtyCameras=!0,this.instances.delete(t))},t.clearCameras=function(){this.cameras.length=0,this._dirtyCameras=!0},t._calculateSortDistances=function(e,t,i,n){for(var s=0;s<t;s++){var r=e[s];if(!r.command&&!(r.layer<=2))if(r.calculateSortDistance)r.zdist=r.calculateSortDistance(r,i,n);else{var a=r.aabb.center,o=a.x-i.x,h=a.y-i.y,l=a.z-i.z;r.zdist=o*n.x+h*n.y+l*n.z}}},t._sortVisible=function(e,t,i){var n=this.instances,s=e?this.transparentSortMode:this.opaqueSortMode;if(0!==s){var r=e?n.visibleTransparent[i]:n.visibleOpaque[i];5===s?($l=t.getPosition(),Ql=t.forward,this.customCalculateSortValues&&this.customCalculateSortValues(r.list,r.length,$l,Ql),r.list.length!==r.length&&(r.list.length=r.length),this.customSortCallback&&r.list.sort(this.customSortCallback)):(3!==s&&4!==s||($l=t.getPosition(),Ql=t.forward,this._calculateSortDistances(r.list,r.length,$l,Ql)),r.list.length!==r.length&&(r.list.length=r.length),r.list.sort(oc[s]))}},Z(e,[{key:"hasClusteredLights",get:function(){return this._clusteredLightsSet.size>0}},{key:"enabled",get:function(){return this._enabled},set:function(e){e!==this._enabled&&(this._enabled=e,e?(this.incrementCounter(),this.onEnable&&this.onEnable()):(this.decrementCounter(),this.onDisable&&this.onDisable()))}},{key:"clearColorBuffer",get:function(){return this._clearColorBuffer},set:function(e){this._clearColorBuffer=e,this._dirtyCameras=!0}},{key:"clearDepthBuffer",get:function(){return this._clearDepthBuffer},set:function(e){this._clearDepthBuffer=e,this._dirtyCameras=!0}},{key:"clearStencilBuffer",get:function(){return this._clearStencilBuffer},set:function(e){this._clearStencilBuffer=e,this._dirtyCameras=!0}},{key:"clusteredLightsSet",get:function(){return this._clusteredLightsSet}}]),e}(),fc=["uSceneDepthMap","uDepthMap"],pc=["uSceneColorMap","texture_grabPass"],mc=function(){function e(e,t){this.scene=t,this.device=e,this.layer=null,this.device.webgl2||this.device.isWebGPU?this.initMainPath():this.initFallbackPath()}e.requiresRenderPass=function(e,t){return!e.webgl2&&!e.isWebGPU&&t.renderSceneDepthMap};var t=e.prototype;return t.setupUniform=function(e,t,i){(t?fc:pc).forEach((function(t){return e.scope.resolve(t).setValue(i)}))},t.allocateTexture=function(e,t,i,n,s,r){return new Yn(e,{name:i,format:n,width:t?t.colorBuffer.width:e.width,height:t?t.colorBuffer.height:e.height,mipmaps:r,minFilter:s?0:r?5:1,magFilter:s?0:1,addressU:1,addressV:1})},t.getSourceColorFormat=function(e){var t;return null!=(t=null==e?void 0:e.format)?t:this.device.framebufferFormat},t.shouldReallocate=function(e,t,i){if(i&&(null==e?void 0:e.colorBuffer.format)!==this.getSourceColorFormat(t))return!0;var n=(null==t?void 0:t.width)||this.device.width,s=(null==t?void 0:t.height)||this.device.height;return!e||n!==e.width||s!==e.height},t.allocateRenderTarget=function(e,t,i,n,s,r,a){var o=a?fc:pc,h=this.allocateTexture(i,t,o[0],n,s,r);return e?(e.destroyFrameBuffers(),s?e._depthBuffer=h:(e._colorBuffer=h,e._colorBuffers=[h])):e=new Di({name:"renderTargetSceneGrab",colorBuffer:s?null:h,depthBuffer:s?h:null,depth:!s,stencil:i.supportsStencil,autoResolve:!1}),e},t.releaseRenderTarget=function(e){e&&(e.destroyTextureBuffers(),e.destroy())},t.initMainPath=function(){var e=this.device,t=this;this.layer=new dc({enabled:!1,name:"Depth",id:1,onDisable:function(){t.releaseRenderTarget(this.depthRenderTarget),this.depthRenderTarget=null,t.releaseRenderTarget(this.colorRenderTarget),this.colorRenderTarget=null},onPreRenderOpaque:function(i){var n,s=this.cameras[i];if(s.renderSceneColorMap){var r;if(t.shouldReallocate(this.colorRenderTarget,null==(r=s.renderTarget)?void 0:r.colorBuffer,!0)){var a;t.releaseRenderTarget(this.colorRenderTarget);var o=t.getSourceColorFormat(null==(a=s.renderTarget)?void 0:a.colorBuffer);this.colorRenderTarget=t.allocateRenderTarget(this.colorRenderTarget,s.renderTarget,e,o,!1,!0,!1)}var h=this.colorRenderTarget.colorBuffer;e.isWebGPU?(e.copyRenderTarget(s.renderTarget,this.colorRenderTarget,!0,!1),e.mipmapRenderer.generate(this.colorRenderTarget.colorBuffer.impl)):(e.copyRenderTarget(e.renderTarget,this.colorRenderTarget,!0,!1),e.activeTexture(e.maxCombinedTextures-1),e.bindTexture(h),e.gl.generateMipmap(h.impl._glTarget)),t.setupUniform(e,!1,h)}s.renderSceneDepthMap&&(t.shouldReallocate(this.depthRenderTarget,null==(n=s.renderTarget)?void 0:n.depthBuffer)&&(t.releaseRenderTarget(this.depthRenderTarget),this.depthRenderTarget=t.allocateRenderTarget(this.depthRenderTarget,s.renderTarget,e,Je,!0,!1,!0)),e.copyRenderTarget(e.renderTarget,this.depthRenderTarget,!1,!0),t.setupUniform(e,!0,this.depthRenderTarget.depthBuffer))},onPostRenderOpaque:function(e){}})},t.initFallbackPath=function(){var e=this,t=this.device,i=this.scene;this.layer=new dc({enabled:!1,name:"Depth",id:1,shaderPass:2,onEnable:function(){this.depthRenderTarget=new Di({name:"depthRenderTarget-webgl1",depth:!0,stencil:t.supportsStencil,autoResolve:!1,graphicsDevice:t}),this.renderTarget=this.depthRenderTarget},onDisable:function(){this.depthRenderTarget.destroyTextureBuffers(),this.renderTarget=null,e.releaseRenderTarget(this.colorRenderTarget),this.colorRenderTarget=null},onPostCull:function(n){var s=this.cameras[n];if(s.renderSceneDepthMap){var r,a,o;if(null==(r=this.depthRenderTarget)||!r.colorBuffer||e.shouldReallocate(this.depthRenderTarget,null==(a=s.renderTarget)?void 0:a.depthBuffer))null==(o=this.depthRenderTarget)||o.destroyTextureBuffers(),this.depthRenderTarget=e.allocateRenderTarget(this.depthRenderTarget,s.renderTarget,t,7,!1,!1,!0),this.renderTarget=this.depthRenderTarget;for(var h=this.instances.visibleOpaque[n],l=h.list,c=i.layers,u=c.subLayerEnabled,d=c.subLayerList,f=c.getLayerById(0).renderTarget,p=0,m=c.layerList,_=0;_<m.length;_++){var g=m[_];if(g===this)break;if(g.renderTarget===f&&g.enabled&&u[_]){var v=g.cameras.indexOf(s);if(!(v<0)){var y=d[_]?g.instances.visibleTransparent[v]:g.instances.visibleOpaque[v],x=y.length;y=y.list;for(var S=0;S<x;S++){var b=y[S];b.material&&b.material.depthWrite&&!b._noDepthDrawGl1&&(l[p]=b,p++)}}}}h.length=p}},onPreRenderOpaque:function(i){var n=this.cameras[i];if(n.renderSceneColorMap){var s;if(e.shouldReallocate(this.colorRenderTarget,null==(s=n.renderTarget)?void 0:s.colorBuffer)){var r;e.releaseRenderTarget(this.colorRenderTarget);var a=e.getSourceColorFormat(null==(r=n.renderTarget)?void 0:r.colorBuffer);this.colorRenderTarget=e.allocateRenderTarget(this.colorRenderTarget,n.renderTarget,t,a,!1,!1,!1)}var o=this.colorRenderTarget._colorBuffer;o.impl._glTexture||o.impl.initialize(t,o),t.bindTexture(o);var h=t.gl;h.copyTexImage2D(h.TEXTURE_2D,0,o.impl._glFormat,0,0,o.width,o.height,0),o._needsUpload=!1,o._needsMipmapsUpload=!1,e.setupUniform(t,!1,o)}n.renderSceneDepthMap&&e.setupUniform(t,!0,this.depthRenderTarget.colorBuffer)},onDrawCall:function(){t.setBlendState(yi.NOBLEND)},onPostRenderOpaque:function(e){this.cameras[e].renderSceneDepthMap&&(this.instances.visibleOpaque[e].length=0)}})},t.patch=function(e){e.onEnable=this.layer.onEnable,e.onDisable=this.layer.onDisable,e.onPreRenderOpaque=this.layer.onPreRenderOpaque,e.onPostRenderOpaque=this.layer.onPostRenderOpaque,e.shaderPass=this.layer.shaderPass,e.onPostCull=this.layer.onPostCull,e.onDrawCall=this.layer.onDrawCall},e}(),_c=new ue(254/255,254/255,254/255,254/255),gc={drawCalls:[],isNewMaterial:[],lightMaskChanged:[],clear:function(){this.drawCalls.length=0,this.isNewMaterial.length=0,this.lightMaskChanged.length=0}};var vc,yc=function(e){function t(t){var i,n=(i=e.call(this,t)||this).device;i._forwardDrawCalls=0,i._materialSwitches=0,i._depthMapTime=0,i._forwardTime=0,i._sortTime=0;var s=n.scope;return i.fogColorId=s.resolve("fog_color"),i.fogStartId=s.resolve("fog_start"),i.fogEndId=s.resolve("fog_end"),i.fogDensityId=s.resolve("fog_density"),i.ambientId=s.resolve("light_globalAmbient"),i.skyboxIntensityId=s.resolve("skyboxIntensity"),i.cubeMapRotationMatrixId=s.resolve("cubeMapRotationMatrix"),i.pcssDiskSamplesId=s.resolve("pcssDiskSamples[0]"),i.pcssSphereSamplesId=s.resolve("pcssSphereSamples[0]"),i.lightColorId=[],i.lightDir=[],i.lightDirId=[],i.lightShadowMapId=[],i.lightShadowMatrixId=[],i.lightShadowParamsId=[],i.lightShadowIntensity=[],i.lightRadiusId=[],i.lightPos=[],i.lightPosId=[],i.lightWidth=[],i.lightWidthId=[],i.lightHeight=[],i.lightHeightId=[],i.lightInAngleId=[],i.lightOutAngleId=[],i.lightCookieId=[],i.lightCookieIntId=[],i.lightCookieMatrixId=[],i.lightCookieOffsetId=[],i.lightShadowSearchAreaId=[],i.lightCameraParamsId=[],i.shadowMatrixPaletteId=[],i.shadowCascadeDistancesId=[],i.shadowCascadeCountId=[],i.screenSizeId=s.resolve("uScreenSize"),i._screenSize=new Float32Array(4),i.fogColor=new Float32Array(3),i.ambientColor=new Float32Array(3),i.pcssDiskSamples=function(e){for(var t=[],i=0;i<e;++i){var n=Math.sqrt(i+.5)/Math.sqrt(e);t.push(n)}return t}(16),i.pcssSphereSamples=function(e){for(var t=[],i=0;i<e;i++){var n=i/e,s=Math.sqrt(1-n*n);t.push(s)}return t}(16),i}Q(t,e);var i=t.prototype;return i.destroy=function(){e.prototype.destroy.call(this)},i.dispatchGlobalLights=function(e){if(this.ambientColor[0]=e.ambientLight.r,this.ambientColor[1]=e.ambientLight.g,this.ambientColor[2]=e.ambientLight.b,e.gammaCorrection)for(var t=0;t<3;t++)this.ambientColor[t]=Math.pow(this.ambientColor[t],2.2);if(e.physicalUnits)for(var i=0;i<3;i++)this.ambientColor[i]*=e.ambientLuminance;this.ambientId.setValue(this.ambientColor),this.skyboxIntensityId.setValue(e.physicalUnits?e.skyboxLuminance:e.skyboxIntensity),this.cubeMapRotationMatrixId.setValue(e._skyboxRotationMat3.data)},i._resolveLight=function(e,t){var i="light"+t;this.lightColorId[t]=e.resolve(i+"_color"),this.lightDir[t]=new Float32Array(3),this.lightDirId[t]=e.resolve(i+"_direction"),this.lightShadowMapId[t]=e.resolve(i+"_shadowMap"),this.lightShadowMatrixId[t]=e.resolve(i+"_shadowMatrix"),this.lightShadowParamsId[t]=e.resolve(i+"_shadowParams"),this.lightShadowIntensity[t]=e.resolve(i+"_shadowIntensity"),this.lightShadowSearchAreaId[t]=e.resolve(i+"_shadowSearchArea"),this.lightRadiusId[t]=e.resolve(i+"_radius"),this.lightPos[t]=new Float32Array(3),this.lightPosId[t]=e.resolve(i+"_position"),this.lightWidth[t]=new Float32Array(3),this.lightWidthId[t]=e.resolve(i+"_halfWidth"),this.lightHeight[t]=new Float32Array(3),this.lightHeightId[t]=e.resolve(i+"_halfHeight"),this.lightInAngleId[t]=e.resolve(i+"_innerConeAngle"),this.lightOutAngleId[t]=e.resolve(i+"_outerConeAngle"),this.lightCookieId[t]=e.resolve(i+"_cookie"),this.lightCookieIntId[t]=e.resolve(i+"_cookieIntensity"),this.lightCookieMatrixId[t]=e.resolve(i+"_cookieMatrix"),this.lightCookieOffsetId[t]=e.resolve(i+"_cookieOffset"),this.lightCameraParamsId[t]=e.resolve(i+"_cameraParams"),this.shadowMatrixPaletteId[t]=e.resolve(i+"_shadowMatrixPalette[0]"),this.shadowCascadeDistancesId[t]=e.resolve(i+"_shadowCascadeDistances[0]"),this.shadowCascadeCountId[t]=e.resolve(i+"_shadowCascadeCount")},i.setLTCDirectionalLight=function(e,t,i,n,s){this.lightPos[t][0]=n.x-i.x*s,this.lightPos[t][1]=n.y-i.y*s,this.lightPos[t][2]=n.z-i.z*s,this.lightPosId[t].setValue(this.lightPos[t]);var r=e.transformVector(new me(-.5,0,0));this.lightWidth[t][0]=r.x*s,this.lightWidth[t][1]=r.y*s,this.lightWidth[t][2]=r.z*s,this.lightWidthId[t].setValue(this.lightWidth[t]);var a=e.transformVector(new me(0,0,.5));this.lightHeight[t][0]=a.x*s,this.lightHeight[t][1]=a.y*s,this.lightHeight[t][2]=a.z*s,this.lightHeightId[t].setValue(this.lightHeight[t])},i.dispatchDirectLights=function(e,t,i,n){for(var s=0,r=this.device.scope,a=0;a<e.length;a++)if(e[a].mask&i){var o=e[a],h=o._node.getWorldTransform();if(this.lightColorId[s]||this._resolveLight(r,s),this.lightColorId[s].setValue(t.gammaCorrection?o._linearFinalColor:o._finalColor),h.getY(o._direction).mulScalar(-1),o._direction.normalize(),this.lightDir[s][0]=o._direction.x,this.lightDir[s][1]=o._direction.y,this.lightDir[s][2]=o._direction.z,this.lightDirId[s].setValue(this.lightDir[s]),0!==o.shape&&this.setLTCDirectionalLight(h,s,o._direction,n._node.getPosition(),n.farClip),o.castShadows){var l=o.getRenderData(n,0),c=o._getUniformBiasValues(l);this.lightShadowMapId[s].setValue(l.shadowBuffer),this.lightShadowMatrixId[s].setValue(l.shadowMatrix.data),this.shadowMatrixPaletteId[s].setValue(o._shadowMatrixPalette),this.shadowCascadeDistancesId[s].setValue(o._shadowCascadeDistances),this.shadowCascadeCountId[s].setValue(o.numCascades),this.lightShadowIntensity[s].setValue(o.shadowIntensity);var u=1/(l.shadowCamera.renderTarget.width/o.penumbraSize);this.lightShadowSearchAreaId[s].setValue(u);var d=o._shadowCameraParams;d.length=4,d[0]=l.depthRangeCompensation,d[1]=l.shadowCamera._farClip,d[2]=l.shadowCamera._nearClip,d[3]=1,this.lightCameraParamsId[s].setValue(d);var f=o._shadowRenderParams;f.length=4,f[0]=o._shadowResolution,f[1]=c.normalBias,f[2]=c.bias,f[3]=0,this.lightShadowParamsId[s].setValue(f)}s++}return s},i.setLTCPositionalLight=function(e,t){var i=e.transformVector(new me(-.5,0,0));this.lightWidth[t][0]=i.x,this.lightWidth[t][1]=i.y,this.lightWidth[t][2]=i.z,this.lightWidthId[t].setValue(this.lightWidth[t]);var n=e.transformVector(new me(0,0,.5));this.lightHeight[t][0]=n.x,this.lightHeight[t][1]=n.y,this.lightHeight[t][2]=n.z,this.lightHeightId[t].setValue(this.lightHeight[t])},i.dispatchOmniLight=function(e,t,i,n){var s=i._node.getWorldTransform();if(this.lightColorId[n]||this._resolveLight(t,n),this.lightRadiusId[n].setValue(i.attenuationEnd),this.lightColorId[n].setValue(e.gammaCorrection?i._linearFinalColor:i._finalColor),s.getTranslation(i._position),this.lightPos[n][0]=i._position.x,this.lightPos[n][1]=i._position.y,this.lightPos[n][2]=i._position.z,this.lightPosId[n].setValue(this.lightPos[n]),0!==i.shape&&this.setLTCPositionalLight(s,n),i.castShadows){var r=i.getRenderData(null,0);this.lightShadowMapId[n].setValue(r.shadowBuffer);var a=i._getUniformBiasValues(r),o=i._shadowRenderParams;o.length=4,o[0]=i._shadowResolution,o[1]=a.normalBias,o[2]=a.bias,o[3]=1/i.attenuationEnd,this.lightShadowParamsId[n].setValue(o),this.lightShadowIntensity[n].setValue(i.shadowIntensity);var h=1/(r.shadowCamera.renderTarget.width/i.penumbraSize);this.lightShadowSearchAreaId[n].setValue(h);var l=i._shadowCameraParams;l.length=4,l[0]=1,l[1]=r.shadowCamera._farClip,l[2]=r.shadowCamera._nearClip,l[3]=0,this.lightCameraParamsId[n].setValue(l)}i._cookie&&(this.lightCookieId[n].setValue(i._cookie),this.lightShadowMatrixId[n].setValue(s.data),this.lightCookieIntId[n].setValue(i.cookieIntensity))},i.dispatchSpotLight=function(e,t,i,n){var s=i._node.getWorldTransform();if(this.lightColorId[n]||this._resolveLight(t,n),this.lightInAngleId[n].setValue(i._innerConeAngleCos),this.lightOutAngleId[n].setValue(i._outerConeAngleCos),this.lightRadiusId[n].setValue(i.attenuationEnd),this.lightColorId[n].setValue(e.gammaCorrection?i._linearFinalColor:i._finalColor),s.getTranslation(i._position),this.lightPos[n][0]=i._position.x,this.lightPos[n][1]=i._position.y,this.lightPos[n][2]=i._position.z,this.lightPosId[n].setValue(this.lightPos[n]),0!==i.shape&&this.setLTCPositionalLight(s,n),s.getY(i._direction).mulScalar(-1),i._direction.normalize(),this.lightDir[n][0]=i._direction.x,this.lightDir[n][1]=i._direction.y,this.lightDir[n][2]=i._direction.z,this.lightDirId[n].setValue(this.lightDir[n]),i.castShadows){var r=i.getRenderData(null,0);this.lightShadowMapId[n].setValue(r.shadowBuffer),this.lightShadowMatrixId[n].setValue(r.shadowMatrix.data);var a=i._getUniformBiasValues(r),o=i._shadowRenderParams;o.length=4,o[0]=i._shadowResolution,o[1]=a.normalBias,o[2]=a.bias,o[3]=1/i.attenuationEnd,this.lightShadowParamsId[n].setValue(o),this.lightShadowIntensity[n].setValue(i.shadowIntensity);var h=1/(r.shadowCamera.renderTarget.width/i.penumbraSize),l=r.shadowCamera._fov*Math.PI/180,c=1/Math.tan(l/2);this.lightShadowSearchAreaId[n].setValue(h*c);var u=i._shadowCameraParams;u.length=4,u[0]=1,u[1]=r.shadowCamera._farClip,u[2]=r.shadowCamera._nearClip,u[3]=0,this.lightCameraParamsId[n].setValue(u)}if(i._cookie){if(!i.castShadows){var d=Ko.evalSpotCookieMatrix(i);this.lightShadowMatrixId[n].setValue(d.data)}this.lightCookieId[n].setValue(i._cookie),this.lightCookieIntId[n].setValue(i.cookieIntensity),i._cookieTransform&&(i._cookieTransformUniform[0]=i._cookieTransform.x,i._cookieTransformUniform[1]=i._cookieTransform.y,i._cookieTransformUniform[2]=i._cookieTransform.z,i._cookieTransformUniform[3]=i._cookieTransform.w,this.lightCookieMatrixId[n].setValue(i._cookieTransformUniform),i._cookieOffsetUniform[0]=i._cookieOffset.x,i._cookieOffsetUniform[1]=i._cookieOffset.y,this.lightCookieOffsetId[n].setValue(i._cookieOffsetUniform))}},i.dispatchLocalLights=function(e,t,i,n,s){for(var r=n,a=this.device.scope,o=e[1],h=o.length,l=0;l<h;l++){var c=o[l];c.mask&i&&(c.isStatic||(this.dispatchOmniLight(t,a,c,r),r++))}var u=0;if(s)for(var d=s[u];d&&1===d._type;)this.dispatchOmniLight(t,a,d,r),r++,d=s[++u];for(var f=e[2],p=f.length,m=0;m<p;m++){var _=f[m];_.mask&i&&(_.isStatic||(this.dispatchSpotLight(t,a,_,r),r++))}if(s)for(var g=s[u];g&&2===g._type;)this.dispatchSpotLight(t,a,g,r),r++,g=s[++u]},i.renderForwardPrepareMaterials=function(e,t,i,n,s,r,a){var o=function(e,t,i){gc.drawCalls.push(e),gc.isNewMaterial.push(t),gc.lightMaskChanged.push(i)};gc.clear();for(var h,l,c,u=this.device,d=this.scene,f=r?r._lightHash:0,p=null,m=0;m<i;m++){var _=t[m];if(!s||!_.mask||s&_.mask)if(_.command)o(_,!1,!1);else{_.ensureMaterial(u);var g=_.material,v=_._shaderDefs,y=_.mask;if(g&&g===p&&v!==h&&(p=null),(_.isStatic||l)&&(p=null),g!==p&&(this._materialSwitches++,g._scene=d,g.dirty&&(g.updateUniforms(u,d),g.dirty=!1),g._dirtyBlend&&(d.layers._dirtyBlend=!0)),!_._shader[a]||_._shaderDefs!==v||_._lightHash!==f){if(_.isStatic)_.updatePassShader(d,a,_._staticLightList,n,this.viewUniformFormat,this.viewBindGroupFormat);else{var x=a+"_"+v+"_"+f;_._shader[a]=g.variants[x],_._shader[a]||(_.updatePassShader(d,a,null,n,this.viewUniformFormat,this.viewBindGroupFormat),g.variants[x]=_._shader[a])}_._lightHash=f}o(_,g!==p,!p||y!==c),p=g,h=v,c=y,l=_.isStatic}}return null==u.endShaderBatch||u.endShaderBatch(),gc},i.renderForwardInternal=function(e,t,i,n,s,r){for(var a=this.device,o=this.scene,h=1<<n,l=r?-1:1,c=this.scene.clusteredLightingEnabled,u=t.drawCalls.length,d=0;d<u;d++){var f=t.drawCalls[d];if(f.command)f.command();else{var p,m,_=t.isNewMaterial[d],g=t.lightMaskChanged[d],v=f.material;f._shaderDefs;var y=f.mask;if(_){var x=f._shader[n];if(!x.failed&&a.setShader(x),x.failed)break;if(v.setParameters(a),g){var S=this.dispatchDirectLights(i[0],o,y,e);c||this.dispatchLocalLights(i,o,y,S,f._staticLightList)}this.alphaTestId.setValue(v.alphaTest),a.setBlendState(v.blendState),a.setDepthState(v.depthState),a.setAlphaToCoverage(v.alphaToCoverage),v.depthBias||v.slopeDepthBias?(a.setDepthBias(!0),a.setDepthBiasValues(v.depthBias,v.slopeDepthBias)):a.setDepthBias(!1)}this.setupCullMode(e._cullFaces,l,f);var b=null!=(p=f.stencilFront)?p:v.stencilFront,w=null!=(m=f.stencilBack)?m:v.stencilBack;a.setStencilState(b,w);var T=f.mesh;f.setParameters(a,h),this.setVertexBuffers(a,T),this.setMorphing(a,f.morphInstance),this.setSkinning(a,f),this.setupMeshUniformBuffers(f,n);var A=f.renderStyle;if(a.setIndexBuffer(T.indexBuffer[A]),null==s||s(f,d),e.xr&&e.xr.session&&e.xr.views.length)for(var C=e.xr.views,E=0;E<C.length;E++){var M=C[E];a.setViewport(M.viewport.x,M.viewport.y,M.viewport.z,M.viewport.w),this.projId.setValue(M.projMat.data),this.projSkyboxId.setValue(M.projMat.data),this.viewId.setValue(M.viewOffMat.data),this.viewInvId.setValue(M.viewInvOffMat.data),this.viewId3.setValue(M.viewMat3.data),this.viewProjId.setValue(M.projViewOffMat.data),this.viewPosId.setValue(M.position),0===E?this.drawInstance(a,f,T,A,!0):this.drawInstance2(a,f,T,A),this._forwardDrawCalls++}else this.drawInstance(a,f,T,A,!0),this._forwardDrawCalls++;d<u-1&&!t.isNewMaterial[d+1]&&v.setParameters(a,f.parameters)}}},i.renderForward=function(e,t,i,n,s,r,a,o,h){var l=this.renderForwardPrepareMaterials(e,t,i,n,r,o,s);this.renderForwardInternal(e,l,n,s,a,h),gc.clear()},i.setSceneConstants=function(){var e=this.scene;if(this.dispatchGlobalLights(e),e.fog!==Nr){if(this.fogColor[0]=e.fogColor.r,this.fogColor[1]=e.fogColor.g,this.fogColor[2]=e.fogColor.b,e.gammaCorrection)for(var t=0;t<3;t++)this.fogColor[t]=Math.pow(this.fogColor[t],2.2);this.fogColorId.setValue(this.fogColor),e.fog===Ur?(this.fogStartId.setValue(e.fogStart),this.fogEndId.setValue(e.fogEnd)):this.fogDensityId.setValue(e.fogDensity)}var i=this.device;this._screenSize[0]=i.width,this._screenSize[1]=i.height,this._screenSize[2]=1/i.width,this._screenSize[3]=1/i.height,this.screenSizeId.setValue(this._screenSize),this.pcssDiskSamplesId.setValue(this.pcssDiskSamples),this.pcssSphereSamplesId.setValue(this.pcssSphereSamples)},i.updateLightStats=function(e,t){},i.buildFrameGraph=function(e,t){var i=this,n=this.scene.clusteredLightingEnabled;if(e.reset(),this.update(t),n){var s=new ga(this.device,(function(){i.scene.lighting.cookiesEnabled&&(i.renderCookies(t._splitLights[2]),i.renderCookies(t._splitLights[1]))}));s.requiresCubemaps=!1,e.addRenderPass(s);var r=new ga(this.device);if(r.requiresCubemaps=!1,e.addRenderPass(r),this.scene.lighting.shadowsEnabled){var a=t._splitLights;this._shadowRendererLocal.prepareClusteredRenderPass(r,a[2],a[1])}r.after=function(){i.updateClusters(t)}}else{var o=t._splitLights;this._shadowRendererLocal.buildNonClusteredRenderPasses(e,o[2],o[1])}for(var h=0,l=!0,c=null,u=t._renderActions,d=function(){var n=u[f],s=t.layerList[n.layerIndex],r=s.cameras[n.cameraIndex];if(!n.isLayerEnabled(t))return"continue";var a=1===s.id&&(r.renderSceneColorMap||r.renderSceneDepthMap);n.hasDirectionalShadowLights&&r&&i._shadowRendererDirectional.buildFrameGraph(e,n,r),l&&(l=!1,h=f,c=n.renderTarget);for(var o=f+1;u[o]&&!u[o].isLayerEnabled(t);)o++;var d=u[o],p=!!d&&1===t.layerList[d.layerIndex].id&&(r.renderSceneColorMap||r.renderSceneDepthMap);if(!d||d.renderTarget!==c||d.hasDirectionalShadowLights||p||a){if(i.addMainRenderPass(e,t,c,h,f,a),n.triggerPostprocess&&null!=r&&r.onPostprocessing){var m=new ga(i.device,(function(){i.renderPassPostprocessing(n,t)}));m.requiresCubemaps=!1,e.addRenderPass(m)}l=!0}},f=h;f<u.length;f++)d()},i.addMainRenderPass=function(e,t,i,n,s,r){var a=this,o={start:n,end:s},h=new ga(this.device,(function(){a.renderPassRenderActions(t,o)})),l=t._renderActions,c=l[n],u=l[s],d=t.layerList[c.layerIndex].cameras[c.cameraIndex];d&&(c.firstCameraUse&&d.onPreRender&&(h.before=function(){d.onPreRender()}),u.lastCameraUse&&d.onPostRender&&(h.after=function(){d.onPostRender()}));var f=r&&mc.requiresRenderPass(this.device,d);(!r||f)&&(h.init(i),h.fullSizeClearRect=d.camera.fullSizeClearRect,f?(h.setClearColor(_c),h.setClearDepth(1)):h.fullSizeClearRect&&(c.clearColor&&h.setClearColor(d.camera.clearColor),c.clearDepth&&h.setClearDepth(d.camera.clearDepth),c.clearStencil&&h.setClearStencil(d.camera.clearStencil))),e.addRenderPass(h)},i.update=function(e){this.frameUpdate(),this.shadowRenderer.frameUpdate();var t=this.scene.clusteredLightingEnabled;this.scene._updateSky(this.device);var i=this.updateLayerComposition(e,t),n=0!=(2&i);this.updateLightStats(e,i),this.beginFrame(e,n),this.setSceneConstants(),this.cullComposition(e),this.gpuUpdate(e._meshInstances)},i.renderPassPostprocessing=function(e,t){t.layerList[e.layerIndex].cameras[e.cameraIndex].onPostprocessing()},i.renderPassRenderActions=function(e,t){for(var i=e._renderActions,n=t.start;n<=t.end;n++)this.renderRenderAction(e,i[n],n===t.start)},i.renderRenderAction=function(e,t,i){var n=this.scene.clusteredLightingEnabled,s=this.device,r=t.layerIndex,a=e.layerList[r],o=e.subLayerList[r],h=t.cameraIndex,l=a.cameras[h];if(t.isLayerEnabled(e)){if(!o&&a.onPreRenderOpaque?a.onPreRenderOpaque(h):o&&a.onPreRenderTransparent&&a.onPreRenderTransparent(h),a._preRenderCalledForCameras&1<<h||(a.onPreRender&&a.onPreRender(h),a._preRenderCalledForCameras|=1<<h),l){var c,u,d;this.setupViewport(l.camera,t.renderTarget),i&&l.camera.fullSizeClearRect||this.clear(l.camera,t.clearColor,t.clearDepth,t.clearStencil),a._sortVisible(o,l.camera.node,h);var f=a.instances,p=o?f.visibleTransparent[h]:f.visibleOpaque[h];this.scene.immediate.onPreRenderLayer(a,p,o),n&&t.lightClusters&&(t.lightClusters.activate(this.lightTextureAtlas),this.clustersDebugRendered||this.scene.lighting.debugLayer!==a.id||(this.clustersDebugRendered=!0)),this.scene._activeCamera=l.camera;var m=this.setCameraUniforms(l.camera,t.renderTarget);s.supportsUniformBuffers&&this.setupViewUniformBuffers(t.viewBindGroups,this.viewUniformFormat,this.viewBindGroupFormat,m);var _=!!(l.camera._flipFaces^(null==t||null==(c=t.renderTarget)?void 0:c.flipY)),g=null!=(u=null==(d=l.camera.shaderPassInfo)?void 0:d.index)?u:a.shaderPass,v=this._forwardDrawCalls;this.renderForward(l.camera,p.list,p.length,a._splitLights,g,a.cullingMask,a.onDrawCall,a,_),a._forwardDrawCalls+=this._forwardDrawCalls-v,s.setBlendState(yi.NOBLEND),s.setStencilState(null,null),s.setAlphaToCoverage(!1),s.setDepthBias(!1)}!o&&a.onPostRenderOpaque?a.onPostRenderOpaque(h):o&&a.onPostRenderTransparent&&a.onPostRenderTransparent(h),!a.onPostRender||a._postRenderCalledForCameras&1<<h||(a._postRenderCounter&=~(o?2:1),0===a._postRenderCounter&&(a.onPostRender(h),a._postRenderCalledForCameras|=1<<h,a._postRenderCounter=a._postRenderCounterMax))}},t}(Jh),xc=function(e,t){if(e.size!==t.size)return!1;for(var i,n=ie(e);!(i=n()).done;){var s=i.value;if(!t.has(s))return!1}return!0},Sc=function(e,t){return e.priority-t.priority},bc=function(e){return e.sort(Sc)},wc=function(){function e(){this.layerIndex=0,this.cameraIndex=0,this.camera=null,this.renderTarget=null,this.lightClusters=null,this.clearColor=!1,this.clearDepth=!1,this.clearStencil=!1,this.triggerPostprocess=!1,this.firstCameraUse=!1,this.lastCameraUse=!1,this.directionalLightsSet=new Set,this.directionalLights=[],this.directionalLightsIndices=[],this.viewBindGroups=[]}var t=e.prototype;return t.destroy=function(){this.viewBindGroups.forEach((function(e){e.defaultUniformBuffer.destroy(),e.destroy()})),this.viewBindGroups.length=0},t.reset=function(){this.lightClusters=null,this.directionalLightsSet.clear(),this.directionalLights.length=0,this.directionalLightsIndices.length=0},t.isLayerEnabled=function(e){return e.layerList[this.layerIndex].enabled&&e.subLayerEnabled[this.layerIndex]},t.collectDirectionalLights=function(e,t,i){this.directionalLightsSet.clear(),this.directionalLights.length=0,this.directionalLightsIndices.length=0;for(var n=0;n<t.length;n++){var s=t[n];if(s.castShadows)for(var r=0;r<e.length;r++)if(e[r]._splitLights[0].indexOf(s)>=0&&!this.directionalLightsSet.has(s)){this.directionalLightsSet.add(s),this.directionalLights.push(s);var a=i.indexOf(s);this.directionalLightsIndices.push(a)}}},Z(e,[{key:"hasDirectionalShadowLights",get:function(){return this.directionalLights.length>0}}]),e}(),Tc=function(){function e(){this.shadowCastersSet=new Set,this.shadowCastersList=[]}var t=e.prototype;return t.clearShadowCasters=function(){this.shadowCastersSet.clear(),this.shadowCastersList.length=0},t.addShadowCasters=function(e){for(var t=0;t<e.length;t++){var i=e[t];this.shadowCastersSet.has(i)||(this.shadowCastersSet.add(i),this.shadowCastersList.push(i))}},e}(),Ac=new Set,Cc=[],Ec=function(e){function t(t){var i;return void 0===t&&(t="Untitled"),(i=e.call(this)||this).name=t,i.layerList=[],i.subLayerList=[],i.subLayerEnabled=[],i._opaqueOrder={},i._transparentOrder={},i._dirty=!1,i._dirtyBlend=!1,i._dirtyLights=!1,i._dirtyCameras=!1,i._meshInstances=[],i._meshInstancesSet=new Set,i._lights=[],i._lightsMap=new Map,i._lightCompositionData=[],i._splitLights=[[],[],[]],i.cameras=[],i._renderActions=[],i._worldClusters=[],i._emptyWorldClusters=null,i}Q(t,e);var i=t.prototype;return i.destroy=function(){this._emptyWorldClusters&&(this._emptyWorldClusters.destroy(),this._emptyWorldClusters=null),this._worldClusters.forEach((function(e){e.destroy()})),this._worldClusters=null,this._renderActions.forEach((function(e){return e.destroy()})),this._renderActions=null},i.getEmptyWorldClusters=function(e){return this._emptyWorldClusters||(this._emptyWorldClusters=new lh(e),this._emptyWorldClusters.name="ClusterEmpty",this._emptyWorldClusters.update([],!1,null)),this._emptyWorldClusters},i._splitLightsArray=function(e){var t=e._lights;e._splitLights[0].length=0,e._splitLights[1].length=0,e._splitLights[2].length=0;for(var i=0;i<t.length;i++){var n=t[i];n.enabled&&e._splitLights[n._type].push(n)}},i._update=function(e,t){void 0===t&&(t=!1);var i=this.layerList.length,n=0;if(!this._dirty||!this._dirtyLights||!this._dirtyCameras)for(var s=0;s<i;s++){var r=this.layerList[s];r._dirty&&(this._dirty=!0),r._dirtyLights&&(this._dirtyLights=!0),r._dirtyCameras&&(this._dirtyCameras=!0)}function a(e,t,i){for(var n=!1,s=i.length,r=0;r<s;r++){var a=i[r];if(!t.has(a)){t.add(a),e.push(a);var o=a.material;o&&o._dirtyBlend&&(n=!0,o._dirtyBlend=!1)}}return n}if(this._dirty){n|=1,this._meshInstances.length=0,this._meshInstancesSet.clear();for(var o=0;o<i;o++){var h=this.layerList[o];h.passThrough||(this._dirtyBlend=a(this._meshInstances,this._meshInstancesSet,h.opaqueMeshInstances)||this._dirtyBlend,this._dirtyBlend=a(this._meshInstances,this._meshInstancesSet,h.transparentMeshInstances)||this._dirtyBlend),h._dirty=!1}this._dirty=!1}function l(e,t,i){for(var n=0;n<t.length;){var s;(null==(s=t[n].material)?void 0:s.transparent)===i?(e.push(t[n]),t[n]=t[t.length-1],t.length--):n++}}if(this._dirtyBlend){n|=8;for(var c=0;c<i;c++){var u=this.layerList[c];u.passThrough||(l(u.opaqueMeshInstances,u.transparentMeshInstances,!1),l(u.transparentMeshInstances,u.opaqueMeshInstances,!0))}this._dirtyBlend=!1}if(this._dirtyLights&&(n|=2,this._dirtyLights=!1,this.updateLights()),n&&this.updateShadowCasters(),this._dirtyCameras||2&n){this._dirtyCameras=!1,n|=4,this.cameras.length=0;for(var d=0;d<i;d++){var f=this.layerList[d];f._dirtyCameras=!1;for(var p=0;p<f.cameras.length;p++){var m=f.cameras[p];this.cameras.indexOf(m)<0&&this.cameras.push(m)}}this.cameras.length>1&&bc(this.cameras);for(var _=[],g=0,v=0;v<this.cameras.length;v++){var y=this.cameras[v];_.length=0;for(var x=!0,S=g,b=null,w=!1,T=0;T<i;T++){var A=this.layerList[T],C=this.subLayerEnabled[T];if(A&&C&&A.cameras.length>0&&y.layers.indexOf(A.id)>=0){_.push(A),w||A.id!==y.disablePostEffectsLayer||(w=!0,b&&(b.triggerPostprocess=!0));var E=A.cameras.indexOf(y);E>=0&&(b=this.addRenderAction(this._renderActions,g,A,T,E,x,w),g++,x=!1)}}S<g&&(this._renderActions[S].collectDirectionalLights(_,this._splitLights[0],this._lights),b.lastCameraUse=!0),!w&&b&&(b.triggerPostprocess=!0),y.renderTarget&&y.postEffectsEnabled&&this.propagateRenderTarget(S-1,y)}for(var M=g;M<this._renderActions.length;M++)this._renderActions[M].destroy();this._renderActions.length=g}return 7&n&&t&&this.allocateLightClusters(e),2&n&&this._logRenderActions(),n},i.updateShadowCasters=function(){for(var e=this._lights.length,t=0;t<e;t++)this._lightCompositionData[t].clearShadowCasters();for(var i=this.layerList.length,n=0;n<i;n++){var s=this.layerList[n];if(!Ac.has(s)){Ac.add(s);for(var r=s._lights,a=0;a<r.length;a++)if(r[a].castShadows){var o=this._lightsMap.get(r[a]);this._lightCompositionData[o].addShadowCasters(s.shadowCasters)}}}Ac.clear()},i.updateLights=function(){this._lights.length=0,this._lightsMap.clear();for(var e=this.layerList.length,t=0;t<e;t++){var i=this.layerList[t];if(!Ac.has(i)){Ac.add(i);for(var n=i._lights,s=0;s<n.length;s++){var r=n[s],a=this._lightsMap.get(r);if(void 0===a){a=this._lights.length,this._lightsMap.set(r,a),this._lights.push(r);var o=this._lightCompositionData[a];o||(o=new Tc,this._lightCompositionData[a]=o)}}}this._splitLightsArray(i),i._dirtyLights=!1}Ac.clear(),this._splitLightsArray(this);var h=this._lights.length;this._lightCompositionData.length=h},i.findCompatibleCluster=function(e,t,i){for(var n=0;n<t;n++){var s=this._renderActions[n],r=this.layerList[s.layerIndex];if(s.lightClusters!==i){if(e===r)return s.lightClusters;if(s.lightClusters&&xc(e._clusteredLightsSet,r._clusteredLightsSet))return s.lightClusters}}return null},i.allocateLightClusters=function(e){Cc.push.apply(Cc,this._worldClusters);var t=this.getEmptyWorldClusters(e);this._worldClusters.length=0;for(var i=this._renderActions.length,n=0;n<i;n++){var s=this._renderActions[n],r=this.layerList[s.layerIndex];if(s.lightClusters=null,r.hasClusteredLights)if((this.subLayerList[s.layerIndex]?r.transparentMeshInstances:r.opaqueMeshInstances).length){var a=this.findCompatibleCluster(r,n,t);a||(Cc.length&&(a=Cc.pop()),a||(a=new lh(e)),a.name="Cluster-"+this._worldClusters.length,this._worldClusters.push(a)),s.lightClusters=a}s.lightClusters||(s.lightClusters=t)}Cc.forEach((function(e){e.destroy()})),Cc.length=0},i.addRenderAction=function(e,t,i,n,s,r,a){var o=e[t];o||(o=e[t]=new wc);var h=i.renderTarget,l=i.cameras[s];l&&l.renderTarget&&1!==i.id&&(h=l.renderTarget);for(var c=!1,u=t-1;u>=0;u--)if(e[u].camera===l&&e[u].renderTarget===h){c=!0;break}var d=r||!c,f=!!d&&l.clearColorBuffer,p=!!d&&l.clearDepthBuffer,m=!!d&&l.clearStencilBuffer;return f||(f=i.clearColorBuffer),p||(p=i.clearDepthBuffer),m||(m=i.clearStencilBuffer),a&&l.postEffectsEnabled&&(h=null),o.reset(),o.triggerPostprocess=!1,o.layerIndex=n,o.cameraIndex=s,o.camera=l,o.renderTarget=h,o.clearColor=f,o.clearDepth=p,o.clearStencil=m,o.firstCameraUse=r,o.lastCameraUse=!1,o},i.propagateRenderTarget=function(e,t){for(var i=e;i>=0;i--){var n=this._renderActions[i],s=this.layerList[n.layerIndex];if(n.renderTarget&&1!==s.id)break;if(1!==s.id){var r=null==n?void 0:n.camera.camera;if(r&&(!t.camera.rect.equals(r.rect)||!t.camera.scissorRect.equals(r.scissorRect)))break;n.renderTarget=t.renderTarget}}},i._logRenderActions=function(){},i._isLayerAdded=function(e){return this.layerList.indexOf(e)>=0},i._isSublayerAdded=function(e,t){for(var i=0;i<this.layerList.length;i++)if(this.layerList[i]===e&&this.subLayerList[i]===t)return!0;return!1},i.push=function(e){this._isLayerAdded(e)||(this.layerList.push(e),this.layerList.push(e),this._opaqueOrder[e.id]=this.subLayerList.push(!1)-1,this._transparentOrder[e.id]=this.subLayerList.push(!0)-1,this.subLayerEnabled.push(!0),this.subLayerEnabled.push(!0),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("add",e))},i.insert=function(e,t){if(!this._isLayerAdded(e)){this.layerList.splice(t,0,e,e),this.subLayerList.splice(t,0,!1,!0);var i=this.layerList.length;this._updateOpaqueOrder(t,i-1),this._updateTransparentOrder(t,i-1),this.subLayerEnabled.splice(t,0,!0,!0),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("add",e)}},i.remove=function(e){var t=this.layerList.indexOf(e);for(delete this._opaqueOrder[t],delete this._transparentOrder[t];t>=0;)this.layerList.splice(t,1),this.subLayerList.splice(t,1),this.subLayerEnabled.splice(t,1),t=this.layerList.indexOf(e),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("remove",e);var i=this.layerList.length;this._updateOpaqueOrder(0,i-1),this._updateTransparentOrder(0,i-1)},i.pushOpaque=function(e){this._isSublayerAdded(e,!1)||(this.layerList.push(e),this._opaqueOrder[e.id]=this.subLayerList.push(!1)-1,this.subLayerEnabled.push(!0),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("add",e))},i.insertOpaque=function(e,t){if(!this._isSublayerAdded(e,!1)){this.layerList.splice(t,0,e),this.subLayerList.splice(t,0,!1);var i=this.subLayerList.length;this._updateOpaqueOrder(t,i-1),this.subLayerEnabled.splice(t,0,!0),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("add",e)}},i.removeOpaque=function(e){for(var t=0,i=this.layerList.length;t<i;t++)if(this.layerList[t]===e&&!this.subLayerList[t])return this.layerList.splice(t,1),this.subLayerList.splice(t,1),i--,this._updateOpaqueOrder(t,i-1),this.subLayerEnabled.splice(t,1),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,void(this.layerList.indexOf(e)<0&&this.fire("remove",e))},i.pushTransparent=function(e){this._isSublayerAdded(e,!0)||(this.layerList.push(e),this._transparentOrder[e.id]=this.subLayerList.push(!0)-1,this.subLayerEnabled.push(!0),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("add",e))},i.insertTransparent=function(e,t){if(!this._isSublayerAdded(e,!0)){this.layerList.splice(t,0,e),this.subLayerList.splice(t,0,!0);var i=this.subLayerList.length;this._updateTransparentOrder(t,i-1),this.subLayerEnabled.splice(t,0,!0),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,this.fire("add",e)}},i.removeTransparent=function(e){for(var t=0,i=this.layerList.length;t<i;t++)if(this.layerList[t]===e&&this.subLayerList[t])return this.layerList.splice(t,1),this.subLayerList.splice(t,1),i--,this._updateTransparentOrder(t,i-1),this.subLayerEnabled.splice(t,1),this._dirty=!0,this._dirtyLights=!0,this._dirtyCameras=!0,void(this.layerList.indexOf(e)<0&&this.fire("remove",e))},i._getSublayerIndex=function(e,t){var i=this.layerList.indexOf(e);if(i<0)return-1;if(this.subLayerList[i]!==t){if((i=this.layerList.indexOf(e,i+1))<0)return-1;if(this.subLayerList[i]!==t)return-1}return i},i.getOpaqueIndex=function(e){return this._getSublayerIndex(e,!1)},i.getTransparentIndex=function(e){return this._getSublayerIndex(e,!0)},i.getLayerById=function(e){for(var t=0;t<this.layerList.length;t++)if(this.layerList[t].id===e)return this.layerList[t];return null},i.getLayerByName=function(e){for(var t=0;t<this.layerList.length;t++)if(this.layerList[t].name===e)return this.layerList[t];return null},i._updateOpaqueOrder=function(e,t){for(var i=e;i<=t;i++)!1===this.subLayerList[i]&&(this._opaqueOrder[this.layerList[i].id]=i)},i._updateTransparentOrder=function(e,t){for(var i=e;i<=t;i++)!0===this.subLayerList[i]&&(this._transparentOrder[this.layerList[i].id]=i)},i._sortLayersDescending=function(e,t,i){for(var n=-1,s=-1,r=0,a=e.length;r<a;r++){var o=e[r];i.hasOwnProperty(o)&&(n=Math.max(n,i[o]))}for(var h=0,l=t.length;h<l;h++){var c=t[h];i.hasOwnProperty(c)&&(s=Math.max(s,i[c]))}return-1===n&&-1!==s?1:-1===s&&-1!==n?-1:s-n},i.sortTransparentLayers=function(e,t){return this._sortLayersDescending(e,t,this._transparentOrder)},i.sortOpaqueLayers=function(e,t){return this._sortLayersDescending(e,t,this._opaqueOrder)},t}(p),Mc=new me,Pc={bias:0,normalBias:0},Rc={r:0,g:1,b:2,a:3},Ic={directional:0,omni:1,point:1,spot:2},Lc=[[new ve(0,0,1,1)],[new ve(0,0,.5,.5),new ve(0,.5,.5,.5)],[new ve(0,0,.5,.5),new ve(0,.5,.5,.5),new ve(.5,0,.5,.5)],[new ve(0,0,.5,.5),new ve(0,.5,.5,.5),new ve(.5,0,.5,.5),new ve(.5,.5,.5,.5)]],Dc=0,Oc=function(){function e(e,t,i,n){this.light=n,this.camera=t,this.shadowCamera=Nh.createShadowCamera(e,n._shadowType,n._type,i),this.shadowMatrix=new Te,this.shadowViewport=new ve(0,0,1,1),this.shadowScissor=new ve(0,0,1,1),this.depthRangeCompensation=0,this.face=i,this.visibleCasters=[],this.viewBindGroups=[]}return e.prototype.destroy=function(){this.viewBindGroups.forEach((function(e){e.defaultUniformBuffer.destroy(),e.destroy()})),this.viewBindGroups.length=0},Z(e,[{key:"shadowBuffer",get:function(){var e=this.shadowCamera.renderTarget;if(e){var t=this.light;return 1===t._type?e.colorBuffer:t._isPcf&&t.device.supportsDepthShadow?e.depthBuffer:e.colorBuffer}return null}}]),e}(),kc=function(){function e(e){this.device=e,this.id=Dc++,this._type=0,this._color=new ue(.8,.8,.8),this._intensity=1,this._affectSpecularity=!0,this._luminance=0,this._castShadows=!1,this._enabled=!1,this.mask=1,this.isStatic=!1,this.key=0,this.bakeDir=!0,this.bakeNumSamples=1,this.bakeArea=0,this.attenuationStart=10,this.attenuationEnd=10,this._falloffMode=0,this._shadowType=0,this._vsmBlurSize=11,this.vsmBlurMode=1,this.vsmBias=.0025,this._cookie=null,this.cookieIntensity=1,this._cookieFalloff=!0,this._cookieChannel="rgb",this._cookieTransform=null,this._cookieTransformUniform=new Float32Array(4),this._cookieOffset=null,this._cookieOffsetUniform=new Float32Array(2),this._cookieTransformSet=!1,this._cookieOffsetSet=!1,this._innerConeAngle=40,this._outerConeAngle=45,this.cascades=null,this._shadowMatrixPalette=null,this._shadowCascadeDistances=null,this.numCascades=1,this.cascadeDistribution=.5,this._shape=0,this._finalColor=new Float32Array([.8,.8,.8]);var t=Math.pow(this._finalColor[0],2.2);this._linearFinalColor=new Float32Array([t,t,t]),this._position=new me(0,0,0),this._direction=new me(0,0,0),this._innerConeAngleCos=Math.cos(this._innerConeAngle*Math.PI/180),this._updateOuterAngle(this._outerConeAngle),this._usePhysicalUnits=void 0,this._shadowMap=null,this._shadowRenderParams=[],this._shadowCameraParams=[],this.shadowDistance=40,this._shadowResolution=1024,this.shadowBias=-5e-4,this.shadowIntensity=1,this._normalOffsetBias=0,this.shadowUpdateMode=2,this.shadowUpdateOverrides=null,this._penumbraSize=1,this._isVsm=!1,this._isPcf=!0,this._cookieMatrix=null,this._atlasViewport=null,this.atlasViewportAllocated=!1,this.atlasVersion=0,this.atlasSlotIndex=0,this.atlasSlotUpdated=!1,this._scene=null,this._node=null,this._renderData=[],this.visibleThisFrame=!1,this.maxScreenSize=0}var t=e.prototype;return t.destroy=function(){this._destroyShadowMap(),this.releaseRenderData(),this._renderData=null},t.releaseRenderData=function(){if(this._renderData){for(var e=0;e<this._renderData.length;e++)this._renderData[e].destroy();this._renderData.length=0}},t._updateOuterAngle=function(e){var t=e*Math.PI/180;this._outerConeAngleCos=Math.cos(t),this._outerConeAngleSin=Math.sin(t)},t.beginFrame=function(){this.visibleThisFrame=0===this._type&&this._enabled,this.maxScreenSize=0,this.atlasViewportAllocated=!1,this.atlasSlotUpdated=!1},t._destroyShadowMap=function(){if(this.releaseRenderData(),this._shadowMap&&(this._shadowMap.cached||this._shadowMap.destroy(),this._shadowMap=null),0===this.shadowUpdateMode&&(this.shadowUpdateMode=1),this.shadowUpdateOverrides)for(var e=0;e<this.shadowUpdateOverrides.length;e++)0===this.shadowUpdateOverrides[e]&&(this.shadowUpdateOverrides[e]=1)},t.getRenderData=function(e,t){for(var i=0;i<this._renderData.length;i++){var n=this._renderData[i];if(n.camera===e&&n.face===t)return n}var s=new Oc(this.device,e,t,this);return this._renderData.push(s),s},t.clone=function(){var t=new e(this.device);return t.type=this._type,t.setColor(this._color),t.intensity=this._intensity,t.affectSpecularity=this._affectSpecularity,t.luminance=this._luminance,t.castShadows=this.castShadows,t._enabled=this._enabled,t.attenuationStart=this.attenuationStart,t.attenuationEnd=this.attenuationEnd,t.falloffMode=this._falloffMode,t.shadowType=this._shadowType,t.vsmBlurSize=this._vsmBlurSize,t.vsmBlurMode=this.vsmBlurMode,t.vsmBias=this.vsmBias,t.penumbraSize=this.penumbraSize,t.shadowUpdateMode=this.shadowUpdateMode,t.mask=this.mask,this.shadowUpdateOverrides&&(t.shadowUpdateOverrides=this.shadowUpdateOverrides.slice()),t.innerConeAngle=this._innerConeAngle,t.outerConeAngle=this._outerConeAngle,t.numCascades=this.numCascades,t.cascadeDistribution=this.cascadeDistribution,t.shape=this._shape,t.shadowBias=this.shadowBias,t.normalOffsetBias=this._normalOffsetBias,t.shadowResolution=this._shadowResolution,t.shadowDistance=this.shadowDistance,t.shadowIntensity=this.shadowIntensity,t},e.getLightUnitConversion=function(e,t,i){switch(void 0===t&&(t=Math.PI/4),void 0===i&&(i=0),e){case 2:var n=Math.cos(t),s=Math.cos(i);return 2*Math.PI*(1-s+(s-n)/2);case 1:return 4*Math.PI;case 0:return 1}},t._getUniformBiasValues=function(e){var t=e.shadowCamera._farClip;switch(this._type){case 1:Pc.bias=this.shadowBias,Pc.normalBias=this._normalOffsetBias;break;case 2:this._isVsm?Pc.bias=-2e-4:(Pc.bias=20*this.shadowBias,!this.device.webgl2&&this.device.extStandardDerivatives&&(Pc.bias*=-100)),Pc.normalBias=this._isVsm?this.vsmBias/(this.attenuationEnd/7):this._normalOffsetBias;break;case 0:this._isVsm?Pc.bias=-2e-4:(Pc.bias=this.shadowBias/t*100,!this.device.webgl2&&this.device.extStandardDerivatives&&(Pc.bias*=-100)),Pc.normalBias=this._isVsm?this.vsmBias/(t/7):this._normalOffsetBias}return Pc},t.getColor=function(){return this._color},t.getBoundingSphere=function(e){if(2===this._type){var t=this.attenuationEnd,i=this._outerConeAngle,n=this._outerConeAngleCos,s=this._node;Mc.copy(s.up),i>45?(e.radius=t*this._outerConeAngleSin,Mc.mulScalar(-t*n)):(e.radius=t/(2*n),Mc.mulScalar(-e.radius)),e.center.add2(s.getPosition(),Mc)}else 1===this._type&&(e.center=this._node.getPosition(),e.radius=this.attenuationEnd)},t.getBoundingBox=function(e){if(2===this._type){var t=this.attenuationEnd,i=this._outerConeAngle,n=this._node,s=Math.abs(Math.sin(i*ce.DEG_TO_RAD)*t);e.center.set(0,.5*-t,0),e.halfExtents.set(s,.5*t,s),e.setFromTransformedAabb(e,n.getWorldTransform(),!0)}else 1===this._type&&(e.center.copy(this._node.getPosition()),e.halfExtents.set(this.attenuationEnd,this.attenuationEnd,this.attenuationEnd))},t._updateFinalColor=function(){var t=this._color,i=t.r,n=t.g,s=t.b,r=this._intensity;this._usePhysicalUnits&&(r=this._luminance/e.getLightUnitConversion(this._type,this._outerConeAngle*ce.DEG_TO_RAD,this._innerConeAngle*ce.DEG_TO_RAD));var a=this._finalColor,o=this._linearFinalColor;a[0]=i*r,a[1]=n*r,a[2]=s*r,r>=1?(o[0]=Math.pow(i,2.2)*r,o[1]=Math.pow(n,2.2)*r,o[2]=Math.pow(s,2.2)*r):(o[0]=Math.pow(a[0],2.2),o[1]=Math.pow(a[1],2.2),o[2]=Math.pow(a[2],2.2))},t.setColor=function(){1===arguments.length?this._color.set(arguments[0].r,arguments[0].g,arguments[0].b):3===arguments.length&&this._color.set(arguments[0],arguments[1],arguments[2]),this._updateFinalColor()},t.layersDirty=function(){var e;null!=(e=this._scene)&&e.layers&&(this._scene.layers._dirtyLights=!0)},t.updateKey=function(){var e=this._type<<29|(this._castShadows?1:0)<<28|this._shadowType<<25|this._falloffMode<<23|(0!==this._normalOffsetBias?1:0)<<22|(this._cookie?1:0)<<21|(this._cookieFalloff?1:0)<<20|Rc[this._cookieChannel.charAt(0)]<<18|(this._cookieTransform?1:0)<<12|this._shape<<10|this.numCascades-1<<8|(this.affectSpecularity?1:0)<<7;3===this._cookieChannel.length&&(e|=Rc[this._cookieChannel.charAt(1)]<<16,e|=Rc[this._cookieChannel.charAt(2)]<<14),e!==this.key&&null!==this._scene&&this.layersDirty(),this.key=e},Z(e,[{key:"numCascades",get:function(){return this.cascades.length},set:function(e){this.cascades&&this.numCascades===e||(this.cascades=Lc[e-1],this._shadowMatrixPalette=new Float32Array(64),this._shadowCascadeDistances=new Float32Array(4),this._destroyShadowMap(),this.updateKey())}},{key:"shadowMap",get:function(){return this._shadowMap},set:function(e){this._shadowMap!==e&&(this._destroyShadowMap(),this._shadowMap=e)}},{key:"numShadowFaces",get:function(){var e=this._type;return 0===e?this.numCascades:1===e?6:1}},{key:"type",get:function(){return this._type},set:function(e){if(this._type!==e){this._type=e,this._destroyShadowMap(),this.updateKey();var t=this._shadowType;this._shadowType=null,this.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();var t=this._shadowType;this._shadowType=null,this.shadowType=t}}},{key:"usePhysicalUnits",get:function(){return this._usePhysicalUnits},set:function(e){this._usePhysicalUnits!==e&&(this._usePhysicalUnits=e,this._updateFinalColor())}},{key:"shadowType",get:function(){return this._shadowType},set:function(e){if(this._shadowType!==e){var t=this.device;1===this._type&&0!==e&&6!==e&&(e=0);var i=t.supportsDepthShadow;4!==e||i||(e=0),3!==e||t.textureFloatRenderable||(e=2),2!==e||t.textureHalfFloatRenderable||(e=1),this._isVsm=e>=1&&e<=3,this._isPcf=5===e||0===e||4===e,this._shadowType=e,this._destroyShadowMap(),this.updateKey()}}},{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled!==e&&(this._enabled=e,this.layersDirty())}},{key:"castShadows",get:function(){return this._castShadows&&4!==this.mask&&0!==this.mask},set:function(e){this._castShadows!==e&&(this._castShadows=e,this._destroyShadowMap(),this.layersDirty(),this.updateKey())}},{key:"shadowResolution",get:function(){return this._shadowResolution},set:function(e){this._shadowResolution!==e&&(e=1===this._type?Math.min(e,this.device.maxCubeMapSize):Math.min(e,this.device.maxTextureSize),this._shadowResolution=e,this._destroyShadowMap())}},{key:"vsmBlurSize",get:function(){return this._vsmBlurSize},set:function(e){this._vsmBlurSize!==e&&(e%2==0&&e++,this._vsmBlurSize=e)}},{key:"normalOffsetBias",get:function(){return this._normalOffsetBias},set:function(e){this._normalOffsetBias!==e&&((!this._normalOffsetBias&&e||this._normalOffsetBias&&!e)&&this.updateKey(),this._normalOffsetBias=e)}},{key:"falloffMode",get:function(){return this._falloffMode},set:function(e){this._falloffMode!==e&&(this._falloffMode=e,this.updateKey())}},{key:"innerConeAngle",get:function(){return this._innerConeAngle},set:function(e){this._innerConeAngle!==e&&(this._innerConeAngle=e,this._innerConeAngleCos=Math.cos(e*Math.PI/180),this._usePhysicalUnits&&this._updateFinalColor())}},{key:"outerConeAngle",get:function(){return this._outerConeAngle},set:function(e){this._outerConeAngle!==e&&(this._outerConeAngle=e,this._updateOuterAngle(e),this._usePhysicalUnits&&this._updateFinalColor())}},{key:"penumbraSize",get:function(){return this._penumbraSize},set:function(e){this._penumbraSize=e}},{key:"intensity",get:function(){return this._intensity},set:function(e){this._intensity!==e&&(this._intensity=e,this._updateFinalColor())}},{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._updateFinalColor())}},{key:"cookieMatrix",get:function(){return this._cookieMatrix||(this._cookieMatrix=new Te),this._cookieMatrix}},{key:"atlasViewport",get:function(){return this._atlasViewport||(this._atlasViewport=new ve(0,0,1,1)),this._atlasViewport}},{key:"cookie",get:function(){return this._cookie},set:function(e){this._cookie!==e&&(this._cookie=e,this.updateKey())}},{key:"cookieFalloff",get:function(){return this._cookieFalloff},set:function(e){this._cookieFalloff!==e&&(this._cookieFalloff=e,this.updateKey())}},{key:"cookieChannel",get:function(){return this._cookieChannel},set:function(e){if(this._cookieChannel!==e){if(e.length<3)for(var t=e.charAt(e.length-1),i=3-e.length,n=0;n<i;n++)e+=t;this._cookieChannel=e,this.updateKey()}}},{key:"cookieTransform",get:function(){return this._cookieTransform},set:function(e){this._cookieTransform!==e&&(this._cookieTransform=e,this._cookieTransformSet=!!e,e&&!this._cookieOffset&&(this.cookieOffset=new ge,this._cookieOffsetSet=!1),this.updateKey())}},{key:"cookieOffset",get:function(){return this._cookieOffset},set:function(e){this._cookieOffset!==e&&(!(!this._cookieTransformSet&&!e)&&!e&&this._cookieOffset?this._cookieOffset.set(0,0):this._cookieOffset=e,this._cookieOffsetSet=!!e,e&&!this._cookieTransform&&(this.cookieTransform=new ve(1,1,0,0),this._cookieTransformSet=!1),this.updateKey())}}]),e}(),Fc=function(){function e(e,t,i){this._areaLightsEnabled=!1,this._cells=new me(10,3,10),this._maxLightsPerCell=255,this._shadowsEnabled=!0,this._shadowType=0,this._shadowAtlasResolution=2048,this._cookiesEnabled=!1,this._cookieAtlasResolution=2048,this.debugLayer=void 0,this.atlasSplit=null,this._supportsAreaLights=e,this._maxTextureSize=t,this._dirtyLightsFnc=i}return e.prototype.applySettings=function(e){this.shadowsEnabled=e.lightingShadowsEnabled,this.cookiesEnabled=e.lightingCookiesEnabled,this.areaLightsEnabled=e.lightingAreaLightsEnabled,this.shadowAtlasResolution=e.lightingShadowAtlasResolution,this.cookieAtlasResolution=e.lightingCookieAtlasResolution,this.maxLightsPerCell=e.lightingMaxLightsPerCell,this.shadowType=e.lightingShadowType,this.cell=new me(e.lightingCells)},Z(e,[{key:"cells",get:function(){return this._cells},set:function(e){this._cells.copy(e)}},{key:"maxLightsPerCell",get:function(){return this._maxLightsPerCell},set:function(e){this._maxLightsPerCell=ce.clamp(e,1,255)}},{key:"cookieAtlasResolution",get:function(){return this._cookieAtlasResolution},set:function(e){this._cookieAtlasResolution=ce.clamp(e,32,this._maxTextureSize)}},{key:"shadowAtlasResolution",get:function(){return this._shadowAtlasResolution},set:function(e){this._shadowAtlasResolution=ce.clamp(e,32,this._maxTextureSize)}},{key:"shadowType",get:function(){return this._shadowType},set:function(e){this._shadowType!==e&&(this._shadowType=e,this._dirtyLightsFnc())}},{key:"cookiesEnabled",get:function(){return this._cookiesEnabled},set:function(e){this._cookiesEnabled!==e&&(this._cookiesEnabled=e,this._dirtyLightsFnc())}},{key:"areaLightsEnabled",get:function(){return this._areaLightsEnabled},set:function(e){this._supportsAreaLights&&this._areaLightsEnabled!==e&&(this._areaLightsEnabled=e,this._dirtyLightsFnc())}},{key:"shadowsEnabled",get:function(){return this._shadowsEnabled},set:function(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this._dirtyLightsFnc())}}]),e}(),Bc=new yi(!0,0,1,1),Nc=function(){function e(e){var t=this;this.morph=e,e.incRefCount(),this.device=e.device,this._weights=[],this._weightMap=new Map;for(var i=0;i<e._targets.length;i++){var n=e._targets[i];n.name&&this._weightMap.set(n.name,i),this.setWeight(i,n.defaultWeight)}if(this._activeTargets=[],e.useTextureMorph){this.shaderCache={},this.maxSubmitCount=this.device.maxTextures,this._shaderMorphWeights=new Float32Array(this.maxSubmitCount);var s=function(i,n){return t[n]=e._createTexture(i,e._renderTextureFormat),new Di({colorBuffer:t[n],depth:!1})};e.morphPositions&&(this.rtPositions=s("MorphRTPos","texturePositions")),e.morphNormals&&(this.rtNormals=s("MorphRTNrm","textureNormals")),this._textureParams=new Float32Array([e.morphTextureWidth,e.morphTextureHeight,1/e.morphTextureWidth,1/e.morphTextureHeight]);for(var r=0;r<this.maxSubmitCount;r++)this["morphBlendTex"+r]=this.device.scope.resolve("morphBlendTex"+r);this.morphFactor=this.device.scope.resolve("morphFactor[0]"),this.zeroTextures=!1}else this.maxSubmitCount=8,this._shaderMorphWeights=new Float32Array(this.maxSubmitCount),this._shaderMorphWeightsA=new Float32Array(this._shaderMorphWeights.buffer,0,4),this._shaderMorphWeightsB=new Float32Array(this._shaderMorphWeights.buffer,16,4),this._activeVertexBuffers=new Array(this.maxSubmitCount)}var t=e.prototype;return t.destroy=function(){this.shader=null;var e=this.morph;e&&(this.morph=null,e.decRefCount(),e.refCount<1&&e.destroy()),this.rtPositions&&(this.rtPositions.destroy(),this.rtPositions=null),this.texturePositions&&(this.texturePositions.destroy(),this.texturePositions=null),this.rtNormals&&(this.rtNormals.destroy(),this.rtNormals=null),this.textureNormals&&(this.textureNormals.destroy(),this.textureNormals=null)},t.clone=function(){return new e(this.morph)},t._getWeightIndex=function(e){return"string"==typeof e?this._weightMap.get(e):e},t.getWeight=function(e){var t=this._getWeightIndex(e);return this._weights[t]},t.setWeight=function(e,t){var i=this._getWeightIndex(e);this._weights[i]=t,this._dirty=!0},t._getFragmentShader=function(e){var t="";e>0&&(t+="varying vec2 uv0;\nuniform highp float morphFactor["+e+"];\n");for(var i=0;i<e;i++)t+="uniform highp sampler2D morphBlendTex"+i+";\n";t+="void main (void) {\n highp vec4 color = vec4(0, 0, 0, 1);\n";for(var n=0;n<e;n++)t+=" color.xyz += morphFactor["+n+"] * texture2D(morphBlendTex"+n+", uv0).xyz;\n";return t+=" gl_FragColor = color;\n}\n"},t._getShader=function(e){var t=this.shaderCache[e];if(!t){var i=this._getFragmentShader(e);t=Ca(this.device,"\n attribute vec2 vertex_position;\n varying vec2 uv0;\n void main(void) {\n gl_Position = vec4(vertex_position, 0.5, 1.0);\n uv0 = vertex_position.xy * 0.5 + 0.5;\n }\n ",i,"textureMorph"+e),this.shaderCache[e]=t}return t},t._updateTextureRenderTarget=function(e,t){for(var i=this,n=this.device,s=function(t,s){i.morphFactor.setValue(i._shaderMorphWeights),n.setBlendState(s?Bc:yi.NOBLEND);var r=i._getShader(t);Da(n,e,r)},r=0,a=!1,o=this._activeTargets.length,h=0;h<o;h++){var l=this._activeTargets[h],c=l.target[t];c&&(this["morphBlendTex"+r].setValue(c),this._shaderMorphWeights[r]=l.weight,++r>=this.maxSubmitCount&&(s(r,a),r=0,a=!0))}(r>0||0===o&&!this.zeroTextures)&&s(r,a)},t._updateTextureMorph=function(){this.device,(this._activeTargets.length>0||!this.zeroTextures)&&(this.rtPositions&&this._updateTextureRenderTarget(this.rtPositions,"texturePositions"),this.rtNormals&&this._updateTextureRenderTarget(this.rtNormals,"textureNormals"),this.zeroTextures=0===this._activeTargets.length)},t._updateVertexMorph=function(){for(var e=this.maxSubmitCount,t=0;t<e;t++)this._shaderMorphWeights[t]=0,this._activeVertexBuffers[t]=null;for(var i=0,n=this.morph.morphPositions?4:0,s=0;s<this._activeTargets.length;s++){var r=this._activeTargets[s].target;r._vertexBufferPositions&&(this._activeVertexBuffers[i]=r._vertexBufferPositions,this._shaderMorphWeights[i]=this._activeTargets[s].weight,i++),r._vertexBufferNormals&&(this._activeVertexBuffers[n]=r._vertexBufferNormals,this._shaderMorphWeights[n]=this._activeTargets[s].weight,n++)}},t.update=function(){this._dirty=!1;for(var e=this.morph._targets,t=0,i=0;i<e.length;i++){var n=Math.abs(this.getWeight(i));if(n>1e-5){this._activeTargets.length<=t&&(this._activeTargets[t]={});var s=this._activeTargets[t++];s.absWeight=n,s.weight=this.getWeight(i),s.target=e[i]}}this._activeTargets.length=t;var r=this.morph.maxActiveTargets;this._activeTargets.length>r&&(this._activeTargets.sort((function(e,t){return e.absWeight<t.absWeight?1:t.absWeight<e.absWeight?-1:0})),this._activeTargets.length=r),this.morph.useTextureMorph?this._updateTextureMorph():this._updateVertexMorph()},e}(),Uc=function(){function e(){this.graph=null,this.meshInstances=[],this.skinInstances=[],this.morphInstances=[],this.cameras=[],this.lights=[],this._shadersVersion=0,this._immutable=!1}var t=e.prototype;return t.getGraph=function(){return this.graph},t.setGraph=function(e){this.graph=e},t.getCameras=function(){return this.cameras},t.setCameras=function(e){this.cameras=e},t.getLights=function(){return this.lights},t.setLights=function(e){this.lights=e},t.getMaterials=function(){for(var e=[],t=0;t<this.meshInstances.length;t++){var i=this.meshInstances[t];-1===e.indexOf(i.material)&&e.push(i.material)}return e},t.clone=function(){for(var t=[],i=[],n=function e(n){var s=n.clone();t.push(n),i.push(s);for(var r=0;r<n._children.length;r++)s.addChild(e(n._children[r]));return s}(this.graph),s=[],r=[],a=[],o=0;o<this.skinInstances.length;o++){for(var h=this.skinInstances[o].skin,l=new Ja(h),c=[],u=0;u<h.boneNames.length;u++){var d=h.boneNames[u],f=n.findByName(d);c.push(f)}l.bones=c,r.push(l)}for(var p=0;p<this.morphInstances.length;p++){var m=this.morphInstances[p].morph,_=new Nc(m);a.push(_)}for(var g=0;g<this.meshInstances.length;g++){var v=this.meshInstances[g],y=t.indexOf(v.node),x=new Co(v.mesh,v.material,i[y]);if(v.skinInstance){var S=this.skinInstances.indexOf(v.skinInstance);x.skinInstance=r[S]}if(v.morphInstance){var b=this.morphInstances.indexOf(v.morphInstance);x.morphInstance=a[b]}s.push(x)}var w=new e;return w.graph=n,w.meshInstances=s,w.skinInstances=r,w.morphInstances=a,w.getGraph().syncHierarchy(),w},t.destroy=function(){for(var e=this.meshInstances,t=0;t<e.length;t++)e[t].destroy();this.meshInstances.length=0},t.generateWireframe=function(){Co._prepareRenderStyleForArray(this.meshInstances,1)},e}(),zc=function(e){function t(t,i,n){var s,r=(void 0===n?{}:n).preferHighPrecision,a=void 0!==r&&r;(s=e.call(this)||this)._aabb=void 0,s.preferHighPrecision=void 0,s.device=i||Kr.get(),s.preferHighPrecision=a,s._targets=t.slice();var o=s.device;if(o.supportsMorphTargetTexturesCore){var h=o.extTextureHalfFloat&&o.textureHalfFloatRenderable?Ye:void 0,l=o.extTextureFloat&&o.textureFloatRenderable?Ze:void 0;s._renderTextureFormat=s.preferHighPrecision?null!=l?l:h:null!=h?h:l;var c=o.extTextureHalfFloat&&o.textureHalfFloatUpdatable?Ye:void 0,u=o.extTextureFloat?Ke:void 0;s._textureFormat=s.preferHighPrecision?null!=u?u:c:null!=c?c:u,void 0!==s._renderTextureFormat&&void 0!==s._textureFormat&&(s._useTextureMorph=!0)}return s._init(),s._updateMorphFlags(),s}Q(t,e);var i=t.prototype;return i._init=function(){if(this._useTextureMorph&&(this._useTextureMorph=this._initTextureBased()),!this._useTextureMorph)for(var e=0;e<this._targets.length;e++)this._targets[e]._initVertexBuffers(this.device);for(var t=0;t<this._targets.length;t++)this._targets[t]._postInit()},i._findSparseSet=function(e,t,i,n){for(var s=1,r=e[0].length,a=0;a<r;a+=3){for(var o=!1,h=0;h<e.length;h++){var l=e[h];if(0!==l[a]||0!==l[a+1]||0!==l[a+2]){o=!0;break}}o?(t.push(s+n),i.push(a/3),s++):t.push(0+n)}return s},i._initTextureBased=function(){for(var e=this.device.isWebGPU,t=e?0:.2,i=[],n=[],s=0;s<this._targets.length;s++){var r=this._targets[s];r.options.deltaPositions&&(i.push(r.options.deltaPositions),n.push({target:r,name:"texturePositions"})),r.options.deltaNormals&&(i.push(r.options.deltaNormals),n.push({target:r,name:"textureNormals"}))}var a=[],o=[],h=this._findSparseSet(i,a,o,t),l=Math.min(this.device.maxTextureSize,4096),c=Math.ceil(Math.sqrt(h));c=Math.min(c,l);var u=Math.ceil(h/c);if(u>l)return!1;this.morphTextureWidth=c,this.morphTextureHeight=u;var d=!1,f=3,p=Xo.float2Half;this._textureFormat===Ye&&(d=!0,f=4);for(var m=[],_=0;_<i.length;_++)m.push(this._createTexture("MorphTarget",this._textureFormat));for(var g=0;g<i.length;g++){var v=i[g],y=m[g],x=y.lock();if(d)for(var S=0;S<o.length;S++){var b=3*o[S],w=S*f+f;x[w]=p(v[b]),x[w+1]=p(v[b+1]),x[w+2]=p(v[b+2])}else for(var T=0;T<o.length;T++){var A=3*o[T],C=T*f+f;x[C]=v[A],x[C+1]=v[A+1],x[C+2]=v[A+2]}y.unlock(),n[g].target._setTexture(n[g].name,y)}var E=[{semantic:zt,components:1,type:e?5:6}];return this.vertexBufferIds=new Ei(this.device,new Pi(this.device,E,a.length),a.length,0,e?new Uint32Array(a):new Float32Array(a)),!0},i.destroy=function(){var e;null==(e=this.vertexBufferIds)||e.destroy(),this.vertexBufferIds=null;for(var t=0;t<this._targets.length;t++)this._targets[t].destroy();this._targets.length=0},i._updateMorphFlags=function(){this._morphPositions=!1,this._morphNormals=!1;for(var e=0;e<this._targets.length;e++){var t=this._targets[e];t.morphPositions&&(this._morphPositions=!0),t.morphNormals&&(this._morphNormals=!0)}},i._createTexture=function(e,t){return new Yn(this.device,{width:this.morphTextureWidth,height:this.morphTextureHeight,format:t,cubemap:!1,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1,name:e})},Z(t,[{key:"aabb",get:function(){if(!this._aabb){for(var e=new me,t=new me,i=0;i<this._targets.length;i++){var n=this._targets[i].aabb;e.min(n.getMin()),t.max(n.getMax())}this._aabb=new Ie,this._aabb.setMinMax(e,t)}return this._aabb}},{key:"morphPositions",get:function(){return this._morphPositions}},{key:"morphNormals",get:function(){return this._morphNormals}},{key:"maxActiveTargets",get:function(){return this._useTextureMorph?this._targets.length:this._morphPositions&&this._morphNormals?4:8}},{key:"useTextureMorph",get:function(){return this._useTextureMorph}},{key:"targets",get:function(){return this._targets}}]),t}(Yr),Vc=function(){function e(e){this.used=!1,2===arguments.length&&(e=arguments[1]),this.options=e,this._name=e.name,this._defaultWeight=e.defaultWeight||0,this._aabb=e.aabb,this.deltaPositions=e.deltaPositions}var t=e.prototype;return t.destroy=function(){var e,t,i,n;null==(e=this._vertexBufferPositions)||e.destroy(),this._vertexBufferPositions=null,null==(t=this._vertexBufferNormals)||t.destroy(),this._vertexBufferNormals=null,null==(i=this.texturePositions)||i.destroy(),this.texturePositions=null,null==(n=this.textureNormals)||n.destroy(),this.textureNormals=null},t.clone=function(){return new e(this.options)},t._postInit=function(){this.options.preserveData||(this.options=null),this.used=!0},t._initVertexBuffers=function(e){var t=this.options;this._vertexBufferPositions=this._createVertexBuffer(e,t.deltaPositions,t.deltaPositionsType),this._vertexBufferNormals=this._createVertexBuffer(e,t.deltaNormals,t.deltaNormalsType),this._vertexBufferPositions&&(this.deltaPositions=this._vertexBufferPositions.lock())},t._createVertexBuffer=function(e,t,i){return void 0===i&&(i=6),t?new Ei(e,new Pi(e,[{semantic:At,components:3,type:i}]),t.length/3,0,t):null},t._setTexture=function(e,t){this[e]=t},Z(e,[{key:"name",get:function(){return this._name}},{key:"defaultWeight",get:function(){return this._defaultWeight}},{key:"aabb",get:function(){return this._aabb||(this._aabb=new Ie,this.deltaPositions&&this._aabb.compute(this.deltaPositions)),this._aabb}},{key:"morphPositions",get:function(){return!!this._vertexBufferPositions||!!this.texturePositions}},{key:"morphNormals",get:function(){return!!this._vertexBufferNormals||!!this.textureNormals}}]),e}(),Gc={generateKey:function(e){var t="particle";for(var i in e)e.hasOwnProperty(i)&&(t+=e[i]);return t},_animTex:function(e){var t="";return t+=e.animTexLoop?Sa.particleAnimFrameLoopVS:Sa.particleAnimFrameClampVS,t+=Sa.particleAnimTexVS},createShaderDefinition:function(e,t){var i="#define PARTICLE_"+(t.useCpu?"CPU":"GPU")+"\n",n="#define PARTICLE\n"+i,s="#define VERTEXSHADER\n"+i;t.mesh&&(s+="#define USE_MESH\n"),t.localSpace&&(s+="#define LOCAL_SPACE\n"),t.screenSpace&&(s+="#define SCREEN_SPACE\n"),t.animTex&&(s+="\nuniform vec2 animTexTilesParams;\n"),t.animTex&&(s+="\nuniform vec4 animTexParams;\n"),t.animTex&&(s+="\nuniform vec2 animTexIndexParams;\n"),2===t.normal&&(s+="\nvarying mat3 ParticleMat;\n"),1===t.normal&&(s+="\nvarying vec3 Normal;\n"),t.soft&&(s+="\nvarying float vDepth;\n");var r=t.customFace?Sa.particle_customFaceVS:Sa.particle_billboardVS;return t.useCpu?(t.soft>0&&(s+=Sa.screenDepthPS),s+=Sa.particle_cpuVS,t.localSpace&&(s+=Sa.particle_localShiftVS),t.animTex&&(s+=this._animTex(t)),t.alignToMotion&&(s+=Sa.particle_pointAlongVS),s+=t.mesh?Sa.particle_meshVS:r,1===t.normal&&(s+=Sa.particle_normalVS),2===t.normal&&(s+=Sa.particle_TBNVS),t.stretch>0&&(s+=Sa.particle_stretchVS),s+=Sa.particle_cpu_endVS,t.soft>0&&(s+=Sa.particle_softVS)):(s+=Sa.particle_initVS,s+=t.pack8?Sa.particleInputRgba8PS:Sa.particleInputFloatPS,t.soft>0&&(s+=Sa.screenDepthPS),s+=Sa.particleVS,t.localSpace&&(s+=Sa.particle_localShiftVS),t.animTex&&(s+=this._animTex(t)),t.wrap&&(s+=Sa.particle_wrapVS),t.alignToMotion&&(s+=Sa.particle_pointAlongVS),s+=t.mesh?Sa.particle_meshVS:r,1===t.normal&&(s+=Sa.particle_normalVS),2===t.normal&&(s+=Sa.particle_TBNVS),t.stretch>0&&(s+=Sa.particle_stretchVS),s+=Sa.particle_endVS,t.soft>0&&(s+=Sa.particle_softVS)),s+="}\n",t.normal>0&&(1===t.normal?n+="\nvarying vec3 Normal;\n":2===t.normal&&(n+="\nvarying mat3 ParticleMat;\n"),n+="\nuniform vec3 lightCube[6];\n"),t.soft&&(n+="\nvarying float vDepth;\n"),0===t.normal&&"none"===t.fog&&(t.srgb=!1),n+=Sa.decodePS,n+=Ba(t.gamma),n+=Na(t.toneMap),"linear"===t.fog?n+=Sa.fogLinearPS:"exp"===t.fog?n+=Sa.fogExpPS:"exp2"===t.fog?n+=Sa.fogExp2PS:n+=Sa.fogNonePS,2===t.normal&&(n+="\nuniform sampler2D normalMap;\n"),t.soft>0&&(n+=Sa.screenDepthPS),n+=Sa.particlePS,t.soft>0&&(n+=Sa.particle_softPS),1===t.normal&&(n+="\nvec3 normal = Normal;\n"),2===t.normal&&(n+=Sa.particle_normalMapPS),t.normal>0&&(n+=t.halflambert?Sa.particle_halflambertPS:Sa.particle_lambertPS),t.normal>0&&(n+=Sa.particle_lightingPS),2===t.blend?n+=Sa.particle_blendNormalPS:1===t.blend?n+=Sa.particle_blendAddPS:5===t.blend&&(n+=Sa.particle_blendMultiplyPS),n+=Sa.particle_endPS,vs.createDefinition(e,{name:"ParticleShader",vertexCode:s,fragmentCode:n})}},Hc=1,Wc=new Te,Xc=new Te,jc=new me,qc=new me,Yc=new me,Kc=new me,Zc=new me,$c=new me,Qc=new me,Jc=new me,eu=new me,tu=new me,iu=new me,nu=new me,su=new me;function ru(e){return e-Math.floor(e)}function au(e){return Math.max(Math.min(e,1),0)}function ou(e,t){return e-t*Math.floor(e/t)}function hu(e){var t=ru(e),i=ru(255*e);return[t-=i/255,i-=i/255]}var lu=function(){function e(e){this._emitter=e}var t=e.prototype;return t.calcSpawnPosition=function(e,t,i,n,s){var r=this._emitter,a=Math.random(),o=Math.random(),h=Math.random(),l=Math.random();if(r.useCpu&&(e[4*s+0+2*r.numParticlesPot*4]=a,e[4*s+1+2*r.numParticlesPot*4]=o,e[4*s+2+2*r.numParticlesPot*4]=h),qc.x=a-.5,qc.y=o-.5,qc.z=h-.5,0===r.emitterShape){var c=Math.max(Math.abs(qc.x),Math.max(Math.abs(qc.y),Math.abs(qc.z))),u=c+(.5-c)*i[0],d=c+(.5-c)*i[1],f=c+(.5-c)*i[2];qc.x=u*(c===Math.abs(qc.x)?Math.sign(qc.x):2*qc.x),qc.y=d*(c===Math.abs(qc.y)?Math.sign(qc.y):2*qc.y),qc.z=f*(c===Math.abs(qc.z)?Math.sign(qc.z):2*qc.z),r.localSpace?jc.copy(t.transformPoint(qc)):jc.copy(n).add(t.transformPoint(qc))}else{qc.normalize();var p=0===r.emitterRadius?0:r.emitterRadiusInner/r.emitterRadius,m=l*(1-p)+p;r.localSpace?jc.copy(qc.mulScalar(m*r.emitterRadius)):jc.copy(n).add(qc.mulScalar(m*r.emitterRadius))}var _,g,v,y,x,S=-ce.lerp(r.rate,r.rate2,a)*s;if(r.pack8){var b=(jc.x-r.worldBounds.center.x)/r.worldBoundsSize.x+.5,w=(jc.y-r.worldBounds.center.y)/r.worldBoundsSize.y+.5,T=(jc.z-r.worldBounds.center.z)/r.worldBoundsSize.z+.5,A=ce.lerp(r.startAngle*ce.DEG_TO_RAD,r.startAngle2*ce.DEG_TO_RAD,a);A=A%(2*Math.PI)/(2*Math.PI);var C=hu(b);e[4*s]=C[0],e[4*s+1]=C[1];var E=hu(w);e[4*s+2]=E[0],e[4*s+3]=E[1];var M=hu(T);e[4*s+0+4*r.numParticlesPot]=M[0],e[4*s+1+4*r.numParticlesPot]=M[1];var P=hu(A);e[4*s+2+4*r.numParticlesPot]=P[0],e[4*s+3+4*r.numParticlesPot]=P[1];e[4*s+3+4*r.numParticlesPot*2]=1;var R=Math.max(r.lifetime,(r.numParticles-1)*Math.max(r.rate,r.rate2)),I=r.lifetime+1,L=(g=ru(_=S=(S+R)/(R+I)),v=ru(255*_),y=ru(65025*_),x=ru(160581375*_),[g-=v/255,v-=y/255,y-=x/255,x-=x/255]);e[4*s+0+4*r.numParticlesPot*3]=L[0],e[4*s+1+4*r.numParticlesPot*3]=L[1],e[4*s+2+4*r.numParticlesPot*3]=L[2],e[4*s+3+4*r.numParticlesPot*3]=L[3]}else e[4*s]=jc.x,e[4*s+1]=jc.y,e[4*s+2]=jc.z,e[4*s+3]=ce.lerp(r.startAngle*ce.DEG_TO_RAD,r.startAngle2*ce.DEG_TO_RAD,a),e[4*s+3+4*r.numParticlesPot]=S},t.update=function(e,t,i,n,s,r,a,o){var h,l,c,u=this._emitter;if(u.meshInstance.node){for(var d=u.meshInstance.node.worldTransform,f=0;f<12;f++)Wc.data[f]=d.data[f];Xc.copy(Wc),Xc.invert(),vc=u.meshInstance.node.localScale,Hc=Math.max(Math.max(vc.x,vc.y),vc.z)}r=null===u.meshInstance.node||u.localSpace?me.ZERO:u.meshInstance.node.getPosition();for(var p,m,_,g,v,y,x,S,b=u.camera?u.camera._node.getPosition():me.ZERO,w=u.useMesh?17:15,T=u.precision-1,A=0;A<u.numParticles;A++){var C=Math.floor(u.vbCPU[A*u.numParticleVerts*(u.useMesh?6:4)+3]),E=i[4*C+0+2*u.numParticlesPot*4];Yc.x=E,Yc.y=i[4*C+1+2*u.numParticlesPot*4],Yc.z=i[4*C+2+2*u.numParticlesPot*4];var M=u.rate+(u.rate2-u.rate)*E,P=u.lifetime,R=i[4*C+3+4*u.numParticlesPot]+a,I=au(R/P),L=0,D=0;(R-a<=0||R>=P)&&this.calcSpawnPosition(i,n,s,r,C);var O=R>0&&R<P;O&&(c=I*T,p=Math.floor(c),m=Math.ceil(c),c%=1,_=(h=u.qRotSpeed[p])+((l=u.qRotSpeed[m])-h)*c,g=(h=u.qRotSpeed2[p])+((l=u.qRotSpeed2[m])-h)*c,L=(h=u.qScale[p])+((l=u.qScale[m])-h)*c,v=(h=u.qScale2[p])+((l=u.qScale2[m])-h)*c,y=(h=u.qAlpha[p])+((l=u.qAlpha[m])-h)*c,x=(h=u.qAlpha2[p])+((l=u.qAlpha2[m])-h)*c,S=(h=u.qRadialSpeed[p])+((l=u.qRadialSpeed[m])-h)*c,S+=100*E%1*((h=u.qRadialSpeed2[p])+((l=u.qRadialSpeed2[m])-h)*c-S),Kc.x=i[4*C],Kc.y=i[4*C+1],Kc.z=i[4*C+2],u.localSpace?eu.copy(Kc):eu.copy(Kc).sub(r),eu.normalize().mulScalar(S),p*=3,m*=3,h=u.qLocalVelocity[p],l=u.qLocalVelocity[m],$c.x=h+(l-h)*c,h=u.qLocalVelocity[p+1],l=u.qLocalVelocity[m+1],$c.y=h+(l-h)*c,h=u.qLocalVelocity[p+2],l=u.qLocalVelocity[m+2],$c.z=h+(l-h)*c,h=u.qLocalVelocity2[p],l=u.qLocalVelocity2[m],Jc.x=h+(l-h)*c,h=u.qLocalVelocity2[p+1],l=u.qLocalVelocity2[m+1],Jc.y=h+(l-h)*c,h=u.qLocalVelocity2[p+2],l=u.qLocalVelocity2[m+2],Jc.z=h+(l-h)*c,h=u.qVelocity[p],l=u.qVelocity[m],Zc.x=h+(l-h)*c,h=u.qVelocity[p+1],l=u.qVelocity[m+1],Zc.y=h+(l-h)*c,h=u.qVelocity[p+2],l=u.qVelocity[m+2],Zc.z=h+(l-h)*c,h=u.qVelocity2[p],l=u.qVelocity2[m],Qc.x=h+(l-h)*c,h=u.qVelocity2[p+1],l=u.qVelocity2[m+1],Qc.y=h+(l-h)*c,h=u.qVelocity2[p+2],l=u.qVelocity2[m+2],Qc.z=h+(l-h)*c,$c.x+=(Jc.x-$c.x)*Yc.x,$c.y+=(Jc.y-$c.y)*Yc.y,$c.z+=(Jc.z-$c.z)*Yc.z,u.initialVelocity>0&&(1===u.emitterShape?(qc.copy(Yc).mulScalar(2).sub(me.ONE).normalize(),$c.add(qc.mulScalar(u.initialVelocity))):$c.add(me.FORWARD.mulScalar(u.initialVelocity))),Zc.x+=(Qc.x-Zc.x)*Yc.x,Zc.y+=(Qc.y-Zc.y)*Yc.y,Zc.z+=(Qc.z-Zc.z)*Yc.z,_+=(g-_)*Yc.y,L=(L+1e4*E%1*(v-L))*Hc,D=1e3*E%1*(x-y),u.meshInstance.node&&(u.localSpace?($c.x/=vc.x,$c.y/=vc.y,$c.z/=vc.z):Wc.transformPoint($c,$c)),u.localSpace?(Xc.transformPoint(Zc,Zc),$c.add(Zc).add(eu)):($c.add(Zc.mul(vc)),$c.add(eu.mul(vc))),nu.copy($c),tu.copy(Kc).add($c.mulScalar(a)),iu.copy(tu),i[4*C]=iu.x,i[4*C+1]=iu.y,i[4*C+2]=iu.z,i[4*C+3]+=_*a,u.wrap&&u.wrapBounds&&(u.localSpace||iu.sub(r),iu.x=ou(iu.x,u.wrapBounds.x)-.5*u.wrapBounds.x,iu.y=ou(iu.y,u.wrapBounds.y)-.5*u.wrapBounds.y,iu.z=ou(iu.z,u.wrapBounds.z)-.5*u.wrapBounds.z,u.localSpace||iu.add(r)),u.sort>0&&(1===u.sort?(su.copy(iu).sub(b),u.particleDistance[C]=-(su.x*su.x+su.y*su.y+su.z*su.z)):2===u.sort?u.particleDistance[C]=R:3===u.sort&&(u.particleDistance[C]=-R))),o?R<0&&(i[4*C+3+2*u.numParticlesPot*4]=-1):(R>=P&&(R-=Math.max(P,(u.numParticles-1)*M),i[4*C+3+2*u.numParticlesPot*4]=u.loop?1:-1),R<0&&u.loop&&(i[4*C+3+2*u.numParticlesPot*4]=1)),i[4*C+3+2*u.numParticlesPot*4]<0&&(O=!1),i[4*C+3+4*u.numParticlesPot]=R;for(var k=0;k<u.numParticleVerts;k++){var F=(A*u.numParticleVerts+k)*(u.useMesh?6:4),B=u.vbCPU[F],N=u.vbCPU[F+1],U=u.vbCPU[F+2];O||(B=N=U=0);var z=A*u.numParticleVerts*w+k*w;e[z]=iu.x,e[z+1]=iu.y,e[z+2]=iu.z,e[z+3]=I,e[z+4]=u.alignToMotion?0:i[4*C+3],e[z+5]=L,e[z+6]=D,e[z+7]=nu.x,e[z+8]=B,e[z+9]=N,e[z+10]=U,e[z+11]=nu.y,e[z+12]=C,e[z+13]=nu.z,e[z+14]=u.vbCPU[F+3],u.useMesh&&(e[z+15]=u.vbCPU[F+4],e[z+16]=u.vbCPU[F+5])}}if(u.sort>0&&u.camera){for(var V=u.useMesh?6:4,G=u.particleDistance,H=0;H<u.numParticles;H++)t[H][0]=H,t[H][1]=G[Math.floor(u.vbCPU[H*u.numParticleVerts*V+3])];u.vbOld.set(u.vbCPU),t.sort((function(e,t){return e[1]-t[1]}));for(var W=0;W<u.numParticles;W++)for(var X=t[W][0]*u.numParticleVerts*V,j=W*u.numParticleVerts*V,q=0;q<u.numParticleVerts*V;q++)u.vbCPU[j+q]=u.vbOld[X+q]}},e}(),cu=new _e,uu=new _e,du=new _e,fu=function(){function e(e,t){this._emitter=e,this.frameRandomUniform=new Float32Array(3),this.emitterPosUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),this.worldBoundsMulUniform=new Float32Array(3),this.worldBoundsAddUniform=new Float32Array(3),this.inBoundsSizeUniform=new Float32Array(3),this.inBoundsCenterUniform=new Float32Array(3),this.constantParticleTexIN=t.scope.resolve("particleTexIN"),this.constantParticleTexOUT=t.scope.resolve("particleTexOUT"),this.constantEmitterPos=t.scope.resolve("emitterPos"),this.constantEmitterScale=t.scope.resolve("emitterScale"),this.constantSpawnBounds=t.scope.resolve("spawnBounds"),this.constantSpawnPosInnerRatio=t.scope.resolve("spawnPosInnerRatio"),this.constantSpawnBoundsSphere=t.scope.resolve("spawnBoundsSphere"),this.constantSpawnBoundsSphereInnerRatio=t.scope.resolve("spawnBoundsSphereInnerRatio"),this.constantInitialVelocity=t.scope.resolve("initialVelocity"),this.constantFrameRandom=t.scope.resolve("frameRandom"),this.constantDelta=t.scope.resolve("delta"),this.constantRate=t.scope.resolve("rate"),this.constantRateDiv=t.scope.resolve("rateDiv"),this.constantLifetime=t.scope.resolve("lifetime"),this.constantGraphSampleSize=t.scope.resolve("graphSampleSize"),this.constantGraphNumSamples=t.scope.resolve("graphNumSamples"),this.constantInternalTex0=t.scope.resolve("internalTex0"),this.constantInternalTex1=t.scope.resolve("internalTex1"),this.constantInternalTex2=t.scope.resolve("internalTex2"),this.constantInternalTex3=t.scope.resolve("internalTex3"),this.constantEmitterMatrix=t.scope.resolve("emitterMatrix"),this.constantEmitterMatrixInv=t.scope.resolve("emitterMatrixInv"),this.constantNumParticles=t.scope.resolve("numParticles"),this.constantNumParticlesPot=t.scope.resolve("numParticlesPot"),this.constantLocalVelocityDivMult=t.scope.resolve("localVelocityDivMult"),this.constantVelocityDivMult=t.scope.resolve("velocityDivMult"),this.constantRotSpeedDivMult=t.scope.resolve("rotSpeedDivMult"),this.constantSeed=t.scope.resolve("seed"),this.constantStartAngle=t.scope.resolve("startAngle"),this.constantStartAngle2=t.scope.resolve("startAngle2"),this.constantOutBoundsMul=t.scope.resolve("outBoundsMul"),this.constantOutBoundsAdd=t.scope.resolve("outBoundsAdd"),this.constantInBoundsSize=t.scope.resolve("inBoundsSize"),this.constantInBoundsCenter=t.scope.resolve("inBoundsCenter"),this.constantMaxVel=t.scope.resolve("maxVel"),this.constantFaceTangent=t.scope.resolve("faceTangent"),this.constantFaceBinorm=t.scope.resolve("faceBinorm")}var t=e.prototype;return t._setInputBounds=function(){this.inBoundsSizeUniform[0]=this._emitter.prevWorldBoundsSize.x,this.inBoundsSizeUniform[1]=this._emitter.prevWorldBoundsSize.y,this.inBoundsSizeUniform[2]=this._emitter.prevWorldBoundsSize.z,this.constantInBoundsSize.setValue(this.inBoundsSizeUniform),this.inBoundsCenterUniform[0]=this._emitter.prevWorldBoundsCenter.x,this.inBoundsCenterUniform[1]=this._emitter.prevWorldBoundsCenter.y,this.inBoundsCenterUniform[2]=this._emitter.prevWorldBoundsCenter.z,this.constantInBoundsCenter.setValue(this.inBoundsCenterUniform)},t.randomize=function(){this.frameRandomUniform[0]=Math.random(),this.frameRandomUniform[1]=Math.random(),this.frameRandomUniform[2]=Math.random()},t.update=function(e,t,i,n,s){var r=this._emitter;e.setBlendState(yi.NOBLEND),e.setDepthState(xi.NODEPTH),e.setCullMode(0),this.randomize(),this.constantGraphSampleSize.setValue(1/r.precision),this.constantGraphNumSamples.setValue(r.precision),this.constantNumParticles.setValue(r.numParticles),this.constantNumParticlesPot.setValue(r.numParticlesPot),this.constantInternalTex0.setValue(r.internalTex0),this.constantInternalTex1.setValue(r.internalTex1),this.constantInternalTex2.setValue(r.internalTex2),this.constantInternalTex3.setValue(r.internalTex3);var a=r.meshInstance.node,o=null===a?me.ONE:a.localScale;if(r.pack8){this.worldBoundsMulUniform[0]=r.worldBoundsMul.x,this.worldBoundsMulUniform[1]=r.worldBoundsMul.y,this.worldBoundsMulUniform[2]=r.worldBoundsMul.z,this.constantOutBoundsMul.setValue(this.worldBoundsMulUniform),this.worldBoundsAddUniform[0]=r.worldBoundsAdd.x,this.worldBoundsAddUniform[1]=r.worldBoundsAdd.y,this.worldBoundsAddUniform[2]=r.worldBoundsAdd.z,this.constantOutBoundsAdd.setValue(this.worldBoundsAddUniform),this._setInputBounds();var h=r.maxVel*Math.max(Math.max(o.x,o.y),o.z);h=Math.max(h,1),this.constantMaxVel.setValue(h)}var l=null===a||r.localSpace?me.ZERO:a.getPosition(),c=null===a?Te.IDENTITY:a.getWorldTransform();0===r.emitterShape?(cu.setFromMat4(t),this.constantSpawnBounds.setValue(cu.data),this.constantSpawnPosInnerRatio.setValue(i)):(this.constantSpawnBoundsSphere.setValue(r.emitterRadius),this.constantSpawnBoundsSphereInnerRatio.setValue(0===r.emitterRadius?0:r.emitterRadiusInner/r.emitterRadius)),this.constantInitialVelocity.setValue(r.initialVelocity),uu.setFromMat4(c),c.invertTo3x3(du),this.emitterPosUniform[0]=l.x,this.emitterPosUniform[1]=l.y,this.emitterPosUniform[2]=l.z,this.constantEmitterPos.setValue(this.emitterPosUniform),this.constantFrameRandom.setValue(this.frameRandomUniform),this.constantDelta.setValue(n),this.constantRate.setValue(r.rate),this.constantRateDiv.setValue(r.rate2-r.rate),this.constantStartAngle.setValue(r.startAngle*ce.DEG_TO_RAD),this.constantStartAngle2.setValue(r.startAngle2*ce.DEG_TO_RAD),this.constantSeed.setValue(r.seed),this.constantLifetime.setValue(r.lifetime),this.emitterScaleUniform[0]=o.x,this.emitterScaleUniform[1]=o.y,this.emitterScaleUniform[2]=o.z,this.constantEmitterScale.setValue(this.emitterScaleUniform),this.constantEmitterMatrix.setValue(uu.data),this.constantEmitterMatrixInv.setValue(du.data),this.constantLocalVelocityDivMult.setValue(r.localVelocityUMax),this.constantVelocityDivMult.setValue(r.velocityUMax),this.constantRotSpeedDivMult.setValue(r.rotSpeedUMax[0]);var u=r.swapTex?r.particleTexOUT:r.particleTexIN;u=r.beenReset?r.particleTexStart:u;var d=r.swapTex?r.particleTexIN:r.particleTexOUT;this.constantParticleTexIN.setValue(u),Da(e,r.swapTex?r.rtParticleTexIN:r.rtParticleTexOUT,s?r.shaderParticleUpdateOnStop:r.loop?r.shaderParticleUpdateRespawn:r.shaderParticleUpdateNoRespawn),r.material.setParameter("particleTexOUT",u),r.material.setParameter("particleTexIN",d),r.beenReset=!1,r.swapTex=!r.swapTex,r.prevWorldBoundsSize.copy(r.worldBoundsSize),r.prevWorldBoundsCenter.copy(r.worldBounds.center),r.pack8&&this._setInputBounds()},e}(),pu=[[-1,-1],[1,-1],[1,1],[-1,1]];function mu(e,t,i,n,s,r,a){void 0===s&&(s=Ze);var o=0;a&&7===s&&(o=1);var h=new Yn(e,{width:t,height:i,format:s,cubemap:!1,mipmaps:!1,minFilter:o,magFilter:o,addressU:1,addressV:1,name:"ParticleSystemTexture"}),l=h.lock();if(7===s){for(var c=new Uint8Array(n.length),u=0;u<n.length;u++)c[u]=n[u]*r*255;n=c}return l.set(n),h.unlock(),h}function _u(e){return Math.max(Math.min(e,1),0)}var gu,vu,yu=new fe([0,0,1,0]),xu=new fe([0,1,1,1]),Su=new pe([0,0,1,0],[0,0,1,0],[0,0,1,0]),bu=new pe([0,1,1,1],[0,1,1,1],[0,1,1,1]),wu=2,Tu=new Float32Array(3),Au=new Te,Cu=new me,Eu=new me,Mu=new me;function Pu(e,t){void 0!==vu[e]&&null!==vu[e]?gu[e]=vu[e]:gu[e]=t}function Ru(e,t,i){return(255*e<<16|255*t<<8|255*i)/(1<<24)}function Iu(e,t){for(var i=e.length/3,n=new Array(4*i),s=0;s<i;s++)n[4*s]=e[3*s],n[4*s+1]=e[3*s+1],n[4*s+2]=e[3*s+2],n[4*s+3]=Ru(t[3*s],t[3*s+1],t[3*s+2]);return n}function Lu(e,t){for(var i=t.length,n=e.length/i,s=0;s<n;s++)for(var r=0;r<i;r++){var a=Math.abs(e[s*i+r]);t[r]=Math.max(t[r],a)}}function Du(e,t,i){var n=function(e,t){for(var i=new Float32Array(e.length),n=0;n<e.length;n++)i[n]=e[n]-t[n];return i}(t,e);return Lu(n,i),function(e,t){for(var i=t.length,n=e.length/i,s=0;s<n;s++)for(var r=0;r<i;r++)e[s*i+r]/=0===t[r]?1:t[r],e[s*i+r]*=.5,e[s*i+r]+=.5}(n,i),n}var Ou=new Jn,ku=function(){function e(e,t){this.graphicsDevice=e;var i=e;this.precision=32,this._addTimeTime=0,gu=this,vu=t,Pu("numParticles",1),this.numParticles>e.maxTextureSize&&(this.numParticles=e.maxTextureSize),Pu("rate",1),Pu("rate2",this.rate),Pu("lifetime",50),Pu("emitterExtents",new me(0,0,0)),Pu("emitterExtentsInner",new me(0,0,0)),Pu("emitterRadius",0),Pu("emitterRadiusInner",0),Pu("emitterShape",0),Pu("initialVelocity",1),Pu("wrap",!1),Pu("localSpace",!1),Pu("screenSpace",!1),Pu("wrapBounds",null),Pu("colorMap",this.defaultParamTexture),Pu("normalMap",null),Pu("loop",!0),Pu("preWarm",!1),Pu("sort",0),Pu("mode",0),Pu("scene",null),Pu("lighting",!1),Pu("halfLambert",!1),Pu("intensity",1),Pu("stretch",0),Pu("alignToMotion",!1),Pu("depthSoftening",0),Pu("mesh",null),Pu("particleNormal",new me(0,1,0)),Pu("orientation",0),Pu("depthWrite",!1),Pu("noFog",!1),Pu("blendType",2),Pu("node",null),Pu("startAngle",0),Pu("startAngle2",this.startAngle),Pu("animTilesX",1),Pu("animTilesY",1),Pu("animStartFrame",0),Pu("animNumFrames",1),Pu("animNumAnimations",1),Pu("animIndex",0),Pu("randomizeAnimIndex",!1),Pu("animSpeed",1),Pu("animLoop",!0),this._gpuUpdater=new fu(this,i),this._cpuUpdater=new lu(this),this.constantLightCube=i.scope.resolve("lightCube[0]"),this.emitterPosUniform=new Float32Array(3),this.wrapBoundsUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),Pu("colorGraph",bu),Pu("colorGraph2",this.colorGraph),Pu("scaleGraph",xu),Pu("scaleGraph2",this.scaleGraph),Pu("alphaGraph",xu),Pu("alphaGraph2",this.alphaGraph),Pu("localVelocityGraph",Su),Pu("localVelocityGraph2",this.localVelocityGraph),Pu("velocityGraph",Su),Pu("velocityGraph2",this.velocityGraph),Pu("rotationSpeedGraph",yu),Pu("rotationSpeedGraph2",this.rotationSpeedGraph),Pu("radialSpeedGraph",yu),Pu("radialSpeedGraph2",this.radialSpeedGraph),this.lightCube=new Float32Array(18),this.lightCubeDir=new Array(6),this.lightCubeDir[0]=new me(-1,0,0),this.lightCubeDir[1]=new me(1,0,0),this.lightCubeDir[2]=new me(0,-1,0),this.lightCubeDir[3]=new me(0,1,0),this.lightCubeDir[4]=new me(0,0,-1),this.lightCubeDir[5]=new me(0,0,1),this.animTilesParams=new Float32Array(2),this.animParams=new Float32Array(4),this.animIndexParams=new Float32Array(2),this.internalTex0=null,this.internalTex1=null,this.internalTex2=null,this.colorParam=null,this.vbToSort=null,this.vbOld=null,this.particleDistance=null,this.camera=null,this.swapTex=!1,this.useMesh=!0,this.useCpu=!e.supportsGpuParticles,this.pack8=!0,this.localBounds=new Ie,this.worldBoundsNoTrail=new Ie,this.worldBoundsTrail=[new Ie,new Ie],this.worldBounds=new Ie,this.worldBoundsSize=new me,this.prevWorldBoundsSize=new me,this.prevWorldBoundsCenter=new me,this.prevEmitterExtents=this.emitterExtents,this.prevEmitterRadius=this.emitterRadius,this.worldBoundsMul=new me,this.worldBoundsAdd=new me,this.timeToSwitchBounds=0,this.shaderParticleUpdateRespawn=null,this.shaderParticleUpdateNoRespawn=null,this.shaderParticleUpdateOnStop=null,this.numParticleVerts=0,this.numParticleIndices=0,this.material=null,this.meshInstance=null,this.drawOrder=0,this.seed=Math.random(),this.fixedTimeStep=1/60,this.maxSubSteps=10,this.simTime=0,this.simTimeTotal=0,this.beenReset=!1,this._layer=null,this.rebuild()}var t=e.prototype;return t.onChangeCamera=function(){this.regenShader(),this.resetMaterial()},t.calculateBoundsMad=function(){this.worldBoundsMul.x=1/this.worldBoundsSize.x,this.worldBoundsMul.y=1/this.worldBoundsSize.y,this.worldBoundsMul.z=1/this.worldBoundsSize.z,this.worldBoundsAdd.copy(this.worldBounds.center).mul(this.worldBoundsMul).mulScalar(-1),this.worldBoundsAdd.x+=.5,this.worldBoundsAdd.y+=.5,this.worldBoundsAdd.z+=.5},t.calculateWorldBounds=function(){if(this.node){if(this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),!this.useCpu){(0===this.emitterShape?!this.emitterExtents.equals(this.prevEmitterExtents):!(this.emitterRadius===this.prevEmitterRadius))&&this.calculateLocalBounds()}var e=this.node.getWorldTransform();this.localSpace?this.worldBoundsNoTrail.copy(this.localBounds):this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,e),this.worldBoundsTrail[0].add(this.worldBoundsNoTrail),this.worldBoundsTrail[1].add(this.worldBoundsNoTrail);var t=this.simTimeTotal;t>=this.timeToSwitchBounds&&(this.worldBoundsTrail[0].copy(this.worldBoundsTrail[1]),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.timeToSwitchBounds=t+this.lifetime),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.localSpace?(this.meshInstance.aabb.setFromTransformedAabb(this.worldBounds,e),this.meshInstance.mesh.aabb.setFromTransformedAabb(this.worldBounds,e)):(this.meshInstance.aabb.copy(this.worldBounds),this.meshInstance.mesh.aabb.copy(this.worldBounds)),this.meshInstance._aabbVer=1-this.meshInstance._aabbVer,this.pack8&&this.calculateBoundsMad()}},t.resetWorldBounds=function(){this.node&&(this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,this.localSpace?Te.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBoundsNoTrail),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.simTimeTotal=0,this.timeToSwitchBounds=0)},t.calculateLocalBounds=function(){for(var e,t,i,n=Number.MAX_VALUE,s=Number.MAX_VALUE,r=Number.MAX_VALUE,a=-Number.MAX_VALUE,o=-Number.MAX_VALUE,h=-Number.MAX_VALUE,l=0,c=0,u=this.lifetime/this.precision,d=[this.qVelocity,this.qVelocity2],f=[this.qLocalVelocity,this.qLocalVelocity2],p=[0,0],m=[0,0],_=[0,0],g=[0,0],v=[0,0],y=0;y<this.precision+1;y++){for(var x=Math.min(y,this.precision-1),S=0;S<2;S++)e=f[S][3*x+0]*u+p[S],t=f[S][3*x+1]*u+m[S],i=f[S][3*x+2]*u+_[S],n=Math.min(e,n),s=Math.min(t,s),r=Math.min(i,r),a=Math.max(e,a),o=Math.max(t,o),h=Math.max(i,h),p[S]=e,m[S]=t,_[S]=i;for(var b=0;b<2;b++)v[b]+=u*Math.sqrt(d[b][3*x+0]*d[b][3*x+0]+d[b][3*x+1]*d[b][3*x+1]+d[b][3*x+2]*d[b][3*x+2]);g[0]+=this.qRadialSpeed[x]*u,g[1]+=this.qRadialSpeed2[x]*u,l=Math.max(l,Math.max(Math.abs(g[0]),Math.abs(g[1]))),c=Math.max(c,this.qScale[x])}0===this.emitterShape?(e=.5*this.emitterExtents.x,t=.5*this.emitterExtents.y,i=.5*this.emitterExtents.z):(e=this.emitterRadius,t=this.emitterRadius,i=this.emitterRadius);var w=Math.max(v[0],v[1]);Eu.x=n-c-e-l-w,Eu.y=s-c-t-l-w,Eu.z=r-c-i-l-w,Mu.x=a+c+e+l+w,Mu.y=o+c+t+l+w,Mu.z=h+c+i+l+w,this.localBounds.setMinMax(Eu,Mu)},t.rebuild=function(){var e=this.graphicsDevice;(null===this.colorMap&&(this.colorMap=this.defaultParamTexture),this.spawnBounds=0===this.emitterShape?this.emitterExtents:this.emitterRadius,this.useCpu=this.useCpu||this.sort>0||e.maxVertexTextures<=1||e.fragmentUniformsCount<64||e.forceCpuParticles||!e.extTextureFloat,this._destroyResources(),this.pack8=(this.pack8||!e.textureFloatRenderable)&&!this.useCpu,wu=this.useCpu||this.pack8?4:2,this.useMesh=!1,this.mesh)&&(this.numParticles*this.mesh.vertexBuffer.numVertices>65535||(this.useMesh=!0));this.numParticlesPot=ce.nextPowerOfTwo(this.numParticles),this.rebuildGraphs(),this.calculateLocalBounds(),this.resetWorldBounds(),this.node&&(this.worldBounds.setFromTransformedAabb(this.localBounds,this.localSpace?Te.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBounds),this.worldBoundsTrail[1].copy(this.worldBounds),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.pack8&&this.calculateBoundsMad()),this.vbToSort=new Array(this.numParticles);for(var t=0;t<this.numParticles;t++)this.vbToSort[t]=[0,0];this.particleDistance=new Float32Array(this.numParticles),this._gpuUpdater.randomize(),this.particleTex=new Float32Array(this.numParticlesPot*wu*4);var i=null===this.node||this.localSpace?me.ZERO:this.node.getPosition();0===this.emitterShape&&(null===this.node||this.localSpace?Au.setTRS(me.ZERO,Ae.IDENTITY,this.spawnBounds):Au.setTRS(me.ZERO,this.node.getRotation(),Cu.copy(this.spawnBounds).mul(this.node.localScale)),Tu[0]=0!==this.emitterExtents.x?this.emitterExtentsInner.x/this.emitterExtents.x:0,Tu[1]=0!==this.emitterExtents.y?this.emitterExtentsInner.y/this.emitterExtents.y:0,Tu[2]=0!==this.emitterExtents.z?this.emitterExtentsInner.z/this.emitterExtents.z:0);for(var n=0;n<this.numParticles;n++)this._cpuUpdater.calcSpawnPosition(this.particleTex,Au,Tu,i,n),this.useCpu&&(this.particleTex[4*n+3+2*this.numParticlesPot*4]=1);this.particleTexStart=new Float32Array(this.numParticlesPot*wu*4);for(var s=0;s<this.particleTexStart.length;s++)this.particleTexStart[s]=this.particleTex[s];this.useCpu||(this.pack8?(this.particleTexIN=mu(e,this.numParticlesPot,wu,this.particleTex,7,1,!1),this.particleTexOUT=mu(e,this.numParticlesPot,wu,this.particleTex,7,1,!1),this.particleTexStart=mu(e,this.numParticlesPot,wu,this.particleTexStart,7,1,!1)):(this.particleTexIN=mu(e,this.numParticlesPot,wu,this.particleTex),this.particleTexOUT=mu(e,this.numParticlesPot,wu,this.particleTex),this.particleTexStart=mu(e,this.numParticlesPot,wu,this.particleTexStart)),this.rtParticleTexIN=new Di({colorBuffer:this.particleTexIN,depth:!1}),this.rtParticleTexOUT=new Di({colorBuffer:this.particleTexOUT,depth:!1}),this.swapTex=!1);var r=(this.localSpace?"#define LOCAL_SPACE\n":"")+Sa.particleUpdaterInitPS+(this.pack8?Sa.particleInputRgba8PS+Sa.particleOutputRgba8PS:Sa.particleInputFloatPS+Sa.particleOutputFloatPS)+(0===this.emitterShape?Sa.particleUpdaterAABBPS:Sa.particleUpdaterSpherePS)+Sa.particleUpdaterStartPS,a=r+Sa.particleUpdaterRespawnPS+Sa.particleUpdaterEndPS,o=r+Sa.particleUpdaterNoRespawnPS+Sa.particleUpdaterEndPS,h=r+Sa.particleUpdaterOnStopPS+Sa.particleUpdaterEndPS,l=this.emitterShape+""+this.pack8+this.localSpace;this.shaderParticleUpdateRespawn=Ca(e,Sa.fullscreenQuadVS,a,"fsQuad0"+l),this.shaderParticleUpdateNoRespawn=Ca(e,Sa.fullscreenQuadVS,o,"fsQuad1"+l),this.shaderParticleUpdateOnStop=Ca(e,Sa.fullscreenQuadVS,h,"fsQuad2"+l),this.numParticleVerts=this.useMesh?this.mesh.vertexBuffer.numVertices:4,this.numParticleIndices=this.useMesh?this.mesh.indexBuffer[0].numIndices:6,this._allocate(this.numParticles);var c=new Jr(e);c.vertexBuffer=this.vertexBuffer,c.indexBuffer[0]=this.indexBuffer,c.primitive[0].type=4,c.primitive[0].base=0,c.primitive[0].count=this.numParticles*this.numParticleIndices,c.primitive[0].indexed=!0,this.material=new Ya,this.material.name=this.node.name,this.material.cull=0,this.material.alphaWrite=!1,this.material.blendType=this.blendType,this.material.depthWrite=this.depthWrite,this.material.emitter=this,this.regenShader(),this.resetMaterial();var u=!this.meshInstance||this.meshInstance.visible;this.meshInstance=new Co(c,this.material,this.node),this.meshInstance.pick=!1,this.meshInstance.updateKey(),this.meshInstance.cull=!0,this.meshInstance._noDepthDrawGl1=!0,this.localSpace?this.meshInstance.aabb.setFromTransformedAabb(this.worldBounds,this.node.getWorldTransform()):this.meshInstance.aabb.copy(this.worldBounds),this.meshInstance._updateAabb=!1,this.meshInstance.visible=u,this._initializeTextures(),this.resetTime(),this.addTime(0,!1),this.preWarm&&this.prewarm(this.lifetime)},t._isAnimated=function(){return this.animNumFrames>=1&&(this.animTilesX>1||this.animTilesY>1)&&(this.colorMap&&this.colorMap!==this.defaultParamTexture||this.normalMap)},t.rebuildGraphs=function(){var e=this.precision,t=this.graphicsDevice;this.qLocalVelocity=this.localVelocityGraph.quantize(e),this.qVelocity=this.velocityGraph.quantize(e),this.qColor=this.colorGraph.quantizeClamped(e,0,1),this.qRotSpeed=this.rotationSpeedGraph.quantize(e),this.qScale=this.scaleGraph.quantize(e),this.qAlpha=this.alphaGraph.quantize(e),this.qRadialSpeed=this.radialSpeedGraph.quantize(e),this.qLocalVelocity2=this.localVelocityGraph2.quantize(e),this.qVelocity2=this.velocityGraph2.quantize(e),this.qColor2=this.colorGraph2.quantizeClamped(e,0,1),this.qRotSpeed2=this.rotationSpeedGraph2.quantize(e),this.qScale2=this.scaleGraph2.quantize(e),this.qAlpha2=this.alphaGraph2.quantize(e),this.qRadialSpeed2=this.radialSpeedGraph2.quantize(e);for(var i=0;i<e;i++)this.qRotSpeed[i]*=ce.DEG_TO_RAD,this.qRotSpeed2[i]*=ce.DEG_TO_RAD;if(this.localVelocityUMax=new Float32Array(3),this.velocityUMax=new Float32Array(3),this.colorUMax=new Float32Array(3),this.rotSpeedUMax=[0],this.scaleUMax=[0],this.alphaUMax=[0],this.radialSpeedUMax=[0],this.qLocalVelocityDiv=Du(this.qLocalVelocity,this.qLocalVelocity2,this.localVelocityUMax),this.qVelocityDiv=Du(this.qVelocity,this.qVelocity2,this.velocityUMax),this.qColorDiv=Du(this.qColor,this.qColor2,this.colorUMax),this.qRotSpeedDiv=Du(this.qRotSpeed,this.qRotSpeed2,this.rotSpeedUMax),this.qScaleDiv=Du(this.qScale,this.qScale2,this.scaleUMax),this.qAlphaDiv=Du(this.qAlpha,this.qAlpha2,this.alphaUMax),this.qRadialSpeedDiv=Du(this.qRadialSpeed,this.qRadialSpeed2,this.radialSpeedUMax),this.pack8){var n=[0,0,0];Lu(this.qVelocity,n);var s=[0,0,0];Lu(this.qVelocity2,s);var r=[0,0,0];Lu(this.qLocalVelocity,r);var a=[0,0,0];Lu(this.qLocalVelocity2,a);var o=[0];Lu(this.qRadialSpeed,o);var h=[0];Lu(this.qRadialSpeed2,h);var l=Math.max(n[0],s[0]);l=Math.max(l,n[1]),l=Math.max(l,s[1]),l=Math.max(l,n[2]),l=Math.max(l,s[2]);var c=Math.max(r[0],a[0]);c=Math.max(c,r[1]),c=Math.max(c,a[1]),c=Math.max(c,r[2]),c=Math.max(c,a[2]);var u=Math.max(o[0],h[0]);this.maxVel=l+c+u}this.useCpu||(this.internalTex0=mu(t,e,1,Iu(this.qLocalVelocity,this.qLocalVelocityDiv)),this.internalTex1=mu(t,e,1,Iu(this.qVelocity,this.qVelocityDiv)),this.internalTex2=mu(t,e,1,function(e,t,i,n,s){for(var r=new Array(4*e.length),a=0;a<e.length;a++)r[4*a]=e[a],r[4*a+1]=t[a],r[4*a+2]=0,r[4*a+3]=Ru(i[a],n[a],s[a]);return r}(this.qRotSpeed,this.qScale,this.qScaleDiv,this.qRotSpeedDiv,this.qAlphaDiv)),this.internalTex3=mu(t,e,1,function(e,t){for(var i=new Array(4*e.length),n=0;n<e.length;n++)i[4*n]=e[n],i[4*n+1]=t[n],i[4*n+2]=0,i[4*n+3]=0;return i}(this.qRadialSpeed,this.qRadialSpeedDiv))),this.colorParam=mu(t,e,1,function(e,t){for(var i=new Array(4*t.length),n=0;n<t.length;n++)i[4*n]=e[3*n],i[4*n+1]=e[3*n+1],i[4*n+2]=e[3*n+2],i[4*n+3]=t[n];return i}(this.qColor,this.qAlpha),7,1,!0)},t._initializeTextures=function(){this.colorMap&&(this.material.setParameter("colorMap",this.colorMap),this.lighting&&this.normalMap&&this.material.setParameter("normalMap",this.normalMap))},t.regenShader=function(){var e=wa(this.graphicsDevice);e.register("particle",Gc);var t=null!==this.normalMap;this.normalOption=0,this.lighting&&(this.normalOption=t?2:1),this.material.getShaderVariant=function(t,i,n,s,r,a,o,h){this.emitter.scene&&this.emitter.camera!==this.emitter.scene._activeCamera&&(this.emitter.camera=this.emitter.scene._activeCamera,this.emitter.onChangeCamera());var l=this.emitter.inTools,c=new va(o,h);return e.getProgram("particle",{pass:0,useCpu:this.emitter.useCpu,normal:this.emitter.normalOption,halflambert:this.emitter.halfLambert,stretch:this.emitter.stretch,alignToMotion:this.emitter.alignToMotion,soft:this.emitter.depthSoftening,mesh:this.emitter.useMesh,gamma:this.emitter.scene?this.emitter.scene.gammaCorrection:0,toneMap:this.emitter.scene?this.emitter.scene.toneMapping:0,fog:this.emitter.scene&&!this.emitter.noFog?this.emitter.scene.fog:"none",wrap:this.emitter.wrap&&this.emitter.wrapBounds,localSpace:this.emitter.localSpace,screenSpace:!l&&this.emitter.screenSpace,blend:this.blendType,animTex:this.emitter._isAnimated(),animTexLoop:this.emitter.animLoop,pack8:this.emitter.pack8,customFace:0!==this.emitter.orientation},c)},this.material.shader=this.material.getShaderVariant()},t.resetMaterial=function(){var e=this.material;e.setParameter("stretch",this.stretch),this._isAnimated()&&(e.setParameter("animTexTilesParams",this.animTilesParams),e.setParameter("animTexParams",this.animParams),e.setParameter("animTexIndexParams",this.animIndexParams)),e.setParameter("colorMult",this.intensity),this.useCpu||(e.setParameter("internalTex0",this.internalTex0),e.setParameter("internalTex1",this.internalTex1),e.setParameter("internalTex2",this.internalTex2),e.setParameter("internalTex3",this.internalTex3)),e.setParameter("colorParam",this.colorParam),e.setParameter("numParticles",this.numParticles),e.setParameter("numParticlesPot",this.numParticlesPot),e.setParameter("lifetime",this.lifetime),e.setParameter("rate",this.rate),e.setParameter("rateDiv",this.rate2-this.rate),e.setParameter("seed",this.seed),e.setParameter("scaleDivMult",this.scaleUMax[0]),e.setParameter("alphaDivMult",this.alphaUMax[0]),e.setParameter("radialSpeedDivMult",this.radialSpeedUMax[0]),e.setParameter("graphNumSamples",this.precision),e.setParameter("graphSampleSize",1/this.precision),e.setParameter("emitterScale",new Float32Array([1,1,1])),this.pack8&&(this._gpuUpdater._setInputBounds(),e.setParameter("inBoundsSize",this._gpuUpdater.inBoundsSizeUniform),e.setParameter("inBoundsCenter",this._gpuUpdater.inBoundsCenterUniform),e.setParameter("maxVel",this.maxVel)),this.wrap&&this.wrapBounds&&(this.wrapBoundsUniform[0]=this.wrapBounds.x,this.wrapBoundsUniform[1]=this.wrapBounds.y,this.wrapBoundsUniform[2]=this.wrapBounds.z,e.setParameter("wrapBounds",this.wrapBoundsUniform)),this.colorMap&&e.setParameter("colorMap",this.colorMap),this.lighting&&this.normalMap&&e.setParameter("normalMap",this.normalMap),this.depthSoftening>0&&e.setParameter("softening",1/(this.depthSoftening*this.depthSoftening*100)),this.stretch>0&&(e.cull=0),this._compParticleFaceParams()},t._compParticleFaceParams=function(){var e,t;if(0===this.orientation)e=new Float32Array([1,0,0]),t=new Float32Array([0,0,1]);else{var i;if(1===this.orientation)i=this.particleNormal.normalize();else i=(null===this.node?Te.IDENTITY:this.node.getWorldTransform()).transformVector(this.particleNormal).normalize();var n=new me(1,0,0);1===Math.abs(n.dot(i))&&n.set(0,0,1);var s=(new me).cross(i,n).normalize();n.cross(s,i).normalize(),e=new Float32Array([n.x,n.y,n.z]),t=new Float32Array([s.x,s.y,s.z])}this.material.setParameter("faceTangent",e),this.material.setParameter("faceBinorm",t)},t._allocate=function(e){var t=e*this.numParticleVerts,i=e*this.numParticleIndices;if(void 0===this.vertexBuffer||this.vertexBuffer.getNumVertices()!==t){if(this.useCpu){var n=[{semantic:At,components:4,type:6},{semantic:Ct,components:4,type:6},{semantic:Et,components:4,type:6},{semantic:Mt,components:1,type:6},{semantic:Pt,components:this.useMesh?4:2,type:6}],s=new Pi(this.graphicsDevice,n);this.vertexBuffer=new Ei(this.graphicsDevice,s,t,1),this.indexBuffer=new As(this.graphicsDevice,1,i)}else{var r=[{semantic:At,components:4,type:6}];this.useMesh&&r.push({semantic:Ct,components:2,type:6});var a=new Pi(this.graphicsDevice,r);this.vertexBuffer=new Ei(this.graphicsDevice,a,t,1),this.indexBuffer=new As(this.graphicsDevice,1,i)}var o,h,l,c=new Float32Array(this.vertexBuffer.lock());if(this.useMesh){h=(o=new Float32Array(this.mesh.vertexBuffer.lock())).length/this.mesh.vertexBuffer.numVertices;for(var u=0;u<this.mesh.vertexBuffer.format.elements.length;u++)if(this.mesh.vertexBuffer.format.elements[u].name===_t){l=this.mesh.vertexBuffer.format.elements[u].offset/4;break}}for(var d=0;d<t;d++){var f=Math.floor(d/this.numParticleVerts);if(this.useMesh){var p=d%this.numParticleVerts;c[6*d]=o[p*h],c[6*d+1]=o[p*h+1],c[6*d+2]=o[p*h+2],c[6*d+3]=f,c[6*d+4]=o[p*h+l+0],c[6*d+5]=1-o[p*h+l+1]}else{var m=d%4;c[4*d]=pu[m][0],c[4*d+1]=pu[m][1],c[4*d+2]=0,c[4*d+3]=f}}this.useCpu&&(this.vbCPU=new Float32Array(c),this.vbOld=new Float32Array(this.vbCPU.length)),this.vertexBuffer.unlock(),this.useMesh&&this.mesh.vertexBuffer.unlock();var _=0,g=new Uint16Array(this.indexBuffer.lock());this.useMesh&&(o=new Uint16Array(this.mesh.indexBuffer[0].lock()));for(var v=0;v<e;v++)if(this.useMesh)for(var y=0;y<this.numParticleIndices;y++)g[v*this.numParticleIndices+y]=o[y]+v*this.numParticleVerts;else{var x=4*v;g[_++]=x,g[_++]=x+1,g[_++]=x+2,g[_++]=x,g[_++]=x+2,g[_++]=x+3}this.indexBuffer.unlock(),this.useMesh&&this.mesh.indexBuffer[0].unlock()}},t.reset=function(){if(this.beenReset=!0,this.seed=Math.random(),this.material.setParameter("seed",this.seed),this.useCpu)for(var e=0;e<this.particleTexStart.length;e++)this.particleTex[e]=this.particleTexStart[e];else this._initializeTextures();this.resetWorldBounds(),this.resetTime();var t=this.loop;this.loop=!0,this.addTime(0,!1),this.loop=t,this.preWarm&&this.prewarm(this.lifetime)},t.prewarm=function(e){for(var t=e/this.lifetime,i=Math.min(Math.floor(t*this.precision),this.precision),n=e/i,s=0;s<i;s++)this.addTime(n,!1)},t.resetTime=function(){var e,t;this.endTime=(e=this,t=Math.max(e.rate,e.rate2)*e.numParticles+e.lifetime,Date.now()+1e3*t)},t.finishFrame=function(){this.useCpu&&this.vertexBuffer.unlock()},t.addTime=function(e,t){var i,n=this.graphicsDevice;if(this.simTimeTotal+=e,this.calculateWorldBounds(),this._isAnimated()){var s=this.animTilesParams;s[0]=1/this.animTilesX,s[1]=1/this.animTilesY;var r=this.animParams;r[0]=this.animStartFrame,r[1]=this.animNumFrames*this.animSpeed,r[2]=this.animNumFrames-1,r[3]=this.animNumAnimations-1;var a=this.animIndexParams;a[0]=this.animIndex,a[1]=this.randomizeAnimIndex}this.scene&&this.camera!==this.scene._activeCamera&&(this.camera=this.scene._activeCamera,this.onChangeCamera()),0===this.emitterShape&&(Tu[0]=0!==this.emitterExtents.x?this.emitterExtentsInner.x/this.emitterExtents.x:0,Tu[1]=0!==this.emitterExtents.y?this.emitterExtentsInner.y/this.emitterExtents.y:0,Tu[2]=0!==this.emitterExtents.z?this.emitterExtentsInner.z/this.emitterExtents.z:0,null===this.meshInstance.node?Au.setTRS(me.ZERO,Ae.IDENTITY,this.emitterExtents):Au.setTRS(me.ZERO,this.meshInstance.node.getRotation(),Cu.copy(this.emitterExtents).mul(this.meshInstance.node.localScale)));var o=null===this.meshInstance.node?me.ONE:this.meshInstance.node.localScale;if(this.emitterScaleUniform[0]=o.x,this.emitterScaleUniform[1]=o.y,this.emitterScaleUniform[2]=o.z,this.material.setParameter("emitterScale",this.emitterScaleUniform),this.localSpace&&this.meshInstance.node&&(i=this.meshInstance.node.getPosition(),this.emitterPosUniform[0]=i.x,this.emitterPosUniform[1]=i.y,this.emitterPosUniform[2]=i.z,this.material.setParameter("emitterPos",this.emitterPosUniform)),this._compParticleFaceParams(),this.useCpu){var h=new Float32Array(this.vertexBuffer.lock());this._cpuUpdater.update(h,this.vbToSort,this.particleTex,Au,Tu,i,e,t)}else this._gpuUpdater.update(n,Au,Tu,e,t);this.loop||Date.now()>this.endTime&&(this.onFinished&&this.onFinished(),this.meshInstance.visible=!1),this.meshInstance&&(this.meshInstance.drawOrder=this.drawOrder)},t._destroyResources=function(){this.particleTexIN&&(this.particleTexIN.destroy(),this.particleTexIN=null),this.particleTexOUT&&(this.particleTexOUT.destroy(),this.particleTexOUT=null),this.particleTexStart&&this.particleTexStart.destroy&&(this.particleTexStart.destroy(),this.particleTexStart=null),this.rtParticleTexIN&&(this.rtParticleTexIN.destroy(),this.rtParticleTexIN=null),this.rtParticleTexOUT&&(this.rtParticleTexOUT.destroy(),this.rtParticleTexOUT=null),this.internalTex0&&(this.internalTex0.destroy(),this.internalTex0=null),this.internalTex1&&(this.internalTex1.destroy(),this.internalTex1=null),this.internalTex2&&(this.internalTex2.destroy(),this.internalTex2=null),this.internalTex3&&(this.internalTex3.destroy(),this.internalTex3=null),this.colorParam&&(this.colorParam.destroy(),this.colorParam=null),this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=void 0),this.indexBuffer&&(this.indexBuffer.destroy(),this.indexBuffer=void 0),this.material&&(this.material.destroy(),this.material=null)},t.destroy=function(){this.camera=null,this._destroyResources()},Z(e,[{key:"defaultParamTexture",get:function(){var e=this;return Ou.get(this.graphicsDevice,(function(){for(var t=16,i=new Float32Array(1024),n=0;n<t;n++)for(var s=0;s<t;s++){var r=s+1-8.5,a=n+1-8.5,o=_u(1-_u(Math.sqrt(r*r+a*a)/t)-.5),h=n*t+s;i[4*h]=1,i[4*h+1]=1,i[4*h+2]=1,i[4*h+3]=o}var l=mu(e.graphicsDevice,t,t,i,7,1,!0);return l.minFilter=1,l.magFilter=1,l}))}}]),e}(),Fu={generateKey:function(e){return"cubemap"===e.type?"skybox-"+e.type+"-"+e.encoding+"-"+e.useIntensity+"-"+e.gamma+"-"+e.toneMapping+"-"+e.fixSeams+"-"+e.mip:"skybox-"+e.type+"-"+e.encoding+"-"+e.useIntensity+"-"+e.gamma+"-"+e.toneMapping},createShaderDefinition:function(e,t){var i="";if("cubemap"===t.type){i+=t.mip?Sa.fixCubemapSeamsStretchPS:Sa.fixCubemapSeamsNonePS,i+=t.useIntensity?Sa.envMultiplyPS:Sa.envConstPS,i+=Sa.decodePS,i+=Ba(t.gamma),i+=Na(t.toneMapping),i+=Sa.skyboxHDRPS.replace(/\$DECODE/g,al.decodeFunc(t.encoding)).replace(/\$FIXCONST/g,1-1/[128,64,16,8,4,2][t.mip]+"")}else i+=t.useIntensity?Sa.envMultiplyPS:Sa.envConstPS,i+=Sa.decodePS,i+=Ba(t.gamma),i+=Na(t.toneMapping),i+=Sa.sphericalPS,i+=Sa.envAtlasPS,i+=Sa.skyboxEnvPS.replace(/\$DECODE/g,al.decodeFunc(t.encoding));return vs.createDefinition(e,{name:"SkyboxShader",attributes:{aPosition:lt},vertexCode:Sa.skyboxVS,fragmentCode:i})}},Bu=function(){function e(e,t,i){this.meshInstance=void 0;var n=new Ya;n.getShaderVariant=function(n,s,r,a,o,h,l,c){var u={pass:o,encoding:i.encoding,useIntensity:1!==t.skyboxIntensity||t.physicalUnits,gamma:1===o?t.gammaCorrection?3:0:t.gammaCorrection,toneMapping:1===o?0:t.toneMapping};i.cubemap?(u.type="cubemap",u.mip=i.fixCubemapSeams?t.skyboxMip:0,u.fixSeams=i.fixCubemapSeams):u.type="envAtlas";var d=new va(l,c),f=wa(e);return f.register("skybox",Fu),f.getProgram("skybox",u,d)},i.cubemap?n.setParameter("texture_cubeMap",i):(n.setParameter("texture_envAtlas",i),n.setParameter("mipLevel",t._skyboxMip)),n.cull=2,n.depthWrite=!1;var s=t.layers.getLayerById(2);if(s){var r=new go("Skybox"),a=fa(e),o=new Co(a,n,r);this.meshInstance=o,o.cull=!1,o._noDepthDrawGl1=!0,o.pick=!1,s.addMeshInstances([o]),this.skyLayer=s}}return e.prototype.destroy=function(){this.meshInstance&&(this.skyLayer&&this.skyLayer.removeMeshInstances([this.meshInstance]),this.meshInstance.destroy(),this.meshInstance=null)},e}(),Nu=new go;Nu.worldTransform=Te.IDENTITY,Nu._dirtyWorld=Nu._dirtyNormal=!1;var Uu=function(){function e(e,t,i){this.material=t,this.layer=i,this.positions=[],this.colors=[],this.mesh=new Jr(e),this.meshInstance=null}var t=e.prototype;return t.addLines=function(e,t){for(var i=this.positions,n=e.length,s=0;s<n;s++){var r=e[s];i.push(r.x,r.y,r.z)}var a=this.colors;if(t.length)for(var o=0;o<n;o++){var h=t[o];a.push(h.r,h.g,h.b,h.a)}else for(var l=0;l<n;l++)a.push(t.r,t.g,t.b,t.a)},t.addLinesArrays=function(e,t){for(var i=this.positions,n=0;n<e.length;n+=3)i.push(e[n],e[n+1],e[n+2]);var s=this.colors;if(t.length)for(var r=0;r<t.length;r+=4)s.push(t[r],t[r+1],t[r+2],t[r+3]);else for(var a=e.length/3,o=0;o<a;o++)s.push(t.r,t.g,t.b,t.a)},t.onPreRender=function(e,t){this.positions.length>0&&this.material.transparent===t&&(this.mesh.setPositions(this.positions),this.mesh.setColors(this.colors),this.mesh.update(1,!1),this.meshInstance||(this.meshInstance=new Co(this.mesh,this.material,Nu)),this.positions.length=0,this.colors.length=0,e.list.push(this.meshInstance),e.length++)},e}(),zu=function(){function e(e){this.device=e,this.map=new Map}var t=e.prototype;return t.getBatch=function(e,t){var i=this.map.get(e);return i||(i=new Uu(this.device,e,t),this.map.set(e,i)),i},t.onPreRender=function(e,t){this.map.forEach((function(i){i.onPreRender(e,t)}))},e}(),Vu=[],Gu=function(){function e(e){this.device=e,this.quadMesh=null,this.textureShader=null,this.depthTextureShader=null,this.cubeLocalPos=null,this.cubeWorldPos=null,this.batchesMap=new Map,this.allBatches=new Set,this.updatedLayers=new Set,this._materialDepth=null,this._materialNoDepth=null,this.layerMeshInstances=new Map}var t=e.prototype;return t.createMaterial=function(e){var t=new Ka;return t.vertexColors=!0,t.blendType=2,t.depthTest=e,t.update(),t},t.getBatch=function(e,t){var i=this.batchesMap.get(e);i||(i=new zu(this.device),this.batchesMap.set(e,i)),this.allBatches.add(i);var n=t?this.materialDepth:this.materialNoDepth;return i.getBatch(n,e)},t.getShader=function(e,t){if(!this[e]){this[e]=Ca(this.device,"\n attribute vec2 vertex_position;\n uniform mat4 matrix_model;\n varying vec2 uv0;\n void main(void) {\n gl_Position = matrix_model * vec4(vertex_position, 0, 1);\n uv0 = vertex_position.xy + 0.5;\n }\n ",t,"DebugShader:"+e)}return this[e]},t.getTextureShader=function(){return this.getShader("textureShader","\n varying vec2 uv0;\n uniform sampler2D colorMap;\n void main (void) {\n gl_FragColor = vec4(texture2D(colorMap, uv0).xyz, 1);\n }\n ")},t.getUnfilterableTextureShader=function(){return this.getShader("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 ")},t.getDepthTextureShader=function(){return this.getShader("depthTextureShader","\n "+Sa.screenDepthPS+"\n varying vec2 uv0;\n void main() {\n float depth = getLinearScreenDepth(uv0) * camera_params.x;\n gl_FragColor = vec4(vec3(depth), 1.0);\n }\n ")},t.getQuadMesh=function(){return this.quadMesh||(this.quadMesh=new Jr(this.device),this.quadMesh.setPositions([-.5,-.5,0,.5,-.5,0,-.5,.5,0,.5,.5,0]),this.quadMesh.update(5)),this.quadMesh},t.drawMesh=function(e,t,i,n,s){if(!n){var r=this.getGraphNode(t);n=new Co(i,e,r)}var a=this.layerMeshInstances.get(s);a||(a=[],this.layerMeshInstances.set(s,a)),a.push(n)},t.drawWireAlignedBox=function(e,t,i,n,s){Vu.push(e.x,e.y,e.z,e.x,t.y,e.z,e.x,t.y,e.z,t.x,t.y,e.z,t.x,t.y,e.z,t.x,e.y,e.z,t.x,e.y,e.z,e.x,e.y,e.z,e.x,e.y,t.z,e.x,t.y,t.z,e.x,t.y,t.z,t.x,t.y,t.z,t.x,t.y,t.z,t.x,e.y,t.z,t.x,e.y,t.z,e.x,e.y,t.z,e.x,e.y,e.z,e.x,e.y,t.z,e.x,t.y,e.z,e.x,t.y,t.z,t.x,t.y,e.z,t.x,t.y,t.z,t.x,e.y,e.z,t.x,e.y,t.z),this.getBatch(s,n).addLinesArrays(Vu,i),Vu.length=0},t.drawWireSphere=function(e,t,i,n,s,r){for(var a=2*Math.PI/n,o=0,h=0;h<n;h++){var l=Math.sin(o),c=Math.cos(o);o+=a;var u=Math.sin(o),d=Math.cos(o);Vu.push(e.x+t*l,e.y,e.z+t*c),Vu.push(e.x+t*u,e.y,e.z+t*d),Vu.push(e.x+t*l,e.y+t*c,e.z),Vu.push(e.x+t*u,e.y+t*d,e.z),Vu.push(e.x,e.y+t*l,e.z+t*c),Vu.push(e.x,e.y+t*u,e.z+t*d)}this.getBatch(r,s).addLinesArrays(Vu,i),Vu.length=0},t.getGraphNode=function(e){var t=new go("ImmediateDebug");return t.worldTransform=e,t._dirtyWorld=t._dirtyNormal=!1,t},t.onPreRenderLayer=function(e,t,i){if(this.batchesMap.forEach((function(n,s){s===e&&n.onPreRender(t,i)})),!this.updatedLayers.has(e)){this.updatedLayers.add(e);var n=this.layerMeshInstances.get(e);if(n){for(var s=0;s<n.length;s++)t.list[t.length+s]=n[s];t.length+=n.length,n.length=0}}},t.onPostRender=function(){this.allBatches.clear(),this.updatedLayers.clear()},Z(e,[{key:"materialDepth",get:function(){return this._materialDepth||(this._materialDepth=this.createMaterial(!0)),this._materialDepth}},{key:"materialNoDepth",get:function(){return this._materialNoDepth||(this._materialNoDepth=this.createMaterial(!1)),this._materialNoDepth}}]),e}(),Hu=function(e){function t(t){var i;return(i=e.call(this)||this).ambientBake=!1,i.ambientBakeOcclusionBrightness=0,i.ambientBakeOcclusionContrast=0,i.ambientLight=new ue(0,0,0),i.ambientLuminance=0,i.exposure=1,i.fogColor=new ue(0,0,0),i.fogDensity=0,i.fogEnd=1e3,i.fogStart=1,i.lightmapSizeMultiplier=1,i.lightmapMaxResolution=2048,i.lightmapMode=1,i.lightmapFilterEnabled=!1,i.lightmapHDR=!1,i.root=null,i.sky=null,i.physicalUnits=!1,i.device=t||Kr.get(),i._gravity=new me(0,-9.8,0),i._layers=null,i._fog=Nr,i._gammaCorrection=1,i._toneMapping=0,i._skyboxCubeMap=null,i._prefilteredCubemaps=[],i._envAtlas=null,i._internalEnvAtlas=null,i._skyboxIntensity=1,i._skyboxLuminance=0,i._skyboxMip=0,i._skyboxRotationShaderInclude=!1,i._skyboxRotation=new Ae,i._skyboxRotationMat3=new _e,i._skyboxRotationMat4=new Te,i._ambientBakeNumSamples=1,i._ambientBakeSpherePart=.4,i._lightmapFilterRange=10,i._lightmapFilterSmoothness=.2,i._clusteredLightingEnabled=!0,i._lightingParams=new Fc(i.device.supportsAreaLights,i.device.maxTextureSize,(function(){i._layers._dirtyLights=!0})),i._stats={meshInstances:0,lights:0,dynamicLights:0,bakedLights:0,lastStaticPrepareFullTime:0,lastStaticPrepareSearchTime:0,lastStaticPrepareWriteTime:0,lastStaticPrepareTriAabbTime:0,lastStaticPrepareCombineTime:0,updateShadersTime:0},i.updateShaders=!0,i._shaderVersion=0,i._statsUpdated=!1,i.immediate=new Gu(i.device),i}Q(t,e);var i=t.prototype;return i.destroy=function(){this._resetSky(),this.root=null,this.off()},i.drawLine=function(e,t,i,n,s){void 0===i&&(i=ue.WHITE),void 0===n&&(n=!0),void 0===s&&(s=this.defaultDrawLayer),this.immediate.getBatch(s,n).addLines([e,t],[i,i])},i.drawLines=function(e,t,i,n){void 0===i&&(i=!0),void 0===n&&(n=this.defaultDrawLayer),this.immediate.getBatch(n,i).addLines(e,t)},i.drawLineArrays=function(e,t,i,n){void 0===i&&(i=!0),void 0===n&&(n=this.defaultDrawLayer),this.immediate.getBatch(n,i).addLinesArrays(e,t)},i.applySettings=function(e){var t,i,n,s=this,r=e.physics,a=e.render;this._gravity.set(r.gravity[0],r.gravity[1],r.gravity[2]),this.ambientLight.set(a.global_ambient[0],a.global_ambient[1],a.global_ambient[2]),this.ambientLuminance=a.ambientLuminance,this._fog=a.fog,this.fogColor.set(a.fog_color[0],a.fog_color[1],a.fog_color[2]),this.fogStart=a.fog_start,this.fogEnd=a.fog_end,this.fogDensity=a.fog_density,this._gammaCorrection=a.gamma_correction,this._toneMapping=a.tonemapping,this.lightmapSizeMultiplier=a.lightmapSizeMultiplier,this.lightmapMaxResolution=a.lightmapMaxResolution,this.lightmapMode=a.lightmapMode,this.exposure=a.exposure,this._skyboxIntensity=null!=(t=a.skyboxIntensity)?t:1,this._skyboxLuminance=null!=(i=a.skyboxLuminance)?i:2e4,this._skyboxMip=null!=(n=a.skyboxMip)?n:0,a.skyboxRotation&&(this.skyboxRotation=(new Ae).setFromEulerAngles(a.skyboxRotation[0],a.skyboxRotation[1],a.skyboxRotation[2])),this.clusteredLightingEnabled=a.clusteredLightingEnabled,this.lighting.applySettings(a),["lightmapFilterEnabled","lightmapFilterRange","lightmapFilterSmoothness","ambientBake","ambientBakeNumSamples","ambientBakeSpherePart","ambientBakeOcclusionBrightness","ambientBakeOcclusionContrast"].forEach((function(e){a.hasOwnProperty(e)&&(s[e]=a[e])})),this._resetSky()},i._getSkyboxTex=function(){var e=this._prefilteredCubemaps;if(this._skyboxMip){return e[[0,1,3,4,5,6][this._skyboxMip]]||this._envAtlas||e[0]||this._skyboxCubeMap}return this._skyboxCubeMap||e[0]||this._envAtlas},i._updateSky=function(e){if(!this.sky){var t=this._getSkyboxTex();t&&(this.sky=new Bu(e,this,t),this.fire("set:skybox",t))}},i._resetSky=function(){var e;null==(e=this.sky)||e.destroy(),this.sky=null,this.updateShaders=!0},i.setSkybox=function(e){e?(this.skybox=e[0]||null,e[1]&&!e[1].cubemap?this.envAtlas=e[1]:this.prefilteredCubemaps=e.slice(1)):(this.skybox=null,this.envAtlas=null)},Z(t,[{key:"defaultDrawLayer",get:function(){return this.layers.getLayerById(3)}},{key:"ambientBakeNumSamples",get:function(){return this._ambientBakeNumSamples},set:function(e){this._ambientBakeNumSamples=ce.clamp(Math.floor(e),1,255)}},{key:"ambientBakeSpherePart",get:function(){return this._ambientBakeSpherePart},set:function(e){this._ambientBakeSpherePart=ce.clamp(e,.001,1)}},{key:"clusteredLightingEnabled",get:function(){return this._clusteredLightingEnabled},set:function(e){this._clusteredLightingEnabled||!e?this._clusteredLightingEnabled=e:console.error("Turning on disabled clustered lighting is not currently supported")}},{key:"drawCalls",get:function(){var e=this.layers._meshInstances;return e.length||(this.layers._update(this.device,this.clusteredLightingEnabled),e=this.layers._meshInstances),e},set:function(e){}},{key:"envAtlas",get:function(){return this._envAtlas},set:function(e){e!==this._envAtlas&&(this._envAtlas=e,e&&(e.addressU=1,e.addressV=1,e.minFilter=1,e.magFilter=1,e.mipmaps=!1),this._prefilteredCubemaps=[],this._internalEnvAtlas&&(this._internalEnvAtlas.destroy(),this._internalEnvAtlas=null),this._resetSky())}},{key:"fog",get:function(){return this._fog},set:function(e){e!==this._fog&&(this._fog=e,this.updateShaders=!0)}},{key:"gammaCorrection",get:function(){return this._gammaCorrection},set:function(e){e!==this._gammaCorrection&&(this._gammaCorrection=e,this.updateShaders=!0)}},{key:"layers",get:function(){return this._layers},set:function(e){var t=this._layers;this._layers=e,this.fire("set:layers",t,e)}},{key:"lighting",get:function(){return this._lightingParams}},{key:"lightmapFilterRange",get:function(){return this._lightmapFilterRange},set:function(e){this._lightmapFilterRange=Math.max(e,.001)}},{key:"lightmapFilterSmoothness",get:function(){return this._lightmapFilterSmoothness},set:function(e){this._lightmapFilterSmoothness=Math.max(e,.001)}},{key:"prefilteredCubemaps",get:function(){return this._prefilteredCubemaps},set:function(e){e=e||[];var t=this._prefilteredCubemaps,i=t.length!==e.length||t.some((function(t,i){return t!==e[i]}));if(i){var n=6===e.length&&e.every((function(e){return!!e}));n?(this._internalEnvAtlas=Cl.generatePrefilteredAtlas(e,{target:this._internalEnvAtlas}),this._envAtlas=this._internalEnvAtlas):(this._internalEnvAtlas&&(this._internalEnvAtlas.destroy(),this._internalEnvAtlas=null),this._envAtlas=null),this._prefilteredCubemaps=e.slice(),this._resetSky()}}},{key:"skybox",get:function(){return this._skyboxCubeMap},set:function(e){e!==this._skyboxCubeMap&&(this._skyboxCubeMap=e,this._resetSky())}},{key:"skyboxIntensity",get:function(){return this._skyboxIntensity},set:function(e){e!==this._skyboxIntensity&&(this._skyboxIntensity=e,this._resetSky())}},{key:"skyboxLuminance",get:function(){return this._skyboxLuminance},set:function(e){e!==this._skyboxLuminance&&(this._skyboxLuminance=e,this._resetSky())}},{key:"skyboxMip",get:function(){return this._skyboxMip},set:function(e){e!==this._skyboxMip&&(this._skyboxMip=e,this._resetSky())}},{key:"skyboxRotation",get:function(){return this._skyboxRotation},set:function(e){if(!this._skyboxRotation.equals(e)){var t=e.equals(Ae.IDENTITY);this._skyboxRotation.copy(e),t?this._skyboxRotationMat3.setIdentity():(this._skyboxRotationMat4.setTRS(me.ZERO,e,me.ONE),this._skyboxRotationMat4.invertTo3x3(this._skyboxRotationMat3)),this._skyboxRotationShaderInclude||t||(this._skyboxRotationShaderInclude=!0,this._resetSky())}}},{key:"toneMapping",get:function(){return this._toneMapping},set:function(e){e!==this._toneMapping&&(this._toneMapping=e,this.updateShaders=!0)}},{key:"lightmapPixelFormat",get:function(){return this.lightmapHDR&&this.device.getHdrFormat(!1,!0,!1,!0)||7}}]),t}(p),Wu=function(e,t,i){this.device=e,this.inverseBindPose=t,this.boneNames=i},Xu=[0,0,1,0,0,1,0,0,1,0,0,1],ju=[0,1,3,2,3,1],qu=function(e){function t(t,i){var n;return(n=e.call(this)||this)._device=t,n._pixelsPerUnit=i&&void 0!==i.pixelsPerUnit?i.pixelsPerUnit:1,n._renderMode=i&&void 0!==i.renderMode?i.renderMode:0,n._atlas=i&&void 0!==i.atlas?i.atlas:null,n._frameKeys=i&&void 0!==i.frameKeys?i.frameKeys:null,n._meshes=[],n._updatingProperties=!1,n._meshesDirty=!1,n._atlas&&n._frameKeys&&n._createMeshes(),n}Q(t,e);var i=t.prototype;return i._createMeshes=function(){for(var e=this._meshes.length,t=0;t<e;t++){var i=this._meshes[t];i&&i.destroy()}var n=this._frameKeys.length;this._meshes=new Array(n);for(var s=1===this.renderMode||2===this._renderMode?this._create9SliceMesh:this._createSimpleMesh,r=0;r<n;r++){var a=this._atlas.frames[this._frameKeys[r]];this._meshes[r]=a?s.call(this,a):null}this.fire("set:meshes")},i._createSimpleMesh=function(e){var t=e.rect,i=this._atlas.texture.width,n=this._atlas.texture.height,s=t.z/this._pixelsPerUnit,r=t.w/this._pixelsPerUnit,a=e.pivot.x,o=e.pivot.y,h=[-a*s,-o*r,0,(1-a)*s,-o*r,0,(1-a)*s,(1-o)*r,0,-a*s,(1-o)*r,0],l=t.x/i,c=1-t.y/n,u=(t.x+t.z)/i,d=1-(t.y+t.w)/n,f=[l,c,u,c,u,d,l,d];return ra(this._device,h,{uvs:f,normals:Xu,indices:ju})},i._create9SliceMesh=function(){for(var e=ge.ONE,t=[],i=[],n=[],s=[],r=0,a=0;a<=3;a++)for(var o=0===a||3===a?0:1,h=0;h<=3;h++){var l=-e.x+2*e.x*(a<=1?0:3)/3,c=-(-e.y+2*e.y*(h<=1?0:3)/3),u=0===h||3===h?0:1;t.push(-l,0,c),i.push(0,1,0),n.push(o,u),a<3&&h<3&&(s.push(r+3+1,r+1,r),s.push(r+3+1,r+3+2,r+1)),r++}var d={normals:i,uvs:n,indices:s};return ra(this._device,t,d)},i._onSetFrames=function(e){this._updatingProperties?this._meshesDirty=!0:this._createMeshes()},i._onFrameChanged=function(e,t){var i=this._frameKeys.indexOf(e);i<0||(t?0===this.renderMode&&(this._meshes[i]=this._createSimpleMesh(t)):this._meshes[i]=null,this.fire("set:meshes"))},i._onFrameRemoved=function(e){var t=this._frameKeys.indexOf(e);t<0||(this._meshes[t]=null,this.fire("set:meshes"))},i.startUpdate=function(){this._updatingProperties=!0,this._meshesDirty=!1},i.endUpdate=function(){this._updatingProperties=!1,this._meshesDirty&&this._atlas&&this._frameKeys&&this._createMeshes(),this._meshesDirty=!1},i.destroy=function(){for(var e,t=ie(this._meshes);!(e=t()).done;){var i=e.value;i&&i.destroy()}this._meshes.length=0},Z(t,[{key:"frameKeys",get:function(){return this._frameKeys},set:function(e){this._frameKeys=e,this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes()),this.fire("set:frameKeys",e)}},{key:"atlas",get:function(){return this._atlas},set:function(e){e!==this._atlas&&(this._atlas&&(this._atlas.off("set:frames",this._onSetFrames,this),this._atlas.off("set:frame",this._onFrameChanged,this),this._atlas.off("remove:frame",this._onFrameRemoved,this)),this._atlas=e,this._atlas&&this._frameKeys&&(this._atlas.on("set:frames",this._onSetFrames,this),this._atlas.on("set:frame",this._onFrameChanged,this),this._atlas.on("remove:frame",this._onFrameRemoved,this),this._updatingProperties?this._meshesDirty=!0:this._createMeshes()),this.fire("set:atlas",e))}},{key:"pixelsPerUnit",get:function(){return this._pixelsPerUnit},set:function(e){this._pixelsPerUnit!==e&&(this._pixelsPerUnit=e,this.fire("set:pixelsPerUnit",e),this._atlas&&this._frameKeys&&0===this.renderMode&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes()))}},{key:"renderMode",get:function(){return this._renderMode},set:function(e){if(this._renderMode!==e){var t=this._renderMode;this._renderMode=e,this.fire("set:renderMode",e),0!==t&&0!==e||this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes())}}},{key:"meshes",get:function(){return this._meshes}}]),t}(p),Yu=function(e){function t(){var t;return(t=e.call(this)||this)._texture=null,t._frames=null,t}Q(t,e);var i=t.prototype;return i.setFrame=function(e,t){var i=this._frames[e];i?(i.rect.copy(t.rect),i.pivot.copy(t.pivot),i.border.copy(t.border)):(i={rect:t.rect.clone(),pivot:t.pivot.clone(),border:t.border.clone()},this._frames[e]=i),this.fire("set:frame",e.toString(),i)},i.removeFrame=function(e){var t=this._frames[e];t&&(delete this._frames[e],this.fire("remove:frame",e.toString(),t))},i.destroy=function(){this._texture&&this._texture.destroy()},Z(t,[{key:"texture",get:function(){return this._texture},set:function(e){this._texture=e,this.fire("set:texture",e)}},{key:"frames",get:function(){return this._frames},set:function(e){this._frames=e,this.fire("set:frames",e)}}]),t}(p),Ku=function(e,t,i,n){this.time=e,this.position=t,this.rotation=i,this.scale=n},Zu=function(){this._name="",this._keys=[]},$u=function(){function e(){this.name="",this.duration=0,this._nodes=[],this._nodeDict={}}var t=e.prototype;return t.getNode=function(e){return this._nodeDict[e]},t.addNode=function(e){this._nodes.push(e),this._nodeDict[e._name]=e},Z(e,[{key:"nodes",get:function(){return this._nodes}}]),e}(),Qu=function(){function e(){this._written=!1,this._name="",this._keyFrames=[],this._quat=new Ae,this._pos=new me,this._scale=new me,this._targetNode=null}var t=e.prototype;return t.getTarget=function(){return this._targetNode},t.setTarget=function(e){this._targetNode=e},e}(),Ju=function(){function e(e){var t=this;this.looping=!0,this._animation=null,this._time=0,this._interpolatedKeys=[],this._interpolatedKeyDict={},this._currKeyIndices={},this.graph=null;!function e(i){var n=new Qu;n._name=i.name,t._interpolatedKeys.push(n),t._interpolatedKeyDict[i.name]=n,t._currKeyIndices[i.name]=0;for(var s=0;s<i._children.length;s++)e(i._children[s])}(e)}var t=e.prototype;return t.addTime=function(e){if(null!==this._animation){var t=this._animation._nodes,i=this._animation.duration;if(this._time===i&&!this.looping)return;if(this._time+=e,this._time>i){this._time=this.looping?0:i;for(var n=0;n<t.length;n++){var s=t[n]._name;this._currKeyIndices[s]=0}}else if(this._time<0){this._time=this.looping?i:0;for(var r=0;r<t.length;r++){var a=t[r],o=a._name;this._currKeyIndices[o]=a._keys.length-2}}for(var h=e>=0?1:-1,l=0;l<t.length;l++){var c=t[l],u=c._name,d=c._keys,f=this._interpolatedKeyDict[u];if(void 0!==f){var p=!1;if(1!==d.length)for(var m=this._currKeyIndices[u];m<d.length-1&&m>=0;m+=h){var _=d[m],g=d[m+1];if(_.time<=this._time&&g.time>=this._time){var v=(this._time-_.time)/(g.time-_.time);f._pos.lerp(_.position,g.position,v),f._quat.slerp(_.rotation,g.rotation,v),f._scale.lerp(_.scale,g.scale,v),f._written=!0,this._currKeyIndices[u]=m,p=!0;break}}(1===d.length||!p&&0===this._time&&this.looping)&&(f._pos.copy(d[0].position),f._quat.copy(d[0].rotation),f._scale.copy(d[0].scale),f._written=!0)}}}},t.blend=function(e,t,i){for(var n=this._interpolatedKeys.length,s=0;s<n;s++){var r=e._interpolatedKeys[s],a=t._interpolatedKeys[s],o=this._interpolatedKeys[s];r._written&&a._written?(o._quat.slerp(r._quat,t._interpolatedKeys[s]._quat,i),o._pos.lerp(r._pos,t._interpolatedKeys[s]._pos,i),o._scale.lerp(r._scale,a._scale,i),o._written=!0):r._written?(o._quat.copy(r._quat),o._pos.copy(r._pos),o._scale.copy(r._scale),o._written=!0):a._written&&(o._quat.copy(a._quat),o._pos.copy(a._pos),o._scale.copy(a._scale),o._written=!0)}},t.setGraph=function(e){if(this.graph=e,e)for(var t=0;t<this._interpolatedKeys.length;t++){var i=this._interpolatedKeys[t],n=e.findByName(i._name);this._interpolatedKeys[t].setTarget(n)}else for(var s=0;s<this._interpolatedKeys.length;s++)this._interpolatedKeys[s].setTarget(null)},t.updateGraph=function(){if(this.graph)for(var e=0;e<this._interpolatedKeys.length;e++){var t=this._interpolatedKeys[e];if(t._written){var i=t.getTarget();i.localPosition.copy(t._pos),i.localRotation.copy(t._quat),i.localScale.copy(t._scale),i._dirtyLocal||i._dirtifyLocal(),t._written=!1}}},Z(e,[{key:"animation",get:function(){return this._animation},set:function(e){this._animation=e,this.currentTime=0}},{key:"currentTime",get:function(){return this._time},set:function(e){this._time=e;for(var t=this._interpolatedKeys.length,i=0;i<t;i++){var n=this._interpolatedKeys[i]._name;this._currKeyIndices[n]=0}this.addTime(0),this.updateGraph()}},{key:"numNodes",get:function(){return this._interpolatedKeys.length}}]),e}(),ed=new ve,td=function(){function e(e){this.device=e,this.needsDepthBuffer=!1}var t=e.prototype;return t.render=function(e,t,i){},t.drawQuad=function(e,t,i){var n;if(i){var s=e?e.width:this.device.width,r=e?e.height:this.device.height;n=ed.set(i.x*s,i.y*r,i.z*s,i.w*r)}this.device.setBlendState(yi.NOBLEND),Da(this.device,e,t,n)},e}();function id(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}function nd(e,t,i){var n=2*(e+.5)/i-1,s=2*(t+.5)/i-1,r=1/i,a=(n*=1-1/i)-r,o=(s*=1-1/i)-r,h=n+r,l=s+r,c=id(a,o)-id(a,l)-id(h,o)+id(h,l);return 0===e&&0===t||e===i-1&&0===t||0===e&&t===i-1||e===i-1&&t===i-1?c/=3:0!==e&&0!==t&&e!==i-1&&t!==i-1||(c*=.5),c}td.quadVertexShader="\n attribute vec2 aPosition;\n varying vec2 vUv0;\n void main(void)\n {\n gl_Position = vec4(aPosition, 0.0, 1.0);\n vUv0 = getImageEffectUV((aPosition.xy + 1.0) * 0.5);\n }\n ";var sd,rd=function(){function e(e,t){var i=this;this.processedCache=new Map,this.definitionsCache=new Map,this._device=e,this._generators={},this._isClearingCache=!1,this._precached=!1,this._programsCollection=[],this._defaultStdMatOption=new Ll,this._defaultStdMatOptionMin=new Ll,t.shaderOptBuilder.updateRef(this._defaultStdMatOption,{},t,null,[],0,null),t.shaderOptBuilder.updateMinRef(this._defaultStdMatOptionMin,{},t,null,[],4,null),e.on("destroy:shader",(function(e){i.removeFromCache(e)}))}var t=e.prototype;return t.destroy=function(){this.clearCache()},t.register=function(e,t){this.isRegistered(e)||(this._generators[e]=t)},t.unregister=function(e){this.isRegistered(e)&&delete this._generators[e]},t.isRegistered=function(e){return void 0!==this._generators[e]},t.generateShaderDefinition=function(e,t,i,n){var s=this.definitionsCache.get(i);if(!s){var r,a,o,h;null!=(r=n.litOptions)&&r.lights&&(h=n.litOptions.lights,n.litOptions.lights=h.map((function(e){var t=e.clone?e.clone():e;return t.key=e.key,t}))),this.storeNewProgram(t,n),null!=(a=n.litOptions)&&a.lights&&(n.litOptions.lights=h),this._precached;var l=this._device;(s=e.createShaderDefinition(l,n)).name=null!=(o=s.name)?o:n.pass?t+"-pass:"+n.pass:t,this.definitionsCache.set(i,s)}return s},t.getCachedShader=function(e){return this.processedCache.get(e)},t.setCachedShader=function(e,t){this.processedCache.set(e,t)},t.getProgram=function(e,t,i){var n=this._generators[e];if(!n)return null;var s=n.generateKey(t),r=s+"#"+i.generateKey(),a=this.getCachedShader(r);if(!a){var o=this.generateShaderDefinition(n,e,s,t),h="";if(void 0!==t.pass)h="-"+Fa.get(this._device).getByIndex(t.pass).name;var l={name:""+o.name+h+"-proc",attributes:o.attributes,vshader:o.vshader,fshader:o.fshader,processingOptions:i};a=new Nn(this._device,l),this.setCachedShader(r,a)}return a},t.storeNewProgram=function(e,t){var i={};if("standard"===e){var n=this._getDefaultStdMatOptions(t.pass);for(var s in t)(t.hasOwnProperty(s)&&n[s]!==t[s]||"pass"===s)&&(i[s]=t[s]);for(var r in t.litOptions)i[r]=t.litOptions[r]}else i=t;this._programsCollection.push(JSON.stringify({name:e,options:i}))},t.dumpPrograms=function(){var e="let device = pc.app ? pc.app.graphicsDevice : pc.Application.getApplication().graphicsDevice;\n";e+="let shaders = [",this._programsCollection[0]&&(e+="\n\t"+this._programsCollection[0]);for(var t=1;t<this._programsCollection.length;++t)e+=",\n\t"+this._programsCollection[t];e+="\n];\n",e+="device.getProgramLibrary().precompile(shaders);\n",e+='if (pc.version != "'+l+'" || pc.revision != "'+c+'")\n',e+='\tconsole.warn("precompile-shaders.js: engine version mismatch, rebuild shaders lib with current engine");';var i=document.createElement("a");i.setAttribute("href","data:text/plain;charset=utf-8,"+encodeURIComponent(e)),i.setAttribute("download","precompile-shaders.js"),i.style.display="none",document.body.appendChild(i),i.click(),document.body.removeChild(i)},t.clearCache=function(){this._isClearingCache=!0,this.processedCache.forEach((function(e){e.destroy()})),this.processedCache.clear(),this._isClearingCache=!1},t.removeFromCache=function(e){var t=this;this._isClearingCache||this.processedCache.forEach((function(i,n){e===i&&t.processedCache.delete(n)}))},t._getDefaultStdMatOptions=function(e){var t=Fa.get(this._device).getByIndex(e);return 2===e||3===e||t.isShadow?this._defaultStdMatOptionMin:this._defaultStdMatOption},t.precompile=function(e){if(e)for(var t=new Array(e.length),i=0;i<e.length;i++){if("standard"===e[i].name){var n=e[i].options,s=this._getDefaultStdMatOptions(n.pass);for(var r in s)s.hasOwnProperty(r)&&void 0===n[r]&&(n[r]=s[r])}t[i]=this.getProgram(e[i].name,e[i].options)}this._precached=!0},e}(),ad={bakeDirLmEndPS:"\n vec4 dirLm = texture2D(texture_dirLightMap, vUv1);\n\n if (bakeDir > 0.5) {\n if (dAtten > 0.00001) {\n dirLm.xyz = dirLm.xyz * 2.0 - vec3(1.0);\n dAtten = saturate(dAtten);\n gl_FragColor.rgb = normalize(dLightDirNormW.xyz*dAtten + dirLm.xyz*dirLm.w) * 0.5 + vec3(0.5);\n gl_FragColor.a = dirLm.w + dAtten;\n gl_FragColor.a = max(gl_FragColor.a, 1.0 / 255.0);\n } else {\n gl_FragColor = dirLm;\n }\n } else {\n gl_FragColor.rgb = dirLm.xyz;\n gl_FragColor.a = max(dirLm.w, dAtten > 0.00001? (1.0/255.0) : 0.0);\n }\n",bakeLmEndPS:"\n#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",dilatePS:"\n\nvarying vec2 vUv0;\n\nuniform sampler2D source;\nuniform vec2 pixelOffset;\n\nvoid main(void) {\n vec4 c = texture2D(source, vUv0);\n c = c.a>0.0? c : texture2D(source, vUv0 - pixelOffset);\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(0, -pixelOffset.y));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(pixelOffset.x, -pixelOffset.y));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(-pixelOffset.x, 0));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(pixelOffset.x, 0));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(-pixelOffset.x, pixelOffset.y));\n c = c.a>0.0? c : texture2D(source, vUv0 + vec2(0, pixelOffset.y));\n c = c.a>0.0? c : texture2D(source, vUv0 + pixelOffset);\n gl_FragColor = c;\n}\n",bilateralDeNoisePS:"\n// bilateral filter, based on https://www.shadertoy.com/view/4dfGDH# and\n// http://people.csail.mit.edu/sparis/bf_course/course_notes.pdf\n\n// A bilateral filter is a non-linear, edge-preserving, and noise-reducing smoothing filter for images.\n// It replaces the intensity of each pixel with a weighted average of intensity values from nearby pixels.\n// This weight can be based on a Gaussian distribution. Crucially, the weights depend not only on\n// Euclidean distance of pixels, but also on the radiometric differences (e.g., range differences, such\n// as color intensity, depth distance, etc.). This preserves sharp edges.\n\nfloat normpdf3(in vec3 v, in float sigma) {\n return 0.39894 * exp(-0.5 * dot(v, v) / (sigma * sigma)) / sigma;\n}\n\nvec3 decodeRGBM(vec4 rgbm) {\n vec3 color = (8.0 * rgbm.a) * rgbm.rgb;\n return color * color;\n}\n\nfloat saturate(float x) {\n return clamp(x, 0.0, 1.0);\n}\n\nvec4 encodeRGBM(vec3 color) { // modified RGBM\n vec4 encoded;\n encoded.rgb = pow(color.rgb, vec3(0.5));\n encoded.rgb *= 1.0 / 8.0;\n\n encoded.a = saturate( max( max( encoded.r, encoded.g ), max( encoded.b, 1.0 / 255.0 ) ) );\n encoded.a = ceil(encoded.a * 255.0) / 255.0;\n\n encoded.rgb /= encoded.a;\n return encoded;\n}\n\n// filter size\n#define MSIZE 15\n\nvarying vec2 vUv0;\nuniform sampler2D source;\nuniform vec2 pixelOffset;\nuniform vec2 sigmas;\nuniform float bZnorm;\nuniform float kernel[MSIZE];\n\nvoid main(void) {\n \n vec4 pixelRgbm = texture2D(source, vUv0);\n\n // lightmap specific optimization - skip pixels that were not baked\n // this also allows dilate filter that work on the output of this to work correctly, as it depends on .a being zero\n // to dilate, which the following blur filter would otherwise modify\n if (pixelRgbm.a <= 0.0) {\n gl_FragColor = pixelRgbm;\n return ;\n }\n\n // range sigma - controls blurriness based on a pixel distance\n float sigma = sigmas.x;\n\n // domain sigma - controls blurriness based on a pixel similarity (to preserve edges)\n float bSigma = sigmas.y;\n\n vec3 pixelHdr = decodeRGBM(pixelRgbm);\n vec3 accumulatedHdr = vec3(0.0);\n float accumulatedFactor = 0.0;\n\n // read out the texels\n const int kSize = (MSIZE-1)/2;\n for (int i = -kSize; i <= kSize; ++i) {\n for (int j = -kSize; j <= kSize; ++j) {\n \n // sample the pixel with offset\n vec2 coord = vUv0 + vec2(float(i), float(j)) * pixelOffset;\n vec4 rgbm = texture2D(source, coord);\n\n // lightmap - only use baked pixels\n if (rgbm.a > 0.0) {\n vec3 hdr = decodeRGBM(rgbm);\n\n // bilateral factors\n float factor = kernel[kSize + j] * kernel[kSize + i];\n factor *= normpdf3(hdr - pixelHdr, bSigma) * bZnorm;\n\n // accumulate\n accumulatedHdr += factor * hdr;\n accumulatedFactor += factor;\n }\n }\n }\n\n gl_FragColor = encodeRGBM(accumulatedHdr / accumulatedFactor);\n}\n"},od="FILL_WINDOW",hd="KEEP_ASPECT",ld="AUTO",cd="FIXED";function ud(){return sd}function dd(e){sd=e,Kr.set(null==e?void 0:e.graphicsDevice)}var fd=function(){function e(){}return e.push=function(t,i){i&&e._types.length>0?console.assert("Script Ordering Error. Contact support@playcanvas.com"):e._types.push(t)},e}();fd._types=[];var pd=!1,md=!1,_d={app:null,create:function(e,t){if(pd){var i=t(_d.app);i._pcScriptName=e,fd.push(i,pd),this.fire("created",e,t)}},attribute:function(e,t,i,n){},createLoadingScreen:function(e){md||(md=!0,e(ud()))}};Object.defineProperty(_d,"legacy",{get:function(){return pd},set:function(e){pd=e}}),m.attach(_d);var gd=function(){function e(){this.renderPasses=[],this.renderTargetMap=new Map}var t=e.prototype;return t.addRenderPass=function(e){this.renderPasses.push(e)},t.reset=function(){this.renderPasses.length=0},t.compile=function(){for(var e=this.renderTargetMap,t=this.renderPasses,i=0;i<t.length;i++){var n=t[i],s=n.renderTarget;if(void 0!==s){var r=e.get(s);if(r){for(var a=n.colorArrayOps.length,o=0;o<a;o++){n.colorArrayOps[o].clear||(r.colorArrayOps[o].store=!0)}n.depthStencilOps.clearDepth||(r.depthStencilOps.storeDepth=!0),n.depthStencilOps.clearStencil||(r.depthStencilOps.storeStencil=!0)}e.set(s,n)}}for(var h=null,l=null,c=0;c<t.length;c++){var u=t[c],d=u.renderTarget,f=null==d?void 0:d.colorBuffer;if(null!=f&&f.cubemap){if(h===f)for(var p=l.colorArrayOps.length,m=0;m<p;m++)l.colorArrayOps[m].mipmaps=!1;h=d.colorBuffer,l=u}else u.requiresCubemaps&&(h=null,l=null)}e.forEach((function(e,t){null===t&&(e.colorOps.store=!0,e.colorOps.resolve=!1,e.colorOps.mipmaps=!1)})),e.clear()},t.render=function(e){this.compile();for(var t=this.renderPasses,i=0;i<t.length;i++)t[i].render()},e}(),vd=function(){function e(e,t){this.texture0=e,this.texture1=t}return e.prototype.destroy=function(){var e,t;null==(e=this.texture0)||e.destroy(),null==(t=this.texture1)||t.destroy()},e}(),yd=new Jn,xd=function(){function e(){}return e.createTexture=function(e,t,i,n){return void 0===n&&(n=""),new Yn(e,{name:"AreaLightLUT"+n,width:i,height:i,format:t,addressU:1,addressV:1,type:Vt,magFilter:1,minFilter:0,anisotropy:1,mipmaps:!1})},e.applyTextures=function(e,t,i){yd.remove(e),yd.get(e,(function(){return new vd(t,t===i?null:i)})),e.scope.resolve("areaLightsLutTex1").setValue(t),e.scope.resolve("areaLightsLutTex2").setValue(i)},e.createPlaceholder=function(t){var i=e.createTexture(t,t.areaLightLutFormat,2,"placeholder");i.lock().fill(0),i.unlock(),e.applyTextures(t,i,i)},e.set=function(t,i,n){function s(t,i,n){var s=e.createTexture(t,n,64);return s.lock().set(i),s.unlock(),s}function r(e,t,i){for(var n=e.length,s=new Float32Array(n),r=0;r<n;r++){var a=r%4;s[r]=(e[r]+t[a])*i[a]}return s}function a(e){for(var t=e.length,i=new Uint16Array(t),n=Xo.float2Half,s=0;s<t;s++)i[s]=n(e[s]);return i}function o(e){for(var t=e.length,i=new Uint8ClampedArray(t),n=0;n<t;n++)i[n]=255*e[n];return i}var h,l,c=i,u=n,d=t.areaLightLutFormat;if(d===Ze)h=c,l=u;else if(d===Ye)h=a(c),l=a(u);else{h=o(r(c,[0,.2976,.01381,0],[.999,3.08737,1.6546,.603249])),l=o(r(u,[-.306897,0,0,0],[1.442787,1,1,1]))}var f=s(t,h,d),p=s(t,l,d);e.applyTextures(t,f,p)},e}(),Sd="en-US",bd={en:"en-US",es:"en-ES",zh:"zh-CN","zh-HK":"zh-TW","zh-TW":"zh-HK","zh-MO":"zh-HK",fr:"fr-FR",de:"de-DE",it:"it-IT",ru:"ru-RU",ja:"ja-JP"},wd={};function Td(e,t){for(var i=0,n=e.length;i<n;i++)wd[e[i]]=t}function Ad(e){var t=e.indexOf("-");return-1!==t?e.substring(0,t):e}function Cd(e,t){if(t[e])return e;var i=bd[e];if(i&&t[i])return i;var n=Ad(e);return t[i=bd[n]]?i:t[n]?n:Sd}Td(["ja","ko","th","vi","zh","id"],(function(e){return 0})),Td(["fa","hi"],(function(e){return e>=0&&e<=1?0:1})),Td(["fr","pt"],(function(e){return e>=0&&e<2?0:1})),Td(["da"],(function(e){return 1===e||!Number.isInteger(e)&&e>=0&&e<=1?0:1})),Td(["de","en","it","el","es","tr","fi","sv","nb","no","ur"],(function(e){return 1===e?0:1})),Td(["ru","uk"],(function(e){if(Number.isInteger(e)){var t=e%10,i=e%100;if(1===t&&11!==i)return 0;if(t>=2&&t<=4&&(i<12||i>14))return 1;if(0===t||t>=5&&t<=9||i>=11&&i<=14)return 2}return 3})),Td(["pl"],(function(e){if(Number.isInteger(e)){if(1===e)return 0;var t=e%10,i=e%100;if(t>=2&&t<=4&&(i<12||i>14))return 1;if(t>=0&&t<=1||t>=5&&t<=9||i>=12&&i<=14)return 2}return 3})),Td(["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 Ed=wd[Ad(Sd)];function Md(e){return wd[e]||Ed}var Pd,Rd=new RegExp("^\\s*(?:(?:[a-z]+[a-z0-9\\-\\+\\.]*:)?//|data:|blob:)","i"),Id=function(){function e(e,t,i,n,s,r){void 0===e&&(e=""),void 0===t&&(t=""),void 0===i&&(i=null),void 0===n&&(n=null),void 0===s&&(s=null),void 0===r&&(r=null),this.url=e,this.filename=t,this.hash=i,this.size=n,this.opt=s,this.contents=r}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}(),Ld=-1,Dd={pvr:"extCompressedTexturePVRTC",dxt:"extCompressedTextureS3TC",etc2:"extCompressedTextureETC",etc1:"extCompressedTextureETC1",basis:"canvas"},Od=["pvr","dxt","etc2","etc1","basis"],kd=function(e){function t(t,i,n,s,r){var a;return(a=e.call(this)||this)._id=Ld--,a.name=t||"",a.type=i,a.tags=new ae(ee(a)),a._preload=!1,a._file=null,a._data=s||{},a.options=r||{},a._resources=[],a._i18n={},a.loaded=!1,a.loading=!1,a.registry=null,n&&(a.file=n),a}Q(t,e);var i=t.prototype;return i.getFileUrl=function(){var e=this.file;if(!e||!e.url)return null;var t=e.url;if(this.registry&&this.registry.prefix&&!Rd.test(t)&&(t=this.registry.prefix+t),"script"!==this.type&&e.hash){var i=-1!==t.indexOf("?")?"&":"?";t+=i+"t="+e.hash}return t},i.getAbsoluteUrl=function(e){if(e.startsWith("blob:")||e.startsWith("data:"))return e;var t=v.getDirectory(this.file.url);return v.join(t,e)},i.getLocalizedAssetId=function(e){return e=Cd(e,this._i18n),this._i18n[e]||null},i.addLocalizedAssetId=function(e,t){this._i18n[e]=t,this.fire("add:localized",e,t)},i.removeLocalizedAssetId=function(e){var t=this._i18n[e];t&&(delete this._i18n[e],this.fire("remove:localized",e,t))},i.ready=function(e,t){t=t||this,this.loaded?e.call(t,this):this.once("load",(function(i){e.call(t,i)}))},i.reload=function(){this.loaded&&(this.loaded=!1,this.registry.load(this))},i.unload=function(){if(this.loaded||0!==this._resources.length){this.fire("unload",this),this.registry.fire("unload:"+this.id,this);var e=this._resources;this.resources=[],this.loaded=!1,this.file&&this.registry._loader.clearCache(this.getFileUrl(),this.type);for(var t=0;t<e.length;++t){var i=e[t];i&&i.destroy&&i.destroy()}}},t.fetchArrayBuffer=function(e,t,i,n){var s;void 0===n&&(n=0),null!=i&&null!=(s=i.file)&&s.contents?setTimeout((function(){t(null,i.file.contents)})):Tr.get(e,{cache:!0,responseType:"arraybuffer",retry:n>0,maxRetries:n},t)},Z(t,[{key:"id",get:function(){return this._id},set:function(e){this._id=e}},{key:"file",get:function(){return this._file},set:function(e){var t=this;if(e&&e.variants&&-1!==["texture","textureatlas","bundle"].indexOf(this.type)){var i,n,s=(null==(i=this.registry)||null==(n=i._loader)?void 0:n._app)||ud(),r=null==s?void 0:s.graphicsDevice;if(r)for(var a=function(){var i=Od[o];if(e.variants[i]&&r[Dd[i]])return e=e.variants[i],"break";if(s.enableBundles){var n=s.bundles.listBundlesForAsset(t);if(n&&n.find((function(e){var t;return null==e||null==(t=e.file)?void 0:t.variants[i]})))return"break"}},o=0,h=Od.length;o<h;o++){if("break"===a())break}}var l=this._file,c=e?new Id(e.url,e.filename,e.hash,e.size,e.opt,e.contents):null;(!!c!=!!l||c&&!c.equals(l))&&(this._file=c,this.fire("change",this,"file",c,l),this.reload())}},{key:"data",get:function(){return this._data},set:function(e){var t=this._data;this._data=e,e!==t&&(this.fire("change",this,"data",e,t),this.loaded&&this.registry._loader.patch(this,this.registry))}},{key:"resource",get:function(){return this._resources[0]},set:function(e){var t=this._resources[0];this._resources[0]=e,this.fire("change",this,"resource",e,t)}},{key:"resources",get:function(){return this._resources},set:function(e){var t=this._resources;this._resources=e,this.fire("change",this,"resources",e,t)}},{key:"preload",get:function(){return this._preload},set:function(e){e=!!e,this._preload!==e&&(this._preload=e,this._preload&&!this.loaded&&!this.loading&&this.registry&&this.registry.load(this))}},{key:"loadFaces",get:function(){return this._loadFaces},set:function(e){e=!!e,this.hasOwnProperty("_loadFaces")&&e===this._loadFaces||(this._loadFaces=e,this.loaded&&this.registry._loader.patch(this,this.registry))}}]),t}(p),Fd=function(){function e(e){void 0===e&&(e=null),this._index={},this._key=void 0,this._key=e}var t=e.prototype;return t.addItem=function(e){for(var t,i=ie(e.tags._list);!(t=i()).done;){var n=t.value;this.add(n,e)}},t.removeItem=function(e){for(var t,i=ie(e.tags._list);!(t=i()).done;){var n=t.value;this.remove(n,e)}},t.add=function(e,t){this._index[e]&&-1!==this._index[e].list.indexOf(t)||(this._index[e]||(this._index[e]={list:[]},this._key&&(this._index[e].keys={})),this._index[e].list.push(t),this._key&&(this._index[e].keys[t[this._key]]=t))},t.remove=function(e,t){if(this._index[e]&&(!this._key||this._index[e].keys[t[this._key]])){var i=this._index[e].list.indexOf(t);-1!==i&&(this._index[e].list.splice(i,1),this._key&&delete this._index[e].keys[t[this._key]],0===this._index[e].list.length&&delete this._index[e])}},t.find=function(e){for(var t,i,n,s,r,a=this,o={},h=[],l=function(e,t){return a._index[e].list.length-a._index[t].list.length},c=0;c<e.length;c++){if((i=e[c])instanceof Array){if(0===i.length)continue;if(1!==i.length){r=!1;for(var u=0;u<i.length;u++)if(!this._index[i[u]]){r=!0;break}if(r)continue;1===(s=(n=i.slice(0).sort(l)).slice(1)).length&&(s=s[0]);for(var d=0;d<this._index[n[0]].list.length;d++)t=this._index[n[0]].list[d],(this._key?!o[t[this._key]]:-1===h.indexOf(t))&&t.tags.has(s)&&(this._key&&(o[t[this._key]]=!0),h.push(t));continue}i=i[0]}if(i&&"string"==typeof i&&this._index[i])for(var f=0;f<this._index[i].list.length;f++)t=this._index[i].list[f],this._key?o[t[this._key]]||(o[t[this._key]]=!0,h.push(t)):-1===h.indexOf(t)&&h.push(t)}return h},e}(),Bd=function(e){function t(t){var i;return(i=e.call(this)||this)._assets=new Set,i._idToAsset=new Map,i._urlToAsset=new Map,i._tags=new Fd("_id"),i.prefix=null,i._loader=t,i}Q(t,e);var i=t.prototype;return i.list=function(e){void 0===e&&(e={});var t=Array.from(this._assets);return void 0!==e.preload?t.filter((function(t){return t.preload===e.preload})):t},i.add=function(e){var t,i;this._assets.has(e)||(this._assets.add(e),this._idToAsset.set(e.id,e),null!=(t=e.file)&&t.url&&this._urlToAsset.set(e.file.url,e),e.registry=this,this._tags.addItem(e),e.tags.on("add",this._onTagAdd,this),e.tags.on("remove",this._onTagRemove,this),this.fire("add",e),this.fire("add:"+e.id,e),null!=(i=e.file)&&i.url&&this.fire("add:url:"+e.file.url,e),e.preload&&this.load(e))},i.remove=function(e){var t,i;return!!this._assets.has(e)&&(this._assets.delete(e),this._idToAsset.delete(e.id),null!=(t=e.file)&&t.url&&this._urlToAsset.delete(e.file.url),this._tags.removeItem(e),e.tags.off("add",this._onTagAdd,this),e.tags.off("remove",this._onTagRemove,this),e.fire("remove",e),this.fire("remove",e),this.fire("remove:"+e.id,e),null!=(i=e.file)&&i.url&&this.fire("remove:url:"+e.file.url,e),!0)},i.get=function(e){return this._idToAsset.get(Number(e))},i.getByUrl=function(e){return this._urlToAsset.get(e)},i.load=function(e){var t=this;if(!e.loading&&!e.loaded){var i=e.file,n=function(n){n instanceof Array?e.resources=n:e.resource=n,t._loader.patch(e,t),t.fire("load",e),t.fire("load:"+e.id,e),i&&i.url&&t.fire("load:url:"+i.url,e),e.fire("load",e)};if(i||"cubemap"===e.type)this.fire("load:start",e),this.fire("load:"+e.id+":start",e),e.loading=!0,this._loader.load(e.getFileUrl(),e.type,(function(i,s,r){if(e.loaded=!0,e.loading=!1,i)t.fire("error",i,e),t.fire("error:"+e.id,i,e),e.fire("error",i,e);else{if(!_d.legacy&&"script"===e.type){var a=t._loader.getHandler("script");a._cache[e.id]&&a._cache[e.id].parentNode===document.head&&document.head.removeChild(a._cache[e.id]),a._cache[e.id]=r}n(s)}}),e);else{var s=this._loader.open(e.type,e.data);e.loaded=!0,n(s)}}},i.loadFromUrl=function(e,t,i){this.loadFromUrlAndFilename(e,null,t,i)},i.loadFromUrlAndFilename=function(e,t,i,n){var s=this,r=v.getBasename(t||e),a={filename:t||r,url:e},o=this.getByUrl(e);if(o){if(o.loaded)return void n(o.loadFromUrlError||null,o)}else o=new kd(r,i,a),this.add(o);var h=function(e){e.once("load",(function(e){"material"===i?s._loadTextures(e,(function(t,i){n(t,e)})):n(null,e)})),e.once("error",(function(t){t&&(s.loadFromUrlError=t),n(t,e)})),s.load(e)};o.resource?n(null,o):"model"===i?this._loadModel(o,h):h(o)},i._loadModel=function(e,t){var i=this,n=e.getFileUrl(),s=v.getExtension(n);if(".json"===s||".glb"===s){var r=v.getDirectory(n),a=v.getBasename(n),o=v.join(r,a.replace(s,".mapping.json"));this._loader.load(o,"json",(function(n,s){n?(e.data={mapping:[]},t(e)):i._loadMaterials(e,s,(function(i,n){e.data=s,t(e)}))}))}else t(e)},i._loadMaterials=function(e,t,i){for(var n=this,s=[],r=0,a=function(e,t){n._loadTextures(t,(function(e,n){s.push(t),s.length===r&&i(null,s)}))},o=0;o<t.mapping.length;o++){var h=t.mapping[o].path;if(h){r++;var l=e.getAbsoluteUrl(h);this.loadFromUrl(l,"material",a)}}0===r&&i(null,s)},i._loadTextures=function(e,t){var i=[],n=0,s=e.data;if("path"===s.mappingFormat){for(var r=function(e,s){e&&console.error(e),i.push(s),i.length===n&&t(null,i)},a=zl,o=0;o<a.length;o++){var h=s[a[o]];if(h&&"string"==typeof h){n++;var l=e.getAbsoluteUrl(h);this.loadFromUrl(l,"texture",r)}}0===n&&t(null,i)}else t(null,i)},i._onTagAdd=function(e,t){this._tags.add(e,t)},i._onTagRemove=function(e,t){this._tags.remove(e,t)},i.findByTag=function(){return this._tags.find(arguments)},i.filter=function(e){return Array.from(this._assets).filter((function(t){return e(t)}))},i.find=function(e,t){var i;return null!=(i=Array.from(this._assets).find((function(i){return i.name===e&&(!t||i.type===t)})))?i:null},i.findAll=function(e,t){return Array.from(this._assets).filter((function(i){return i.name===e&&(!t||i.type===t)}))},t}(p),Nd=function(){function e(e){this._assets=e,this._bundleAssets={},this._assetsInBundles={},this._urlsInBundles={},this._fileRequests={},this._assets.on("add",this._onAssetAdded,this),this._assets.on("remove",this._onAssetRemoved,this)}var t=e.prototype;return t._onAssetAdded=function(e){if("bundle"===e.type){this._bundleAssets[e.id]=e,this._registerBundleEventListeners(e.id);for(var t=0,i=e.data.assets.length;t<i;t++)this._indexAssetInBundle(e.data.assets[t],e)}else this._assetsInBundles[e.id]&&this._indexAssetFileUrls(e)},t._registerBundleEventListeners=function(e){this._assets.on("load:"+e,this._onBundleLoaded,this),this._assets.on("error:"+e,this._onBundleError,this)},t._unregisterBundleEventListeners=function(e){this._assets.off("load:"+e,this._onBundleLoaded,this),this._assets.off("error:"+e,this._onBundleError,this)},t._indexAssetInBundle=function(e,t){if(this._assetsInBundles[e]){var i=this._assetsInBundles[e];-1===i.indexOf(t)&&i.push(t)}else this._assetsInBundles[e]=[t];var n=this._assets.get(e);n&&this._indexAssetFileUrls(n)},t._indexAssetFileUrls=function(e){var t=this._getAssetFileUrls(e);if(t)for(var i=0,n=t.length;i<n;i++){var s=t[i];this._urlsInBundles[s]=this._assetsInBundles[e.id]}},t._getAssetFileUrls=function(e){var t=e.getFileUrl();if(!t)return null;var i=[t=this._normalizeUrl(t)];if("font"===e.type)for(var n=e.data.info.maps.length,s=1;s<n;s++)i.push(t.replace(".png",s+".png"));return i},t._normalizeUrl=function(e){return e&&e.split("?")[0]},t._onAssetRemoved=function(e){if("bundle"===e.type){for(var t in delete this._bundleAssets[e.id],this._unregisterBundleEventListeners(e.id),this._assetsInBundles){var i=this._assetsInBundles[t],n=i.indexOf(e);if(-1!==n&&(i.splice(n,1),!i.length))for(var s in delete this._assetsInBundles[t],this._urlsInBundles)this._urlsInBundles[s]===i&&delete this._urlsInBundles[s]}this._onBundleError("Bundle "+e.id+" was removed",e)}else if(this._assetsInBundles[e.id]){delete this._assetsInBundles[e.id];for(var r=this._getAssetFileUrls(e),a=0,o=r.length;a<o;a++)delete this._urlsInBundles[r[a]]}},t._onBundleLoaded=function(e){var t=this;e.resource?requestAnimationFrame((function(){if(t._fileRequests)for(var i in t._fileRequests){var n=t._urlsInBundles[i];if(n&&-1!==n.indexOf(e)){var s=decodeURIComponent(i),r=null;e.resource.hasBlobUrl(s)||(r="Bundle "+e.id+" does not contain URL "+i);for(var a=t._fileRequests[i],o=0,h=a.length;o<h;o++)r?a[o](r):a[o](null,e.resource.getBlobUrl(s));delete t._fileRequests[i]}}})):this._onBundleError("Bundle "+e.id+" failed to load",e)},t._onBundleError=function(e,t){for(var i in this._fileRequests){if(!this._findLoadedOrLoadingBundleForUrl(i)){for(var n=this._fileRequests[i],s=0,r=n.length;s<r;s++)n[s](e);delete this._fileRequests[i]}}},t._findLoadedOrLoadingBundleForUrl=function(e){var t=this._urlsInBundles[e];if(!t)return null;for(var i=t.length,n=0;n<i;n++)if(t[n].loaded&&t[n].resource)return t[n];for(var s=0;s<i;s++)if(t[s].loading)return t[s];return null},t.listBundlesForAsset=function(e){return this._assetsInBundles[e.id]||null},t.list=function(){var e=[];for(var t in this._bundleAssets)e.push(this._bundleAssets[t]);return e},t.hasUrl=function(e){return!!this._urlsInBundles[e]},t.canLoadUrl=function(e){return!!this._findLoadedOrLoadingBundleForUrl(e)},t.loadUrl=function(e,t){var i=this._findLoadedOrLoadingBundleForUrl(e);if(i)if(i.loaded){var n=decodeURIComponent(e);if(!i.resource.hasBlobUrl(n))return void t("Bundle "+i.id+" does not contain URL "+e);t(null,i.resource.getBlobUrl(n))}else this._fileRequests.hasOwnProperty(e)?this._fileRequests[e].push(t):this._fileRequests[e]=[t];else t("URL "+e+" not found in any bundles")},t.destroy=function(){for(var e in this._assets.off("add",this._onAssetAdded,this),this._assets.off("remove",this._onAssetRemoved,this),this._bundleAssets)this._unregisterBundleEventListeners(e);this._assets=null,this._bundleAssets=null,this._assetsInBundles=null,this._urlsInBundles=null,this._fileRequests=null},e}(),Ud=function(e){function t(){var t;return(t=e.call(this)||this).anim=void 0,t.animation=void 0,t.audiolistener=void 0,t.audiosource=void 0,t.button=void 0,t.camera=void 0,t.collision=void 0,t.element=void 0,t.joint=void 0,t.layoutchild=void 0,t.layoutgroup=void 0,t.light=void 0,t.model=void 0,t.particlesystem=void 0,t.render=void 0,t.rigidbody=void 0,t.screen=void 0,t.script=void 0,t.scrollbar=void 0,t.scrollview=void 0,t.sound=void 0,t.sprite=void 0,t.zone=void 0,t.list=[],t}Q(t,e);var i=t.prototype;return i.add=function(e){var t=e.id;if(this[t])throw new Error("ComponentSystem name '"+t+"' already registered or not allowed");this[t]=e,this.list.push(e)},i.remove=function(e){var t=e.id;if(!this[t])throw new Error("No ComponentSystem named '"+t+"' registered");delete this[t];var i=this.list.indexOf(this[t]);-1!==i&&this.list.splice(i,1)},i.destroy=function(){this.off();for(var e=0;e<this.list.length;e++)this.list[e].destroy()},t}(p),zd=function(){function e(e){this._blobUrls={};for(var t=0,i=e.length;t<i;t++)e[t].url&&(this._blobUrls[e[t].name]=e[t].url)}var t=e.prototype;return t.hasBlobUrl=function(e){return!!this._blobUrls[e]},t.getBlobUrl=function(e){return this._blobUrls[e]},t.destroy=function(){for(var e in this._blobUrls)URL.revokeObjectURL(this._blobUrls[e]);this._blobUrls=null},e}();function Vd(e){var t,i;if("undefined"!=typeof TextDecoder)try{t=new TextDecoder("utf-8"),i=new TextDecoder("windows-1252")}catch(e){console.warn("TextDecoder not supported - pc.Untar module will not work")}else console.warn("TextDecoder not supported - pc.Untar module will not work");function n(e){this._fields=e}function s(e){this._arrayBuffer=e||new ArrayBuffer(0),this._bufferView=new DataView(this._arrayBuffer),this._globalPaxHeader=null,this._paxHeader=null,this._bytesRead=0}n.parse=function(e,i,s){for(var r=new Uint8Array(e,i,s),a=0,o=[];a<s;){var h=void 0;for(h=a;h<s&&32!==r[h];h++);if(h>=s)throw new Error("Invalid PAX header data format.");var l=parseInt(t.decode(new Uint8Array(e,i+a,h-a)),10),c=t.decode(new Uint8Array(e,i+h+1,l-(h-a)-2)).split("=");if(2!==c.length)throw new Error("Invalid PAX header data format.");0===c[1].length&&(c[1]=null),o.push({name:c[0],value:c[1]}),a+=l}return new n(o)},n.prototype.applyHeader=function(e){for(var t=0;t<this._fields.length;t++){var i=this._fields[t].name,n=this._fields[t].value;"path"===i&&(i="name"),null===n?delete e[i]:e[i]=n}},e||(Pd=s),s.prototype._hasNext=function(){return this._bytesRead+4<this._arrayBuffer.byteLength&&0!==this._bufferView.getUint32(this._bytesRead)},s.prototype._readNextFile=function(){var t=new DataView(this._arrayBuffer,this._bytesRead,512),s=i.decode(t);this._bytesRead+=512;var r=s.substring(0,100).replace(/\0/g,""),a=s.substring(257,263),o=parseInt(s.substring(124,136),8),h=s.substring(156,157),l=this._bytesRead,c=null,u=!1;switch(h){case"0":case"":if(u=!0,!e){var d=new Blob([this._arrayBuffer.slice(this._bytesRead,this._bytesRead+o)]);c=URL.createObjectURL(d)}break;case"g":this._globalPaxHeader=n.parse(this._arrayBuffer,this._bytesRead,o);break;case"x":this._paxHeader=n.parse(this._arrayBuffer,this._bytesRead,o)}this._bytesRead+=o;var f=o%512;if(0!==f&&(this._bytesRead+=512-f),!u)return null;if(-1!==a.indexOf("ustar")){var p=s.substring(345,500).replace(/\0/g,"");p.length>0&&(r=p.trim()+r.trim())}var m={name:r,start:l,size:o,url:c};return this._globalPaxHeader&&this._globalPaxHeader.applyHeader(m),this._paxHeader&&(this._paxHeader.applyHeader(m),this._paxHeader=null),m},s.prototype.untar=function(e){if(!t)return console.error("Cannot untar because TextDecoder interface is not available for this platform."),[];for(var i=[];this._hasNext();){var n=this._readNextFile();n&&(e&&n.name&&(n.name=e+n.name),i.push(n))}return i},e&&(self.onmessage=function(e){var t=e.data.id;try{var i=new s(e.data.arrayBuffer).untar(e.data.prefix);postMessage({id:t,files:i,arrayBuffer:e.data.arrayBuffer},[e.data.arrayBuffer])}catch(e){postMessage({id:t,error:e.toString()})}})}var Gd=null;var Hd=function(){function e(e){this._requestId=0,this._pendingRequests={},this._filenamePrefix=e,this._worker=new Worker(function(){if(!Gd){var e="("+Vd.toString()+")(true)\n\n",t=new Blob([e],{type:"application/javascript"});Gd=URL.createObjectURL(t)}return Gd}()),this._worker.addEventListener("message",this._onMessage.bind(this))}var t=e.prototype;return t._onMessage=function(e){var t=e.data.id;if(this._pendingRequests[t]){var i=this._pendingRequests[t];if(delete this._pendingRequests[t],e.data.error)i(e.data.error);else{for(var n=e.data.arrayBuffer,s=0,r=e.data.files.length;s<r;s++){var a=e.data.files[s],o=new Blob([n.slice(a.start,a.start+a.size)]);a.url=URL.createObjectURL(o)}i(null,e.data.files)}}},t.untar=function(e,t){var i=this._requestId++;this._pendingRequests[i]=t,this._worker.postMessage({id:i,prefix:this._filenamePrefix,arrayBuffer:e},[e])},t.hasPendingRequests=function(){return Object.keys(this._pendingRequests).length>0},t.destroy=function(){this._worker&&(this._worker.terminate(),this._worker=null,this._pendingRequests=null)},e}();Vd();var Wd=function(){function e(e){this.handlerType="bundle",this._assets=e.assets,this._worker=null,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i=this;Tr.get(e.load,{responseType:wr.ResponseType.ARRAY_BUFFER,retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(n,s){if(n)t("Error loading bundle resource "+e.original+": "+n);else try{i._untar(s,t)}catch(i){t("Error loading bundle resource "+e.original+": "+i)}}))},t._untar=function(e,t){var i=this;if(M.workers)i._worker||(i._worker=new Hd(i._assets.prefix)),i._worker.untar(e,(function(e,n){t(e,n),i._worker.hasPendingRequests()||(i._worker.destroy(),i._worker=null)}));else{var n=new Pd(e).untar(i._assets.prefix);t(null,n)}},t.open=function(e,t){return new zd(t)},t.patch=function(e,t){},e}(),Xd=function(){function e(e){this._handlers={},this._requests={},this._cache={},this._app=e}var t=e.prototype;return t.addHandler=function(e,t){this._handlers[e]=t,t._loader=this},t.removeHandler=function(e){delete this._handlers[e]},t.getHandler=function(e){return this._handlers[e]},e.makeKey=function(e,t){return e+"-"+t},t.load=function(t,i,n,s){var r=this._handlers[i];if(r)if(t){var a=e.makeKey(t,i);if(void 0!==this._cache[a])n(null,this._cache[a]);else if(this._requests[a])this._requests[a].push(n);else{this._requests[a]=[n];var o=this,h=function(e,t){e?o._onFailure(a,e):r.load(t,(function(e,i,n){if(o._requests[a])if(e)o._onFailure(a,e);else try{o._onSuccess(a,r.open(t.original,i,s),n)}catch(e){o._onFailure(a,e)}}),s)},l=t.split("?")[0];if(this._app.enableBundles&&this._app.bundles.hasUrl(l)){if(!this._app.bundles.canLoadUrl(l))return void h("Bundle for "+t+" not loaded yet");this._app.bundles.loadUrl(l,(function(e,t){h(e,{load:t,original:l})}))}else h(null,{load:t,original:s&&s.file.filename||t})}}else this._loadNull(r,n,s);else n("No resource handler for asset type: '"+i+"' when loading ["+t+"]")},t._loadNull=function(e,t,i){e.load(null,(function(n,s,r){if(n)t(n);else try{t(null,e.open(null,s,i),r)}catch(e){t(e)}}),i)},t._onSuccess=function(e,t,i){null!==t?this._cache[e]=t:delete this._cache[e];for(var n=0;n<this._requests[e].length;n++)this._requests[e][n](null,t,i);delete this._requests[e]},t._onFailure=function(e,t){if(console.error(t),this._requests[e]){for(var i=0;i<this._requests[e].length;i++)this._requests[e][i](t);delete this._requests[e]}},t.open=function(e,t){var i=this._handlers[e];return i?i.open(null,t):(console.warn("No resource handler found for: "+e),t)},t.patch=function(e,t){var i=this._handlers[e.type];i?i.patch&&i.patch(e,t):console.warn("No resource handler found for: "+e.type)},t.clearCache=function(t,i){var n=e.makeKey(t,i);delete this._cache[n]},t.getFromCache=function(t,i){var n=e.makeKey(t,i);if(this._cache[n])return this._cache[n]},t.enableRetry=function(e){for(var t in void 0===e&&(e=5),e=Math.max(0,e)||0,this._handlers)this._handlers[t].maxRetries=e},t.disableRetry=function(){for(var e in this._handlers)this._handlers[e].maxRetries=0},t.destroy=function(){this._handlers={},this._requests={},this._cache={}},e}(),jd=function(){function e(){}var t=e.prototype;return t._validate=function(e){if(!e.header)throw new Error('pc.I18n#addData: Missing "header" field');if(!e.header.version)throw new Error('pc.I18n#addData: Missing "header.version" field');if(1!==e.header.version)throw new Error('pc.I18n#addData: Invalid "header.version" field');if(!e.data)throw new Error('pc.I18n#addData: Missing "data" field');if(!Array.isArray(e.data))throw new Error('pc.I18n#addData: "data" field must be an array');for(var t=0,i=e.data.length;t<i;t++){var n=e.data[t];if(!n.info)throw new Error('pc.I18n#addData: missing "data['+t+'].info" field');if(!n.info.locale)throw new Error('pc.I18n#addData: missing "data['+t+'].info.locale" field');if("string"!=typeof n.info.locale)throw new Error('pc.I18n#addData: "data['+t+'].info.locale" must be a string');if(!n.messages)throw new Error('pc.I18n#addData: missing "data['+t+'].messages" field')}},t.parse=function(e){return e.data},e}(),qd=function(e){function t(t){var i;return(i=e.call(this)||this).locale=Sd,i._translations={},i._availableLangs={},i._app=t,i._assets=[],i._parser=new jd,i}Q(t,e),t.findAvailableLocale=function(e,t){return Cd(e,t)};var i=t.prototype;return i.findAvailableLocale=function(e){if(this._translations[e])return e;var t=Ad(e);return this._findFallbackLocale(e,t)},i.getText=function(e,t){var i,n=e;t||(t=this._locale,i=this._lang);var s=this._translations[t];return s||(i||(i=Ad(t)),t=this._findFallbackLocale(t,i),s=this._translations[t]),s&&s.hasOwnProperty(e)&&(n=s[e],Array.isArray(n)&&(n=n[0]),null==n&&(n=e)),n},i.getPluralText=function(e,t,i){var n,s,r=e;i?s=Md(n=Ad(i)):(i=this._locale,n=this._lang,s=this._pluralFn);var a=this._translations[i];if(a||(s=Md(n=Ad(i=this._findFallbackLocale(i,n))),a=this._translations[i]),a&&a[e]&&s){var o=s(t);null==(r=a[e][o])&&(r=e)}return r},i.addData=function(e){var t;try{t=this._parser.parse(e)}catch(e){return void console.error(e)}for(var i=0,n=t.length;i<n;i++){var s=t[i],r=s.info.locale,a=s.messages;if(!this._translations[r]){this._translations[r]={};var o=Ad(r);this._availableLangs[o]||(this._availableLangs[o]=r)}Object.assign(this._translations[r],a),this.fire("data:add",r,a)}},i.removeData=function(e){var t;try{t=this._parser.parse(e)}catch(e){return void console.error(e)}for(var i=0,n=t.length;i<n;i++){var s=t[i],r=s.info.locale,a=this._translations[r];if(a){var o=s.messages;for(var h in o)delete a[h];0===Object.keys(a).length&&(delete this._translations[r],delete this._availableLangs[Ad(r)]),this.fire("data:remove",r,o)}}},i.destroy=function(){this._translations=null,this._availableLangs=null,this._assets=null,this._parser=null,this.off()},i._findFallbackLocale=function(e,t){var i=bd[e];return i&&this._translations[i]||(i=bd[t])&&this._translations[i]||(i=this._availableLangs[t])&&this._translations[i]?i:Sd},i._onAssetAdd=function(e){e.on("load",this._onAssetLoad,this),e.on("change",this._onAssetChange,this),e.on("remove",this._onAssetRemove,this),e.on("unload",this._onAssetUnload,this),e.resource&&this._onAssetLoad(e)},i._onAssetLoad=function(e){this.addData(e.resource)},i._onAssetChange=function(e){e.resource&&this.addData(e.resource)},i._onAssetRemove=function(e){e.off("load",this._onAssetLoad,this),e.off("change",this._onAssetChange,this),e.off("remove",this._onAssetRemove,this),e.off("unload",this._onAssetUnload,this),e.resource&&this.removeData(e.resource),this._app.assets.once("add:"+e.id,this._onAssetAdd,this)},i._onAssetUnload=function(e){e.resource&&this.removeData(e.resource)},Z(t,[{key:"assets",get:function(){return this._assets},set:function(e){for(var t={},i=0,n=e.length;i<n;i++){t[e[i]instanceof kd?e[i].id:e[i]]=!0}for(var s=this._assets.length;s--;){var r=this._assets[s];if(!t[r]){this._app.assets.off("add:"+r,this._onAssetAdd,this);var a=this._app.assets.get(r);a&&this._onAssetRemove(a),this._assets.splice(s,1)}}for(var o in t){var h=parseInt(o,10);if(-1===this._assets.indexOf(h)){this._assets.push(h);var l=this._app.assets.get(h);l?this._onAssetAdd(l):this._app.assets.once("add:"+h,this._onAssetAdd,this)}}}},{key:"locale",get:function(){return this._locale},set:function(e){if(this._locale!==e){var t=Ad(e);if("in"!==t||(n=t="id",e=-1!==(s=(i=e).indexOf("-"))?n+i.substring(s):n,this._locale!==e)){var i,n,s,r=this._locale;this._locale=e,this._lang=t,this._pluralFn=Md(this._lang),this.fire("set:locale",e,r)}}}}]),t}(p),Yd=function(e){function t(t){var i;return(i=e.call(this)||this).app=t,i._scripts={},i._list=[],i}Q(t,e);var i=t.prototype;return i.destroy=function(){this.app=null,this.off()},i.add=function(e){var t=this,i=e.__name;return this._scripts.hasOwnProperty(i)?(setTimeout((function(){if(e.prototype.swap){var n=t._scripts[i],s=t._list.indexOf(n);t._list[s]=e,t._scripts[i]=e,t.fire("swap",i,e),t.fire("swap:"+i,e)}else console.warn("script registry already has '"+i+"' script, define 'swap' method for new script type to enable code hot swapping")})),!1):(this._scripts[i]=e,this._list.push(e),this.fire("add",i,e),this.fire("add:"+i,e),setTimeout((function(){if(t._scripts.hasOwnProperty(i)&&t.app&&t.app.systems&&t.app.systems.script){var e,n=t.app.systems.script._components,s=[],r=[];for(n.loopIndex=0;n.loopIndex<n.length;n.loopIndex++){var a=n.items[n.loopIndex];if(a._scriptsIndex[i]&&a._scriptsIndex[i].awaiting){a._scriptsData&&a._scriptsData[i]&&(e=a._scriptsData[i].attributes);var o=a.create(i,{preloading:!0,ind:a._scriptsIndex[i].ind,attributes:e});o&&s.push(o)}}for(var h=0;h<s.length;h++)s[h].__initializeAttributes();for(var l=0;l<s.length;l++)s[l].enabled&&(s[l]._initialized=!0,r.push(s[l]),s[l].initialize&&s[l].initialize());for(var c=0;c<r.length;c++)r[c].enabled&&!r[c]._postInitialized&&(r[c]._postInitialized=!0,r[c].postInitialize&&r[c].postInitialize())}})),!0)},i.remove=function(e){var t=e,i=e;if("string"!=typeof i?i=t.__name:t=this.get(i),this.get(i)!==t)return!1;delete this._scripts[i];var n=this._list.indexOf(t);return this._list.splice(n,1),this.fire("remove",i,t),this.fire("remove:"+i,t),!0},i.get=function(e){return this._scripts[e]||null},i.has=function(e){if("string"==typeof e)return this._scripts.hasOwnProperty(e);if(!e)return!1;var t=e.__name;return this._scripts[t]===e},i.list=function(){return this._list},t}(p),Kd=[],Zd=function(e){function t(t,i){var n;return void 0===i&&(i=ud()),(n=e.call(this,t)||this).anim=void 0,n.animation=void 0,n.audiolistener=void 0,n.button=void 0,n.camera=void 0,n.collision=void 0,n.element=void 0,n.layoutchild=void 0,n.layoutgroup=void 0,n.light=void 0,n.model=void 0,n.particlesystem=void 0,n.render=void 0,n.rigidbody=void 0,n.screen=void 0,n.script=void 0,n.scrollbar=void 0,n.scrollview=void 0,n.sound=void 0,n.sprite=void 0,n.c={},n._app=void 0,n._destroying=!1,n._guid=null,n._template=!1,n._app=i,n}Q(t,e);var i=t.prototype;return i.addComponent=function(e,t){var i=this._app.systems[e];return i?this.c[e]?null:i.addComponent(this,t):null},i.removeComponent=function(e){var t=this._app.systems[e];t&&this.c[e]&&t.removeComponent(this)},i.findComponent=function(e){var t=this.findOne((function(t){return t.c&&t.c[e]}));return t&&t.c[e]},i.findComponents=function(e){return this.find((function(t){return t.c&&t.c[e]})).map((function(t){return t.c[e]}))},i.getGuid=function(){return this._guid||this.setGuid(_.create()),this._guid},i.setGuid=function(e){var t=this._app._entityIndex;this._guid&&delete t[this._guid],this._guid=e,t[this._guid]=this},i._notifyHierarchyStateChanged=function(e,t){var i=!1;e===this&&0===Kd.length&&(i=!0),e._beingEnabled=!0,e._onHierarchyStateChanged(t),e._onHierarchyStatePostChanged&&Kd.push(e);for(var n=e._children,s=0,r=n.length;s<r;s++)n[s]._enabled&&this._notifyHierarchyStateChanged(n[s],t);if(e._beingEnabled=!1,i){for(var a=0;a<Kd.length;a++)Kd[a]._onHierarchyStatePostChanged();Kd.length=0}},i._onHierarchyStateChanged=function(t){e.prototype._onHierarchyStateChanged.call(this,t);var i=this.c;for(var n in i)if(i.hasOwnProperty(n)){var s=i[n];s.enabled&&(t?s.onEnable():s.onDisable())}},i._onHierarchyStatePostChanged=function(){var e=this.c;for(var t in e)e.hasOwnProperty(t)&&e[t].onPostStateChange()},i.findByGuid=function(e){if(this._guid===e)return this;var t=this._app._entityIndex[e];return t&&(t===this||t.isDescendantOf(this))?t:null},i.destroy=function(){for(var e in this._destroying=!0,this.c)this.c[e].enabled=!1;for(var i in this.c)this.c[i].system.removeComponent(this);this._parent&&this._parent.removeChild(this);for(var n=this._children;n.length;){var s=n.pop();s._parent=null,s instanceof t&&s.destroy()}this.fire("destroy",this),this.off(),this._guid&&delete this._app._entityIndex[this._guid],this._destroying=!1},i.clone=function(){var e={},t=this._cloneRecursively(e);return e[this.getGuid()]=t,$d(this,this,t,e),t},i._cloneRecursively=function(i){var n=new this.constructor(void 0,this._app);for(var s in e.prototype._cloneInternal.call(this,n),this.c){this.c[s].system.cloneComponent(this,n)}for(var r=0;r<this._children.length;r++){var a=this._children[r];if(a instanceof t){var o=a._cloneRecursively(i);n.addChild(o),i[a.getGuid()]=o}}return n},t}(go);function $d(e,t,i,n){if(t instanceof Zd){var s=t.c;for(var r in s)for(var a=s[r],o=a.system.getPropertiesOfType("entity"),h=0,l=o.length;h<l;h++){var c=o[h].name,u=a[c];if(!!e.findByGuid(u)){var d=n[u].getGuid();d&&(i.c[r][c]=d)}}s.script&&!i._app.useLegacyScriptAttributeCloning&&i.script.resolveDuplicatedEntityReferenceProperties(s.script,n),s.render&&i.render.resolveDuplicatedEntityReferenceProperties(s.render,n),s.anim&&i.anim.resolveDuplicatedEntityReferenceProperties(s.anim,n);for(var f=t.children.filter((function(e){return e instanceof Zd})),p=i.children.filter((function(e){return e instanceof Zd})),m=0,_=f.length;m<_;m++)$d(e,f[m],p[m],n)}}var Qd=function(){function e(e,t){this.name=e,this.url=t,this.data=null,this._loading=!1,this._onLoadedCallbacks=[]}return Z(e,[{key:"loaded",get:function(){return!!this.data}},{key:"loading",get:function(){return this._loading}}]),e}(),Jd=function(){function e(e){this._app=e,this._list=[],this._index={},this._urlIndex={}}var t=e.prototype;return t.destroy=function(){this._app=null},t.list=function(){return this._list},t.add=function(e,t){if(this._index.hasOwnProperty(e))return!1;var i=new Qd(e,t),n=this._list.push(i);return this._index[i.name]=n-1,this._urlIndex[i.url]=n-1,!0},t.find=function(e){return this._index.hasOwnProperty(e)?this._list[this._index[e]]:null},t.findByUrl=function(e){return this._urlIndex.hasOwnProperty(e)?this._list[this._urlIndex[e]]:null},t.remove=function(e){if(this._index.hasOwnProperty(e)){var t=this._index[e],i=this._list[t];delete this._urlIndex[i.url],delete this._index[e],this._list.splice(t,1);for(var n=0;n<this._list.length;n++)i=this._list[n],this._index[i.name]=n,this._urlIndex[i.url]=n}},t._loadSceneData=function(e,t,i){var n=this._app,s=e;if("string"==typeof e&&(e=this.findByUrl(s)||this.find(s)||new Qd("Untitled",s)),s=e.url)if(e.loaded)i(null,e);else{if(n.assets&&n.assets.prefix&&!Rd.test(s)&&(s=v.join(n.assets.prefix,s)),e._onLoadedCallbacks.push(i),!e._loading)n.loader.getHandler("hierarchy").load(s,(function(i,n){e.data=n,e._loading=!1;for(var s=0;s<e._onLoadedCallbacks.length;s++)e._onLoadedCallbacks[s](i,e);t||(e.data=null),e._onLoadedCallbacks.length=0}));e._loading=!0}else i("Cannot find scene to load")},t.loadSceneData=function(e,t){this._loadSceneData(e,!0,t)},t.unloadSceneData=function(e){"string"==typeof e&&(e=this.findByUrl(e)),e&&(e.data=null)},t._loadSceneHierarchy=function(e,t,i){var n=this;this._loadSceneData(e,!1,(function(e,s){if(e)i&&i(e);else{t&&t(s);var r=n._app;r._preloadScripts(s.data,(function(){var e=r.loader.getHandler("hierarchy");r.systems.script.preloading=!0;var t=e.open(s.url,s.data);r.systems.script.preloading=!1,r.loader.clearCache(s.url,"hierarchy"),r.root.addChild(t),r.systems.fire("initialize",t),r.systems.fire("postInitialize",t),r.systems.fire("postPostInitialize",t),i&&i(null,t)}))}}))},t.loadSceneHierarchy=function(e,t){this._loadSceneHierarchy(e,null,t)},t.loadSceneSettings=function(e,t){var i=this;this._loadSceneData(e,!1,(function(e,n){e?t&&t(e):(i._app.applySceneSettings(n.data.settings),t&&t(null))}))},t.changeScene=function(e,t){var i=this._app;this._loadSceneHierarchy(e,(function(e){for(var t=i.root.children;t.length>0;){var n=t[0];n.reparent(null),null==n.destroy||n.destroy()}i.applySceneSettings(e.data.settings)}),t)},t.loadScene=function(e,t){var i=this,n=this._app,s=n.loader.getHandler("scene");n.assets&&n.assets.prefix&&!Rd.test(e)&&(e=v.join(n.assets.prefix,e)),s.load(e,(function(r,a){if(r)t&&t(r);else{n._preloadScripts(a,(function(){n.systems.script.preloading=!0;var r=s.open(e,a),o=i.findByUrl(e);o&&!o.loaded&&(o.data=a),n.systems.script.preloading=!1,n.loader.clearCache(e,"scene"),n.loader.patch({resource:r,type:"scene"},n.assets),n.root.addChild(r.root),n.systems.rigidbody&&"undefined"!=typeof Ammo&&n.systems.rigidbody.gravity.set(r._gravity.x,r._gravity.y,r._gravity.z),t&&t(null,r)}))}}))},e}(),ef=function(){function e(e){this.frame={fps:0,ms:0,dt:0,updateStart:0,updateTime:0,renderStart:0,renderTime:0,physicsStart:0,physicsTime:0,cullTime:0,sortTime:0,skinTime:0,morphTime:0,instancingTime:0,triangles:0,otherPrimitives:0,shaders:0,materials:0,cameras:0,shadowMapUpdates:0,shadowMapTime:0,depthMapTime:0,forwardTime:0,lightClustersTime:0,lightClusters:0,_timeToCountFrames:0,_fpsAccum:0},this.drawCalls={forward:0,depth:0,shadow:0,immediate:0,misc:0,total:0,skinned:0,instanced:0,removedByInstancing:0},this.misc={renderTargetCreationTime:0},this.particles={updatesPerFrame:0,_updatesPerFrame:0,frameTime:0,_frameTime:0},this.shaders=e._shaderStats,this.vram=e._vram,Object.defineProperty(this.vram,"totalUsed",{get:function(){return this.tex+this.vb+this.ib}}),Object.defineProperty(this.vram,"geom",{get:function(){return this.vb+this.ib}})}return Z(e,[{key:"scene",get:function(){return ud().scene._stats}},{key:"lightmapper",get:function(){var e;return null==(e=ud().lightmapper)?void 0:e.stats}},{key:"batcher",get:function(){var e=ud()._batcher;return e?e._stats:null}}]),e}(),tf=function(){function e(e){this.length=e,this.count=0}var t=e.prototype;return t.inc=function(){this.count++},t.done=function(){return this.count===this.length},e}();e.app=null;var nf=function(t){function i(n){var s;return s=t.call(this)||this,i._applications[n.id]=ee(s),dd(ee(s)),e.app=ee(s),s._destroyRequested=!1,s._inFrameUpdate=!1,s._time=0,s.timeScale=1,s.maxDeltaTime=.1,s.frame=0,s.autoRender=!0,s.renderNextFrame=!1,s.useLegacyScriptAttributeCloning=_d.legacy,s._librariesLoaded=!1,s._fillMode=hd,s._resolutionMode=cd,s._allowResize=!0,s.context=ee(s),s}Q(i,t);var n=i.prototype;return n.init=function(e){var t=this,i=e.graphicsDevice;this.graphicsDevice=i,Kr.set(i),this._initDefaultMaterial(),this._initProgramLibrary(),this.stats=new ef(i),this._soundManager=e.soundManager,this.loader=new Xd(this),ih.init(i),this._entityIndex={},this.scene=new Hu(i),this._registerSceneImmediate(this.scene),this.root=new Zd,this.root._enabledInHierarchy=!0,this.assets=new Bd(this.loader),e.assetPrefix&&(this.assets.prefix=e.assetPrefix),this.bundles=new Nd(this.assets),this.enableBundles="undefined"!=typeof TextDecoder,this.scriptsOrder=e.scriptsOrder||[],this.scripts=new Yd(this),this.i18n=new qd(this),this.scenes=new Jd(this);var n=this;this.defaultLayerWorld=new dc({name:"World",id:0}),this.sceneGrab=new mc(this.graphicsDevice,this.scene),this.defaultLayerDepth=this.sceneGrab.layer,this.defaultLayerSkybox=new dc({enabled:!0,name:"Skybox",id:2,opaqueSortMode:0}),this.defaultLayerUi=new dc({enabled:!0,name:"UI",id:4,transparentSortMode:1,passThrough:!1}),this.defaultLayerImmediate=new dc({enabled:!0,name:"Immediate",id:3,opaqueSortMode:0,passThrough:!0});var s=new Ec("default");s.pushOpaque(this.defaultLayerWorld),s.pushOpaque(this.defaultLayerDepth),s.pushOpaque(this.defaultLayerSkybox),s.pushTransparent(this.defaultLayerWorld),s.pushOpaque(this.defaultLayerImmediate),s.pushTransparent(this.defaultLayerImmediate),s.pushTransparent(this.defaultLayerUi),this.scene.layers=s,this.scene.on("set:layers",(function(e,t){for(var i,s=t.layerList,r=0;r<s.length;r++)switch((i=s[r]).id){case 1:n.sceneGrab.patch(i);break;case 4:i.passThrough=n.defaultLayerUi.passThrough;break;case 3:i.passThrough=n.defaultLayerImmediate.passThrough}})),xd.createPlaceholder(i),this.renderer=new yc(i),this.renderer.scene=this.scene,this.frameGraph=new gd,this.lightmapper=null,e.lightmapper&&(this.lightmapper=new e.lightmapper(i,this.root,this.scene,this.renderer,this.assets),this.once("prerender",this._firstBake,this)),this._batcher=null,e.batchManager&&(this._batcher=new e.batchManager(i,this.root,this.scene),this.once("prerender",this._firstBatch,this)),this.keyboard=e.keyboard||null,this.mouse=e.mouse||null,this.touch=e.touch||null,this.gamepads=e.gamepads||null,this.elementInput=e.elementInput||null,this.elementInput&&(this.elementInput.app=this),this.xr=e.xr?new e.xr(this):null,this.elementInput&&this.elementInput.attachSelectEvents(),this._inTools=!1,this._skyboxAsset=null,this._scriptPrefix=e.scriptPrefix||"",this.enableBundles&&this.loader.addHandler("bundle",new Wd(this)),e.resourceHandlers.forEach((function(e){var i=new e(t);t.loader.addHandler(i.handlerType,i)})),this.systems=new Ud,e.componentSystems.forEach((function(e){t.systems.add(new e(t))})),this._visibilityChangeHandler=this.onVisibilityChange.bind(this),"undefined"!=typeof document&&(void 0!==document.hidden?(this._hiddenAttr="hidden",document.addEventListener("visibilitychange",this._visibilityChangeHandler,!1)):void 0!==document.mozHidden?(this._hiddenAttr="mozHidden",document.addEventListener("mozvisibilitychange",this._visibilityChangeHandler,!1)):void 0!==document.msHidden?(this._hiddenAttr="msHidden",document.addEventListener("msvisibilitychange",this._visibilityChangeHandler,!1)):void 0!==document.webkitHidden&&(this._hiddenAttr="webkitHidden",document.addEventListener("webkitvisibilitychange",this._visibilityChangeHandler,!1))),this.tick=rf(this)},i.getApplication=function(e){return e?i._applications[e]:ud()},n._initDefaultMaterial=function(){var e=new Yl;e.name="Default Material",e.shadingModel=1,function(e,t){Wa.get(e,(function(){return t}))}(this.graphicsDevice,e)},n._initProgramLibrary=function(){var e=new rd(this.graphicsDevice,new Yl);Ta(this.graphicsDevice,e)},n.configure=function(e,t){var i=this;Tr.get(e,(function(e,n){if(e)t(e);else{var s=n.application_properties,r=n.scenes,a=n.assets;i._parseApplicationProperties(s,(function(e){i._parseScenes(r),i._parseAssets(a),t(e||null)}))}}))},n.preload=function(e){var t=this;this.fire("preload:start");var i=this.assets.list({preload:!0}),n=new tf(i.length),s=!1,r=function(){t.graphicsDevice&&!s&&n.done()&&(s=!0,t.fire("preload:end"),e())},a=i.length;if(n.length)for(var o=function(e){n.inc(),t.fire("preload:progress",n.count/a),n.done()&&r()},h=function(e,i){n.inc(),t.fire("preload:progress",n.count/a),n.done()&&r()},l=0;l<i.length;l++)i[l].loaded?(n.inc(),this.fire("preload:progress",n.count/a),n.done()&&r()):(i[l].once("load",o),i[l].once("error",h),this.assets.load(i[l]));else r()},n._preloadScripts=function(e,t){var i=this;if(_d.legacy){this.systems.script.preloading=!0;var n=this._getScriptReferences(e),s=n.length,r=new tf(s),a=/^http(s)?:\/\//;if(s)for(var o=function(e,n){e&&console.error(e),r.inc(),r.done()&&(i.systems.script.preloading=!1,t())},h=0;h<s;h++){var l=n[h];!a.test(l.toLowerCase())&&this._scriptPrefix&&(l=v.join(this._scriptPrefix,n[h])),this.loader.load(l,"script",o)}else this.systems.script.preloading=!1,t()}else t()},n._parseApplicationProperties=function(e,t){if("number"==typeof e.maxAssetRetries&&e.maxAssetRetries>0&&this.loader.enableRetry(e.maxAssetRetries),e.useDevicePixelRatio||(e.useDevicePixelRatio=e.use_device_pixel_ratio),e.resolutionMode||(e.resolutionMode=e.resolution_mode),e.fillMode||(e.fillMode=e.fill_mode),this._width=e.width,this._height=e.height,e.useDevicePixelRatio&&(this.graphicsDevice.maxPixelRatio=window.devicePixelRatio),this.setCanvasResolution(e.resolutionMode,this._width,this._height),this.setCanvasFillMode(e.fillMode,this._width,this._height),e.layers&&e.layerOrder){var i=new Ec("application"),n={};for(var s in e.layers){var r=e.layers[s];r.id=parseInt(s,10),r.enabled=1!==r.id,n[s]=new dc(r)}for(var a=0,o=e.layerOrder.length;a<o;a++){var h=e.layerOrder[a],l=n[h.layer];l&&(h.transparent?i.pushTransparent(l):i.pushOpaque(l),i.subLayerEnabled[a]=h.enabled)}this.scene.layers=i}if(e.batchGroups){var c=this.batcher;if(c)for(var u=0,d=e.batchGroups.length;u<d;u++){var f=e.batchGroups[u];c.addGroup(f.name,f.dynamic,f.maxAabbSize,f.id,f.layers)}}e.i18nAssets&&(this.i18n.assets=e.i18nAssets),this._loadLibraries(e.libraries,t)},n._loadLibraries=function(e,t){var i=this,n=e.length,s=n,r=/^http(s)?:\/\//;if(n)for(var a=function(e,n){s--,e?t(e):0===s&&(i.onLibrariesLoaded(),t(null))},o=0;o<n;++o){var h=e[o];!r.test(h.toLowerCase())&&this._scriptPrefix&&(h=v.join(this._scriptPrefix,h)),this.loader.load(h,"script",a)}else this.onLibrariesLoaded(),t(null)},n._parseScenes=function(e){if(e)for(var t=0;t<e.length;t++)this.scenes.add(e[t].name,e[t].url)},n._parseAssets=function(e){var t=[],i={},n={};if(_d.legacy){if(this.enableBundles)for(var s in e)"bundle"===e[s].type&&(n[s]=!0,t.push(e[s]));for(var r in e)n[r]||t.push(e[r])}else{for(var a=0;a<this.scriptsOrder.length;a++){var o=this.scriptsOrder[a];e[o]&&(i[o]=!0,t.push(e[o]))}if(this.enableBundles)for(var h in e)"bundle"===e[h].type&&(n[h]=!0,t.push(e[h]));for(var l in e)i[l]||n[l]||t.push(e[l])}for(var c=0;c<t.length;c++){var u=t[c],d=new kd(u.name,u.type,u.file,u.data);if(d.id=parseInt(u.id,10),d.preload=!!u.preload&&u.preload,d.loaded="script"===u.type&&u.data&&u.data.loadingType>0,d.tags.add(u.tags),u.i18n)for(var f in u.i18n)d.addLocalizedAssetId(f,u.i18n[f]);this.assets.add(d)}},n._getScriptReferences=function(e){var t=[];e.settings.priority_scripts&&(t=e.settings.priority_scripts);for(var i=[],n={},s=0;s<t.length;s++)i.push(t[s]),n[t[s]]=!0;var r=e.entities;for(var a in r)if(r[a].components.script)for(var o=r[a].components.script.scripts,h=0;h<o.length;h++)n[o[h].url]||(i.push(o[h].url),n[o[h].url]=!0);return i},n.start=function(){this.frame=0,this.fire("start",{timestamp:oe(),target:this}),this._librariesLoaded||this.onLibrariesLoaded(),this.systems.fire("initialize",this.root),this.fire("initialize"),this.systems.fire("postInitialize",this.root),this.systems.fire("postPostInitialize",this.root),this.fire("postinitialize"),this.tick()},n.inputUpdate=function(e){this.controller&&this.controller.update(e),this.mouse&&this.mouse.update(),this.keyboard&&this.keyboard.update(),this.gamepads&&this.gamepads.update()},n.update=function(e){this.frame++,this.graphicsDevice.updateClientRect(),_d.legacy&&this.systems.fire("fixedUpdate",1/60),this.systems.fire(this._inTools?"toolsUpdate":"update",e),this.systems.fire("animationUpdate",e),this.systems.fire("postUpdate",e),this.fire("update",e),this.inputUpdate(e)},n.frameStart=function(){this.graphicsDevice.frameStart()},n.render=function(){this.fire("prerender"),this.root.syncHierarchy(),this._batcher&&this._batcher.updateAll(),this.renderComposition(this.scene.layers),this.fire("postrender")},n.renderComposition=function(e){this.renderer.buildFrameGraph(this.frameGraph,e),this.frameGraph.render(this.graphicsDevice)},n._fillFrameStatsBasic=function(e,t,i){var n=this.stats.frame;n.dt=t,n.ms=i,e>n._timeToCountFrames?(n.fps=n._fpsAccum,n._fpsAccum=0,n._timeToCountFrames=e+1e3):n._fpsAccum++,this.stats.drawCalls.total=this.graphicsDevice._drawCallsPerFrame,this.graphicsDevice._drawCallsPerFrame=0},n._fillFrameStats=function(){var e=this.stats.frame;e.cameras=this.renderer._camerasRendered,e.materials=this.renderer._materialSwitches,e.shaders=this.graphicsDevice._shaderSwitchesPerFrame,e.shadowMapUpdates=this.renderer._shadowMapUpdates,e.shadowMapTime=this.renderer._shadowMapTime,e.depthMapTime=this.renderer._depthMapTime,e.forwardTime=this.renderer._forwardTime;var t=this.graphicsDevice._primsPerFrame;e.triangles=t[4]/3+Math.max(t[5]-2,0)+Math.max(t[6]-2,0),e.cullTime=this.renderer._cullTime,e.sortTime=this.renderer._sortTime,e.skinTime=this.renderer._skinTime,e.morphTime=this.renderer._morphTime,e.lightClusters=this.renderer._lightClusters,e.lightClustersTime=this.renderer._lightClustersTime,e.otherPrimitives=0;for(var i=0;i<t.length;i++)i<4&&(e.otherPrimitives+=t[i]),t[i]=0;this.renderer._camerasRendered=0,this.renderer._materialSwitches=0,this.renderer._shadowMapUpdates=0,this.graphicsDevice._shaderSwitchesPerFrame=0,this.renderer._cullTime=0,this.renderer._layerCompositionUpdateTime=0,this.renderer._lightClustersTime=0,this.renderer._sortTime=0,this.renderer._skinTime=0,this.renderer._morphTime=0,this.renderer._shadowMapTime=0,this.renderer._depthMapTime=0,this.renderer._forwardTime=0,(e=this.stats.drawCalls).forward=this.renderer._forwardDrawCalls,e.culled=this.renderer._numDrawCallsCulled,e.depth=0,e.shadow=this.renderer._shadowDrawCalls,e.skinned=this.renderer._skinDrawCalls,e.immediate=0,e.instanced=0,e.removedByInstancing=0,e.misc=e.total-(e.forward+e.shadow),this.renderer._depthDrawCalls=0,this.renderer._shadowDrawCalls=0,this.renderer._forwardDrawCalls=0,this.renderer._numDrawCallsCulled=0,this.renderer._skinDrawCalls=0,this.renderer._immediateRendered=0,this.renderer._instancedDrawCalls=0,this.stats.misc.renderTargetCreationTime=this.graphicsDevice.renderTargetCreationTime,(e=this.stats.particles).updatesPerFrame=e._updatesPerFrame,e.frameTime=e._frameTime,e._updatesPerFrame=0,e._frameTime=0},n.setCanvasFillMode=function(e,t,i){this._fillMode=e,this.resizeCanvas(t,i)},n.setCanvasResolution=function(e,t,i){this._resolutionMode=e,e===ld&&void 0===t&&(t=this.graphicsDevice.canvas.clientWidth,i=this.graphicsDevice.canvas.clientHeight),this.graphicsDevice.resizeCanvas(t,i)},n.isHidden=function(){return document[this._hiddenAttr]},n.onVisibilityChange=function(){this.isHidden()?this._soundManager&&this._soundManager.suspend():this._soundManager&&this._soundManager.resume()},n.resizeCanvas=function(e,t){if(this._allowResize&&(!this.xr||!this.xr.session)){var i=window.innerWidth,n=window.innerHeight;if(this._fillMode===hd){var s=this.graphicsDevice.canvas.width/this.graphicsDevice.canvas.height;s>i/n?t=(e=i)/s:e=(t=n)*s}else this._fillMode===od&&(e=i,t=n);return this.graphicsDevice.canvas.style.width=e+"px",this.graphicsDevice.canvas.style.height=t+"px",this.updateCanvasSize(),{width:e,height:t}}},n.updateCanvasSize=function(){var e;if(this._allowResize&&(null==(e=this.xr)||!e.active)&&this._resolutionMode===ld){var t=this.graphicsDevice.canvas;this.graphicsDevice.resizeCanvas(t.clientWidth,t.clientHeight)}},n.onLibrariesLoaded=function(){this._librariesLoaded=!0,this.systems.rigidbody&&this.systems.rigidbody.onLibraryLoaded()},n.applySceneSettings=function(e){var t;if(this.systems.rigidbody&&"undefined"!=typeof Ammo){var i=e.physics.gravity;this.systems.rigidbody.gravity.set(i[0],i[1],i[2])}this.scene.applySettings(e),e.render.hasOwnProperty("skybox")&&(e.render.skybox?(t=this.assets.get(e.render.skybox))?this.setSkybox(t):this.assets.once("add:"+e.render.skybox,this.setSkybox,this):this.setSkybox(null))},n.setAreaLightLuts=function(e,t){e&&t&&xd.set(this.graphicsDevice,e,t)},n.setSkybox=function(e){var t=this;if(e!==this._skyboxAsset){var i=function(){t.setSkybox(null)},n=function(){t.scene.setSkybox(t._skyboxAsset?t._skyboxAsset.resources:null)};this._skyboxAsset&&(this.assets.off("load:"+this._skyboxAsset.id,n,this),this.assets.off("remove:"+this._skyboxAsset.id,i,this),this._skyboxAsset.off("change",n,this)),this._skyboxAsset=e,this._skyboxAsset&&(this.assets.on("load:"+this._skyboxAsset.id,n,this),this.assets.once("remove:"+this._skyboxAsset.id,i,this),this._skyboxAsset.on("change",n,this),0!==this.scene.skyboxMip||this._skyboxAsset.loadFaces||(this._skyboxAsset.loadFaces=!0),this.assets.load(this._skyboxAsset)),n()}},n._firstBake=function(){var e;null==(e=this.lightmapper)||e.bake(null,this.scene.lightmapMode)},n._firstBatch=function(){var e;null==(e=this.batcher)||e.generate()},n._processTimestamp=function(e){return e},n.drawLine=function(e,t,i,n,s){this.scene.drawLine(e,t,i,n,s)},n.drawLines=function(e,t,i,n){void 0===i&&(i=!0),void 0===n&&(n=this.scene.defaultDrawLayer),this.scene.drawLines(e,t,i,n)},n.drawLineArrays=function(e,t,i,n){void 0===i&&(i=!0),void 0===n&&(n=this.scene.defaultDrawLayer),this.scene.drawLineArrays(e,t,i,n)},n.drawWireSphere=function(e,t,i,n,s,r){void 0===i&&(i=ue.WHITE),void 0===n&&(n=20),void 0===s&&(s=!0),void 0===r&&(r=this.scene.defaultDrawLayer),this.scene.immediate.drawWireSphere(e,t,i,n,s,r)},n.drawWireAlignedBox=function(e,t,i,n,s){void 0===i&&(i=ue.WHITE),void 0===n&&(n=!0),void 0===s&&(s=this.scene.defaultDrawLayer),this.scene.immediate.drawWireAlignedBox(e,t,i,n,s)},n.drawMeshInstance=function(e,t){void 0===t&&(t=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(null,null,null,e,t)},n.drawMesh=function(e,t,i,n){void 0===n&&(n=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(t,i,e,null,n)},n.drawQuad=function(e,t,i){void 0===i&&(i=this.scene.defaultDrawLayer),this.scene.immediate.drawMesh(t,e,this.scene.immediate.getQuadMesh(),null,i)},n.drawTexture=function(e,t,i,n,s,r,a,o){if(void 0===a&&(a=this.scene.defaultDrawLayer),void 0===o&&(o=!0),!1!==o||this.graphicsDevice.isWebGPU){var h=new Te;h.setTRS(new me(e,t,0),Ae.IDENTITY,new me(i,-n,0)),r||((r=new Ya).cull=0,r.setParameter("colorMap",s),r.shader=o?this.scene.immediate.getTextureShader():this.scene.immediate.getUnfilterableTextureShader(),r.update()),this.drawQuad(h,r,a)}},n.drawDepthTexture=function(e,t,i,n,s){void 0===s&&(s=this.scene.defaultDrawLayer);var r=new Ya;r.cull=0,r.shader=this.scene.immediate.getDepthTextureShader(),r.update(),this.drawTexture(e,t,i,n,null,r,s)},n.destroy=function(){var e;if(this._inFrameUpdate)this._destroyRequested=!0;else{var t=this.graphicsDevice.canvas.id;this.off("librariesloaded"),"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this._visibilityChangeHandler,!1),document.removeEventListener("mozvisibilitychange",this._visibilityChangeHandler,!1),document.removeEventListener("msvisibilitychange",this._visibilityChangeHandler,!1),document.removeEventListener("webkitvisibilitychange",this._visibilityChangeHandler,!1)),this._visibilityChangeHandler=null,this.root.destroy(),this.root=null,this.mouse&&(this.mouse.off(),this.mouse.detach(),this.mouse=null),this.keyboard&&(this.keyboard.off(),this.keyboard.detach(),this.keyboard=null),this.touch&&(this.touch.off(),this.touch.detach(),this.touch=null),this.elementInput&&(this.elementInput.detach(),this.elementInput=null),this.gamepads&&(this.gamepads.destroy(),this.gamepads=null),this.controller&&(this.controller=null),this.systems.destroy(),this.scene.layers&&this.scene.layers.destroy();for(var n=this.assets.list(),s=0;s<n.length;s++)n[s].unload(),n[s].off();for(var r in this.assets.off(),this.bundles.destroy(),this.bundles=null,this.i18n.destroy(),this.i18n=null,this.loader.getHandler("script")._cache){var a=this.loader.getHandler("script")._cache[r],o=a.parentNode;o&&o.removeChild(a)}this.loader.getHandler("script")._cache={},this.loader.destroy(),this.loader=null,this.scene.destroy(),this.scene=null,this.systems=null,this.context=null,this.scripts.destroy(),this.scripts=null,this.scenes.destroy(),this.scenes=null,null==(e=this.lightmapper)||e.destroy(),this.lightmapper=null,this._batcher&&(this._batcher.destroy(),this._batcher=null),this._entityIndex={},this.defaultLayerDepth.onPreRenderOpaque=null,this.defaultLayerDepth.onPostRenderOpaque=null,this.defaultLayerDepth.onDisable=null,this.defaultLayerDepth.onEnable=null,this.defaultLayerDepth=null,this.defaultLayerWorld=null,null==this||this.xr.end(),null==this||this.xr.destroy(),this.renderer.destroy(),this.renderer=null,this.graphicsDevice.destroy(),this.graphicsDevice=null,this.tick=null,this.off(),this._soundManager&&(this._soundManager.destroy(),this._soundManager=null),_d.app=null,i._applications[t]=null,ud()===this&&dd(null)}},n.getEntityFromIndex=function(e){return this._entityIndex[e]},n._registerSceneImmediate=function(e){this.on("postrender",e.immediate.onPostRender,e.immediate)},Z(i,[{key:"soundManager",get:function(){return this._soundManager}},{key:"batcher",get:function(){return this._batcher}},{key:"fillMode",get:function(){return this._fillMode}},{key:"resolutionMode",get:function(){return this._resolutionMode}}]),i}(p);nf._applications={};var sf={},rf=function(t){var i,n=t;return function(t,s){var r;if(n.graphicsDevice){dd(n),i&&(window.cancelAnimationFrame(i),i=null),e.app=n;var a=n._processTimestamp(t)||oe(),o=a-(n._time||a),h=o/1e3;if(h=ce.clamp(h,0,n.maxDeltaTime),h*=n.timeScale,n._time=a,i=null!=(r=n.xr)&&r.session?n.xr.session.requestAnimationFrame(n.tick):M.browser?window.requestAnimationFrame(n.tick):null,!n.graphicsDevice.contextLost){n._fillFrameStatsBasic(a,h,o),n._inFrameUpdate=!0,n.fire("frameupdate",o);var l,c=!0;if(s)c=null==(l=n.xr)?void 0:l.update(s),n.graphicsDevice.defaultFramebuffer=s.session.renderState.baseLayer.framebuffer;else n.graphicsDevice.defaultFramebuffer=null;c&&(n.update(h),n.fire("framerender"),(n.autoRender||n.renderNextFrame)&&(n.updateCanvasSize(),n.frameStart(),n.render(),n.renderNextFrame=!1),sf.timestamp=oe(),sf.target=n,n.fire("frameend",sf)),n._inFrameUpdate=!1,n._destroyRequested&&n.destroy()}}}},af=function(){this.elementInput=void 0,this.keyboard=void 0,this.mouse=void 0,this.touch=void 0,this.gamepads=void 0,this.scriptPrefix=void 0,this.assetPrefix=void 0,this.scriptsOrder=void 0,this.soundManager=void 0,this.graphicsDevice=void 0,this.lightmapper=void 0,this.batchManager=void 0,this.xr=void 0,this.componentSystems=[],this.resourceHandlers=[]},of=new Oe,hf=function(){function e(e,t){this.scene=e,this.light=t,this.store(),t.numCascades=1,0!==t.type&&(t._node.getWorldTransform(),t.getBoundingSphere(of),this.lightBounds=new Ie,this.lightBounds.center.copy(of.center),this.lightBounds.halfExtents.set(of.radius,of.radius,of.radius))}var t=e.prototype;return t.store=function(){this.mask=this.light.mask,this.shadowUpdateMode=this.light.shadowUpdateMode,this.enabled=this.light.enabled,this.intensity=this.light.intensity,this.rotation=this.light._node.getLocalRotation().clone(),this.numCascades=this.light.numCascades},t.restore=function(){var e=this.light;e.mask=this.mask,e.shadowUpdateMode=this.shadowUpdateMode,e.enabled=this.enabled,e.intensity=this.intensity,e._node.setLocalRotation(this.rotation),e.numCascades=this.numCascades},t.startBake=function(){this.light.enabled=!0,this.light._destroyShadowMap(),this.light.beginFrame()},t.endBake=function(e){var t=this.light;t.enabled=!1,t.shadowMap&&(t.shadowMap.cached&&e.add(t,t.shadowMap),t.shadowMap=null)},e}(),lf=new ge,cf=function(e){function t(){return e.apply(this,arguments)||this}return Q(t,e),t.prototype.prepareVirtualLight=function(e,t){var i=this.light;if(i._node.setLocalRotation(this.rotation),e>0){var n=i.bakeArea;tl(lf,e,t),lf.mulScalar(.5*n),i._node.rotateLocal(lf.x,0,lf.y)}i._node.getWorldTransform();var s=this.scene.gammaCorrection?2.2:1,r=Math.pow(this.intensity,s);i.intensity=Math.pow(r/t,1/s)},Z(t,[{key:"numVirtualLights",get:function(){return 0===this.light.type?this.light.bakeNumSamples:1}}]),t}(hf),uf=new me,df=function(e){function t(t){var i=new Zd("AmbientLight");return i.addComponent("light",{type:"directional",affectDynamic:!0,affectLightmapped:!1,bake:!0,bakeNumSamples:t.ambientBakeNumSamples,castShadows:!0,normalOffsetBias:.05,shadowBias:.2,shadowDistance:1,shadowResolution:2048,shadowType:0,color:ue.WHITE,intensity:1,bakeDir:!1}),e.call(this,t,i.light.light)||this}return Q(t,e),t.prototype.prepareVirtualLight=function(e,t){il(uf,e,t,0,this.scene.ambientBakeSpherePart),this.light._node.lookAt(uf.mulScalar(-1)),this.light._node.rotateLocal(90,0,0);var i=this.scene.gammaCorrection?2.2:1,n=2*Math.PI*this.scene.ambientBakeSpherePart,s=Math.pow(n,i);this.light.intensity=Math.pow(s/t,1/i)},Z(t,[{key:"numVirtualLights",get:function(){return this.light.bakeNumSamples}}]),t}(hf),ff=function(){function e(e,t){void 0===t&&(t=null),this.node=e,this.component=e.render||e.model,t=t||this.component.meshInstances,this.store(),this.meshInstances=t,this.bounds=null,this.renderTargets=[]}var t=e.prototype;return t.store=function(){this.castShadows=this.component.castShadows},t.restore=function(){this.component.castShadows=this.castShadows},e}(),pf=function(){function e(e){this.device=e,this.shaderDilate=Ca(e,Sa.fullscreenQuadVS,ad.dilatePS,"lmDilate"),this.constantTexSource=e.scope.resolve("source"),this.constantPixelOffset=e.scope.resolve("pixelOffset"),this.pixelOffset=new Float32Array(2),this.shaderDenoise=null,this.sigmas=null,this.constantSigmas=null,this.kernel=null}var t=e.prototype;return t.setSourceTexture=function(e){this.constantTexSource.setValue(e)},t.prepare=function(e,t){this.pixelOffset[0]=1/e,this.pixelOffset[1]=1/t,this.constantPixelOffset.setValue(this.pixelOffset)},t.prepareDenoise=function(e,t){this.shaderDenoise||(this.shaderDenoise=Ca(this.device,Sa.fullscreenQuadVS,ad.bilateralDeNoisePS,"lmBilateralDeNoise"),this.sigmas=new Float32Array(2),this.constantSigmas=this.device.scope.resolve("sigmas"),this.constantKernel=this.device.scope.resolve("kernel[0]"),this.bZnorm=this.device.scope.resolve("bZnorm")),this.sigmas[0]=e,this.sigmas[1]=t,this.constantSigmas.setValue(this.sigmas),this.evaluateDenoiseUniforms(e,t)},t.evaluateDenoiseUniforms=function(e,t){function i(e,t){return.39894*Math.exp(-.5*e*e/(t*t))/t}this.kernel=this.kernel||new Float32Array(15);for(var n=this.kernel,s=Math.floor(7),r=0;r<=s;++r){var a=i(r,e);n[s+r]=a,n[s-r]=a}this.constantKernel.setValue(this.kernel);var o=1/i(0,t);this.bZnorm.setValue(o)},e}(),mf=new me,_f=function(){function e(e,t,i,n,s){this.device=e,this.root=t,this.scene=i,this.renderer=n,this.assets=s,this.shadowMapCache=n.shadowMapCache,this._tempSet=new Set,this._initCalled=!1,this.passMaterials=[],this.ambientAOMaterial=null,this.fog="",this.ambientLight=new ue,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(){yo.decRef(this.blackTex),this.blackTex=null,yo.destroy(),this.device=null,this.root=null,this.scene=null,this.renderer=null,this.assets=null},t.initBake=function(e){if(!this._initCalled){this._initCalled=!0,this.lightmapFilters=new pf(e),this.constantBakeDir=e.scope.resolve("bakeDir"),this.materials=[],this.blackTex=new Yn(this.device,{width:4,height:4,format:7,type:Gt,name:"lightmapBlack"}),yo.incRef(this.blackTex);var t=new Vo;t.clearColor.set(0,0,0,0),t.clearColorBuffer=!0,t.clearDepthBuffer=!1,t.clearStencilBuffer=!1,t.frustumCulling=!1,t.projection=1,t.aspectRatio=1,t.node=new go,this.camera=t}if(this.scene.clusteredLightingEnabled){var i=new Fc(e.supportsAreaLights,e.maxTextureSize,(function(){}));this.lightingParams=i;var n=this.scene.lighting;i.shadowsEnabled=n.shadowsEnabled,i.shadowAtlasResolution=n.shadowAtlasResolution,i.cookiesEnabled=n.cookiesEnabled,i.cookieAtlasResolution=n.cookieAtlasResolution,i.areaLightsEnabled=n.areaLightsEnabled,i.cells=new me(3,3,3),i.maxLightsPerCell=4,this.worldClusters=new lh(e),this.worldClusters.name="ClusterLightmapper"}},t.finishBake=function(e){function t(e){yo.decRef(e.colorBuffer),e.destroy()}this.materials=[],this.renderTargets.forEach((function(e){t(e)})),this.renderTargets.clear(),e.forEach((function(e){e.renderTargets.forEach((function(e){t(e)})),e.renderTargets.length=0})),this.ambientAOMaterial=null,this.worldClusters&&(this.worldClusters.destroy(),this.worldClusters=null)},t.createMaterialForPass=function(e,t,i,n){var s=new Yl;if(s.name="lmMaterial-pass:"+i+"-ambient:"+n,s.chunks.APIVersion=pi,s.chunks.transformVS="#define UV1LAYOUT\n"+Sa.transformVS,0===i){var r=ad.bakeLmEndPS;n?r="\n dDiffuseLight = ((dDiffuseLight - 0.5) * max("+t.ambientBakeOcclusionContrast.toFixed(1)+" + 1.0, 0.0)) + 0.5;\n dDiffuseLight += vec3("+t.ambientBakeOcclusionBrightness.toFixed(1)+");\n dDiffuseLight = saturate(dDiffuseLight);\n dDiffuseLight *= dAmbientLight;\n "+r:(s.ambient=new ue(0,0,0),s.ambientTint=!0),s.chunks.basePS=Sa.basePS+(7===t.lightmapPixelFormat?"\n#define LIGHTMAP_RGBM\n":""),s.chunks.endPS=r,s.lightMap=this.blackTex}else s.chunks.basePS=Sa.basePS+"\nuniform sampler2D texture_dirLightMap;\nuniform float bakeDir;\n",s.chunks.endPS=ad.bakeDirLmEndPS;return s.chunks.outputAlphaPS="\n",s.chunks.outputAlphaOpaquePS="\n",s.chunks.outputAlphaPremulPS="\n",s.cull=0,s.forceUv1=!0,s.update(),s},t.createMaterials=function(e,t,i){for(var n=0;n<i;n++)this.passMaterials[n]||(this.passMaterials[n]=this.createMaterialForPass(e,t,n,!1));this.ambientAOMaterial||(this.ambientAOMaterial=this.createMaterialForPass(e,t,0,!0),this.ambientAOMaterial.onUpdateShader=function(e){return e.litOptions.lightMapWithoutAmbient=!0,e.litOptions.separateAmbient=!0,e})},t.createTexture=function(e,t){return new Yn(this.device,{width:e,height:e,format:this.scene.lightmapPixelFormat,mipmaps:!1,type:7===this.scene.lightmapPixelFormat?Gt:Vt,minFilter:0,magFilter:0,addressU:1,addressV:1,name:t})},t.collectModels=function(e,t,i){var n,s,r;if(e.enabled){var a;if(null!=(n=e.model)&&n.model&&null!=(s=e.model)&&s.enabled&&(i&&i.push(new ff(e)),e.model.lightmapped&&t&&(a=e.model.model.meshInstances)),null!=(r=e.render)&&r.enabled&&(i&&i.push(new ff(e)),e.render.lightmapped&&t&&(a=e.render.meshInstances)),a){for(var o=!0,h=0;h<a.length;h++)if(!a[h].mesh.vertexBuffer.format.hasUv1){o=!1;break}if(o){for(var l=[],c=0;c<a.length;c++){var u=a[c].mesh;this._tempSet.has(u)?t.push(new ff(e,[a[c]])):l.push(a[c]),this._tempSet.add(u)}this._tempSet.clear(),l.length>0&&t.push(new ff(e,l))}}for(var d=0;d<e._children.length;d++)this.collectModels(e._children[d],t,i)}},t.prepareShadowCasters=function(e){for(var t=[],i=0;i<e.length;i++){var n=e[i].component;if(n.castShadows=n.castShadowsLightmap,n.castShadowsLightmap)for(var s=e[i].meshInstances,r=0;r<s.length;r++)s[r].visibleThisFrame=!0,t.push(s[r])}return t},t.updateTransforms=function(e){for(var t=0;t<e.length;t++)for(var i=e[t].meshInstances,n=0;n<i.length;n++)i[n].node.getWorldTransform()},t.calculateLightmapSize=function(e){var t,i,n,s=this.scene.lightmapSizeMultiplier||16,r=mf;e.model?(n=e.model.lightmapSizeMultiplier,e.model.asset?(t=this.assets.get(e.model.asset).data).area&&(i=t.area):e.model._area&&(t=e.model)._area&&(i=t._area)):e.render&&(n=e.render.lightmapSizeMultiplier,"asset"!==e.render.type&&e.render._area&&(t=e.render)._area&&(i=t._area));var a={x:1,y:1,z:1,uv:1};i&&(a.x=i.x,a.y=i.y,a.z=i.z,a.uv=i.uv);var o=n||1;a.x*=o,a.y*=o,a.z*=o;var h=e.render||e.model,l=this.computeNodeBounds(h.meshInstances);r.copy(l.halfExtents);var c=a.x*r.y*r.z+a.y*r.x*r.z+a.z*r.x*r.y;return c/=a.uv,c=Math.sqrt(c),Math.min(ce.nextPowerOfTwo(c*s),this.scene.lightmapMaxResolution||2048)},t.setLightmapping=function(e,t,i,n){for(var s=0;s<e.length;s++)for(var r=e[s],a=r.meshInstances,o=0;o<a.length;o++){var h=a[o];if(h.setLightmapped(t),t){n&&(h._shaderDefs|=n),h.mask=2;for(var l=0;l<i;l++){var c=r.renderTargets[l].colorBuffer;c.minFilter=1,c.magFilter=1,h.setRealtimeLightmap(Co.lightmapParamNames[l],c)}}}},t.bake=function(e,t){void 0===t&&(t=1);var i=this.device;if(!i.isWebGPU){var n=oe();this.scene._updateSky(i),this.stats.renderPasses=0,this.stats.shadowMapTime=0,this.stats.forwardTime=0;var s=i._shaderStats.linked,r=i._renderTargetCreationTime,a=i._shaderStats.compileTime,o=[],h=[];if(e){for(var l=0;l<e.length;l++)this.collectModels(e[l],o,null);this.collectModels(this.root,null,h)}else this.collectModels(this.root,o,h);if(o.length>0){this.renderer.shadowRenderer.frameUpdate();var c=1===t?2:1;this.setLightmapping(o,!1,c),this.initBake(i),this.bakeInternal(c,o,h);var u=64;1===t&&(u|=Gr),this.scene.ambientBake&&(u|=qr),this.setLightmapping(o,!0,c,u),this.finishBake(o)}var d=oe();this.stats.totalRenderTime=d-n,this.stats.shadersLinked=i._shaderStats.linked-s,this.stats.compileTime=i._shaderStats.compileTime-a,this.stats.fboTime=i._renderTargetCreationTime-r,this.stats.lightmapCount=o.length}},t.allocateTextures=function(e,t){for(var i=0;i<e.length;i++){for(var n=e[i],s=this.calculateLightmapSize(n.node),r=0;r<t;r++){var a=this.createTexture(s,"lightmapper_lightmap_"+i);yo.incRef(a),n.renderTargets[r]=new Di({colorBuffer:a,depth:!1})}if(!this.renderTargets.has(s)){var o=this.createTexture(s,"lightmapper_temp_lightmap_"+s);yo.incRef(o),this.renderTargets.set(s,new Di({colorBuffer:o,depth:!1}))}}},t.prepareLightsToBake=function(e,t,i){if(this.scene.ambientBake){var n=new df(this.scene);i.push(n)}for(var s=e._lights,r=0;r<s.length;r++){var a=s[r],o=new cf(this.scene,a);t.push(o),a.enabled&&0!=(4&a.mask)&&(a.isStatic=!1,a.mask=4294967295,a.shadowUpdateMode=0===a.type?2:1,i.push(o))}i.sort()},t.restoreLights=function(e){for(var t=0;t<e.length;t++)e[t].restore()},t.setupScene=function(){this.revertStatic=!1,this.scene._needsStaticPrepare&&(this.scene._needsStaticPrepare=!1,this.revertStatic=!0),this.fog=this.scene.fog,this.ambientLight.copy(this.scene.ambientLight),this.scene.fog=Nr,this.scene.ambientBake||this.scene.ambientLight.set(0,0,0),this.renderer.setSceneConstants()},t.restoreScene=function(){this.scene.fog=this.fog,this.scene.ambientLight.copy(this.ambientLight),this.revertStatic&&(this.scene._needsStaticPrepare=!0)},t.computeNodeBounds=function(e){var t=new Ie;if(e.length>0){t.copy(e[0].aabb);for(var i=1;i<e.length;i++)t.add(e[i].aabb)}return t},t.computeNodesBounds=function(e){for(var t=0;t<e.length;t++){var i=e[t].meshInstances;e[t].bounds=this.computeNodeBounds(i)}},t.computeBounds=function(e){for(var t=new Ie,i=0;i<e.length;i++){t.copy(e[0].aabb);for(var n=1;n<e.length;n++)t.add(e[n].aabb)}return t},t.backupMaterials=function(e){for(var t=0;t<e.length;t++)this.materials[t]=e[t].material},t.restoreMaterials=function(e){for(var t=0;t<e.length;t++)e[t].material=this.materials[t]},t.lightCameraPrepare=function(e,t){var i,n=t.light;2===n.type&&((i=n.getRenderData(null,0).shadowCamera)._node.setPosition(n._node.getPosition()),i._node.setRotation(n._node.getRotation()),i._node.rotateLocal(-90,0,0),i.projection=0,i.nearClip=n.attenuationEnd/1e3,i.farClip=n.attenuationEnd,i.aspectRatio=1,i.fov=2*n._outerConeAngle,this.renderer.updateCameraFrustum(i));return i},t.lightCameraPrepareAndCull=function(e,t,i,n){var s=e.light,r=!0;if(0===s.type){mf.copy(n.center),mf.y+=n.halfExtents.y,this.camera.node.setPosition(mf),this.camera.node.setEulerAngles(-90,0,0),this.camera.nearClip=0,this.camera.farClip=2*n.halfExtents.y;var a=Math.max(n.halfExtents.x,n.halfExtents.z);this.camera.orthoHeight=a}else e.lightBounds.intersects(t.bounds)||(r=!1);if(2===s.type){for(var o=!1,h=t.meshInstances,l=0;l<h.length;l++)if(h[l]._isVisible(i)){o=!0;break}o||(r=!1)}return r},t.setupLightArray=function(e,t){e[0].length=0,e[1].length=0,e[2].length=0,e[t.type][0]=t,t.visibleThisFrame=!0},t.renderShadowMap=function(e,t,i){var n=i.light,s=this.scene.clusteredLightingEnabled;if(!e&&n.castShadows){n.shadowMap||s||(n.shadowMap=this.shadowMapCache.get(this.device,n)),0===n.type?this.renderer._shadowRendererDirectional.cull(n,t,this.camera):this.renderer._shadowRendererLocal.cull(n,t);this.renderer.shadowRenderer.render(n,this.camera,!1)}return!0},t.postprocessTextures=function(e,t,i){var n=this.lightmapFilters.shaderDilate,s=this.scene.lightmapFilterEnabled;s&&this.lightmapFilters.prepareDenoise(this.scene.lightmapFilterRange,this.scene.lightmapFilterSmoothness),e.setBlendState(yi.NOBLEND),e.setDepthState(xi.NODEPTH),e.setStencilState(null,null);for(var r=0;r<t.length;r++)for(var a=t[r],o=0;o<i;o++){var h=a.renderTargets[o],l=h.colorBuffer,c=this.renderTargets.get(l.width),u=c.colorBuffer;this.lightmapFilters.prepare(l.width,l.height);for(var d=0;d<1;d++){this.lightmapFilters.setSourceTexture(l),Da(e,c,s&&0===o&&0===d?this.lightmapFilters.shaderDenoise:n),this.lightmapFilters.setSourceTexture(u),Da(e,h,n)}}},t.bakeInternal=function(e,t,i){var n=this.scene,s=this.device,r=n.clusteredLightingEnabled;this.createMaterials(s,n,e),this.setupScene(),n.layers._update(),this.computeNodesBounds(t),this.allocateTextures(t,e);var a=[],o=[];this.prepareLightsToBake(n.layers,a,o),this.updateTransforms(i);var h=this.prepareShadowCasters(i);this.renderer.updateCpuSkinMatrices(h),this.renderer.gpuUpdate(h);var l,c,u,d,f=this.computeBounds(h);for(l=0;l<t.length;l++){for(u=t[l].meshInstances,c=0;c<u.length;c++)(d=u[c]).setLightmapped(!1),d.mask=4,d.setRealtimeLightmap(Co.lightmapParamNames[0],d.material.lightMap?d.material.lightMap:this.blackTex),d.setRealtimeLightmap(Co.lightmapParamNames[1],this.blackTex)}for(c=0;c<o.length;c++)o[c].light.enabled=!1;var p,m,_=[[],[],[]],g=!1;for(l=0;l<o.length;l++){var v=o[l],y=v instanceof df,x=v.numVirtualLights;e>1&&x>1&&v.light.bakeDir&&(x=1);for(var S=0;S<x;S++){x>1&&v.prepareVirtualLight(S,x),v.startBake();var b=!1,w=this.lightCameraPrepare(s,v);for(m=0;m<t.length;m++){var T=t[m];if(u=T.meshInstances,this.lightCameraPrepareAndCull(v,T,w,f)){if(this.setupLightArray(_,v.light),r&&this.renderer.lightTextureAtlas.update(_[2],_[1],this.lightingParams),b=this.renderShadowMap(b,h,v),r){var A=_[2].concat(_[1]);this.worldClusters.update(A,this.scene.gammaCorrection,this.lightingParams)}for(this.backupMaterials(u),p=0;p<e&&!(p>0&&S>0)&&!(y&&p>0);p++){var C=T.renderTargets[p],E=T.renderTargets[p].colorBuffer.width,M=this.renderTargets.get(E),P=M.colorBuffer;0===p?g=n.updateShaders:g&&(n.updateShaders=!0);var R=this.passMaterials[p];for(y&&S+1===x&&0===p&&(R=this.ambientAOMaterial),c=0;c<u.length;c++)u[c].material=R;for(this.renderer.updateShaders(u),this.renderer.setCamera(this.camera,M,!0),1===p&&this.constantBakeDir.setValue(v.light.bakeDir?1:0),r&&this.worldClusters.activate(),this.renderer._forwardTime=0,this.renderer._shadowMapTime=0,this.renderer.renderForward(this.camera,u,u.length,_,1),s.updateEnd(),T.renderTargets[p]=M,this.renderTargets.set(E,C),c=0;c<u.length;c++)(d=u[c]).setRealtimeLightmap(Co.lightmapParamNames[p],P),d._shaderDefs|=64}this.restoreMaterials(u)}}v.endBake(this.shadowMapCache)}}for(this.postprocessTextures(s,t,e),m=0;m<i.length;m++)i[m].restore();this.restoreLights(a),this.restoreScene(),r||this.shadowMapCache.clear()},e}(),gf=function(e){function t(t,i){var n;return(n=e.call(this)||this).system=void 0,n.entity=void 0,n.system=t,n.entity=i,n.system.schema&&!n._accessorsBuilt&&n.buildAccessors(n.system.schema),n.on("set",(function(e,t,i){this.fire("set_"+e,e,t,i)})),n.on("set_enabled",n.onSetEnabled,ee(n)),n}Q(t,e),t._buildAccessors=function(e,t){t.forEach((function(t){var i="object"==typeof t?t.name:t;Object.defineProperty(e,i,{get:function(){return this.data[i]},set:function(e){var t=this.data,n=t[i];t[i]=e,this.fire("set",i,n,e)},configurable:!0})})),e._accessorsBuilt=!0};var i=t.prototype;return i.buildAccessors=function(e){t._buildAccessors(this,e)},i.onSetEnabled=function(e,t,i){t!==i&&this.entity.enabled&&(i?this.onEnable():this.onDisable())},i.onEnable=function(){},i.onDisable=function(){},i.onPostStateChange=function(){},Z(t,[{key:"data",get:function(){var e=this.system.store[this.entity.getGuid()];return e?e.data:null}}]),t}(p),vf=function(e){function t(t){var i;return(i=e.call(this)||this).app=t,i.store={},i.schema=[],i}Q(t,e);var i=t.prototype;return i.addComponent=function(e,t){void 0===t&&(t={});var i=new this.ComponentType(this,e),n=new this.DataType;return this.store[e.getGuid()]={entity:e,data:n},e[this.id]=i,e.c[this.id]=i,this.initializeComponentData(i,t,[]),this.fire("add",e,i),i},i.removeComponent=function(e){var t=this.store[e.getGuid()],i=e.c[this.id];this.fire("beforeremove",e,i),delete this.store[e.getGuid()],e[this.id]=void 0,delete e.c[this.id],this.fire("remove",e,t.data)},i.cloneComponent=function(e,t){var i=this.store[e.getGuid()];return this.addComponent(t,i.data)},i.initializeComponentData=function(e,t,i){void 0===t&&(t={});for(var n=0,s=i.length;n<s;n++){var r=i[n],a=void 0,o=void 0;"object"==typeof r?(a=r.name,o=r.type):(a=r,o=void 0);var h=t[a];void 0!==h?(void 0!==o&&(h=yf(h,o)),e[a]=h):e[a]=e.data[a]}e.enabled&&e.entity.enabled&&e.onEnable()},i.getPropertiesOfType=function(e){var t=[];return(this.schema||[]).forEach((function(i){i&&"object"==typeof i&&i.type===e&&t.push(i)})),t},i.destroy=function(){this.off()},t}(p);function yf(e,t){if(!e)return e;switch(t){case"rgb":return e instanceof ue?e.clone():new ue(e[0],e[1],e[2]);case"rgba":return e instanceof ue?e.clone():new ue(e[0],e[1],e[2],e[3]);case"vec2":return e instanceof ge?e.clone():new ge(e[0],e[1]);case"vec3":return e instanceof me?e.clone():new me(e[0],e[1],e[2]);case"vec4":return e instanceof ve?e.clone():new ve(e[0],e[1],e[2],e[3]);case"boolean":case"number":case"string":case"entity":return e;default:throw new Error("Could not convert unhandled type: "+t)}}var xf=function(){function e(){this._left=1/0,this._right=-1/0,this._len=0,this._recip=0,this._p0=0,this._p1=0,this._t=0,this._hermite={valid:!1,p0:0,m0:0,p1:0,m1:0}}var t=e.prototype;return t.update=function(e,t){if(e<this._left||e>=this._right){var i=t.length;if(i)if(e<t[0])this._left=-1/0,this._right=t[0],this._len=0,this._recip=0,this._p0=this._p1=0;else if(e>=t[i-1])this._left=t[i-1],this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=i-1;else{var n=this._findKey(e,t);this._left=t[n],this._right=t[n+1],this._len=this._right-this._left;var s=1/this._len;this._recip=isFinite(s)?s:0,this._p0=n,this._p1=n+1}else this._left=-1/0,this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=0}this._t=0===this._recip?0:(e-this._left)*this._recip,this._hermite.valid=!1},t._findKey=function(e,t){for(var i=0;e>=t[i+1];)i++;return i},t.eval=function(e,t,i){var n=i._data,s=i._components,r=this._p0*s;if(0===t)for(var a=0;a<s;++a)e[a]=n[r+a];else{var o=this._t,h=this._p1*s;switch(t){case 1:for(var l=0;l<s;++l)e[l]=ce.lerp(n[r+l],n[h+l],o);break;case 2:var c=this._hermite;if(!c.valid){var u=o*o,d=o+o,f=1-o,p=f*f;c.valid=!0,c.p0=(1+d)*p,c.m0=o*p,c.p1=u*(3-d),c.m1=u*(o-1)}for(var m=(3*this._p0+1)*s,_=(3*this._p0+2)*s,g=(3*this._p1+1)*s,v=(3*this._p1+0)*s,y=0;y<s;++y)e[y]=c.p0*n[m+y]+c.m0*n[_+y]*this._len+c.p1*n[g+y]+c.m1*n[v+y]*this._len}}},e}(),Sf=function(e){this._name=e.name+"Snapshot",this._time=-1,this._cache=[],this._results=[];for(var t=0;t<e._inputs.length;++t)this._cache[t]=new xf;for(var i=e._curves,n=e._outputs,s=0;s<i.length;++s){for(var r=n[i[s]._output],a=[],o=0;o<r._components;++o)a[o]=0;this._results[s]=a}},bf=function(){function e(e,t,i,n,s,r){this._name=e.name,this._track=e,this._snapshot=new Sf(e),this._playing=n,this._time=t,this._speed=i,this._loop=s,this._blendWeight=1,this._blendOrder=0,this._eventHandler=r,this.alignCursorToCurrentTime()}var t=e.prototype;return t.nextEventAheadOfTime=function(e){return!!this.nextEvent&&(this.isReverse?this.nextEvent.time<=e:this.nextEvent.time>=e)},t.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<e)},t.resetEventCursor=function(){this._eventCursor=this.isReverse?this._track.events.length-1:0},t.moveEventCursor=function(){this._eventCursor+=this.isReverse?-1:1,this._eventCursor>=this.track.events.length?this._eventCursor=0:this._eventCursor<0&&(this._eventCursor=this.track.events.length-1)},t.clipFrameTime=function(t){var i=e.eventFrame;i.start=0,i.end=t,i.residual=0,this.isReverse?t<0&&(i.start=this.track.duration,i.end=0,i.residual=t+this.track.duration):t>this.track.duration&&(i.start=0,i.end=this.track.duration,i.residual=t-this.track.duration)},t.alignCursorToCurrentTime=function(){for(this.resetEventCursor();this.nextEventBehindTime(this._time)&&this._eventCursor!==this.eventCursorEnd;)this.moveEventCursor()},t.fireNextEvent=function(){this._eventHandler.fire(this.nextEvent.name,$({track:this.track},this.nextEvent)),this.moveEventCursor()},t.fireNextEventInFrame=function(e,t){return!(!this.nextEventAheadOfTime(e)||!this.nextEventBehindTime(t))&&(this.fireNextEvent(),!0)},t.activeEventsForFrame=function(t,i){var n=e.eventFrame;this.clipFrameTime(i);for(var s=this.eventCursor;this.fireNextEventInFrame(t,n.end)&&s!==this.eventCursor;);this.loop&&Math.abs(n.residual)>0&&this.activeEventsForFrame(n.start,n.residual)},t.progressForTime=function(e){return e*this._speed/this._track.duration},t._update=function(e){if(this._playing){var t=this._time,i=this._track.duration,n=this._speed,s=this._loop;this._track.events.length>0&&i>0&&this.activeEventsForFrame(t,t+n*e),t+=n*e,n>=0?t>i&&(s?t=t%i||0:(t=this._track.duration,this.pause())):t<0&&(s?t=i+(t%i||0):(t=0,this.pause())),this._time=t}this._time!==this._snapshot._time&&this._track.eval(this._time,this._snapshot)},t.play=function(){this._playing=!0,this._time=0},t.stop=function(){this._playing=!1,this._time=0},t.pause=function(){this._playing=!1},t.resume=function(){this._playing=!0},t.reset=function(){this._time=0},Z(e,[{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 Sf(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}}]),e}();bf.eventFrame={start:0,end:0,residual:0};var wf="NONE",Tf="PREV_STATE",Af="NEXT_STATE",Cf="PREV_STATE_NEXT_STATE",Ef="NEXT_STATE_PREV_STATE",Mf="GREATER_THAN",Pf="LESS_THAN",Rf="GREATER_THAN_EQUAL_TO",If="LESS_THAN_EQUAL_TO",Lf="EQUAL_TO",Df="NOT_EQUAL_TO",Of="INTEGER",kf="FLOAT",Ff="BOOLEAN",Bf="TRIGGER",Nf="2D_DIRECTIONAL",Uf="2D_CARTESIAN",zf="DIRECT",Vf="START",Gf="END",Hf="ANY",Wf=[Vf,Gf,Hf],Xf="OVERWRITE",jf="ADDITIVE",qf=function(){function e(){}return e.dot=function(e,t){for(var i=e.length,n=0,s=0;s<i;++s)n+=e[s]*t[s];return n},e.normalize=function(t){var i=e.dot(t,t);if(i>0){i=1/Math.sqrt(i);for(var n=t.length,s=0;s<n;++s)t[s]*=i}},e.set=function(t,i,n){var s=t.length;if("quaternion"===n){var r=e.dot(i,i);r>0&&(r=1/Math.sqrt(r));for(var a=0;a<s;++a)t[a]=i[a]*r}else for(var o=0;o<s;++o)t[o]=i[o]},e.blendVec=function(e,t,i,n){for(var s=n?1:1-i,r=e.length,a=0;a<r;++a)e[a]=e[a]*s+t[a]*i},e.blendQuat=function(t,i,n,s){var r=t.length,a=s?1:1-n;e.dot(t,i)<0&&(n=-n);for(var o=0;o<r;++o)t[o]=t[o]*a+i[o]*n;s||e.normalize(t)},e.blend=function(t,i,n,s,r){"quaternion"===s?e.blendQuat(t,i,n,r):e.blendVec(t,i,n,r)},e.stableSort=function(e,t){for(var i=e.length,n=0;n<i-1;++n)for(var s=n+1;s<i;++s)if(t(e[s],e[n])){var r=e[n];e[n]=e[s],e[s]=r}},e}(),Yf=function(){function e(t,i){this._component=t,this.mask=new Int8Array(t.layers.length),this.weights=new Float32Array(t.layers.length),this.totalWeight=0,this.counter=0,this.layerCounter=0,this.valueType=i,this.dirty=!0,this.value=i===e.TYPE_QUAT?[0,0,0,1]:[0,0,0],this.baseValue=null,this.setter=null}var t=e.prototype;return t.getWeight=function(e){return this.dirty&&this.updateWeights(),this._normalizeWeights&&0===this.totalWeight||!this.mask[e]?0:this._normalizeWeights?this.weights[e]/this.totalWeight:ce.clamp(this.weights[e],0,1)},t._layerBlendType=function(e){return this._component.layers[e].blendType},t.setMask=function(e,t){this.mask[e]=t,this._normalizeWeights&&(this._component.layers[e].blendType===Xf&&(this.mask=this.mask.fill(0,0,e)),this.dirty=!0)},t.updateWeights=function(){this.totalWeight=0;for(var e=0;e<this.weights.length;e++)this.weights[e]=this._component.layers[e].weight,this.totalWeight+=this.mask[e]*this.weights[e];this.dirty=!1},t.updateValue=function(t,i){if(0===this.counter&&(qf.set(this.value,e.IDENTITY_QUAT_ARR,this.valueType),this._normalizeWeights||qf.blend(this.value,this.baseValue,1,this.valueType)),this.mask[t]&&0!==this.getWeight(t)){if(this._layerBlendType(t)!==jf||this._normalizeWeights)qf.blend(this.value,i,this.getWeight(t),this.valueType);else if(this.valueType===e.TYPE_QUAT){var n=e.q1.set(this.value[0],this.value[1],this.value[2],this.value[3]),s=e.q2.set(this.baseValue[0],this.baseValue[1],this.baseValue[2],this.baseValue[3]),r=e.q3.set(i[0],i[1],i[2],i[3]),a=s.invert().mul(r);a.slerp(Ae.IDENTITY,a,this.getWeight(t)),n.mul(a),e.quatArr[0]=n.x,e.quatArr[1]=n.y,e.quatArr[2]=n.z,e.quatArr[3]=n.w,qf.set(this.value,e.quatArr,this.valueType)}else e.vecArr[0]=i[0]-this.baseValue[0],e.vecArr[1]=i[1]-this.baseValue[1],e.vecArr[2]=i[2]-this.baseValue[2],qf.blend(this.value,e.vecArr,this.getWeight(t),this.valueType,!0);this.setter&&this.setter(this.value)}},t.unbind=function(){this.setter&&this.setter(this.baseValue)},Z(e,[{key:"_normalizeWeights",get:function(){return this._component.normalizeWeights}}]),e}();Yf.TYPE_QUAT="quaternion",Yf.TYPE_VEC3="vector3",Yf.q1=new Ae,Yf.q2=new Ae,Yf.q3=new Ae,Yf.quatArr=[0,0,0,1],Yf.vecArr=[0,0,0],Yf.IDENTITY_QUAT_ARR=[0,0,0,1];var Kf=function(){function e(e){this._binder=e,this._clips=[],this._inputs=[],this._outputs=[],this._targets={}}var t=e.prototype;return t.addClip=function(e){for(var t=this._targets,i=this._binder,n=e.track.curves,s=e.snapshot,r=[],a=[],o=0;o<n.length;++o)for(var h=n[o].paths,l=0;l<h.length;++l){var c=h[l],u=i.resolve(c),d=t[u&&u.targetPath||null];if(!d&&u){d={target:u,value:[],curves:0,blendCounter:0};for(var f=0;f<d.target.components;++f)d.value.push(0);if(t[u.targetPath]=d,i.animComponent){if(!i.animComponent.targets[u.targetPath]){var p=void 0;p="localRotation"===u.targetPath.substring(u.targetPath.length-13)?Yf.TYPE_QUAT:Yf.TYPE_VEC3,i.animComponent.targets[u.targetPath]=new Yf(i.animComponent,p)}i.animComponent.targets[u.targetPath].layerCounter++,i.animComponent.targets[u.targetPath].setMask(i.layerIndex,1)}}d&&(d.curves++,r.push(s._results[o]),a.push(d))}this._clips.push(e),this._inputs.push(r),this._outputs.push(a)},t.removeClip=function(e){for(var t=this._targets,i=this._binder,n=this._clips,s=n[e].track.curves,r=0;r<s.length;++r)for(var a=s[r].paths,o=0;o<a.length;++o){var h=a[o],l=this._binder.resolve(h);l&&(l.curves--,0===l.curves&&(i.unresolve(h),delete t[l.targetPath],i.animComponent&&i.animComponent.targets[l.targetPath].layerCounter--))}n.splice(e,1),this._inputs.splice(e,1),this._outputs.splice(e,1)},t.removeClips=function(){for(;this._clips.length>0;)this.removeClip(0)},t.updateClipTrack=function(e,t){this._clips.forEach((function(i){i.name.includes(e)&&(i.track=t)})),this.rebind()},t.findClip=function(e){for(var t=this._clips,i=0;i<t.length;++i){var n=t[i];if(n.name===e)return n}return null},t.rebind=function(){var e=this;this._binder.rebind(),this._targets={};var t=[].concat(this.clips);this.removeClips(),t.forEach((function(t){e.addClip(t)}))},t.assignMask=function(e){return this._binder.assignMask(e)},t.update=function(e,t){void 0===t&&(t=!0);var i=this._clips,n=i.map((function(e,t){return t}));qf.stableSort(n,(function(e,t){return i[e].blendOrder<i[t].blendOrder}));for(var s=0;s<n.length;++s){var r=n[s],a=i[r],o=this._inputs[r],h=this._outputs[r],l=a.blendWeight;if(l>0&&a._update(e),!t)break;var c=void 0,u=void 0,d=void 0;if(l>=1)for(var f=0;f<o.length;++f)c=o[f],d=(u=h[f]).value,qf.set(d,c,u.target.type),u.blendCounter++;else if(l>0)for(var p=0;p<o.length;++p)c=o[p],d=(u=h[p]).value,0===u.blendCounter?qf.set(d,c,u.target.type):qf.blend(d,c,l,u.target.type),u.blendCounter++}var m=this._targets,_=this._binder;for(var g in m)if(m.hasOwnProperty(g)){var v=m[g];if(_.animComponent&&v.target.isTransform){var y=_.animComponent.targets[g];y.counter===y.layerCounter&&(y.counter=0),y.path||(y.path=g,y.baseValue=v.target.get(),y.setter=v.target.set),y.updateValue(_.layerIndex,v.value),y.counter++}else v.target.set(v.value);v.blendCounter=0}this._binder.update(e)},Z(e,[{key:"clips",get:function(){return this._clips}}]),e}(),Zf=function(){function e(e){this._events=[].concat(e),this._events.sort((function(e,t){return e.time-t.time}))}return Z(e,[{key:"events",get:function(){return this._events}}]),e}(),$f=function(){function e(e,t,i,n,s,r){void 0===r&&(r=new Zf([])),this._name=e,this._duration=t,this._inputs=i,this._outputs=n,this._curves=s,this._animEvents=r}return e.prototype.eval=function(e,t){t._time=e;for(var i=this._inputs,n=this._outputs,s=this._curves,r=t._cache,a=t._results,o=0;o<i.length;++o)r[o].update(e,i[o]._data);for(var h=0;h<s.length;++h){var l=s[h],c=n[l._output],u=a[h];r[l._input].eval(u,l._interpolation,c)}},Z(e,[{key:"name",get:function(){return this._name}},{key:"duration",get:function(){return this._duration}},{key:"inputs",get:function(){return this._inputs}},{key:"outputs",get:function(){return this._outputs}},{key:"curves",get:function(){return this._curves}},{key:"events",get:function(){return this._animEvents.events},set:function(e){this._animEvents=e}}]),e}();$f.EMPTY=Object.freeze(new $f("empty",Number.MAX_VALUE,[],[],[]));var Qf=function(){function e(){}e.joinPath=function(e,t){t=t||".";return e.map((function(e){return e.replace(/\\/g,"\\\\").replace(new RegExp("\\"+t,"g"),"\\"+t)})).join(t)},e.splitPath=function(e,t){t=t||".";for(var i=[],n="",s=0;s<e.length;){var r=e[s++];"\\"===r&&s<e.length?n+="\\"===(r=e[s++])||r===t?r:"\\"+r:r===t?(i.push(n),n=""):n+=r}return n.length>0&&i.push(n),i},e.encode=function(e,t,i){return(Array.isArray(e)?e.join("/"):e)+"/"+t+"/"+(Array.isArray(i)?i.join("/"):i)};var t=e.prototype;return t.resolve=function(e){return null},t.unresolve=function(e){},t.update=function(e){},e}(),Jf=function(){function e(e,t,i,n){e.set?(this._set=e.set,this._get=e.get):this._set=e,this._type=t,this._components=i,this._targetPath=n,this._isTransform="localRotation"===this._targetPath.substring(this._targetPath.length-13)||"localPosition"===this._targetPath.substring(this._targetPath.length-13)||"localScale"===this._targetPath.substring(this._targetPath.length-10)}return Z(e,[{key:"set",get:function(){return this._set}},{key:"get",get:function(){return this._get}},{key:"type",get:function(){return this._type}},{key:"components",get:function(){return this._components}},{key:"targetPath",get:function(){return this._targetPath}},{key:"isTransform",get:function(){return this._isTransform}}]),e}(),ep=function(){function e(t){var i=this;if(this._isPathInMask=function(e,t){var n=i._mask[e];return!!n&&!!(n.children||t&&!1!==n.value)},this.graph=t,t){this._mask=null;var n={};!function e(t){n[t.name]=t;for(var i=0;i<t.children.length;++i)e(t.children[i])}(t),this.nodes=n,this.targetCache={};var s=function(e){for(var t,i=e;i&&!(i instanceof Zd);)i=i.parent;return i&&(i.render?t=i.render.meshInstances:i.model&&(t=i.model.meshInstances)),t};this.nodeCounts={},this.activeNodes=[],this.handlers={localPosition:function(t){var i=t.localPosition;return e.createAnimTarget((function(e){i.set.apply(i,e)}),"vector",3,t,"localPosition")},localRotation:function(t){var i=t.localRotation;return e.createAnimTarget((function(e){i.set.apply(i,e)}),"quaternion",4,t,"localRotation")},localScale:function(t){var i=t.localScale;return e.createAnimTarget((function(e){i.set.apply(i,e)}),"vector",3,t,"localScale")},weight:function(t,i){i=0===i.indexOf("name.")?i.replace("name.",""):Number(i);var n,r=s(t);if(r)for(var a=function(){if(r[o].node.name===t.name&&r[o].morphInstance){var e=r[o].morphInstance;n||(n=[]),n.push((function(t){e.setWeight(i,t[0])}))}},o=0;o<r.length;++o)a();if(n){return e.createAnimTarget((function(e){for(var t=0;t<n.length;++t)n[t](e)}),"number",1,t,"weight."+i)}return null},materialTexture:function(t,n){var r=s(t);if(r){for(var a,o=0;o<r.length;++o)if(r[o].node.name===t.name){a=r[o];break}if(a){return e.createAnimTarget((function(e){var t=i.animComponent.system.app.assets.get(e[0]);t&&t.resource&&"texture"===t.type&&(a.material[n]=t.resource,a.material.update())}),"vector",1,t,"materialTexture","material")}}return null}}}}var t=e.prototype;return t._isPathActive=function(e){if(!this._mask)return!0;for(var t=[e.entityPath[0],this.graph.name],i=0;i<t.length;++i){var n=t[i];if(this._isPathInMask(n,1===e.entityPath.length))return!0;for(var s=1;s<e.entityPath.length;s++)if(n+="/"+e.entityPath[s],this._isPathInMask(n,s===e.entityPath.length-1))return!0}return!1},t.findNode=function(e){return this._isPathActive(e)?(this.graph&&((t=this.graph.findByPath(e.entityPath))||(t=this.graph.findByPath(e.entityPath.slice(1)))),t||(t=this.nodes[e.entityPath[e.entityPath.length-1]||""]),t):null;var t},e.createAnimTarget=function(e,t,i,n,s,r){var a=Qf.encode(n.path,r||"entity",s);return new Jf(e,t,i,a)},t.resolve=function(e){var t=Qf.encode(e.entityPath,e.component,e.propertyPath),i=this.targetCache[t];if(i)return i;var n=this.findNode(e);if(!n)return null;var s=this.handlers[e.propertyPath];return s&&(i=s(n))?(this.targetCache[t]=i,this.nodeCounts[n.path]?this.nodeCounts[n.path]++:(this.activeNodes.push(n),this.nodeCounts[n.path]=1),i):null},t.unresolve=function(e){if("graph"===e.component){var t=this.nodes[e.entityPath[e.entityPath.length-1]||""];if(this.nodeCounts[t.path]--,0===this.nodeCounts[t.path]){var i=this.activeNodes,n=i.indexOf(t.node),s=i.length;n<s-1&&(i[n]=i[s-1]),i.pop()}}},t.update=function(e){for(var t=this.activeNodes,i=0;i<t.length;++i)t[i]._dirtifyLocal()},t.assignMask=function(e){return e!==this._mask&&(this._mask=e,!0)},e}(),tp=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._animations={},n._assets=[],n._loop=!0,n.animEvaluator=null,n.model=null,n.skeleton=null,n.fromSkel=null,n.toSkel=null,n.animationsIndex={},n.prevAnim=null,n.currAnim=null,n.blend=0,n.blending=!1,n.blendSpeed=0,n.activate=!0,n.speed=1,n}Q(t,e);var i=t.prototype;return i.play=function(e,t){if(void 0===t&&(t=0),this.enabled&&this.entity.enabled&&this.animations[e]){if(this.prevAnim=this.currAnim,this.currAnim=e,this.model){this.skeleton||this.animEvaluator||this._createAnimationController();var i=this.animations[this.prevAnim],n=this.animations[this.currAnim];if(this.blending=t>0&&!!this.prevAnim,this.blending&&(this.blend=0,this.blendSpeed=1/t),this.skeleton&&(this.blending?(this.fromSkel.animation=i,this.fromSkel.addTime(this.skeleton._time),this.toSkel.animation=n):this.skeleton.animation=n),this.animEvaluator){var s=this.animEvaluator;if(this.blending)for(;s.clips.length>1;)s.removeClip(0);else this.animEvaluator.removeClips();var r=new bf(this.animations[this.currAnim],0,1,!0,this.loop);r.name=this.currAnim,r.blendWeight=this.blending?0:1,r.reset(),this.animEvaluator.addClip(r)}}this.playing=!0}},i.getAnimation=function(e){return this.animations[e]},i.setModel=function(e){e!==this.model&&(this._resetAnimationController(),this.model=e,this.animations&&this.currAnim&&this.animations[this.currAnim]&&this.play(this.currAnim))},i.onSetAnimations=function(){var e=this.entity.model;if(e){var t=e.model;t&&t!==this.model&&this.setModel(t)}if(!this.currAnim&&this.activate&&this.enabled&&this.entity.enabled){var i=Object.keys(this._animations);i.length>0&&this.play(i[0])}},i._resetAnimationController=function(){this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animEvaluator=null},i._createAnimationController=function(){var e=this.model,t=this.animations,i=!1,n=!1;for(var s in t){if(t.hasOwnProperty(s))t[s].constructor===$f?n=!0:i=!0}var r=e.getGraph();i?(this.fromSkel=new Ju(r),this.toSkel=new Ju(r),this.skeleton=new Ju(r),this.skeleton.looping=this.loop,this.skeleton.setGraph(r)):n&&(this.animEvaluator=new Kf(new ep(this.entity)))},i.loadAnimationAssets=function(e){var t=this;if(e&&e.length)for(var i=this.system.app.assets,n=function(e){if(e.resources.length>1)for(var i=0;i<e.resources.length;i++)t.animations[e.resources[i].name]=e.resources[i],t.animationsIndex[e.id]=e.resources[i].name;else t.animations[e.name]=e.resource,t.animationsIndex[e.id]=e.name;t.animations=t.animations},s=function(e){e.off("change",t.onAssetChanged,t),e.on("change",t.onAssetChanged,t),e.off("remove",t.onAssetRemoved,t),e.on("remove",t.onAssetRemoved,t),e.resource?n(e):(e.once("load",n,t),t.enabled&&t.entity.enabled&&i.load(e))},r=0,a=e.length;r<a;r++){var o=i.get(e[r]);o?s(o):i.on("add:"+e[r],s)}},i.onAssetChanged=function(e,t,i,n){if("resource"===t||"resources"===t)if("resources"===t&&i&&0===i.length&&(i=null),i){var s=!1;if(i.length>1){if(n&&n.length>1)for(var r=0;r<n.length;r++)delete this.animations[n[r].name];else delete this.animations[e.name];s=!1;for(var a=0;a<i.length;a++)this.animations[i[a].name]=i[a],s||this.currAnim!==i[a].name||this.playing&&this.enabled&&this.entity.enabled&&(s=!0,this.play(i[a].name));s||(this._stopCurrentAnimation(),this.onSetAnimations())}else{if(n&&n.length>1)for(var o=0;o<n.length;o++)delete this.animations[n[o].name];this.animations[e.name]=i[0]||i,s=!1,this.currAnim===e.name&&this.playing&&this.enabled&&this.entity.enabled&&(s=!0,this.play(e.name)),s||(this._stopCurrentAnimation(),this.onSetAnimations())}this.animationsIndex[e.id]=e.name}else{if(n.length>1)for(var h=0;h<n.length;h++)delete this.animations[n[h].name],this.currAnim===n[h].name&&this._stopCurrentAnimation();else delete this.animations[e.name],this.currAnim===e.name&&this._stopCurrentAnimation();delete this.animationsIndex[e.id]}},i.onAssetRemoved=function(e){if(e.off("remove",this.onAssetRemoved,this),this.animations){if(e.resources.length>1)for(var t=0;t<e.resources.length;t++)delete this.animations[e.resources[t].name],this.currAnim===e.resources[t].name&&this._stopCurrentAnimation();else delete this.animations[e.name],this.currAnim===e.name&&this._stopCurrentAnimation();delete this.animationsIndex[e.id]}},i._stopCurrentAnimation=function(){if(this.currAnim=null,this.playing=!1,this.skeleton&&(this.skeleton.currentTime=0,this.skeleton.animation=null),this.animEvaluator){for(var e=0;e<this.animEvaluator.clips.length;++e)this.animEvaluator.clips[e].stop();this.animEvaluator.update(0),this.animEvaluator.removeClips()}},i.onEnable=function(){e.prototype.onEnable.call(this);var t=this.assets,i=this.system.app.assets;if(t)for(var n=0,s=t.length;n<s;n++){var r=t[n];r instanceof kd||(r=i.get(r)),r&&!r.resource&&i.load(r)}if(this.activate&&!this.currAnim){var a=Object.keys(this.animations);a.length>0&&this.play(a[0])}},i.onBeforeRemove=function(){for(var e=0;e<this.assets.length;e++){var t=this.assets[e];"number"==typeof t&&(t=this.system.app.assets.get(t)),t&&(t.off("change",this.onAssetChanged,this),t.off("remove",this.onAssetRemoved,this))}this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animEvaluator=null},i.update=function(e){if(this.blending&&(this.blend+=e*this.blendSpeed,this.blend>=1&&(this.blend=1)),this.playing){var t=this.skeleton;if(null!==t&&null!==this.model){if(this.blending)t.blend(this.fromSkel,this.toSkel,this.blend);else{var i=e*this.speed;t.addTime(i),(this.speed>0&&t._time===t.animation.duration&&!this.loop||this.speed<0&&0===t._time&&!this.loop)&&(this.playing=!1)}this.blending&&1===this.blend&&(t.animation=this.toSkel.animation),t.updateGraph()}}var n=this.animEvaluator;if(n){for(var s=0;s<n.clips.length;++s){var r=n.clips[s];r.speed=this.speed,this.playing?r.resume():r.pause()}this.blending&&n.clips.length>1&&(n.clips[1].blendWeight=this.blend),n.update(e)}this.blending&&1===this.blend&&(this.blending=!1)},Z(t,[{key:"animations",get:function(){return this._animations},set:function(e){this._animations=e,this.onSetAnimations()}},{key:"assets",get:function(){return this._assets},set:function(e){var t=this._assets;if(t&&t.length)for(var i=0;i<t.length;i++)if(t[i]){var n=this.system.app.assets.get(t[i]);if(n){n.off("change",this.onAssetChanged,this),n.off("remove",this.onAssetRemoved,this);var s=this.animationsIndex[n.id];this.currAnim===s&&this._stopCurrentAnimation(),delete this.animations[s],delete this.animationsIndex[n.id]}}this._assets=e;var r=e.map((function(e){return e instanceof kd?e.id:e}));this.loadAnimationAssets(r)}},{key:"currentTime",get:function(){if(this.skeleton)return this.skeleton._time;if(this.animEvaluator){var e=this.animEvaluator.clips;if(e.length>0)return e[e.length-1].time}return 0},set:function(e){if(this.skeleton&&(this.skeleton.currentTime=e,this.skeleton.addTime(0),this.skeleton.updateGraph()),this.animEvaluator)for(var t=this.animEvaluator.clips,i=0;i<t.length;++i)t[i].time=e}},{key:"duration",get:function(){return this.currAnim?this.animations[this.currAnim].duration:0}},{key:"loop",get:function(){return this._loop},set:function(e){if(this._loop=e,this.skeleton&&(this.skeleton.looping=e),this.animEvaluator)for(var t=0;t<this.animEvaluator.clips.length;++t)this.animEvaluator.clips[t].loop=e}}]),t}(gf),ip=function(){this.enabled=!0},np=["enabled"],sp=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="animation",i.ComponentType=tp,i.DataType=ip,i.schema=np,i.on("beforeremove",i.onBeforeRemove,ee(i)),i.app.systems.on("update",i.onUpdate,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){for(var s,r=ie(["activate","enabled","loop","speed","assets"]);!(s=r()).done;){var a=s.value;i.hasOwnProperty(a)&&(t[a]=i[a])}e.prototype.initializeComponentData.call(this,t,i,np)},i.cloneComponent=function(e,t){this.addComponent(t,{}),t.animation.assets=e.animation.assets.slice(),t.animation.speed=e.animation.speed,t.animation.loop=e.animation.loop,t.animation.activate=e.animation.activate,t.animation.enabled=e.animation.enabled;var i={},n=e.animation.animations;for(var s in n)n.hasOwnProperty(s)&&(i[s]=n[s]);t.animation.animations=i;var r={},a=e.animation.animationsIndex;for(var o in a)a.hasOwnProperty(o)&&(r[o]=a[o]);return t.animation.animationsIndex=r,t.animation},i.onBeforeRemove=function(e,t){t.onBeforeRemove()},i.onUpdate=function(e){var t=this.store;for(var i in t)if(t.hasOwnProperty(i)){var n=t[i];n.data.enabled&&n.entity.enabled&&n.entity.animation.update(e)}},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},t}(vf);gf._buildAccessors(tp.prototype,np);var rp=function(){function e(e,t,i,n,s){void 0===s&&(s=1),this._state=e,this._parent=t,this._name=i,Array.isArray(n)?(this._point=new ge(n[0],n[1]),this._pointLength=this._point.length()):(this._point=n,this._pointLength=n),this._speed=s,this._weightedSpeed=1,this._weight=1,this._animTrack=null}return Z(e,[{key:"parent",get:function(){return this._parent}},{key:"name",get:function(){return this._name}},{key:"path",get:function(){return this._parent?this._parent.path+"."+this._name:this._name}},{key:"point",get:function(){return this._point}},{key:"pointLength",get:function(){return this._pointLength}},{key:"weight",get:function(){return this._parent?this._parent.weight*this._weight:this._weight},set:function(e){this._weight=e}},{key:"normalizedWeight",get:function(){var e=this._state.totalWeight;return 0===e?0:this.weight/e}},{key:"speed",get:function(){return this._weightedSpeed*this._speed}},{key:"absoluteSpeed",get:function(){return Math.abs(this._speed)}},{key:"weightedSpeed",get:function(){return this._weightedSpeed},set:function(e){this._weightedSpeed=e}},{key:"animTrack",get:function(){return this._animTrack},set:function(e){this._animTrack=e}}]),e}(),ap=function(e){function t(t,i,n,s,r,a,o,h,l){var c;(c=e.call(this,t,i,n,s)||this)._parameters=r,c._parameterValues=new Array(r.length),c._children=[],c._findParameter=l,c._syncAnimations=!1!==o,c._pointCache={};for(var u=0;u<a.length;u++){var d=a[u];d.children?c._children.push(h(d.type,ee(c),null,n,1,d.parameter?[d.parameter]:d.parameters,d.children,h,l)):c._children.push(new rp(t,ee(c),d.name,d.point,d.speed))}return c}Q(t,e);var i=t.prototype;return i.getChild=function(e){for(var t=0;t<this._children.length;t++)if(this._children[t].name===e)return this._children[t];return null},i.updateParameterValues=function(){for(var e=!0,t=0;t<this._parameterValues.length;t++){var i=this._findParameter(this._parameters[t]).value;this._parameterValues[t]!==i&&(this._parameterValues[t]=i,e=!1)}return e},i.getNodeWeightedDuration=function(e){return this._children[e].animTrack.duration/this._children[e].speedMultiplier*this._children[e].weight},i.getNodeCount=function(){for(var e=0,i=0;i<this._children.length;i++){this._children[i].constructor===t?e+=this._children[i].getNodeCount():e++}return e},Z(t,[{key:"weight",get:function(){return this.calculateWeights(),this._parent?this._parent.weight*this._weight:this._weight}},{key:"syncAnimations",get:function(){return this._syncAnimations}}]),t}(rp),op=function(e){function t(t,i,n,s,r,a,o,h,l){return a.sort((function(e,t){return e.point-t.point})),e.call(this,t,i,n,s,r,a,o,h,l)||this}return Q(t,e),t.prototype.calculateWeights=function(){if(!this.updateParameterValues()){var e=0;this._children[0].weight=0;for(var t=0;t<this._children.length;t++){var i=this._children[t];if(t!==this._children.length-1){var n=this._children[t+1];if(i.point===n.point)i.weight=.5,n.weight=.5;else if(ce.between(this._parameterValues[0],i.point,n.point,!0)){var s=Math.abs(i.point-n.point),r=(s-Math.abs(i.point-this._parameterValues[0]))/s;i.weight=r,n.weight=1-r}else n.weight=0}this._syncAnimations&&(e+=i.animTrack.duration/i.absoluteSpeed*i.weight)}if(this._syncAnimations)for(var a=0;a<this._children.length;a++){var o=this._children[a];o.weightedSpeed=o.animTrack.duration/o.absoluteSpeed/e}}},t}(ap),hp=function(e){function t(){return e.apply(this,arguments)||this}Q(t,e);var i=t.prototype;return i.pointDistanceCache=function(e,t){var i=""+e+t;return this._pointCache[i]||(this._pointCache[i]=this._children[t].point.clone().sub(this._children[e].point)),this._pointCache[i]},i.calculateWeights=function(){var e;if(!this.updateParameterValues()){var i,n;(e=t._p).set.apply(e,this._parameterValues),i=0,n=0;for(var s=0;s<this._children.length;s++){var r=this._children[s],a=r.point;t._pip.set(t._p.x,t._p.y).sub(a);for(var o=Number.MAX_VALUE,h=0;h<this._children.length;h++)if(s!==h){var l=this.pointDistanceCache(s,h),c=ce.clamp(1-t._pip.dot(l)/l.lengthSq(),0,1);c<o&&(o=c)}r.weight=o,i+=o,this._syncAnimations&&(n+=r.animTrack.duration/r.absoluteSpeed*r.weight)}for(var u=0;u<this._children.length;u++){var d=this._children[u];d.weight=d._weight/i,this._syncAnimations&&(d.weightedSpeed=d.animTrack.duration/d.absoluteSpeed/n)}}},t}(ap);hp._p=new ge,hp._pip=new ge;var lp=function(e){function t(){return e.apply(this,arguments)||this}Q(t,e);var i=t.prototype;return i.pointCache=function(e,t){var i=""+e+t;return this._pointCache[i]||(this._pointCache[i]=new ge((this._children[t].pointLength-this._children[e].pointLength)/((this._children[t].pointLength+this._children[e].pointLength)/2),2*ge.angleRad(this._children[e].point,this._children[t].point))),this._pointCache[i]},i.calculateWeights=function(){var e;if(!this.updateParameterValues()){var i,n;(e=t._p).set.apply(e,this._parameterValues);var s=t._p.length();i=0,n=0;for(var r=0;r<this._children.length;r++){for(var a=this._children[r],o=a.point,h=a.pointLength,l=Number.MAX_VALUE,c=0;c<this._children.length;c++)if(r!==c){var u=this.pointCache(r,c),d=this._children[c].pointLength;t._pip.set((s-h)/((d+h)/2),2*ge.angleRad(o,t._p));var f=ce.clamp(1-Math.abs(t._pip.dot(u)/u.lengthSq()),0,1);f<l&&(l=f)}a.weight=l,i+=l,this._syncAnimations&&(n+=a.animTrack.duration/a.absoluteSpeed*a.weight)}for(var p=0;p<this._children.length;p++){var m=this._children[p];if(m.weight=m._weight/i,this._syncAnimations){var _=m.animTrack.duration/n*i;m.weightedSpeed=m.absoluteSpeed*_}}}},t}(ap);lp._p=new ge,lp._pip=new ge;var cp=function(e){function t(){return e.apply(this,arguments)||this}return Q(t,e),t.prototype.calculateWeights=function(){if(!this.updateParameterValues()){for(var e=0,t=0,i=0;i<this._children.length;i++)if(e+=Math.max(this._parameterValues[i],0),this._syncAnimations){var n=this._children[i];t+=n.animTrack.duration/n.absoluteSpeed*n.weight}for(var s=0;s<this._children.length;s++){var r=this._children[s],a=Math.max(this._parameterValues[s],0);e?(r.weight=a/e,this._syncAnimations&&(r.weightedSpeed=r.animTrack.duration/r.absoluteSpeed/t)):(r.weight=0,this._syncAnimations&&(r.weightedSpeed=0))}}},t}(ap),up=function(){function e(e,t,i,n,s){void 0===i&&(i=1),void 0===n&&(n=!0),this._animations={},this._animationList=[],this._controller=e,this._name=t,this._speed=i,this._loop=n,this._hasAnimations=!1,this._blendTree=s?this._createTree(s.type,this,null,t,1,s.parameter?[s.parameter]:s.parameters,s.children,s.syncAnimations,this._createTree,this._controller.findParameter):new rp(this,null,t,1,i)}var t=e.prototype;return t._createTree=function(e,t,i,n,s,r,a,o,h,l){switch(e){case"1D":return new op(t,i,n,s,r,a,o,h,l);case Uf:return new hp(t,i,n,s,r,a,o,h,l);case Nf:return new lp(t,i,n,s,r,a,o,h,l);case zf:return new cp(t,i,n,s,r,a,o,h,l)}},t._getNodeFromPath=function(e){for(var t=this._blendTree,i=1;i<e.length;i++)t=t.getChild(e[i]);return t},t.addAnimation=function(e,t){var i=e.join("."),n=this._animationList.findIndex((function(e){return e.path===i}));if(n>=0)this._animationList[n].animTrack=t;else{var s=this._getNodeFromPath(e);s.animTrack=t,this._animationList.push(s)}this._updateHasAnimations()},t._updateHasAnimations=function(){this._hasAnimations=this._animationList.length>0&&this._animationList.every((function(e){return e.animTrack&&e.animTrack!==$f.EMPTY}))},Z(e,[{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!==rp?this._blendTree.getNodeCount():1}},{key:"playable",get:function(){return-1!==Wf.indexOf(this.name)||this.animations.length===this.nodeCount}},{key:"looping",get:function(){if(this.animations.length>0){var e=this.name+"."+this.animations[0].animTrack.name,t=this._controller.animEvaluator.findClip(e);if(t)return t.loop}return!1}},{key:"totalWeight",get:function(){for(var e=0,t=0;t<this.animations.length;t++)e+=this.animations[t].weight;return e}},{key:"timelineDuration",get:function(){for(var e=0,t=0;t<this.animations.length;t++){var i=this.animations[t];i.animTrack.duration>e&&(e=i.animTrack.duration)}return e}}]),e}(),dp=function(){function e(e){var t=e.from,i=e.to,n=e.time,s=void 0===n?0:n,r=e.priority,a=void 0===r?0:r,o=e.conditions,h=void 0===o?[]:o,l=e.exitTime,c=void 0===l?null:l,u=e.transitionOffset,d=void 0===u?null:u,f=e.interruptionSource,p=void 0===f?wf:f;this._from=t,this._to=i,this._time=s,this._priority=a,this._conditions=h,this._exitTime=c,this._transitionOffset=d,this._interruptionSource=p}return Z(e,[{key:"from",get:function(){return this._from}},{key:"to",get:function(){return this._to},set:function(e){this._to=e}},{key:"time",get:function(){return this._time}},{key:"priority",get:function(){return this._priority}},{key:"conditions",get:function(){return this._conditions}},{key:"exitTime",get:function(){return this._exitTime}},{key:"transitionOffset",get:function(){return this._transitionOffset}},{key:"interruptionSource",get:function(){return this._interruptionSource}},{key:"hasExitTime",get:function(){return!!this.exitTime}}]),e}(),fp=function(){function e(e,t,i,n,s,r,a){var o=this;this.findParameter=function(e){return o._findParameter(e)},this._animEvaluator=e,this._states={},this._stateNames=[],this._eventHandler=s,this._findParameter=r,this._consumeTrigger=a;for(var h=0;h<t.length;h++)this._states[t[h].name]=new up(this,t[h].name,t[h].speed,t[h].loop,t[h].blendTree),this._stateNames.push(t[h].name);this._transitions=i.map((function(e){return new dp($({},e))})),this._findTransitionsFromStateCache={},this._findTransitionsBetweenStatesCache={},this._previousStateName=null,this._activeStateName=Vf,this._activeStateDuration=0,this._activeStateDurationDirty=!0,this._playing=!1,this._activate=n,this._currTransitionTime=1,this._totalTransitionTime=1,this._isTransitioning=!1,this._transitionInterruptionSource=wf,this._transitionPreviousStates=[],this._timeInState=0,this._timeInStateBefore=0}var t=e.prototype;return t.assignMask=function(e){return this._animEvaluator.assignMask(e)},t._findState=function(e){return this._states[e]},t._getActiveStateProgressForTime=function(e){if(this.activeStateName===Vf||this.activeStateName===Gf||this.activeStateName===Hf)return 1;var t=this._animEvaluator.findClip(this.activeStateAnimations[0].name);return t?t.progressForTime(e):null},t._findTransitionsFromState=function(e){var t=this._findTransitionsFromStateCache[e];return t||(t=this._transitions.filter((function(t){return t.from===e})),bc(t),this._findTransitionsFromStateCache[e]=t),t},t._findTransitionsBetweenStates=function(e,t){var i=this._findTransitionsBetweenStatesCache[e+"->"+t];return i||(i=this._transitions.filter((function(i){return i.from===e&&i.to===t})),bc(i),this._findTransitionsBetweenStatesCache[e+"->"+t]=i),i},t._transitionHasConditionsMet=function(e){for(var t=e.conditions,i=0;i<t.length;i++){var n=t[i],s=this._findParameter(n.parameterName);switch(n.predicate){case Mf:if(!(s.value>n.value))return!1;break;case Pf:if(!(s.value<n.value))return!1;break;case Rf:if(!(s.value>=n.value))return!1;break;case If:if(!(s.value<=n.value))return!1;break;case Lf:if(s.value!==n.value)return!1;break;case Df:if(s.value===n.value)return!1}}return!0},t._findTransition=function(e,t){var i=this,n=[];if(e&&t)n=n.concat(this._findTransitionsBetweenStates(e,t));else if(this._isTransitioning)switch(this._transitionInterruptionSource){case Tf:n=(n=n.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(Hf));break;case Af:n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Hf));break;case Cf:n=(n=(n=n.concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Hf));break;case Ef:n=(n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(this._previousStateName))).concat(this._findTransitionsFromState(Hf))}else n=(n=n.concat(this._findTransitionsFromState(this._activeStateName))).concat(this._findTransitionsFromState(Hf));if(n=n.filter((function(e){if(e.to===i.activeStateName)return!1;if(e.hasExitTime){var t=i._getActiveStateProgressForTime(i._timeInStateBefore),n=i._getActiveStateProgressForTime(i._timeInState);if(e.exitTime<1&&i.activeState.loop&&(t-=Math.floor(t),n-=Math.floor(n)),n===t){if(n!==e.exitTime)return null}else if(!(e.exitTime>t&&e.exitTime<=n))return null}return i._transitionHasConditionsMet(e)})),n.length>0){var s=n[0];if(s.to===Gf){var r=this._findTransitionsFromState(Vf)[0];s.to=r.to}return s}return null},t.updateStateFromTransition=function(e){var t,i,n;this.previousState=e.from?this.activeStateName:null,this.activeState=e.to,this._activeStateDurationDirty=!0;for(var s=0;s<e.conditions.length;s++){var r=e.conditions[s];this._findParameter(r.parameterName).type===Bf&&this._consumeTrigger(r.parameterName)}if(this.previousState){this._isTransitioning||(this._transitionPreviousStates=[]),this._transitionPreviousStates.push({name:this._previousStateName,weight:1});for(var a=Math.min(0!==this._totalTransitionTime?this._currTransitionTime/this._totalTransitionTime:1,1),o=0;o<this._transitionPreviousStates.length;o++){this._isTransitioning?o!==this._transitionPreviousStates.length-1?this._transitionPreviousStates[o].weight*=1-a:this._transitionPreviousStates[o].weight=a:this._transitionPreviousStates[o].weight=1,t=this._findState(this._transitionPreviousStates[o].name);for(var h=0;h<t.animations.length;h++)i=t.animations[h],(n=this._animEvaluator.findClip(i.name+".previous."+o))||((n=this._animEvaluator.findClip(i.name)).name=i.name+".previous."+o),o!==this._transitionPreviousStates.length-1&&n.pause()}}this._isTransitioning=!0,this._totalTransitionTime=e.time,this._currTransitionTime=0,this._transitionInterruptionSource=e.interruptionSource;var l=this.activeState,c=e.transitionOffset&&e.transitionOffset>0&&e.transitionOffset<1,u=0,d=0;if(c){var f=l.timelineDuration*e.transitionOffset;u=f,d=f}this._timeInState=u,this._timeInStateBefore=d;for(var p=0;p<l.animations.length;p++){if(n=this._animEvaluator.findClip(l.animations[p].name))n.reset();else{var m=Number.isFinite(l.animations[p].speed)?l.animations[p].speed:l.speed;(n=new bf(l.animations[p].animTrack,this._timeInState,m,!0,l.loop,this._eventHandler)).name=l.animations[p].name,this._animEvaluator.addClip(n)}if(e.time>0?n.blendWeight=0:n.blendWeight=l.animations[p].normalizedWeight,n.play(),c)n.time=l.timelineDuration*e.transitionOffset;else{var _=l.speed>=0?0:this.activeStateDuration;n.time=_}}},t._transitionToState=function(e){if(this._findState(e)){var t=this._findTransition(this._activeStateName,e);t||(this._animEvaluator.removeClips(),t=new dp({from:null,to:e})),this.updateStateFromTransition(t)}},t.assignAnimation=function(e,t,i,n){var s=e.split("."),r=this._findState(s[0]);r||(r=new up(this,s[0],i),this._states[s[0]]=r,this._stateNames.push(s[0])),r.addAnimation(s,t),this._animEvaluator.updateClipTrack(r.name,t),void 0!==i&&(r.speed=i),void 0!==n&&(r.loop=n),!this._playing&&this._activate&&this.playable&&this.play(),this._activeStateDurationDirty=!0},t.removeNodeAnimations=function(e){if(-1!==Wf.indexOf(e))return!1;var t=this._findState(e);return!!t&&(t.animations=[],!0)},t.play=function(e){e&&this._transitionToState(e),this._playing=!0},t.pause=function(){this._playing=!1},t.reset=function(){this._previousStateName=null,this._activeStateName=Vf,this._playing=!1,this._currTransitionTime=1,this._totalTransitionTime=1,this._isTransitioning=!1,this._timeInState=0,this._timeInStateBefore=0,this._animEvaluator.removeClips()},t.rebind=function(){this._animEvaluator.rebind()},t.update=function(e){if(this._playing){var t,i,n;(this.activeState.loop||this._timeInState<this.activeStateDuration)&&(this._timeInStateBefore=this._timeInState,this._timeInState+=e*this.activeState.speed,!this.activeState.loop&&this._timeInState>this.activeStateDuration&&(this._timeInState=this.activeStateDuration,e=this.activeStateDuration-this._timeInStateBefore));var s=this._findTransition(this._activeStateName);if(s&&this.updateStateFromTransition(s),this._isTransitioning)if(this._currTransitionTime+=e,this._currTransitionTime<=this._totalTransitionTime){for(var r=0!==this._totalTransitionTime?this._currTransitionTime/this._totalTransitionTime:1,a=0;a<this._transitionPreviousStates.length;a++){t=this._findState(this._transitionPreviousStates[a].name);for(var o=this._transitionPreviousStates[a].weight,h=0;h<t.animations.length;h++)i=t.animations[h],(n=this._animEvaluator.findClip(i.name+".previous."+a))&&(n.blendWeight=(1-r)*i.normalizedWeight*o)}t=this.activeState;for(var l=0;l<t.animations.length;l++)i=t.animations[l],this._animEvaluator.findClip(i.name).blendWeight=r*i.normalizedWeight}else{this._isTransitioning=!1;for(var c=this.activeStateAnimations.length,u=this._animEvaluator.clips.length,d=0;d<u-c;d++)this._animEvaluator.removeClip(0);this._transitionPreviousStates=[],t=this.activeState;for(var f=0;f<t.animations.length;f++)i=t.animations[f],(n=this._animEvaluator.findClip(i.name))&&(n.blendWeight=i.normalizedWeight)}else if(this.activeState._blendTree.constructor!==rp){t=this.activeState;for(var p=0;p<t.animations.length;p++)i=t.animations[p],(n=this._animEvaluator.findClip(i.name))&&(n.blendWeight=i.normalizedWeight,i.parent.syncAnimations&&(n.speed=i.speed))}this._animEvaluator.update(e,this.activeState.hasAnimations)}},Z(e,[{key:"animEvaluator",get:function(){return this._animEvaluator}},{key:"activeState",get:function(){return this._findState(this._activeStateName)},set:function(e){this._activeStateName=e}},{key:"activeStateName",get:function(){return this._activeStateName}},{key:"activeStateAnimations",get:function(){return this.activeState.animations}},{key:"previousState",get:function(){return this._findState(this._previousStateName)},set:function(e){this._previousStateName=e}},{key:"previousStateName",get:function(){return this._previousStateName}},{key:"playable",get:function(){for(var e=!0,t=0;t<this._stateNames.length;t++)this._states[this._stateNames[t]].playable||(e=!1);return e}},{key:"playing",get:function(){return this._playing},set:function(e){this._playing=e}},{key:"activeStateProgress",get:function(){return this._getActiveStateProgressForTime(this._timeInState)}},{key:"activeStateDuration",get:function(){if(this._activeStateDurationDirty){for(var e=0,t=0;t<this.activeStateAnimations.length;t++){var i=this._animEvaluator.findClip(this.activeStateAnimations[t].name);i&&(e=Math.max(e,i.track.duration))}this._activeStateDuration=e,this._activeStateDurationDirty=!1}return this._activeStateDuration}},{key:"activeStateCurrentTime",get:function(){return this._timeInState},set:function(e){this._timeInStateBefore=e,this._timeInState=e;for(var t=0;t<this.activeStateAnimations.length;t++){var i=this.animEvaluator.findClip(this.activeStateAnimations[t].name);i&&(i.time=e)}}},{key:"transitioning",get:function(){return this._isTransitioning}},{key:"transitionProgress",get:function(){return this._currTransitionTime/this._totalTransitionTime}},{key:"states",get:function(){return this._stateNames}}]),e}(),pp=new ge,mp=new me,_p=new ve,gp=new ue,vp=new Ae,yp=function(e){function t(t,i,n,s,r){var a;return(a=e.call(this,i)||this).animComponent=t,a._mask=s,a.layerName=n,a.layerIndex=r,a}Q(t,e),t._packFloat=function(e){return e[0]},t._packBoolean=function(e){return!!e[0]},t._packVec2=function(e){return pp.x=e[0],pp.y=e[1],pp},t._packVec3=function(e){return mp.x=e[0],mp.y=e[1],mp.z=e[2],mp},t._packVec4=function(e){return _p.x=e[0],_p.y=e[1],_p.z=e[2],_p.w=e[3],_p},t._packColor=function(e){return gp.r=e[0],gp.g=e[1],gp.b=e[2],gp.a=e[3],gp},t._packQuat=function(e){return vp.x=e[0],vp.y=e[1],vp.z=e[2],vp.w=e[3],vp};var i=t.prototype;return i.resolve=function(e){var t,i,n,s=Qf.encode(e.entityPath,e.component,e.propertyPath),r=this.targetCache[s];if(r)return r;switch(e.component){case"entity":t=this._getEntityFromHierarchy(e.entityPath),n=Qf.encode(t.path,"entity",e.propertyPath),i=t;break;case"graph":if(!(i=this.findNode(e)))return null;n=Qf.encode(i.path,"graph",e.propertyPath);break;default:if(!(i=(t=this._getEntityFromHierarchy(e.entityPath)).findComponent(e.component)))return null;n=Qf.encode(t.path,e.component,e.propertyPath)}return r=this._createAnimTargetForProperty(i,e.propertyPath,n),this.targetCache[s]=r,r},i.update=function(e){var t=this.activeNodes;if(t)for(var i=0;i<t.length;i++)t[i]._dirtifyLocal()},i._getEntityFromHierarchy=function(e){if(!this.animComponent.entity.name===e[0])return null;var t=this.animComponent.entity;return 1===e.length?t:t._parent.findByPath(e)},i._resolvePath=function(e,t,i){for(var n=t.length-(i?0:1),s=0;s<n;s++)e=e[t[s]];return e},i._setter=function(e,t,i){var n=this._resolvePath(e,t),s=t[t.length-1],r="set"+s.substring(0,1).toUpperCase()+s.substring(1);if(n[r]){var a=n["get"+s.substring(0,1).toUpperCase()+s.substring(1)].bind(n)();a=[a.x,a.y,a.z,a.w];var o=n[r].bind(n);return{set:function(e){o(i(e))},get:function(){return a}}}var h=n[s];if("object"==typeof h&&h.hasOwnProperty("copy"))return function(e){h.copy(i(e))};if(-1!==[ge,me,ve,ue,Ae].indexOf(n.constructor)&&t.length>1){var l=t.length>2?this._resolvePath(e,t.slice(0,-1)):e,c=t[t.length-2];return function(e){n[s]=i(e),l[c]=n}}return function(e){n[s]=i(e)}},i._createAnimTargetForProperty=function(e,i,n){if(this.handlers&&i[0].startsWith("weight."))return this.handlers.weight(e,i[0].replace("weight.",""));if(this.handlers&&"material"===i[0]&&2===i.length){var s=i[1];if(s.endsWith("Map"))return this.handlers.materialTexture(e,s)}var r,a,o,h=this._resolvePath(e,i,!0);if(void 0===h)return null;if("number"==typeof h)r=this._setter(e,i,t._packFloat),a="vector",o=1;else if("boolean"==typeof h)r=this._setter(e,i,t._packBoolean),a="vector",o=1;else if("object"==typeof h)switch(h.constructor){case ge:r=this._setter(e,i,t._packVec2),a="vector",o=2;break;case me:r=this._setter(e,i,t._packVec3),a="vector",o=3;break;case ve:r=this._setter(e,i,t._packVec4),a="vector",o=4;break;case ue:r=this._setter(e,i,t._packColor),a="vector",o=4;break;case Ae:r=this._setter(e,i,t._packQuat),a="quaternion",o=4;break;default:return null}return-1!==i.indexOf("material")?new Jf((function(t){r(t),e.material.update()}),a,o,n):new Jf(r,a,o,n)},i.rebind=function(){this.targetCache={},this.animComponent.rootBone?this.graph=this.animComponent.rootBone:this.graph=this.animComponent.entity;var e={};!function t(i){e[i.name]=i;for(var n=0;n<i.children.length;++n)t(i.children[n])}(this.graph),this.nodes=e},t}(ep),xp=function(){function e(e,t,i,n,s,r){void 0===n&&(n=1),void 0===s&&(s=Xf),void 0===r&&(r=!0),this._name=e,this._controller=t,this._component=i,this._weight=n,this._blendType=s,this._normalizedWeight=r,this._mask=null,this._blendTime=0,this._blendTimeElapsed=0,this._startingWeight=0,this._targetWeight=0}var t=e.prototype;return t.play=function(e){this._controller.play(e)},t.pause=function(){this._controller.pause()},t.reset=function(){this._controller.reset()},t.rebind=function(){this._controller.rebind()},t.update=function(e){this._blendTime&&(this._blendTimeElapsed<this._blendTime?(this.weight=ce.lerp(this._startingWeight,this._targetWeight,this._blendTimeElapsed/this._blendTime),this._blendTimeElapsed+=e):(this.weight=this._targetWeight,this._blendTime=0,this._blendTimeElapsed=0,this._startingWeight=0,this._targetWeight=0)),this._controller.update(e)},t.blendToWeight=function(e,t){this._startingWeight=this.weight,this._targetWeight=e,this._blendTime=Math.max(0,t),this._blendTimeElapsed=0},t.assignMask=function(e){this._controller.assignMask(e)&&this._component.rebind(),this._mask=e},t.assignAnimation=function(e,t,i,n){t instanceof $f&&(this._controller.assignAnimation(e,t,i,n),0===this._controller._transitions.length&&this._controller._transitions.push(new dp({from:"START",to:e})),this._component.activate&&this._component.playable&&(this._component.playing=!0))},t.removeNodeAnimations=function(e){this._controller.removeNodeAnimations(e)&&(this._component.playing=!1)},t.getAnimationAsset=function(e){return this._component.animationAssets[this.name+":"+e]},t.transition=function(e,t,i){void 0===t&&(t=0),void 0===i&&(i=null),this._controller.updateStateFromTransition(new dp({from:this._controller.activeStateName,to:e,time:t,transitionOffset:i}))},Z(e,[{key:"name",get:function(){return this._name}},{key:"playing",get:function(){return this._controller.playing},set:function(e){this._controller.playing=e}},{key:"playable",get:function(){return this._controller.playable}},{key:"activeState",get:function(){return this._controller.activeStateName}},{key:"previousState",get:function(){return this._controller.previousStateName}},{key:"activeStateProgress",get:function(){return this._controller.activeStateProgress}},{key:"activeStateDuration",get:function(){return this._controller.activeStateDuration}},{key:"activeStateCurrentTime",get:function(){return this._controller.activeStateCurrentTime},set:function(e){var t=this._controller,i=t.playing;t.playing=!0,t.activeStateCurrentTime=e,i||t.update(0),t.playing=i}},{key:"transitioning",get:function(){return this._controller.transitioning}},{key:"transitionProgress",get:function(){return this.transitioning?this._controller.transitionProgress:null}},{key:"states",get:function(){return this._controller.states}},{key:"weight",get:function(){return this._weight},set:function(e){this._weight=e,this._component.dirtifyTargets()}},{key:"blendType",get:function(){return this._blendType},set:function(e){e!==this._blendType&&(this._blendType=e,this._controller.normalizeWeights&&this._component.rebind())}},{key:"mask",get:function(){return this._mask},set:function(e){this._controller.assignMask(e)&&this._component.rebind(),this._mask=e}}]),e}(),Sp=function(){function e(e){if(this._layers=[],this._parameters={},Array.isArray(e.layers))this._layers=e.layers;else for(var t in e.layers){for(var i=e.layers[t],n={name:i.name,blendType:i.blendType,weight:i.weight,states:[],transitions:[]},s=0;s<i.states.length;s++)n.states.push(e.states[i.states[s]]);for(var r=0;r<i.transitions.length;r++){var a=e.transitions[i.transitions[r]];if(a.conditions&&!Array.isArray(a.conditions)){for(var o=Object.keys(a.conditions),h=[],l=0;l<o.length;l++){var c=a.conditions[o[l]];c.parameterName&&h.push(c)}a.conditions=h}Number.isInteger(a.from)&&(a.from=e.states[a.from].name),Number.isInteger(a.to)&&(a.to=e.states[a.to].name),n.transitions.push(a)}this._layers.push(n)}for(var u in e.parameters){var d=e.parameters[u];this._parameters[d.name]={type:d.type,value:d.value}}}return Z(e,[{key:"parameters",get:function(){return Object.assign({},this._parameters)}},{key:"layers",get:function(){return this._layers}}]),e}(),bp=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this).findParameter=function(e){return n._parameters[e]},n.consumeTrigger=function(e){n._consumedTriggers.add(e)},n._stateGraphAsset=null,n._animationAssets={},n._speed=1,n._activate=!0,n._playing=!1,n._rootBone=null,n._stateGraph=null,n._layers=[],n._layerIndices={},n._parameters={},n._targets={},n._consumedTriggers=new Set,n._normalizeWeights=!1,n}Q(t,e);var i=t.prototype;return i._onStateGraphAssetChangeEvent=function(e){var t=this.animationAssets,i=this.layers.map((function(e){return e.mask}));this.removeStateGraph(),this._stateGraph=new Sp(e._data),this.loadStateGraph(this._stateGraph),this.animationAssets=t,this.loadAnimationAssets(),this.layers.forEach((function(e,t){e.mask=i[t]})),this.rebind()},i.dirtifyTargets=function(){for(var e=Object.values(this._targets),t=0;t<e.length;t++)e[t].dirty=!0},i._addLayer=function(e){var t,i=e.name,n=e.states,s=e.transitions,r=e.weight,a=e.mask,o=e.blendType;t=this.rootBone?this.rootBone:this.entity;var h=this._layers.length,l=new yp(this,t,i,a,h),c=new Kf(l),u=new fp(c,n,s,this._activate,this,this.findParameter,this.consumeTrigger);return this._layers.push(new xp(i,u,this,r,o)),this._layerIndices[i]=h,this._layers[h]},i.addLayer=function(e,t,i,n){var s=this.findAnimationLayer(e);if(s)return s;return this._addLayer({name:e,states:[{name:"START",speed:1}],transitions:[],weight:t,mask:i,blendType:n})},i._assignParameters=function(e){this._parameters={};for(var t=Object.keys(e.parameters),i=0;i<t.length;i++){var n=t[i];this._parameters[n]={type:e.parameters[n].type,value:e.parameters[n].value}}},i.loadStateGraph=function(e){this._stateGraph=e,this._assignParameters(e),this._layers=[];for(var t=!1,i=0;i<e.layers.length;i++){var n=e.layers[i];this._addLayer.bind(this)($({},n)),n.states.some((function(e){return e.blendTree}))&&(t=!0)}t||this.setupAnimationAssets()},i.setupAnimationAssets=function(){for(var e=0;e<this._layers.length;e++)for(var t=this._layers[e],i=t.name,n=0;n<t.states.length;n++){var s=t.states[n];if(-1===Wf.indexOf(s)){var r=i+":"+s;this._animationAssets[r]||(this._animationAssets[r]={asset:null})}}this.loadAnimationAssets()},i.loadAnimationAssets=function(){for(var e=0;e<this._layers.length;e++)for(var t=this._layers[e],i=0;i<t.states.length;i++){var n=t.states[i];if(-1===Wf.indexOf(n)){var s=this._animationAssets[t.name+":"+n];if(s&&s.asset){var r=s.asset,a=this.system.app.assets.get(r);a&&(a.resource?this.onAnimationAssetLoaded(t.name,n,a):(a.once("load",function(e,t){return function(i){this.onAnimationAssetLoaded(e,t,i)}.bind(this)}.bind(this)(t.name,n)),this.system.app.assets.load(a)))}else this.findAnimationLayer(t.name).assignAnimation(n,$f.EMPTY)}}},i.onAnimationAssetLoaded=function(e,t,i){this.findAnimationLayer(e).assignAnimation(t,i.resource)},i.removeStateGraph=function(){this._stateGraph=null,this._stateGraphAsset=null,this._animationAssets={},this._layers=[],this._layerIndices={},this._parameters={},this._playing=!1,this.unbind(),this._targets={}},i.reset=function(){this._assignParameters(this._stateGraph);for(var e=0;e<this._layers.length;e++){var t=this._layers[e].playing;this._layers[e].reset(),this._layers[e].playing=t}},i.unbind=function(){var e=this;this._normalizeWeights||Object.keys(this._targets).forEach((function(t){e._targets[t].unbind()}))},i.rebind=function(){this._targets={};for(var e=0;e<this._layers.length;e++)this._layers[e].rebind()},i.findAnimationLayer=function(e){var t=this._layerIndices[e];return this._layers[t]||null},i.addAnimationState=function(e,t,i,n,s){void 0===i&&(i=1),void 0===n&&(n=!0),void 0===s&&(s="Base"),this._stateGraph||this.loadStateGraph(new Sp({layers:[{name:s,states:[{name:"START",speed:1},{name:e,speed:i,loop:n,defaultState:!0}],transitions:[{from:"START",to:e}]}],parameters:{}}));var r,a=this.findAnimationLayer(s);a?a.assignAnimation(e,t,i,n):null==(r=this.addLayer(s))||r.assignAnimation(e,t,i,n)},i.assignAnimation=function(e,t,i,n,s){if(void 0===n&&(n=1),void 0===s&&(s=!0),!this._stateGraph&&-1===e.indexOf("."))return this.loadStateGraph(new Sp({layers:[{name:"Base",states:[{name:"START",speed:1},{name:e,speed:n,loop:s,defaultState:!0}],transitions:[{from:"START",to:e}]}],parameters:{}})),void this.baseLayer.assignAnimation(e,t);var r=i?this.findAnimationLayer(i):this.baseLayer;r&&r.assignAnimation(e,t,n,s)},i.removeNodeAnimations=function(e,t){var i=t?this.findAnimationLayer(t):this.baseLayer;i&&i.removeNodeAnimations(e)},i.getParameterValue=function(e,t){var i=this._parameters[e];if(i&&i.type===t)return i.value},i.setParameterValue=function(e,t,i){var n=this._parameters[e];n&&n.type===t&&(n.value=i)},i.getFloat=function(e){return this.getParameterValue(e,kf)},i.setFloat=function(e,t){this.setParameterValue(e,kf,t)},i.getInteger=function(e){return this.getParameterValue(e,Of)},i.setInteger=function(e,t){"number"==typeof t&&t%1==0&&this.setParameterValue(e,Of,t)},i.getBoolean=function(e){return this.getParameterValue(e,Ff)},i.setBoolean=function(e,t){this.setParameterValue(e,Ff,!!t)},i.getTrigger=function(e){return this.getParameterValue(e,Bf)},i.setTrigger=function(e,t){void 0===t&&(t=!1),this.setParameterValue(e,Bf,!0),t&&this._consumedTriggers.add(e)},i.resetTrigger=function(e){this.setParameterValue(e,Bf,!1)},i.onBeforeRemove=function(){Number.isFinite(this._stateGraphAsset)&&this.system.app.assets.get(this._stateGraphAsset).off("change",this._onStateGraphAssetChangeEvent,this)},i.update=function(e){for(var t=this,i=0;i<this.layers.length;i++)this.layers[i].update(e*this.speed);this._consumedTriggers.forEach((function(e){t.parameters[e].value=!1})),this._consumedTriggers.clear()},i.resolveDuplicatedEntityReferenceProperties=function(e,t){e.rootBone&&t[e.rootBone.getGuid()]?this.rootBone=t[e.rootBone.getGuid()]:this.rebind()},Z(t,[{key:"stateGraphAsset",get:function(){return this._stateGraphAsset},set:function(e){var t=this;if(null!==e){var i,n;if(this._stateGraphAsset)this.system.app.assets.get(this._stateGraphAsset).off("change",this._onStateGraphAssetChangeEvent,this);e instanceof kd?(i=e.id,(n=this.system.app.assets.get(i))||(this.system.app.assets.add(e),n=this.system.app.assets.get(i))):(i=e,n=this.system.app.assets.get(i)),n&&this._stateGraphAsset!==i&&(n.resource?(this._stateGraph=n.resource,this.loadStateGraph(this._stateGraph),n.on("change",this._onStateGraphAssetChangeEvent,this)):(n.once("load",(function(e){t._stateGraph=e.resource,t.loadStateGraph(t._stateGraph)})),n.on("change",this._onStateGraphAssetChangeEvent,this),this.system.app.assets.load(n)),this._stateGraphAsset=i)}else this.removeStateGraph()}},{key:"normalizeWeights",get:function(){return this._normalizeWeights},set:function(e){this._normalizeWeights=e,this.unbind()}},{key:"animationAssets",get:function(){return this._animationAssets},set:function(e){this._animationAssets=e,this.loadAnimationAssets()}},{key:"speed",get:function(){return this._speed},set:function(e){this._speed=e}},{key:"activate",get:function(){return this._activate},set:function(e){this._activate=e}},{key:"playing",get:function(){return this._playing},set:function(e){this._playing=e}},{key:"rootBone",get:function(){return this._rootBone},set:function(e){if("string"==typeof e){var t=this.entity.root.findByGuid(e);this._rootBone=t}else this._rootBone=e instanceof Zd?e:null;this.rebind()}},{key:"stateGraph",get:function(){return this._stateGraph},set:function(e){this._stateGraph=e}},{key:"layers",get:function(){return this._layers}},{key:"layerIndices",get:function(){return this._layerIndices},set:function(e){this._layerIndices=e}},{key:"parameters",get:function(){return this._parameters},set:function(e){this._parameters=e}},{key:"targets",get:function(){return this._targets},set:function(e){this._targets=e}},{key:"playable",get:function(){for(var e=0;e<this._layers.length;e++)if(!this._layers[e].playable)return!1;return!0}},{key:"baseLayer",get:function(){return this._layers.length>0?this._layers[0]:null}}]),t}(gf),wp=function(){this.enabled=!0},Tp=["enabled"],Ap=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="anim",i.ComponentType=bp,i.DataType=wp,i.schema=Tp,i.on("beforeremove",i.onBeforeRemove,ee(i)),i.app.systems.on("animationUpdate",i.onAnimationUpdate,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){var s=this;e.prototype.initializeComponentData.call(this,t,i,Tp);var r=["animationAssets","stateGraph","layers","masks"];Object.keys(i).forEach((function(e){r.includes(e)||(t[e]=i[e])})),i.stateGraph&&(t.stateGraph=i.stateGraph,t.loadStateGraph(t.stateGraph)),i.layers?i.layers.forEach((function(e,i){e._controller.states.forEach((function(n){e._controller._states[n]._animationList.forEach((function(n){if(n.animTrack&&n.animTrack!==$f.EMPTY)t.layers[i].assignAnimation(n.name,n.animTrack);else{var r=s.app.assets.get(e._component._animationAssets[e.name+":"+n.name].asset);r&&!r.loaded&&r.once("load",(function(){t.layers[i].assignAnimation(n.name,r.resource)}))}}))}))})):i.animationAssets&&(t.animationAssets=Object.assign(t.animationAssets,i.animationAssets)),i.masks&&Object.keys(i.masks).forEach((function(e){if(t.layers[e]){var n=i.masks[e].mask,s={};Object.keys(n).forEach((function(e){s[decodeURI(e)]=n[e]})),t.layers[e].mask=s}}))},i.onAnimationUpdate=function(e){var t=this.store;for(var i in t)if(t.hasOwnProperty(i)){var n=t[i].entity.anim;n.data.enabled&&n.entity.enabled&&n.playing&&n.update(e)}},i.cloneComponent=function(e,t){var i;e.anim.rootBone&&e.anim.rootBone!==e||(i={},e.anim.layers.forEach((function(e,n){if(e.mask){var s={};Object.keys(e.mask).forEach((function(i){var n=i.split("/");n.shift();var r=[t.name].concat(n).join("/");s[r]=e.mask[i]})),i[n]={mask:s}}})));var n={stateGraphAsset:e.anim.stateGraphAsset,animationAssets:e.anim.animationAssets,speed:e.anim.speed,activate:e.anim.activate,playing:e.anim.playing,rootBone:e.anim.rootBone,stateGraph:e.anim.stateGraph,layers:e.anim.layers,layerIndices:e.anim.layerIndices,parameters:e.anim.parameters,normalizeWeights:e.anim.normalizeWeights,masks:i};return this.addComponent(t,n)},i.onBeforeRemove=function(e,t){t.onBeforeRemove()},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("animationUpdate",this.onAnimationUpdate,this)},t}(vf);gf._buildAccessors(bp.prototype,Tp);var Cp=function(e){function t(t,i){return e.call(this,t,i)||this}Q(t,e);var i=t.prototype;return i.setCurrentListener=function(){if(this.enabled&&this.entity.audiolistener&&this.entity.enabled){this.system.current=this.entity;var e=this.system.current.getPosition();this.system.manager.listener.setPosition(e)}},i.onEnable=function(){this.setCurrentListener()},i.onDisable=function(){this.system.current===this.entity&&(this.system.current=null)},t}(gf),Ep=function(){this.enabled=!0},Mp=["enabled"],Pp=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="audiolistener",i.ComponentType=Cp,i.DataType=Ep,i.schema=Mp,i.manager=t.soundManager,i.current=null,i.app.systems.on("update",i.onUpdate,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){n=["enabled"],e.prototype.initializeComponentData.call(this,t,i,n)},i.onUpdate=function(e){if(this.current){var t=this.current.getPosition();this.manager.listener.setPosition(t);var i=this.current.getWorldTransform();this.manager.listener.setOrientation(i)}},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},t}(vf);gf._buildAccessors(Cp.prototype,Mp);var Rp=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this).on("set_assets",n.onSetAssets,ee(n)),n.on("set_loop",n.onSetLoop,ee(n)),n.on("set_volume",n.onSetVolume,ee(n)),n.on("set_pitch",n.onSetPitch,ee(n)),n.on("set_minDistance",n.onSetMinDistance,ee(n)),n.on("set_maxDistance",n.onSetMaxDistance,ee(n)),n.on("set_rollOffFactor",n.onSetRollOffFactor,ee(n)),n.on("set_distanceModel",n.onSetDistanceModel,ee(n)),n.on("set_3d",n.onSet3d,ee(n)),n}Q(t,e);var i=t.prototype;return i.play=function(e){if(this.enabled&&this.entity.enabled){var t;this.channel&&this.stop();var i=this.data;if(i.sources[e])if(i["3d"]){var n=this.entity.getPosition();t=this.system.manager.playSound3d(i.sources[e],n,i),i.currentSource=e,i.channel=t}else t=this.system.manager.playSound(i.sources[e],i),i.currentSource=e,i.channel=t}},i.pause=function(){this.channel&&this.channel.pause()},i.unpause=function(){this.channel&&this.channel.paused&&this.channel.unpause()},i.stop=function(){this.channel&&(this.channel.stop(),this.channel=null)},i.onSetAssets=function(e,t,i){var n=[],s=i.length;if(t&&t.length)for(var r=0;r<t.length;r++)if(t[r]){var a=this.system.app.assets.get(t[r]);a&&(a.off("change",this.onAssetChanged,this),a.off("remove",this.onAssetRemoved,this),this.currentSource===a.name&&this.stop())}if(s)for(var o=0;o<s;o++)t.indexOf(i[o])<0&&(i[o]instanceof kd?n.push(i[o].id):n.push(i[o]));!this.system._inTools&&n.length&&this.loadAudioSourceAssets(n)},i.onAssetChanged=function(e,t,i,n){"resource"===t&&(this.data.sources&&(this.data.sources[e.name]=i,this.data.currentSource===e.name&&this.channel&&(this.channel.paused?(this.play(e.name),this.pause()):this.play(e.name))))},i.onAssetRemoved=function(e){e.off("remove",this.onAssetRemoved,this),this.data.sources[e.name]&&(delete this.data.sources[e.name],this.data.currentSource===e.name&&(this.stop(),this.data.currentSource=null))},i.onSetLoop=function(e,t,i){t!==i&&this.channel&&this.channel.setLoop(i)},i.onSetVolume=function(e,t,i){t!==i&&this.channel&&this.channel.setVolume(i)},i.onSetPitch=function(e,t,i){t!==i&&this.channel&&this.channel.setPitch(i)},i.onSetMaxDistance=function(e,t,i){t!==i&&this.channel instanceof Er&&this.channel.setMaxDistance(i)},i.onSetMinDistance=function(e,t,i){t!==i&&this.channel instanceof Er&&this.channel.setMinDistance(i)},i.onSetRollOffFactor=function(e,t,i){t!==i&&this.channel instanceof Er&&this.channel.setRollOffFactor(i)},i.onSetDistanceModel=function(e,t,i){t!==i&&this.channel instanceof Er&&this.channel.setDistanceModel(i)},i.onSet3d=function(e,t,i){if(t!==i&&this.system.initialized&&this.currentSource){var n=!1,s=!1;this.channel&&(n=this.channel.paused,s=this.channel.suspended),this.play(this.currentSource),this.channel&&(this.channel.paused=n,this.channel.suspended=s)}},i.onEnable=function(){var e=this.data.assets;if(e)for(var t=this.system.app.assets,i=0,n=e.length;i<n;i++){var s=e[i];s instanceof kd||(s=t.get(s)),s&&!s.resource&&t.load(s)}this.system.initialized&&(this.data.activate&&!this.channel?this.play(this.currentSource):this.unpause())},i.onDisable=function(){this.pause()},i.loadAudioSourceAssets=function(e){var t=this,i=e.map((function(e){return t.system.app.assets.get(e)})),n={},s=null,r=i.length,a=function(e){r--},o=function(){t.data.sources=n,t.data.currentSource=s,t.enabled&&t.activate&&s&&t.onEnable()};i.forEach((function(i,h){i?(s=s||i.name,i.off("change",t.onAssetChanged,t),i.on("change",t.onAssetChanged,t),i.off("remove",t.onAssetRemoved,t),i.on("remove",t.onAssetRemoved,t),i.off("error",a,t),i.on("error",a,t),i.ready((function(e){n[e.name]=e.resource,0===--r&&o()})),!i.resource&&t.enabled&&t.entity.enabled&&t.system.app.assets.load(i)):(0===--r&&o(),t.system.app.assets.on("add:"+e[h],(function(e){e.ready((function(e){t.data.sources[e.name]=e.resource})),e.resource||t.system.app.assets.load(e)})))}))},t}(gf),Ip=function(){this.enabled=!0,this.assets=[],this.activate=!0,this.volume=1,this.pitch=1,this.loop=!1,this["3d"]=!0,this.minDistance=1,this.maxDistance=1e4,this.rollOffFactor=1,this.distanceModel=We,this.paused=!0,this.sources={},this.currentSource=null,this.channel=null},Lp=["enabled","assets","volume","pitch","loop","activate","3d","minDistance","maxDistance","rollOffFactor","distanceModel","sources","currentSource","channel"],Dp=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="audiosource",i.ComponentType=Rp,i.DataType=Ip,i.schema=Lp,i.manager=t.soundManager,i.initialized=!1,i.app.systems.on("initialize",i.onInitialize,ee(i)),i.app.systems.on("update",i.onUpdate,ee(i)),i.on("remove",i.onRemove,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){n=["activate","volume","pitch","loop","3d","minDistance","maxDistance","rollOffFactor","distanceModel","enabled","assets"],e.prototype.initializeComponentData.call(this,t,i,n),t.paused=!(t.enabled&&t.activate)},i.onInitialize=function(e){e.audiosource&&e.enabled&&e.audiosource.enabled&&e.audiosource.activate&&e.audiosource.play(e.audiosource.currentSource);for(var t=e._children,i=0,n=t.length;i<n;i++)t[i]instanceof Zd&&this.onInitialize(t[i]);this.initialized=!0},i.onUpdate=function(e){var t=this.store;for(var i in t)if(t.hasOwnProperty(i)){var n=t[i],s=n.entity,r=n.data;if(r.enabled&&s.enabled&&r.channel instanceof Er){var a=s.getPosition();r.channel.setPosition(a)}}},i.onRemove=function(e,t){t.channel&&(t.channel.stop(),t.channel=null)},i.setVolume=function(e){this.manager.setVolume(e)},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("initialize",this.onInitialize,this),this.app.systems.off("update",this.onUpdate,this)},t}(vf);gf._buildAccessors(Rp.prototype,Lp);var Op=function(e){function t(t,i,n){var s;if(s=e.call(this)||this,!(t&&t instanceof gf))throw new Error("The parentComponent argument is required and must be a Component");if(!i||"string"!=typeof i)throw new Error("The propertyName argument is required and must be a string");if(n&&"object"!=typeof n)throw new Error("If provided, the eventConfig argument must be an object");return s._parentComponent=t,s._entityPropertyName=i,s._entity=null,s._app=t.system.app,s._configureEventListeners(n||{},{"entity#destroy":s._onEntityDestroy}),s._toggleLifecycleListeners("on"),s}Q(t,e);var i=t.prototype;return i._configureEventListeners=function(e,t){var i=this._parseEventListenerConfig(e,"external",this._parentComponent),n=this._parseEventListenerConfig(t,"internal",this);this._eventListenerConfigs=i.concat(n),this._listenerStatusFlags={},this._gainListeners={},this._loseListeners={}},i._parseEventListenerConfig=function(e,t,i){return Object.keys(e).map((function(n,s){var r=n.split("#"),a=r[0],o=r[1],h=e[n];if(2!==r.length||"string"!=typeof a||0===a.length||"string"!=typeof o||0===o.length)throw new Error("Invalid event listener description: `"+n+"`");if("function"!=typeof h)throw new Error("Invalid or missing callback for event listener `"+n+"`");return{id:t+"_"+s+"_"+n,sourceName:a,eventName:o,callback:h,scope:i}}),this)},i._toggleLifecycleListeners=function(e){this._parentComponent[e]("set_"+this._entityPropertyName,this._onSetEntity,this),this._parentComponent.system[e]("beforeremove",this._onParentComponentRemove,this),this._app.systems[e]("postPostInitialize",this._updateEntityReference,this),this._app[e]("tools:sceneloaded",this._onSceneLoaded,this);for(var t=[],i=0;i<this._eventListenerConfigs.length;++i){var n=this._eventListenerConfigs[i],s=this._app.systems[n.sourceName];s&&(-1===t.indexOf(s)&&t.push(s),s&&"gain"===n.eventName&&(this._gainListeners[n.sourceName]=n),s&&"lose"===n.eventName&&(this._loseListeners[n.sourceName]=n))}for(var r=0;r<t.length;++r)t[r][e]("add",this._onComponentAdd,this),t[r][e]("beforeremove",this._onComponentRemove,this)},i._onSetEntity=function(e,t,i){if(i instanceof Zd)this._updateEntityReference();else{if(null!=i&&"string"!=typeof i)return void console.warn("Entity field `"+this._entityPropertyName+"` was set to unexpected type '"+typeof i+"'");t!==i&&this._updateEntityReference()}},i.onParentComponentEnable=function(){this._entity||this._updateEntityReference()},i._onSceneLoaded=function(){this._updateEntityReference()},i._updateEntityReference=function(){var e,t=this._parentComponent.data[this._entityPropertyName];if(t instanceof Zd)t=(e=t).getGuid(),this._parentComponent.data[this._entityPropertyName]=t;else{var i=this._parentComponent.system.app.root;e=this._parentComponent.entity.isDescendantOf(i)&&t?i.findByGuid(t):null}this._entity!==e&&(this._entity&&this._onBeforeEntityChange(),this._entity=e,this._entity&&this._onAfterEntityChange(),this.fire("set:entity",this._entity))},i._onBeforeEntityChange=function(){this._toggleEntityListeners("off"),this._callAllGainOrLoseListeners(this._loseListeners)},i._onAfterEntityChange=function(){this._toggleEntityListeners("on"),this._callAllGainOrLoseListeners(this._gainListeners)},i._onComponentAdd=function(e,t){var i=t.system.id;e===this._entity&&(this._callGainOrLoseListener(i,this._gainListeners),this._toggleComponentListeners("on",i))},i._onComponentRemove=function(e,t){var i=t.system.id;e===this._entity&&(this._callGainOrLoseListener(i,this._loseListeners),this._toggleComponentListeners("off",i,!0))},i._callAllGainOrLoseListeners=function(e){for(var t in this._entity.c)this._callGainOrLoseListener(t,e)},i._callGainOrLoseListener=function(e,t){if(this._entity.c.hasOwnProperty(e)&&t[e]){var i=t[e];i.callback.call(i.scope)}},i._toggleEntityListeners=function(e,t){if(this._entity)for(var i=0;i<this._eventListenerConfigs.length;++i)this._safeToggleListener(e,this._eventListenerConfigs[i],t)},i._toggleComponentListeners=function(e,t,i){for(var n=0;n<this._eventListenerConfigs.length;++n){var s=this._eventListenerConfigs[n];s.sourceName===t&&this._safeToggleListener(e,s,i)}},i._safeToggleListener=function(e,t,i){var n="on"===e;if(!n||!this._listenerStatusFlags[t.id]){var s=this._getEventSource(t.sourceName,i);s&&(s[e](t.eventName,t.callback,t.scope),this._listenerStatusFlags[t.id]=n)}},i._getEventSource=function(e,t){if("entity"===e)return this._entity;var i=this._entity[e];return i||(t||console.warn("Entity has no component with name "+e),null)},i._onEntityDestroy=function(e){this._entity===e&&(this._toggleEntityListeners("off",!0),this._entity=null)},i._onParentComponentRemove=function(e,t){t===this._parentComponent&&(this._toggleLifecycleListeners("off"),this._toggleEntityListeners("off",!0))},i.hasComponent=function(e){return!(!this._entity||!this._entity.c)&&!!this._entity.c[e]},Z(t,[{key:"entity",get:function(){return this._entity}}]),t}(p),kp="group",Fp="image",Bp="text",Np="stretch",Up="contain",zp="cover",Vp="DEFAULT",Gp="HOVER",Hp="PRESSED",Wp="INACTIVE",Xp={};Xp[Vp]="_defaultTint",Xp[Gp]="hoverTint",Xp[Hp]="pressedTint",Xp[Wp]="inactiveTint";var jp={};jp[Vp]="_defaultSpriteAsset",jp[Gp]="hoverSpriteAsset",jp[Hp]="pressedSpriteAsset",jp[Wp]="inactiveSpriteAsset";var qp={};qp[Vp]="_defaultSpriteFrame",qp[Gp]="hoverSpriteFrame",qp[Hp]="pressedSpriteFrame",qp[Wp]="inactiveSpriteFrame";var Yp=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._visualState=Vp,n._isHovering=!1,n._hoveringCounter=0,n._isPressed=!1,n._defaultTint=new ue(1,1,1,1),n._defaultSpriteAsset=null,n._defaultSpriteFrame=0,n._imageReference=new Op(ee(n),"imageEntity",{"element#gain":n._onImageElementGain,"element#lose":n._onImageElementLose,"element#set:color":n._onSetColor,"element#set:opacity":n._onSetOpacity,"element#set:spriteAsset":n._onSetSpriteAsset,"element#set:spriteFrame":n._onSetSpriteFrame}),n._toggleLifecycleListeners("on",t),n}Q(t,e);var i=t.prototype;return i._toggleLifecycleListeners=function(e,t){this[e]("set_active",this._onSetActive,this),this[e]("set_transitionMode",this._onSetTransitionMode,this),this[e]("set_hoverTint",this._onSetTransitionValue,this),this[e]("set_pressedTint",this._onSetTransitionValue,this),this[e]("set_inactiveTint",this._onSetTransitionValue,this),this[e]("set_hoverSpriteAsset",this._onSetTransitionValue,this),this[e]("set_hoverSpriteFrame",this._onSetTransitionValue,this),this[e]("set_pressedSpriteAsset",this._onSetTransitionValue,this),this[e]("set_pressedSpriteFrame",this._onSetTransitionValue,this),this[e]("set_inactiveSpriteAsset",this._onSetTransitionValue,this),this[e]("set_inactiveSpriteFrame",this._onSetTransitionValue,this),t.app.systems.element[e]("add",this._onElementComponentAdd,this),t.app.systems.element[e]("beforeremove",this._onElementComponentRemove,this)},i._onSetActive=function(e,t,i){t!==i&&this._updateVisualState()},i._onSetTransitionMode=function(e,t,i){t!==i&&(this._cancelTween(),this._resetToDefaultVisualState(t),this._forceReapplyVisualState())},i._onSetTransitionValue=function(e,t,i){t!==i&&this._forceReapplyVisualState()},i._onElementComponentRemove=function(e){this.entity===e&&this._toggleHitElementListeners("off")},i._onElementComponentAdd=function(e){this.entity===e&&this._toggleHitElementListeners("on")},i._onImageElementLose=function(){this._cancelTween(),this._resetToDefaultVisualState(this.transitionMode)},i._onImageElementGain=function(){this._storeDefaultVisualState(),this._forceReapplyVisualState()},i._toggleHitElementListeners=function(e){if(this.entity.element){var t="on"===e;if(t&&this._hasHitElementListeners)return;this.entity.element[e]("mouseenter",this._onMouseEnter,this),this.entity.element[e]("mouseleave",this._onMouseLeave,this),this.entity.element[e]("mousedown",this._onMouseDown,this),this.entity.element[e]("mouseup",this._onMouseUp,this),this.entity.element[e]("touchstart",this._onTouchStart,this),this.entity.element[e]("touchend",this._onTouchEnd,this),this.entity.element[e]("touchleave",this._onTouchLeave,this),this.entity.element[e]("touchcancel",this._onTouchCancel,this),this.entity.element[e]("selectstart",this._onSelectStart,this),this.entity.element[e]("selectend",this._onSelectEnd,this),this.entity.element[e]("selectenter",this._onSelectEnter,this),this.entity.element[e]("selectleave",this._onSelectLeave,this),this.entity.element[e]("click",this._onClick,this),this._hasHitElementListeners=t}},i._storeDefaultVisualState=function(){if(this._imageReference.hasComponent("element")){var e=this._imageReference.entity.element;e.type!==kp&&(this._storeDefaultColor(e.color),this._storeDefaultOpacity(e.opacity),this._storeDefaultSpriteAsset(e.spriteAsset),this._storeDefaultSpriteFrame(e.spriteFrame))}},i._storeDefaultColor=function(e){this._defaultTint.r=e.r,this._defaultTint.g=e.g,this._defaultTint.b=e.b},i._storeDefaultOpacity=function(e){this._defaultTint.a=e},i._storeDefaultSpriteAsset=function(e){this._defaultSpriteAsset=e},i._storeDefaultSpriteFrame=function(e){this._defaultSpriteFrame=e},i._onSetColor=function(e){this._isApplyingTint||(this._storeDefaultColor(e),this._forceReapplyVisualState())},i._onSetOpacity=function(e){this._isApplyingTint||(this._storeDefaultOpacity(e),this._forceReapplyVisualState())},i._onSetSpriteAsset=function(e){this._isApplyingSprite||(this._storeDefaultSpriteAsset(e),this._forceReapplyVisualState())},i._onSetSpriteFrame=function(e){this._isApplyingSprite||(this._storeDefaultSpriteFrame(e),this._forceReapplyVisualState())},i._onMouseEnter=function(e){this._isHovering=!0,this._updateVisualState(),this._fireIfActive("mouseenter",e)},i._onMouseLeave=function(e){this._isHovering=!1,this._isPressed=!1,this._updateVisualState(),this._fireIfActive("mouseleave",e)},i._onMouseDown=function(e){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("mousedown",e)},i._onMouseUp=function(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("mouseup",e)},i._onTouchStart=function(e){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("touchstart",e)},i._onTouchEnd=function(e){e.event.preventDefault(),this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchend",e)},i._onTouchLeave=function(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchleave",e)},i._onTouchCancel=function(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchcancel",e)},i._onSelectStart=function(e){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("selectstart",e)},i._onSelectEnd=function(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("selectend",e)},i._onSelectEnter=function(e){this._hoveringCounter++,1===this._hoveringCounter&&(this._isHovering=!0,this._updateVisualState()),this._fireIfActive("selectenter",e)},i._onSelectLeave=function(e){this._hoveringCounter--,0===this._hoveringCounter&&(this._isHovering=!1,this._isPressed=!1,this._updateVisualState()),this._fireIfActive("selectleave",e)},i._onClick=function(e){this._fireIfActive("click",e)},i._fireIfActive=function(e,t){this.data.active&&this.fire(e,t)},i._updateVisualState=function(e){var t=this._visualState,i=this._determineVisualState();if((t!==i||e)&&this.enabled)switch(this._visualState=i,t===Gp&&this._fireIfActive("hoverend"),t===Hp&&this._fireIfActive("pressedend"),i===Gp&&this._fireIfActive("hoverstart"),i===Hp&&this._fireIfActive("pressedstart"),this.transitionMode){case 0:var n=this[Xp[this._visualState]];this._applyTint(n);break;case 1:var s=jp[this._visualState],r=qp[this._visualState],a=this[s],o=this[r];this._applySprite(a,o)}},i._forceReapplyVisualState=function(){this._updateVisualState(!0)},i._resetToDefaultVisualState=function(e){if(this._imageReference.hasComponent("element"))switch(e){case 0:this._cancelTween(),this._applyTintImmediately(this._defaultTint);break;case 1:this._applySprite(this._defaultSpriteAsset,this._defaultSpriteFrame)}},i._determineVisualState=function(){return this.active?this._isPressed?Hp:this._isHovering?Gp:Vp:Wp},i._applySprite=function(e,t){t=t||0,this._imageReference.hasComponent("element")&&(this._isApplyingSprite=!0,this._imageReference.entity.element.spriteAsset!==e&&(this._imageReference.entity.element.spriteAsset=e),this._imageReference.entity.element.spriteFrame!==t&&(this._imageReference.entity.element.spriteFrame=t),this._isApplyingSprite=!1)},i._applyTint=function(e){this._cancelTween(),0===this.fadeDuration?this._applyTintImmediately(e):this._applyTintWithTween(e)},i._applyTintImmediately=function(e){if(e&&this._imageReference.hasComponent("element")&&this._imageReference.entity.element.type!==kp){var t=Kp(e);this._isApplyingTint=!0,t.equals(this._imageReference.entity.element.color)||(this._imageReference.entity.element.color=t),this._imageReference.entity.element.opacity!==e.a&&(this._imageReference.entity.element.opacity=e.a),this._isApplyingTint=!1}},i._applyTintWithTween=function(e){if(e&&this._imageReference.hasComponent("element")&&this._imageReference.entity.element.type!==kp){var t=Kp(e),i=this._imageReference.entity.element.color,n=this._imageReference.entity.element.opacity;t.equals(i)&&e.a===n||(this._tweenInfo={startTime:oe(),from:new ue(i.r,i.g,i.b,n),to:e.clone(),lerpColor:new ue})}},i._updateTintTween=function(){var e=oe()-this._tweenInfo.startTime,t=0===this.fadeDuration?1:e/this.fadeDuration;if(t=ce.clamp(t,0,1),Math.abs(t-1)>1e-5){var i=this._tweenInfo.lerpColor;i.lerp(this._tweenInfo.from,this._tweenInfo.to,t),this._applyTintImmediately(new ue(i.r,i.g,i.b,i.a))}else this._applyTintImmediately(this._tweenInfo.to),this._cancelTween()},i._cancelTween=function(){delete this._tweenInfo},i.onUpdate=function(){this._tweenInfo&&this._updateTintTween()},i.onEnable=function(){this._isHovering=!1,this._hoveringCounter=0,this._isPressed=!1,this._imageReference.onParentComponentEnable(),this._toggleHitElementListeners("on"),this._forceReapplyVisualState()},i.onDisable=function(){this._toggleHitElementListeners("off"),this._resetToDefaultVisualState(this.transitionMode)},i.onRemove=function(){this._toggleLifecycleListeners("off",this.system),this.onDisable()},t}(gf);function Kp(e){return new ue(e.r,e.g,e.b)}var Zp=function(){this.enabled=!0,this.active=!0,this.imageEntity=null,this.hitPadding=new ve,this.transitionMode=0,this.hoverTint=new ue(.75,.75,.75),this.pressedTint=new ue(.5,.5,.5),this.inactiveTint=new ue(.25,.25,.25),this.fadeDuration=0,this.hoverSpriteAsset=null,this.hoverSpriteFrame=0,this.pressedSpriteAsset=null,this.pressedSpriteFrame=0,this.inactiveSpriteAsset=null,this.inactiveSpriteFrame=0},$p=["enabled","active",{name:"imageEntity",type:"entity"},{name:"hitPadding",type:"vec4"},"transitionMode",{name:"hoverTint",type:"rgba"},{name:"pressedTint",type:"rgba"},{name:"inactiveTint",type:"rgba"},"fadeDuration","hoverSpriteAsset","hoverSpriteFrame","pressedSpriteAsset","pressedSpriteFrame","inactiveSpriteAsset","inactiveSpriteFrame"],Qp=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="button",i.ComponentType=Yp,i.DataType=Zp,i.schema=$p,i.on("beforeremove",i._onRemoveComponent,ee(i)),i.app.systems.on("update",i.onUpdate,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){e.prototype.initializeComponentData.call(this,t,i,$p)},i.onUpdate=function(e){var t=this.store;for(var i in t){var n=t[i].entity,s=n.button;s.enabled&&n.enabled&&s.onUpdate()}},i._onRemoveComponent=function(e,t){t.onRemove()},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},t}(vf);gf._buildAccessors(Yp.prototype,$p);var Jp,em,tm,im=new me,nm=new Ae,sm=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._compoundParent=null,n._hasOffset=!1,n.entity.on("insert",n._onInsert,ee(n)),n.on("set_type",n.onSetType,ee(n)),n.on("set_halfExtents",n.onSetHalfExtents,ee(n)),n.on("set_linearOffset",n.onSetOffset,ee(n)),n.on("set_angularOffset",n.onSetOffset,ee(n)),n.on("set_radius",n.onSetRadius,ee(n)),n.on("set_height",n.onSetHeight,ee(n)),n.on("set_axis",n.onSetAxis,ee(n)),n.on("set_asset",n.onSetAsset,ee(n)),n.on("set_renderAsset",n.onSetRenderAsset,ee(n)),n.on("set_model",n.onSetModel,ee(n)),n.on("set_render",n.onSetRender,ee(n)),n}Q(t,e);var i=t.prototype;return i.onSetType=function(e,t,i){t!==i&&this.system.changeType(this,t,i)},i.onSetHalfExtents=function(e,t,i){var n=this.data.type;this.data.initialized&&"box"===n&&this.system.recreatePhysicalShapes(this)},i.onSetOffset=function(e,t,i){this._hasOffset=!this.data.linearOffset.equals(me.ZERO)||!this.data.angularOffset.equals(Ae.IDENTITY),this.data.initialized&&this.system.recreatePhysicalShapes(this)},i.onSetRadius=function(e,t,i){var n=this.data.type;!this.data.initialized||"sphere"!==n&&"capsule"!==n&&"cylinder"!==n&&"cone"!==n||this.system.recreatePhysicalShapes(this)},i.onSetHeight=function(e,t,i){var n=this.data.type;!this.data.initialized||"capsule"!==n&&"cylinder"!==n&&"cone"!==n||this.system.recreatePhysicalShapes(this)},i.onSetAxis=function(e,t,i){var n=this.data.type;!this.data.initialized||"capsule"!==n&&"cylinder"!==n&&"cone"!==n||this.system.recreatePhysicalShapes(this)},i.onSetAsset=function(e,t,i){var n=this.system.app.assets;if(t){var s=n.get(t);s&&s.off("remove",this.onAssetRemoved,this)}if(i){i instanceof kd&&(this.data.asset=i.id);var r=n.get(this.data.asset);r&&(r.off("remove",this.onAssetRemoved,this),r.on("remove",this.onAssetRemoved,this))}this.data.initialized&&"mesh"===this.data.type&&(i||(this.data.model=null),this.system.recreatePhysicalShapes(this))},i.onSetRenderAsset=function(e,t,i){var n=this.system.app.assets;if(t){var s=n.get(t);s&&s.off("remove",this.onRenderAssetRemoved,this)}if(i){i instanceof kd&&(this.data.renderAsset=i.id);var r=n.get(this.data.renderAsset);r&&(r.off("remove",this.onRenderAssetRemoved,this),r.on("remove",this.onRenderAssetRemoved,this))}this.data.initialized&&"mesh"===this.data.type&&(i||(this.data.render=null),this.system.recreatePhysicalShapes(this))},i.onSetModel=function(e,t,i){this.data.initialized&&"mesh"===this.data.type&&this.system.implementations.mesh.doRecreatePhysicalShape(this)},i.onSetRender=function(e,t,i){this.onSetModel(e,t,i)},i.onAssetRemoved=function(e){e.off("remove",this.onAssetRemoved,this),this.data.asset===e.id&&(this.asset=null)},i.onRenderAssetRemoved=function(e){e.off("remove",this.onRenderAssetRemoved,this),this.data.renderAsset===e.id&&(this.renderAsset=null)},i._getCompoundChildShapeIndex=function(e){for(var t=this.data.shape,i=t.getNumChildShapes(),n=0;n<i;n++){if(t.getChildShape(n).ptr===e.ptr)return n}return null},i._onInsert=function(e){if("undefined"!=typeof Ammo)if(this._compoundParent)this.system.recreatePhysicalShapes(this);else if(!this.entity.rigidbody)for(var t=this.entity.parent;t;){if(t.collision&&"compound"===t.collision.type){0===t.collision.shape.getNumChildShapes()?this.system.recreatePhysicalShapes(t.collision):this.system.recreatePhysicalShapes(this);break}t=t.parent}},i._updateCompound=function(){var e=this.entity;if(e._dirtyWorld){for(var t=e._dirtyLocal,i=e;i&&!t&&(!i.collision||i.collision!==this._compoundParent);)i._dirtyLocal&&(t=!0),i=i.parent;if(t){e.forEach(this.system.implementations.compound._updateEachDescendantTransform,e);var n=this._compoundParent.entity.rigidbody;n&&n.activate()}}},i.getShapePosition=function(){var e=this.entity.getPosition();if(this._hasOffset){var t=this.entity.getRotation(),i=this.data.linearOffset;return nm.copy(t).transformVector(i,im),im.add(e)}return e},i.getShapeRotation=function(){var e=this.entity.getRotation();return this._hasOffset?nm.copy(e).mul(this.data.angularOffset):e},i.onEnable=function(){if("mesh"===this.data.type&&(this.data.asset||this.data.renderAsset)&&this.data.initialized){var e=this.system.app.assets.get(this.data.asset||this.data.renderAsset);if(e&&(!e.resource||!this.data.shape))return void this.system.recreatePhysicalShapes(this)}if(this.entity.rigidbody)this.entity.rigidbody.enabled&&this.entity.rigidbody.enableSimulation();else if(this._compoundParent&&this!==this._compoundParent)if(0===this._compoundParent.shape.getNumChildShapes())this.system.recreatePhysicalShapes(this._compoundParent);else{var t=this.system._getNodeTransform(this.entity,this._compoundParent.entity);this._compoundParent.shape.addChildShape(t,this.data.shape),Ammo.destroy(t),this._compoundParent.entity.rigidbody&&this._compoundParent.entity.rigidbody.activate()}else this.entity.trigger&&this.entity.trigger.enable()},i.onDisable=function(){this.entity.rigidbody?this.entity.rigidbody.disableSimulation():this._compoundParent&&this!==this._compoundParent?this._compoundParent.entity._destroying||(this.system._removeCompoundChild(this._compoundParent,this.data.shape),this._compoundParent.entity.rigidbody&&this._compoundParent.entity.rigidbody.activate()):this.entity.trigger&&this.entity.trigger.disable()},i.onBeforeRemove=function(){this.asset&&(this.asset=null),this.renderAsset&&(this.renderAsset=null),this.entity.off("insert",this._onInsert,this),this.off()},t}(gf),rm=function(){this.enabled=!0,this.type="box",this.halfExtents=new me(.5,.5,.5),this.linearOffset=new me,this.angularOffset=new Ae,this.radius=.5,this.axis=1,this.height=2,this.asset=null,this.renderAsset=null,this.shape=null,this.model=null,this.render=null,this.initialized=!1},am="static",om="dynamic",hm="kinematic",lm=65535,cm=65533,um=function(){function e(e,t,i){this.entity=t.entity,this.component=t,this.app=e,"undefined"==typeof Ammo||Jp||(Jp=new Ammo.btVector3,em=new Ammo.btQuaternion,tm=new Ammo.btTransform),this.initialize(i)}var t=e.prototype;return t.initialize=function(e){var t=this.entity,i=e.shape;if(i&&"undefined"!=typeof Ammo){t.trigger&&t.trigger.destroy();var n=this.component;if(n){var s=n.getShapePosition(),r=n.getShapeRotation();Jp.setValue(s.x,s.y,s.z),em.setValue(r.x,r.y,r.z,r.w)}else{var a=t.getPosition(),o=t.getRotation();Jp.setValue(a.x,a.y,a.z),em.setValue(o.x,o.y,o.z,o.w)}tm.setOrigin(Jp),tm.setRotation(em);var h=this.app.systems.rigidbody.createBody(1,i,tm);h.setRestitution(0),h.setFriction(0),h.setDamping(0,0),Jp.setValue(0,0,0),h.setLinearFactor(Jp),h.setAngularFactor(Jp),h.setCollisionFlags(4|h.getCollisionFlags()),h.entity=t,this.body=h,this.component.enabled&&t.enabled&&this.enable()}},t.destroy=function(){var e=this.body;e&&(this.disable(),this.app.systems.rigidbody.destroyBody(e))},t._getEntityTransform=function(e){var t=this.component;if(t){var i=t.getShapePosition(),n=t.getShapeRotation();Jp.setValue(i.x,i.y,i.z),em.setValue(n.x,n.y,n.z,n.w)}else{var s=this.entity.getPosition(),r=this.entity.getRotation();Jp.setValue(s.x,s.y,s.z),em.setValue(r.x,r.y,r.z,r.w)}e.setOrigin(Jp),e.setRotation(em)},t.updateTransform=function(){this._getEntityTransform(tm);var e=this.body;e.setWorldTransform(tm),e.activate()},t.enable=function(){var e=this.body;if(e){var t=this.app.systems;t.rigidbody.addBody(e,16,65517),t.rigidbody._triggers.push(this),e.forceActivationState(1),this.updateTransform()}},t.disable=function(){var e=this.body;if(e){var t=this.app.systems,i=t.rigidbody._triggers.indexOf(this);i>-1&&t.rigidbody._triggers.splice(i,1),t.rigidbody.removeBody(e),e.forceActivationState(5)}},e}(),dm=new Te,fm=new me,pm=new me,mm=new Ae,_m=new go,gm=["enabled","type","halfExtents","linearOffset","angularOffset","radius","axis","height","asset","renderAsset","shape","model","render"],vm=function(){function e(e){this.system=e}var t=e.prototype;return t.beforeInitialize=function(e,t){t.shape=null,t.model=new Uc,t.model.graph=new go},t.afterInitialize=function(e,t){this.recreatePhysicalShapes(e),e.data.initialized=!0},t.reset=function(e,t){this.beforeInitialize(e,t),this.afterInitialize(e,t)},t.recreatePhysicalShapes=function(e){var t=e.entity,i=e.data;if("undefined"!=typeof Ammo){t.trigger&&(t.trigger.destroy(),delete t.trigger),i.shape&&(e._compoundParent&&(this.system._removeCompoundChild(e._compoundParent,i.shape),e._compoundParent.entity.rigidbody&&e._compoundParent.entity.rigidbody.activate()),this.destroyShape(i)),i.shape=this.createPhysicalShape(e.entity,i);var n=!e._compoundParent;if("compound"!==i.type||e._compoundParent&&e!==e._compoundParent){if("compound"!==i.type&&(e._compoundParent&&e===e._compoundParent&&t.forEach(this.system.implementations.compound._updateEachDescendant,e),!e.rigidbody)){e._compoundParent=null;for(var s=t.parent;s;){if(s.collision&&"compound"===s.collision.type){e._compoundParent=s.collision;break}s=s.parent}}}else e._compoundParent=e,t.forEach(this._addEachDescendant,e);e._compoundParent&&e!==e._compoundParent&&(n&&0===e._compoundParent.shape.getNumChildShapes()?this.system.recreatePhysicalShapes(e._compoundParent):(this.system.updateCompoundChildTransform(t),e._compoundParent.entity.rigidbody&&e._compoundParent.entity.rigidbody.activate())),t.rigidbody?(t.rigidbody.disableSimulation(),t.rigidbody.createBody(),t.enabled&&t.rigidbody.enabled&&t.rigidbody.enableSimulation()):e._compoundParent||(t.trigger?t.trigger.initialize(i):t.trigger=new um(this.system.app,e,i))}},t.createPhysicalShape=function(e,t){},t.updateTransform=function(e,t,i,n){e.entity.trigger&&e.entity.trigger.updateTransform()},t.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 i=this.system.store[e.getGuid()],n={enabled:i.data.enabled,type:i.data.type,halfExtents:[i.data.halfExtents.x,i.data.halfExtents.y,i.data.halfExtents.z],linearOffset:[i.data.linearOffset.x,i.data.linearOffset.y,i.data.linearOffset.z],angularOffset:[i.data.angularOffset.x,i.data.angularOffset.y,i.data.angularOffset.z,i.data.angularOffset.w],radius:i.data.radius,axis:i.data.axis,height:i.data.height,asset:i.data.asset,renderAsset:i.data.renderAsset,model:i.data.model,render:i.data.render};return this.system.addComponent(t,n)},e}(),ym=function(e){function t(){return e.apply(this,arguments)||this}return Q(t,e),t.prototype.createPhysicalShape=function(e,t){if("undefined"!=typeof Ammo){var i=t.halfExtents,n=new Ammo.btVector3(i?i.x:.5,i?i.y:.5,i?i.z:.5),s=new Ammo.btBoxShape(n);return Ammo.destroy(n),s}},t}(vm),xm=function(e){function t(){return e.apply(this,arguments)||this}return Q(t,e),t.prototype.createPhysicalShape=function(e,t){if("undefined"!=typeof Ammo)return new Ammo.btSphereShape(t.radius)},t}(vm),Sm=function(e){function t(){return e.apply(this,arguments)||this}return Q(t,e),t.prototype.createPhysicalShape=function(e,t){var i,n,s,r=null!=(i=t.axis)?i:1,a=null!=(n=t.radius)?n:.5,o=Math.max((null!=(s=t.height)?s:2)-2*a,0),h=null;if("undefined"!=typeof Ammo)switch(r){case 0:h=new Ammo.btCapsuleShapeX(a,o);break;case 1:h=new Ammo.btCapsuleShape(a,o);break;case 2:h=new Ammo.btCapsuleShapeZ(a,o)}return h},t}(vm),bm=function(e){function t(){return e.apply(this,arguments)||this}return Q(t,e),t.prototype.createPhysicalShape=function(e,t){var i,n,s,r=null!=(i=t.axis)?i:1,a=null!=(n=t.radius)?n:.5,o=null!=(s=t.height)?s:1,h=null,l=null;if("undefined"!=typeof Ammo)switch(r){case 0:h=new Ammo.btVector3(.5*o,a,a),l=new Ammo.btCylinderShapeX(h);break;case 1:h=new Ammo.btVector3(a,.5*o,a),l=new Ammo.btCylinderShape(h);break;case 2:h=new Ammo.btVector3(a,a,.5*o),l=new Ammo.btCylinderShapeZ(h)}return h&&Ammo.destroy(h),l},t}(vm),wm=function(e){function t(){return e.apply(this,arguments)||this}return Q(t,e),t.prototype.createPhysicalShape=function(e,t){var i,n,s,r=null!=(i=t.axis)?i:1,a=null!=(n=t.radius)?n:.5,o=null!=(s=t.height)?s:1,h=null;if("undefined"!=typeof Ammo)switch(r){case 0:h=new Ammo.btConeShapeX(a,o);break;case 1:h=new Ammo.btConeShape(a,o);break;case 2:h=new Ammo.btConeShapeZ(a,o)}return h},t}(vm),Tm=function(e){function t(){return e.apply(this,arguments)||this}Q(t,e);var i=t.prototype;return i.beforeInitialize=function(e,t){},i.createAmmoMesh=function(e,t,i){var n;if(this.system._triMeshCache[e.id])n=this.system._triMeshCache[e.id];else{for(var s,r,a=e.vertexBuffer,o=a.getFormat(),h=0;h<o.elements.length;h++){var l=o.elements[h];if(l.name===lt){r=new Float32Array(a.lock(),l.offset),s=l.stride/4;break}}var c=[];e.getIndices(c);var u,d,f,p=e.primitive[0].count/3,m=new Ammo.btVector3,_=new Ammo.btVector3,g=new Ammo.btVector3,v=e.primitive[0].base;n=new Ammo.btTriangleMesh,this.system._triMeshCache[e.id]=n;for(var y=0;y<p;y++)u=c[v+3*y]*s,d=c[v+3*y+1]*s,f=c[v+3*y+2]*s,m.setValue(r[u],r[u+1],r[u+2]),_.setValue(r[d],r[d+1],r[d+2]),g.setValue(r[f],r[f+1],r[f+2]),n.addTriangle(m,_,g,!0);Ammo.destroy(m),Ammo.destroy(_),Ammo.destroy(g)}var x=new Ammo.btBvhTriangleMeshShape(n,!0),S=this.system._getNodeScaling(t);x.setLocalScaling(S),Ammo.destroy(S);var b=this.system._getNodeTransform(t);i.addChildShape(b,x),Ammo.destroy(b)},i.createPhysicalShape=function(e,t){if("undefined"!=typeof Ammo&&(t.model||t.render)){var i=new Ammo.btCompoundShape;if(t.model)for(var n=t.model.meshInstances,s=0;s<n.length;s++)this.createAmmoMesh(n[s].mesh,n[s].node,i);else if(t.render)for(var r=t.render.meshes,a=0;a<r.length;a++)this.createAmmoMesh(r[a],_m,i);var o=e.getWorldTransform().getScale(),h=new Ammo.btVector3(o.x,o.y,o.z);return i.setLocalScaling(h),Ammo.destroy(h),i}},i.recreatePhysicalShapes=function(e){var t=e.data;(t.renderAsset||t.asset)&&e.enabled&&e.entity.enabled?this.loadAsset(e,t.renderAsset||t.asset,t.renderAsset?"render":"model"):this.doRecreatePhysicalShape(e)},i.loadAsset=function(e,t,i){var n=this,s=e.data,r=this.system.app.assets,a=r.get(t);a?(a.ready((function(t){s[i]=t.resource,n.doRecreatePhysicalShape(e)})),r.load(a)):r.once("add:"+t,(function(t){t.ready((function(t){s[i]=t.resource,n.doRecreatePhysicalShape(e)})),r.load(t)}))},i.doRecreatePhysicalShape=function(e){var t=e.entity,i=e.data;i.model||i.render?(this.destroyShape(i),i.shape=this.createPhysicalShape(t,i),t.rigidbody?(t.rigidbody.disableSimulation(),t.rigidbody.createBody(),t.enabled&&t.rigidbody.enabled&&t.rigidbody.enableSimulation()):t.trigger?t.trigger.initialize(i):t.trigger=new um(this.system.app,e,i)):(this.beforeRemove(t,e),this.remove(t,i))},i.updateTransform=function(t,i,n,s){if(t.shape){var r=t.entity.getWorldTransform().getScale(),a=t.shape.getLocalScaling();r.x===a.x()&&r.y===a.y()&&r.z===a.z()||this.doRecreatePhysicalShape(t)}e.prototype.updateTransform.call(this,t,i,n,s)},i.destroyShape=function(e){if(e.shape){for(var t=e.shape.getNumChildShapes(),i=0;i<t;i++){var n=e.shape.getChildShape(i);Ammo.destroy(n)}Ammo.destroy(e.shape),e.shape=null}},t}(vm),Am=function(e){function t(){return e.apply(this,arguments)||this}Q(t,e);var i=t.prototype;return i.createPhysicalShape=function(e,t){if("undefined"!=typeof Ammo)return new Ammo.btCompoundShape},i._addEachDescendant=function(e){e.collision&&!e.rigidbody&&(e.collision._compoundParent=this,e!==this.entity&&e.collision.system.recreatePhysicalShapes(e.collision))},i._updateEachDescendant=function(e){e.collision&&e.collision._compoundParent===this&&(e.collision._compoundParent=null,e===this.entity||e.rigidbody||e.collision.system.recreatePhysicalShapes(e.collision))},i._updateEachDescendantTransform=function(e){e.collision&&e.collision._compoundParent===this.collision._compoundParent&&this.collision.system.updateCompoundChildTransform(e)},t}(vm),Cm=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="collision",i.ComponentType=sm,i.DataType=rm,i.schema=gm,i.implementations={},i._triMeshCache={},i.on("beforeremove",i.onBeforeRemove,ee(i)),i.on("remove",i.onRemove,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){for(var s,r={},a=0,o=(n=["type","halfExtents","radius","axis","height","shape","model","asset","render","renderAsset","enabled","linearOffset","angularOffset"]).length;a<o;a++){var h=n[a];r[h]=i[h]}if(i.hasOwnProperty("asset")?(-1!==(s=n.indexOf("model"))&&n.splice(s,1),-1!==(s=n.indexOf("render"))&&n.splice(s,1)):i.hasOwnProperty("model")&&-1!==(s=n.indexOf("asset"))&&n.splice(s,1),r.type||(r.type=t.data.type),t.data.type=r.type,Array.isArray(r.halfExtents)&&(r.halfExtents=new me(r.halfExtents)),Array.isArray(r.linearOffset)&&(r.linearOffset=new me(r.linearOffset)),Array.isArray(r.angularOffset)){var l=r.angularOffset;3===l.length?r.angularOffset=(new Ae).setFromEulerAngles(l[0],l[1],l[2]):r.angularOffset=new Ae(r.angularOffset)}var c=this._createImplementation(r.type);c.beforeInitialize(t,r),e.prototype.initializeComponentData.call(this,t,r,n),c.afterInitialize(t,r)},i._createImplementation=function(e){if(void 0===this.implementations[e]){var t;switch(e){case"box":t=new ym(this);break;case"sphere":t=new xm(this);break;case"capsule":t=new Sm(this);break;case"cylinder":t=new bm(this);break;case"cone":t=new wm(this);break;case"mesh":t=new Tm(this);break;case"compound":t=new Am(this)}this.implementations[e]=t}return this.implementations[e]},i._getImplementation=function(e){return this.implementations[e.collision.data.type]},i.cloneComponent=function(e,t){return this._getImplementation(e).clone(e,t)},i.onBeforeRemove=function(e,t){this.implementations[t.data.type].beforeRemove(e,t),t.onBeforeRemove()},i.onRemove=function(e,t){this.implementations[t.type].remove(e,t)},i.updateCompoundChildTransform=function(e){if(this._removeCompoundChild(e.collision._compoundParent,e.collision.data.shape),e.enabled&&e.collision.enabled){var t=this._getNodeTransform(e,e.collision._compoundParent.entity);e.collision._compoundParent.shape.addChildShape(t,e.collision.data.shape),Ammo.destroy(t)}},i._removeCompoundChild=function(e,t){if(e.shape.removeChildShape)e.shape.removeChildShape(t);else{var i=e._getCompoundChildShapeIndex(t);null!==i&&e.shape.removeChildShapeByIndex(i)}},i.onTransformChanged=function(e,t,i,n){this.implementations[e.data.type].updateTransform(e,t,i,n)},i.changeType=function(e,t,i){this.implementations[t].beforeRemove(e.entity,e),this.implementations[t].remove(e.entity,e.data),this._createImplementation(i).reset(e,e.data)},i.recreatePhysicalShapes=function(e){this.implementations[e.data.type].recreatePhysicalShapes(e)},i._calculateNodeRelativeTransform=function(e,t){if(e===t){var i=e.getWorldTransform().getScale();dm.setScale(i.x,i.y,i.z)}else this._calculateNodeRelativeTransform(e.parent,t),dm.mul(e.getLocalTransform())},i._getNodeScaling=function(e){var t=e.getWorldTransform().getScale();return new Ammo.btVector3(t.x,t.y,t.z)},i._getNodeTransform=function(e,t){var i,n;t?(this._calculateNodeRelativeTransform(e,t),i=fm,n=mm,dm.getTranslation(i),n.setFromMat4(dm)):(i=e.getPosition(),n=e.getRotation());var s=new Ammo.btQuaternion,r=new Ammo.btTransform;r.setIdentity();var a=r.getOrigin(),o=e.collision;if(o&&o._hasOffset){var h=o.data.linearOffset,l=o.data.angularOffset,c=pm;mm.copy(n).transformVector(h,c),c.add(i),mm.copy(n).mul(l),a.setValue(c.x,c.y,c.z),s.setValue(mm.x,mm.y,mm.z,mm.w)}else a.setValue(i.x,i.y,i.z),s.setValue(n.x,n.y,n.z,n.w);return r.setRotation(s),Ammo.destroy(s),Ammo.destroy(a),r},i.destroy=function(){for(var t in this._triMeshCache)Ammo.destroy(this._triMeshCache[t]);this._triMeshCache=null,e.prototype.destroy.call(this)},t}(vf);gf._buildAccessors(sm.prototype,gm);var Em=new Jn,Mm=function(){function e(e,t,i){this._entity=e,this._element=e.element,this.model=new Uc,this.node=new go,this.model.graph=this.node,this.mesh=t,this.meshInstance=new Co(this.mesh,i,this.node),this.meshInstance.name="ImageElement: "+e.name,this.meshInstance.castShadow=!1,this.meshInstance.receiveShadow=!1,this._meshDirty=!1,this.model.meshInstances.push(this.meshInstance),this._entity.addChild(this.model.graph),this.model._entity=this._entity,this.unmaskMeshInstance=null}var t=e.prototype;return t.destroy=function(){this.setMaterial(null),this._element.removeModelFromLayers(this.model),this.model.destroy(),this.model=null,this.node=null,this.mesh=null,this.meshInstance=null,this._entity=null,this._element=null},t.setMesh=function(e){this.meshInstance&&(this.mesh=e,this.meshInstance.mesh=e,this.meshInstance.visible=!!e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.mesh=e),this.forceUpdateAabb())},t.setMask=function(e){if(this.meshInstance){if(e)for(var t in this.unmaskMeshInstance=new Co(this.mesh,this.meshInstance.material,this.node),this.unmaskMeshInstance.name="Unmask: "+this._entity.name,this.unmaskMeshInstance.castShadow=!1,this.unmaskMeshInstance.receiveShadow=!1,this.unmaskMeshInstance.pick=!1,this.model.meshInstances.push(this.unmaskMeshInstance),this.meshInstance.parameters)this.unmaskMeshInstance.setParameter(t,this.meshInstance.parameters[t].data);else{var i=this.model.meshInstances.indexOf(this.unmaskMeshInstance);i>=0&&this.model.meshInstances.splice(i,1),this.unmaskMeshInstance=null}this._entity.enabled&&this._element.enabled&&(this._element.removeModelFromLayers(this.model),this._element.addModelToLayers(this.model))}},t.setMaterial=function(e){this.meshInstance&&(this.meshInstance.material=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.material=e))},t.setParameter=function(e,t){this.meshInstance&&(this.meshInstance.setParameter(e,t),this.unmaskMeshInstance&&this.unmaskMeshInstance.setParameter(e,t))},t.deleteParameter=function(e){this.meshInstance&&(this.meshInstance.deleteParameter(e),this.unmaskMeshInstance&&this.unmaskMeshInstance.deleteParameter(e))},t.setUnmaskDrawOrder=function(){if(this.meshInstance){if(this.unmaskMeshInstance){var e=function e(t){var i,n=t.children,s=n.length;if(s){for(var r=0;r<s;r++)n[r].element&&(i=n[r]);return i?e(i)||i:null}return null}(this._entity);e&&e.element?this.unmaskMeshInstance.drawOrder=e.element.drawOrder+e.element.getMaskOffset():this.unmaskMeshInstance.drawOrder=this.meshInstance.drawOrder+this._element.getMaskOffset()}}},t.setDrawOrder=function(e){this.meshInstance&&(this.meshInstance.drawOrder=e)},t.setCull=function(e){if(this.meshInstance){var t=this._element,i=null;e&&t._isScreenSpace()&&(i=function(e){return t.isVisibleForCamera(e)}),this.meshInstance.cull=e,this.meshInstance.isVisibleFunc=i,this.unmaskMeshInstance&&(this.unmaskMeshInstance.cull=e,this.unmaskMeshInstance.isVisibleFunc=i)}},t.setScreenSpace=function(e){this.meshInstance&&(this.meshInstance.screenSpace=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.screenSpace=e))},t.setLayer=function(e){this.meshInstance&&(this.meshInstance.layer=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.layer=e))},t.forceUpdateAabb=function(e){this.meshInstance&&(this.meshInstance._aabbVer=-1,this.unmaskMeshInstance&&(this.unmaskMeshInstance._aabbVer=-1))},t.setAabbFunc=function(e){this.meshInstance&&(this.meshInstance._updateAabbFunc=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance._updateAabbFunc=e))},e}(),Pm=function(){function e(e){this._element=e,this._entity=e.entity,this._system=e.system,this._textureAsset=null,this._texture=null,this._materialAsset=null,this._material=null,this._spriteAsset=null,this._sprite=null,this._spriteFrame=0,this._pixelsPerUnit=null,this._targetAspectRatio=-1,this._rect=new ve(0,0,1,1),this._mask=!1,this._maskRef=0,this._outerScale=new ge,this._outerScaleUniform=new Float32Array(2),this._innerOffset=new ve,this._innerOffsetUniform=new Float32Array(4),this._atlasRect=new ve,this._atlasRectUniform=new Float32Array(4),this._defaultMesh=this._createMesh(),this._renderable=new Mm(this._entity,this._defaultMesh,this._material),this._color=new ue(1,1,1,1),this._colorUniform=new Float32Array([1,1,1]),this._renderable.setParameter("material_emissive",this._colorUniform),this._renderable.setParameter("material_opacity",1),this._updateAabbFunc=this._updateAabb.bind(this),this._onScreenChange(this._element.screen),this._element.on("resize",this._onParentResizeOrPivotChange,this),this._element.on("set:pivot",this._onParentResizeOrPivotChange,this),this._element.on("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.on("set:screen",this._onScreenChange,this),this._element.on("set:draworder",this._onDrawOrderChange,this),this._element.on("screen:set:resolution",this._onResolutionChange,this)}var t=e.prototype;return t.destroy=function(){this.textureAsset=null,this.spriteAsset=null,this.materialAsset=null,this._renderable.setMesh(this._defaultMesh),this._renderable.destroy(),this._defaultMesh=null,this._element.off("resize",this._onParentResizeOrPivotChange,this),this._element.off("set:pivot",this._onParentResizeOrPivotChange,this),this._element.off("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.off("set:screen",this._onScreenChange,this),this._element.off("set:draworder",this._onDrawOrderChange,this),this._element.off("screen:set:resolution",this._onResolutionChange,this)},t._onResolutionChange=function(e){},t._onParentResizeOrPivotChange=function(){this._renderable.mesh&&this._updateMesh(this._renderable.mesh)},t._onScreenSpaceChange=function(e){this._updateMaterial(e)},t._onScreenChange=function(e,t){e?this._updateMaterial(e.screen.screenSpace):this._updateMaterial(!1)},t._onDrawOrderChange=function(e){this._renderable.setDrawOrder(e),this.mask&&this._element.screen&&this._element.screen.screen.once("syncdraworder",(function(){this._renderable.setUnmaskDrawOrder()}),this)},t._hasUserMaterial=function(){return!!this._materialAsset||!!this._material&&-1===this._system.defaultImageMaterials.indexOf(this._material)},t._use9Slicing=function(){return this.sprite&&(1===this.sprite.renderMode||2===this.sprite.renderMode)},t._updateMaterial=function(e){var t=!!this._mask,i=!(!this.sprite||1!==this.sprite.renderMode),n=!(!this.sprite||2!==this.sprite.renderMode);this._hasUserMaterial()||(this._material=this._system.getImageElementMaterial(e,t,i,n)),this._renderable&&(this._renderable.setCull(!this._element._isScreenSpace()||this._element._isScreenCulled()),this._renderable.setMaterial(this._material),this._renderable.setScreenSpace(e),this._renderable.setLayer(e?0:15))},t._createMesh=function(){var e=this._element,t=e.calculatedWidth,i=e.calculatedHeight,n=this._rect,s=this._system.app.graphicsDevice,r=new Float32Array([t,0,0,0,0,1,n.x+n.z,1-n.y,t,i,0,0,0,1,n.x+n.z,1-(n.y+n.w),0,0,0,0,0,1,n.x,1-n.y,0,i,0,0,0,1,n.x,1-(n.y+n.w)]),a=Em.get(s,(function(){return new Pi(s,[{semantic:lt,components:3,type:6},{semantic:ct,components:3,type:6},{semantic:_t,components:2,type:6}])})),o=new Ei(s,a,4,0,r.buffer),h=new Jr(s);return h.vertexBuffer=o,h.primitive[0].type=5,h.primitive[0].base=0,h.primitive[0].count=4,h.primitive[0].indexed=!1,h.aabb.setMinMax(me.ZERO,new me(t,i,0)),this._updateMesh(h),h},t._updateMesh=function(e){var t=this._element,i=t.calculatedWidth,n=t.calculatedHeight;if(t.fitMode!==Np&&this._targetAspectRatio>0){var s=t.calculatedWidth/t.calculatedHeight;t.fitMode===Up&&s>this._targetAspectRatio||t.fitMode===zp&&s<this._targetAspectRatio?i=t.calculatedHeight*this._targetAspectRatio:n=t.calculatedWidth/this._targetAspectRatio}var r=t._isScreenSpace();if(this._updateMaterial(r),this._renderable&&this._renderable.forceUpdateAabb(),!this.sprite||1!==this.sprite.renderMode&&2!==this.sprite.renderMode){var a=e.vertexBuffer,o=new Float32Array(a.lock()),h=t.pivot.x,l=t.pivot.y;o[0]=i-h*i,o[1]=0-l*n,o[8]=i-h*i,o[9]=n-l*n,o[16]=0-h*i,o[17]=0-l*n,o[24]=0-h*i,o[25]=n-l*n;var c=1,u=1,d=this._rect;if(this._sprite&&this._sprite.frameKeys[this._spriteFrame]&&this._sprite.atlas){var f=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]];f&&(d=f.rect,c=this._sprite.atlas.texture.width,u=this._sprite.atlas.texture.height)}o[6]=(d.x+d.z)/c,o[7]=1-d.y/u,o[14]=(d.x+d.z)/c,o[15]=1-(d.y+d.w)/u,o[22]=d.x/c,o[23]=1-d.y/u,o[30]=d.x/c,o[31]=1-(d.y+d.w)/u,a.unlock();var p=new me(0-h*i,0-l*n,0),m=new me(i-h*i,n-l*n,0);e.aabb.setMinMax(p,m),this._renderable&&(this._renderable.node.setLocalScale(1,1,1),this._renderable.node.setLocalPosition(0,0,0),this._renderable.setAabbFunc(null))}else{var _=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]],g=2/_.rect.z,v=2/_.rect.w;this._innerOffset.set(_.border.x*g,_.border.y*v,_.border.z*g,_.border.w*v);var y=this.sprite.atlas.texture;this._atlasRect.set(_.rect.x/y.width,_.rect.y/y.height,_.rect.z/y.width,_.rect.w/y.height);var x=null!==this._pixelsPerUnit?this._pixelsPerUnit:this.sprite.pixelsPerUnit,S=_.rect.z/x,b=_.rect.w/x;this._outerScale.set(Math.max(i,this._innerOffset.x*S),Math.max(n,this._innerOffset.y*b));var w=S,T=b;this._outerScale.x/=S,this._outerScale.y/=b,w*=ce.clamp(i/(this._innerOffset.x*S),1e-4,1),T*=ce.clamp(n/(this._innerOffset.y*b),1e-4,1),this._renderable&&(this._innerOffsetUniform[0]=this._innerOffset.x,this._innerOffsetUniform[1]=this._innerOffset.y,this._innerOffsetUniform[2]=this._innerOffset.z,this._innerOffsetUniform[3]=this._innerOffset.w,this._renderable.setParameter("innerOffset",this._innerOffsetUniform),this._atlasRectUniform[0]=this._atlasRect.x,this._atlasRectUniform[1]=this._atlasRect.y,this._atlasRectUniform[2]=this._atlasRect.z,this._atlasRectUniform[3]=this._atlasRect.w,this._renderable.setParameter("atlasRect",this._atlasRectUniform),this._outerScaleUniform[0]=this._outerScale.x,this._outerScaleUniform[1]=this._outerScale.y,this._renderable.setParameter("outerScale",this._outerScaleUniform),this._renderable.setAabbFunc(this._updateAabbFunc),this._renderable.node.setLocalScale(w,T,1),this._renderable.node.setLocalPosition((.5-t.pivot.x)*i,(.5-t.pivot.y)*n,0))}this._meshDirty=!1},t._updateSprite=function(){var e=!1,t=null;if(this._targetAspectRatio=-1,this._sprite&&this._sprite.atlas){t=this._sprite.meshes[this.spriteFrame],e=1===this._sprite.renderMode||2===this._sprite.renderMode;var i=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]];(null==i?void 0:i.rect.w)>0&&(this._targetAspectRatio=i.rect.z/i.rect.w)}this.mesh=e?t:this._defaultMesh,this.refreshMesh()},t.refreshMesh=function(){this.mesh&&(this._element._beingInitialized?this._meshDirty=!0:this._updateMesh(this.mesh))},t._updateAabb=function(e){return e.center.set(0,0,0),e.halfExtents.set(.5*this._outerScale.x,.5*this._outerScale.y,.001),e.setFromTransformedAabb(e,this._renderable.node.getWorldTransform()),e},t._toggleMask=function(){this._element._dirtifyMask();var e=this._element._isScreenSpace();this._updateMaterial(e),this._renderable.setMask(!!this._mask)},t._onMaterialLoad=function(e){this.material=e.resource},t._onMaterialAdded=function(e){this._system.app.assets.off("add:"+e.id,this._onMaterialAdded,this),this._materialAsset===e.id&&this._bindMaterialAsset(e)},t._bindMaterialAsset=function(e){this._entity.enabled&&(e.on("load",this._onMaterialLoad,this),e.on("change",this._onMaterialChange,this),e.on("remove",this._onMaterialRemove,this),e.resource?this._onMaterialLoad(e):this._system.app.assets.load(e))},t._unbindMaterialAsset=function(e){e.off("load",this._onMaterialLoad,this),e.off("change",this._onMaterialChange,this),e.off("remove",this._onMaterialRemove,this)},t._onMaterialChange=function(){},t._onMaterialRemove=function(){},t._onTextureAdded=function(e){this._system.app.assets.off("add:"+e.id,this._onTextureAdded,this),this._textureAsset===e.id&&this._bindTextureAsset(e)},t._bindTextureAsset=function(e){this._entity.enabled&&(e.on("load",this._onTextureLoad,this),e.on("change",this._onTextureChange,this),e.on("remove",this._onTextureRemove,this),e.resource?this._onTextureLoad(e):this._system.app.assets.load(e))},t._unbindTextureAsset=function(e){e.off("load",this._onTextureLoad,this),e.off("change",this._onTextureChange,this),e.off("remove",this._onTextureRemove,this)},t._onTextureLoad=function(e){this.texture=e.resource},t._onTextureChange=function(e){},t._onTextureRemove=function(e){},t._onSpriteAssetAdded=function(e){this._system.app.assets.off("add:"+e.id,this._onSpriteAssetAdded,this),this._spriteAsset===e.id&&this._bindSpriteAsset(e)},t._bindSpriteAsset=function(e){this._entity.enabled&&(e.on("load",this._onSpriteAssetLoad,this),e.on("change",this._onSpriteAssetChange,this),e.on("remove",this._onSpriteAssetRemove,this),e.resource?this._onSpriteAssetLoad(e):this._system.app.assets.load(e))},t._unbindSpriteAsset=function(e){e.off("load",this._onSpriteAssetLoad,this),e.off("change",this._onSpriteAssetChange,this),e.off("remove",this._onSpriteAssetRemove,this),e.data.textureAtlasAsset&&this._system.app.assets.off("load:"+e.data.textureAtlasAsset,this._onTextureAtlasLoad,this)},t._onSpriteAssetLoad=function(e){if(e&&e.resource)if(e.resource.atlas)this.sprite=e.resource;else{var t=e.data.textureAtlasAsset;if(t){var i=this._system.app.assets;i.off("load:"+t,this._onTextureAtlasLoad,this),i.once("load:"+t,this._onTextureAtlasLoad,this)}}else this.sprite=null},t._onSpriteAssetChange=function(e){this._onSpriteAssetLoad(e)},t._onSpriteAssetRemove=function(e){},t._bindSprite=function(e){e.on("set:meshes",this._onSpriteMeshesChange,this),e.on("set:pixelsPerUnit",this._onSpritePpuChange,this),e.on("set:atlas",this._onAtlasTextureChange,this),e.atlas&&e.atlas.on("set:texture",this._onAtlasTextureChange,this)},t._unbindSprite=function(e){e.off("set:meshes",this._onSpriteMeshesChange,this),e.off("set:pixelsPerUnit",this._onSpritePpuChange,this),e.off("set:atlas",this._onAtlasTextureChange,this),e.atlas&&e.atlas.off("set:texture",this._onAtlasTextureChange,this)},t._onSpriteMeshesChange=function(){this._sprite&&(this._spriteFrame=ce.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite()},t._onSpritePpuChange=function(){0!==this.sprite.renderMode&&null===this._pixelsPerUnit&&this._updateSprite()},t._onAtlasTextureChange=function(){this.sprite&&this.sprite.atlas&&this.sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"))},t._onTextureAtlasLoad=function(e){var t=this._spriteAsset;t instanceof kd?this._onSpriteAssetLoad(t):this._onSpriteAssetLoad(this._system.app.assets.get(t))},t.onEnable=function(){if(this._materialAsset){var e=this._system.app.assets.get(this._materialAsset);e&&e.resource!==this._material&&this._bindMaterialAsset(e)}if(this._textureAsset){var t=this._system.app.assets.get(this._textureAsset);t&&t.resource!==this._texture&&this._bindTextureAsset(t)}if(this._spriteAsset){var i=this._system.app.assets.get(this._spriteAsset);i&&i.resource!==this._sprite&&this._bindSpriteAsset(i)}this._element.addModelToLayers(this._renderable.model)},t.onDisable=function(){this._element.removeModelFromLayers(this._renderable.model)},t._setStencil=function(e){this._renderable.meshInstance.stencilFront=e,this._renderable.meshInstance.stencilBack=e;var t=0;if(this._element.maskedBy&&(t=this._element.maskedBy.element._image._maskRef),this._renderable.unmaskMeshInstance){var i=new Ri({ref:t+1,func:2,zpass:5});this._renderable.unmaskMeshInstance.stencilFront=i,this._renderable.unmaskMeshInstance.stencilBack=i}},t._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))}},Z(e,[{key:"color",get:function(){return this._color},set:function(e){var t=e.r,i=e.g,n=e.b;this._color.r===t&&this._color.g===i&&this._color.b===n||(this._color.r=t,this._color.g=i,this._color.b=n,this._colorUniform[0]=t,this._colorUniform[1]=i,this._colorUniform[2]=n,this._renderable.setParameter("material_emissive",this._colorUniform)),this._element&&this._element.fire("set:color",this._color)}},{key:"opacity",get:function(){return this._color.a},set:function(e){e!==this._color.a&&(this._color.a=e,this._renderable.setParameter("material_opacity",e)),this._element&&this._element.fire("set:opacity",e)}},{key:"rect",get:function(){return this._rect},set:function(e){var t,i,n,s;e instanceof ve?(t=e.x,i=e.y,n=e.z,s=e.w):(t=e[0],i=e[1],n=e[2],s=e[3]),t===this._rect.x&&i===this._rect.y&&n===this._rect.z&&s===this._rect.w||(this._rect.set(t,i,n,s),this._renderable.mesh&&(this._element._beingInitialized?this._meshDirty=!0:this._updateMesh(this._renderable.mesh)))}},{key:"material",get:function(){return this._material},set:function(e){if(this._material!==e){if(!e){var t=this._element._isScreenSpace();e=this.mask?t?this._system.defaultScreenSpaceImageMaskMaterial:this._system.defaultImageMaskMaterial:t?this._system.defaultScreenSpaceImageMaterial:this._system.defaultImageMaterial}if(this._material=e,this._materialAsset){var i=this._system.app.assets.get(this._materialAsset);i&&i.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._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._renderable.setParameter("material_emissive",this._colorUniform),this._renderable.setParameter("material_opacity",this._color.a)))}}},{key:"materialAsset",get:function(){return this._materialAsset},set:function(e){var t=this._system.app.assets,i=e;if(e instanceof kd&&(i=e.id),this._materialAsset!==i)if(this._removeMaterialAssetEvents(),this._materialAsset=i,this._materialAsset){var n=t.get(this._materialAsset);n?this._bindMaterialAsset(n):(this._materialAsset=null,this.material=null,this._materialAsset=i,t.on("add:"+this._materialAsset,this._onMaterialAdded,this))}else this._materialAsset=null,this.material=null,this._materialAsset=i}},{key:"texture",get:function(){return this._texture},set:function(e){if(this._texture!==e){if(this._textureAsset){var t=this._system.app.assets.get(this._textureAsset);t&&t.resource!==e&&(this.textureAsset=null)}if(this._texture=e,e){this._spriteAsset&&(this.spriteAsset=null),this._renderable.setParameter("texture_emissiveMap",this._texture),this._renderable.setParameter("texture_opacityMap",this._texture),this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._renderable.setParameter("material_emissive",this._colorUniform),this._renderable.setParameter("material_opacity",this._color.a);var i=this._texture.width/this._texture.height;i!==this._targetAspectRatio&&(this._targetAspectRatio=i,this._element.fitMode!==Np&&this.refreshMesh())}else this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"),this._targetAspectRatio=-1,this._element.fitMode!==Np&&this.refreshMesh()}}},{key:"textureAsset",get:function(){return this._textureAsset},set:function(e){var t=this._system.app.assets,i=e;if(e instanceof kd&&(i=e.id),this._textureAsset!==i){if(this._textureAsset){t.off("add:"+this._textureAsset,this._onTextureAdded,this);var n=t.get(this._textureAsset);n&&(n.off("load",this._onTextureLoad,this),n.off("change",this._onTextureChange,this),n.off("remove",this._onTextureRemove,this))}if(this._textureAsset=i,this._textureAsset){var s=t.get(this._textureAsset);s?this._bindTextureAsset(s):(this.texture=null,t.on("add:"+this._textureAsset,this._onTextureAdded,this))}else this.texture=null}}},{key:"spriteAsset",get:function(){return this._spriteAsset},set:function(e){var t=this._system.app.assets,i=e;if(e instanceof kd&&(i=e.id),this._spriteAsset!==i){if(this._spriteAsset){t.off("add:"+this._spriteAsset,this._onSpriteAssetAdded,this);var n=t.get(this._spriteAsset);n&&this._unbindSpriteAsset(n)}if(this._spriteAsset=i,this._spriteAsset){var s=t.get(this._spriteAsset);s?this._bindSpriteAsset(s):(this.sprite=null,t.on("add:"+this._spriteAsset,this._onSpriteAssetAdded,this))}else this.sprite=null}this._element&&this._element.fire("set:spriteAsset",i)}},{key:"sprite",get:function(){return this._sprite},set:function(e){if(this._sprite!==e){if(this._sprite&&this._unbindSprite(this._sprite),this._spriteAsset){var t=this._system.app.assets.get(this._spriteAsset);t&&t.resource!==e&&(this.spriteAsset=null)}this._sprite=e,this._sprite&&(this._bindSprite(this._sprite),this._textureAsset&&(this.textureAsset=null)),this._sprite&&this._sprite.atlas&&this._sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap")),this._sprite&&(this._spriteFrame=ce.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=ce.clamp(e,0,this._sprite.frameKeys.length-1):this._spriteFrame=e,this._spriteFrame!==t&&this._updateSprite(),this._element&&this._element.fire("set:spriteFrame",e)}},{key:"mesh",get:function(){return this._renderable.mesh},set:function(e){this._renderable.setMesh(e),this._defaultMesh===e?this._renderable.setAabbFunc(null):this._renderable.setAabbFunc(this._updateAabbFunc)}},{key:"mask",get:function(){return this._mask},set:function(e){this._mask!==e&&(this._mask=e,this._toggleMask())}},{key:"pixelsPerUnit",get:function(){return this._pixelsPerUnit},set:function(e){this._pixelsPerUnit!==e&&(this._pixelsPerUnit=e,!this._sprite||1!==this._sprite.renderMode&&2!==this._sprite.renderMode||this._updateSprite())}},{key:"aabb",get:function(){return this._renderable.meshInstance?this._renderable.meshInstance.aabb:null}}]),e}(),Rm=function(e){function t(t){var i;return(i=e.call(this)||this)._app=t,t.i18n.on("set:locale",i._onSetLocale,ee(i)),i._autoLoad=!1,i._disableLocalization=!1,i._defaultAsset=null,i._localizedAsset=null,i}Q(t,e);var i=t.prototype;return i._bindDefaultAsset=function(){var e=this._app.assets.get(this._defaultAsset);e?this._onDefaultAssetAdd(e):this._app.assets.once("add:"+this._defaultAsset,this._onDefaultAssetAdd,this)},i._unbindDefaultAsset=function(){if(this._defaultAsset){this._app.assets.off("add:"+this._defaultAsset,this._onDefaultAssetAdd,this);var e=this._app.assets.get(this._defaultAsset);e&&(e.off("add:localized",this._onLocaleAdd,this),e.off("remove:localized",this._onLocaleRemove,this),e.off("remove",this._onDefaultAssetRemove,this))}},i._onDefaultAssetAdd=function(e){this._defaultAsset===e.id&&(e.on("add:localized",this._onLocaleAdd,this),e.on("remove:localized",this._onLocaleRemove,this),e.once("remove",this._onDefaultAssetRemove,this))},i._onDefaultAssetRemove=function(e){this._defaultAsset===e.id&&(e.off("add:localized",this._onLocaleAdd,this),e.off("remove:localized",this._onLocaleAdd,this),this._app.assets.once("add:"+this._defaultAsset,this._onDefaultAssetAdd,this))},i._bindLocalizedAsset=function(){if(this._autoLoad){var e=this._app.assets.get(this._localizedAsset);e&&(e.on("load",this._onLocalizedAssetLoad,this),e.on("change",this._onLocalizedAssetChange,this),e.on("remove",this._onLocalizedAssetRemove,this),e.resource?this._onLocalizedAssetLoad(e):this._app.assets.load(e))}},i._unbindLocalizedAsset=function(){var e=this._app.assets.get(this._localizedAsset);e&&(e.off("load",this._onLocalizedAssetLoad,this),e.off("change",this._onLocalizedAssetChange,this),e.off("remove",this._onLocalizedAssetRemove,this))},i._onLocalizedAssetAdd=function(e){this._localizedAsset===e.id&&this._bindLocalizedAsset()},i._onLocalizedAssetLoad=function(e){this.fire("load",e)},i._onLocalizedAssetChange=function(e,t,i,n){this.fire("change",e,t,i,n)},i._onLocalizedAssetRemove=function(e){this._localizedAsset===e.id&&(this.localizedAsset=this._defaultAsset),this.fire("remove",e)},i._onLocaleAdd=function(e,t){this._app.i18n.locale===e&&this._onSetLocale(e)},i._onLocaleRemove=function(e,t){this._app.i18n.locale===e&&this._onSetLocale(e)},i._onSetLocale=function(e){if(this._defaultAsset){var t=this._app.assets.get(this._defaultAsset);if(t&&!this._disableLocalization){var i=t.getLocalizedAssetId(e);this.localizedAsset=i||this._defaultAsset}else this.localizedAsset=this._defaultAsset}else this.localizedAsset=null},i.destroy=function(){this.defaultAsset=null,this._app.i18n.off("set:locale",this._onSetLocale,this),this.off()},Z(t,[{key:"defaultAsset",get:function(){return this._defaultAsset},set:function(e){var t=e instanceof kd?e.id:e;this._defaultAsset!==t&&(this._defaultAsset&&this._unbindDefaultAsset(),this._defaultAsset=t,this._defaultAsset&&this._bindDefaultAsset(),this._onSetLocale(this._app.i18n.locale))}},{key:"localizedAsset",get:function(){return this._localizedAsset},set:function(e){var t=e instanceof kd?e.id:e;this._localizedAsset!==t&&(this._localizedAsset&&(this._app.assets.off("add:"+this._localizedAsset,this._onLocalizedAssetAdd,this),this._unbindLocalizedAsset(),this._localizedAsset=null),this._localizedAsset=t,this._localizedAsset&&(this._app.assets.get(this._localizedAsset)?this._bindLocalizedAsset():this._app.assets.once("add:"+this._localizedAsset,this._onLocalizedAssetAdd,this)))}},{key:"autoLoad",get:function(){return this._autoLoad},set:function(e){this._autoLoad!==e&&(this._autoLoad=e,this._autoLoad&&this._localizedAsset&&(this._unbindLocalizedAsset(),this._bindLocalizedAsset()))}},{key:"disableLocalization",get:function(){return this._disableLocalization},set:function(e){this._disableLocalization!==e&&(this._disableLocalization=e,this._onSetLocale(this._app.i18n.locale))}}]),t}(p),Im="msdf",Lm="bitmap",Dm=/[A-Z|a-z|0-9|_|-|/]/,Om=function(){function e(e){this._symbols=e,this._index=0,this._last=0,this._cur=this._symbols.length>0?this._symbols[0]:null,this._buf=[],this._mode="text",this._error=null}var t=e.prototype;return t.read=function(){for(var e=this._read();8===e;)e=this._read();return 0!==e&&1!==e&&(this._last=this._index),e},t.buf=function(){return this._buf},t.last=function(){return this._last},t.error=function(){return this._error},t.debugPrint=function(){for(var e=["EOF","ERROR","TEXT","OPEN_BRACKET","CLOSE_BRACKET","EQUALS","STRING","IDENTIFIER","WHITESPACE"],t=this.read(),i="";i+=(i.length>0?"\n":"")+e[t]+" '"+this.buf().join("")+"'",0!==t&&1!==t;)t=this.read();return i},t._read=function(){return this._buf=[],this._eof()?0:"text"===this._mode?this._text():this._tag()},t._text=function(){for(;;)switch(this._cur){case null:return this._buf.length>0?2:0;case"[":return this._mode="tag",this._buf.length>0?2:this._tag();case"\\":if(this._next(),"["===this._cur)this._store();else this._output("\\");break;default:this._store()}},t._tag=function(){switch(this._cur){case null:return this._error="unexpected end of input reading tag",1;case"[":return this._store(),3;case"]":return this._store(),this._mode="text",4;case"=":return this._store(),5;case" ":case"\t":case"\n":case"\r":case"\v":case"\f":return this._whitespace();case'"':return this._string();default:return this._isIdentifierSymbol(this._cur)?this._identifier():(this._error="unrecognized character",1)}},t._whitespace=function(){for(this._store();-1!==" \t\n\r\v\f".indexOf(this._cur);)this._store();return 8},t._string=function(){for(this._next();;)switch(this._cur){case null:return this._error="unexpected end of input reading string",1;case'"':return this._next(),6;default:this._store()}},t._identifier=function(){for(this._store();null!==this._cur&&this._isIdentifierSymbol(this._cur);)this._store();return 7},t._isIdentifierSymbol=function(e){return 1===e.length&&null!==e.match(Dm)},t._eof=function(){return null===this._cur},t._next=function(){return this._eof()||(this._index++,this._cur=this._index<this._symbols.length?this._symbols[this._index]:null),this._cur},t._store=function(){return this._buf.push(this._cur),this._next()},t._output=function(e){this._buf.push(e)},e}(),km=function(){function e(e){this._scanner=new Om(e),this._error=null}var t=e.prototype;return t.parse=function(e,t){for(;;){switch(this._scanner.read()){case 0:return!0;case 1:default:return!1;case 2:Array.prototype.push.apply(e,this._scanner.buf());break;case 3:if(!this._parseTag(e,t))return!1}}},t.error=function(){return"Error evaluating markup at #"+this._scanner.last().toString()+" ("+(this._scanner.error()||this._error)+")"},t._parseTag=function(e,t){var i=this._scanner.read();if(7!==i)return this._error="expected identifier",!1;var n=this._scanner.buf().join("");if("/"===n[0]){for(var s=t.length-1;s>=0;--s)if(n==="/"+t[s].name&&null===t[s].end)return t[s].end=e.length,4===(i=this._scanner.read())||(this._error="expected close bracket",!1);return this._error="failed to find matching tag",!1}var r={name:n,value:null,attributes:{},start:e.length,end:null};if(5===(i=this._scanner.read())){if(6!==(i=this._scanner.read()))return this._error="expected string",!1;r.value=this._scanner.buf().join(""),i=this._scanner.read()}for(;;){switch(i){case 4:return t.push(r),!0;case 7:var a=this._scanner.buf().join("");if(5!==(i=this._scanner.read()))return this._error="expected equals",!1;if(6!==(i=this._scanner.read()))return this._error="expected string",!1;var o=this._scanner.buf().join("");r.attributes[a]=o;break;default:return this._error="expected close bracket or identifier",!1}i=this._scanner.read()}},e}();function Fm(e,t){for(var i in t)if(t.hasOwnProperty(i)){var n=t[i];n instanceof Object?(e.hasOwnProperty(i)||(e[i]={}),Fm(e[i],t[i])):e[i]=n}}function Bm(e){if(0===e.length)return null;for(var t={},i=0;i<e.length;++i){var n=e[i],s={};s[n.name]={value:n.value,attributes:n.attributes},Fm(t,s)}return t}function Nm(e){var t=new km(e),i=[],n=[];if(!t.parse(i,n))return console.warn(t.error()),{symbols:e,tags:null};var s=n.find((function(e){return null===e.end}));if(s)return console.warn("Markup error: found unclosed tag='"+s.name+"'"),{symbols:e,tags:null};var r=function(e,t){if(0===e.length)return null;for(var i={},n=0;n<e.length;++n){var s=e[n];i.hasOwnProperty(s.start)?null===i[s.start].open?i[s.start].open=[s]:i[s.start].open.push(s):i[s.start]={open:[s],close:null},i.hasOwnProperty(s.end)?null===i[s.end].close?i[s.end].close=[s]:i[s.end].close.push(s):i[s.end]={open:null,close:[s]}}var r=[];function a(e){r=r.filter((function(t){return void 0===e.find((function(e){return e===t}))}))}function o(e){for(var t=0;t<e.length;++t)r.push(e[t])}for(var h=Object.keys(i).sort((function(e,t){return e-t})),l=[],c=0;c<h.length;++c){var u=i[h[c]];null!==u.close&&a(u.close),null!==u.open&&o(u.open),l.push({start:h[c],tags:Bm(r)})}for(var d=[],f=null,p=0;p<l.length;++p){for(var m=l[p];d.length<m.start;)d.push(f?f.tags:null);f=m}for(;d.length<t;)d.push(null);return d}(n,i.length);return{symbols:i,tags:r}}var Um=function(){function e(){}return e.evaluate=function(e){return Nm(e)},e}(),zm=function(){this.count=0,this.quad=0,this.lines={},this.positions=[],this.normals=[],this.uvs=[],this.colors=[],this.indices=[],this.outlines=[],this.shadows=[],this.meshInstance=null};function Vm(e,t){var i=new Jr(e);return i.setPositions(t.positions),i.setNormals(t.normals),i.setColors32(t.colors),i.setUvs(0,t.uvs),i.setIndices(t.indices),i.setVertexStream(Dt,t.outlines,3,void 0,6,!1),i.setVertexStream(Ot,t.shadows,3,void 0,6,!1),i.update(),i}var Gm=/^[\r\n]$/,Hm=/^[ \t]$/,Wm=/^[ \t\-]|[\u200b]$/,Xm=/^[a-z0-9]$/i,jm=/^[\u1100-\u11ff]|[\u3000-\u9fff]|[\ua960-\ua97f]|[\uac00-\ud7ff]$/,qm=/^[〕〉》」』】〙〗〟ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻]$/,Ym=["","","","","","","","","","","","",""],Km={width:0,height:0,xadvance:0,xoffset:0,yoffset:0},Zm=new ue,$m=new ge,Qm=function(){function e(e){this._element=e,this._system=e.system,this._entity=e.entity,this._text="",this._symbols=[],this._colorPalette=[],this._outlinePalette=[],this._shadowPalette=[],this._symbolColors=null,this._symbolOutlineParams=null,this._symbolShadowParams=null,this._i18nKey=null,this._fontAsset=new Rm(this._system.app),this._fontAsset.disableLocalization=!0,this._fontAsset.on("load",this._onFontLoad,this),this._fontAsset.on("change",this._onFontChange,this),this._fontAsset.on("remove",this._onFontRemove,this),this._font=null,this._color=new ue(1,1,1,1),this._colorUniform=new Float32Array(3),this._spacing=1,this._fontSize=32,this._fontMinY=0,this._fontMaxY=0,this._originalFontSize=32,this._maxFontSize=32,this._minFontSize=8,this._autoFitWidth=!1,this._autoFitHeight=!1,this._maxLines=-1,this._lineHeight=32,this._scaledLineHeight=32,this._wrapLines=!1,this._drawOrder=0,this._alignment=new ge(.5,.5),this._autoWidth=!0,this._autoHeight=!0,this.width=0,this.height=0,this._node=new go,this._model=new Uc,this._model.graph=this._node,this._entity.addChild(this._node),this._meshInfo=[],this._material=null,this._aabbDirty=!0,this._aabb=new Ie,this._noResize=!1,this._currentMaterialType=null,this._maskedMaterialSrc=null,this._rtlReorder=!1,this._unicodeConverter=!1,this._rtl=!1,this._outlineColor=new ue(0,0,0,1),this._outlineColorUniform=new Float32Array(4),this._outlineThicknessScale=.2,this._outlineThickness=0,this._shadowColor=new ue(0,0,0,1),this._shadowColorUniform=new Float32Array(4),this._shadowOffsetScale=.005,this._shadowOffset=new ge(0,0),this._shadowOffsetUniform=new Float32Array(2),this._enableMarkup=!1,this._onScreenChange(this._element.screen),e.on("resize",this._onParentResize,this),e.on("set:screen",this._onScreenChange,this),e.on("screen:set:screenspace",this._onScreenSpaceChange,this),e.on("set:draworder",this._onDrawOrderChange,this),e.on("set:pivot",this._onPivotChange,this),this._system.app.i18n.on("set:locale",this._onLocaleSet,this),this._system.app.i18n.on("data:add",this._onLocalizationData,this),this._system.app.i18n.on("data:remove",this._onLocalizationData,this),this._rangeStart=0,this._rangeEnd=0}var t=e.prototype;return t.destroy=function(){this._setMaterial(null),this._model&&(this._element.removeModelFromLayers(this._model),this._model.destroy(),this._model=null),this._fontAsset.destroy(),this.font=null,this._element.off("resize",this._onParentResize,this),this._element.off("set:screen",this._onScreenChange,this),this._element.off("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.off("set:draworder",this._onDrawOrderChange,this),this._element.off("set:pivot",this._onPivotChange,this),this._system.app.i18n.off("set:locale",this._onLocaleSet,this),this._system.app.i18n.off("data:add",this._onLocalizationData,this),this._system.app.i18n.off("data:remove",this._onLocalizationData,this)},t._onParentResize=function(e,t){this._noResize||this._font&&this._updateText()},t._onScreenChange=function(e){e?this._updateMaterial(e.screen.screenSpace):this._updateMaterial(!1)},t._onScreenSpaceChange=function(e){this._updateMaterial(e)},t._onDrawOrderChange=function(e){if(this._drawOrder=e,this._model)for(var t=0,i=this._model.meshInstances.length;t<i;t++)this._model.meshInstances[t].drawOrder=e},t._onPivotChange=function(e){this._font&&this._updateText()},t._onLocaleSet=function(e){if(this._i18nKey){if(this.fontAsset){var t=this._system.app.assets.get(this.fontAsset);t&&t.resource&&t.resource===this._font||(this.font=null)}this._resetLocalizedText()}},t._onLocalizationData=function(e,t){this._i18nKey&&t[this._i18nKey]&&this._resetLocalizedText()},t._resetLocalizedText=function(){this._setText(this._system.app.i18n.getText(this._i18nKey))},t._setText=function(e){if(this.unicodeConverter){var t=this._system.getUnicodeConverter();t?e=t(e):console.warn("Element created with unicodeConverter option but no unicodeConverter function registered")}this._text!==e&&(this._font&&this._updateText(e),this._text=e)},t._updateText=function(e){var t;if(void 0===e&&(e=this._text),this._symbols=G.getSymbols(e.normalize?e.normalize("NFC"):e),0===this._symbols.length&&(this._symbols=[" "]),this._enableMarkup){var i=Um.evaluate(this._symbols);this._symbols=i.symbols,t=i.tags||[]}if(this._rtlReorder){var n=this._system.app.systems.element.getRtlReorder();if(n){var s=n(this._symbols);this._rtl=s.rtl,this._symbols=s.mapping.map((function(e){return this._symbols[e]}),this),t&&(t=s.mapping.map((function(e){return t[e]})))}else console.warn("Element created with rtlReorder option but no rtlReorder function registered")}else this._rtl=!1;var r=function(e,t){return e.toString(!0).toLowerCase()+":"+t.toFixed(2)},a=function(e,t){return e.toString(!0).toLowerCase()+":"+t.x.toFixed(2)+":"+t.y.toFixed(2)};if(t){var o={},h={},l={};this._colorPalette=[Math.round(255*this._color.r),Math.round(255*this._color.g),Math.round(255*this._color.b)],this._outlinePalette=[Math.round(255*this._outlineColor.r),Math.round(255*this._outlineColor.g),Math.round(255*this._outlineColor.b),Math.round(255*this._outlineColor.a),Math.round(255*this._outlineThickness)],this._shadowPalette=[Math.round(255*this._shadowColor.r),Math.round(255*this._shadowColor.g),Math.round(255*this._shadowColor.b),Math.round(255*this._shadowColor.a),Math.round(127*this._shadowOffset.x),Math.round(127*this._shadowOffset.y)],this._symbolColors=[],this._symbolOutlineParams=[],this._symbolShadowParams=[],o[this._color.toString(!1).toLowerCase()]=0,h[r(this._outlineColor,this._outlineThickness)]=0,l[a(this._shadowColor,this._shadowOffset)]=0;for(var c=0,u=this._symbols.length;c<u;++c){var d=t[c],f=0;if(d&&d.color&&d.color.value){var p=d.color.value;if(7===p.length&&"#"===p[0]){var m=p.substring(1).toLowerCase();o.hasOwnProperty(m)?f=o[m]:/^([0-9a-f]{2}){3}$/.test(m)&&(f=this._colorPalette.length/3,o[m]=f,this._colorPalette.push(parseInt(m.substring(0,2),16)),this._colorPalette.push(parseInt(m.substring(2,4),16)),this._colorPalette.push(parseInt(m.substring(4,6),16)))}}this._symbolColors.push(f);var _=0;if(d&&d.outline&&(d.outline.attributes.color||d.outline.attributes.thickness)){var g=d.outline.attributes.color?Zm.fromString(d.outline.attributes.color):this._outlineColor,v=Number(d.outline.attributes.thickness);(Number.isNaN(g.r)||Number.isNaN(g.g)||Number.isNaN(g.b)||Number.isNaN(g.a))&&(g=this._outlineColor),Number.isNaN(v)&&(v=this._outlineThickness);var y=r(g,v);h.hasOwnProperty(y)?_=h[y]:(_=this._outlinePalette.length/5,h[y]=_,this._outlinePalette.push(Math.round(255*g.r),Math.round(255*g.g),Math.round(255*g.b),Math.round(255*g.a),Math.round(255*v)))}this._symbolOutlineParams.push(_);var x=0;if(d&&d.shadow&&(d.shadow.attributes.color||d.shadow.attributes.offset||d.shadow.attributes.offsetX||d.shadow.attributes.offsetY)){var S=d.shadow.attributes.color?Zm.fromString(d.shadow.attributes.color):this._shadowColor,b=Number(d.shadow.attributes.offset),w=Number(d.shadow.attributes.offsetX),T=Number(d.shadow.attributes.offsetY);(Number.isNaN(S.r)||Number.isNaN(S.g)||Number.isNaN(S.b)||Number.isNaN(S.a))&&(S=this._shadowColor);var A=$m.set(Number.isNaN(w)?Number.isNaN(b)?this._shadowOffset.x:b:w,Number.isNaN(T)?Number.isNaN(b)?this._shadowOffset.y:b:T),C=a(S,A);l.hasOwnProperty(C)?x=l[C]:(x=this._shadowPalette.length/6,l[C]=x,this._shadowPalette.push(Math.round(255*S.r),Math.round(255*S.g),Math.round(255*S.b),Math.round(255*S.a),Math.round(127*A.x),Math.round(127*A.y)))}this._symbolShadowParams.push(x)}}else this._colorPalette=[],this._symbolColors=null,this._symbolOutlineParams=null,this._symbolShadowParams=null;this._updateMaterialEmissive(),this._updateMaterialOutline(),this._updateMaterialShadow();for(var E=this._calculateCharsPerTexture(),M=!1,P=this._element,R=P._isScreenSpace(),I=P._isScreenCulled(),L=function(e){return P.isVisibleForCamera(e)},D=0,O=this._meshInfo.length;D<O;D++){var k=E[D]||0,F=this._meshInfo[D];if(F.count!==k){if(M||(P.removeModelFromLayers(this._model),M=!0),F.count=k,F.positions.length=F.normals.length=3*k*4,F.indices.length=3*k*2,F.uvs.length=2*k*4,F.colors.length=4*k*4,F.outlines.length=4*k*3,F.shadows.length=4*k*3,F.meshInstance&&this._removeMeshInstance(F.meshInstance),0===k){F.meshInstance=null;continue}for(var B=0;B<k;B++)F.indices[3*B*2+0]=4*B,F.indices[3*B*2+1]=4*B+1,F.indices[3*B*2+2]=4*B+3,F.indices[3*B*2+3]=4*B+2,F.indices[3*B*2+4]=4*B+3,F.indices[3*B*2+5]=4*B+1,F.normals[4*B*3+0]=0,F.normals[4*B*3+1]=0,F.normals[4*B*3+2]=-1,F.normals[4*B*3+3]=0,F.normals[4*B*3+4]=0,F.normals[4*B*3+5]=-1,F.normals[4*B*3+6]=0,F.normals[4*B*3+7]=0,F.normals[4*B*3+8]=-1,F.normals[4*B*3+9]=0,F.normals[4*B*3+10]=0,F.normals[4*B*3+11]=-1;var N=Vm(this._system.app.graphicsDevice,F),U=new Co(N,this._material,this._node);if(U.name="Text Element: "+this._entity.name,U.castShadow=!1,U.receiveShadow=!1,U.cull=!R,U.screenSpace=R,U.drawOrder=this._drawOrder,I&&(U.cull=!0,U.isVisibleFunc=L),this._setTextureParams(U,this._font.textures[D]),U.setParameter("material_emissive",this._colorUniform),U.setParameter("material_opacity",this._color.a),U.setParameter("font_sdfIntensity",this._font.intensity),U.setParameter("font_pxrange",this._getPxRange(this._font)),U.setParameter("font_textureWidth",this._font.data.info.maps[D].width),U.setParameter("outline_color",this._outlineColorUniform),U.setParameter("outline_thickness",this._outlineThicknessScale*this._outlineThickness),U.setParameter("shadow_color",this._shadowColorUniform),this._symbolShadowParams)this._shadowOffsetUniform[0]=0,this._shadowOffsetUniform[1]=0;else{var z=-this._font.data.info.maps[D].width/this._font.data.info.maps[D].height;this._shadowOffsetUniform[0]=this._shadowOffsetScale*this._shadowOffset.x,this._shadowOffsetUniform[1]=z*this._shadowOffsetScale*this._shadowOffset.y}U.setParameter("shadow_offset",this._shadowOffsetUniform),F.meshInstance=U,this._model.meshInstances.push(U)}}this._element.maskedBy&&this._element._setMaskedBy(this._element.maskedBy),M&&this._element.enabled&&this._entity.enabled&&this._element.addModelToLayers(this._model),this._updateMeshes(),this._rangeStart=0,this._rangeEnd=this._symbols.length,this._updateRenderRange()},t._removeMeshInstance=function(e){e.destroy();var t=this._model.meshInstances.indexOf(e);-1!==t&&this._model.meshInstances.splice(t,1)},t._setMaterial=function(e){if(this._material=e,this._model)for(var t=0,i=this._model.meshInstances.length;t<i;t++){this._model.meshInstances[t].material=e}},t._updateMaterial=function(e){var t=this._element,i=t._isScreenCulled(),n=function(e){return t.isVisibleForCamera(e)},s=this._font&&this._font.type===Im;if(this._material=this._system.getTextElementMaterial(e,s,this._enableMarkup),this._model)for(var r=0,a=this._model.meshInstances.length;r<a;r++){var o=this._model.meshInstances[r];o.cull=!e,o.material=this._material,o.screenSpace=e,i?(o.cull=!0,o.isVisibleFunc=n):o.isVisibleFunc=null}},t._updateMaterialEmissive=function(){this._symbolColors?(this._colorUniform[0]=1,this._colorUniform[1]=1,this._colorUniform[2]=1):(this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b)},t._updateMaterialOutline=function(){this._symbolOutlineParams?(this._outlineColorUniform[0]=0,this._outlineColorUniform[1]=0,this._outlineColorUniform[2]=0,this._outlineColorUniform[3]=1):(this._outlineColorUniform[0]=this._outlineColor.r,this._outlineColorUniform[1]=this._outlineColor.g,this._outlineColorUniform[2]=this._outlineColor.b,this._outlineColorUniform[3]=this._outlineColor.a)},t._updateMaterialShadow=function(){this._symbolOutlineParams?(this._shadowColorUniform[0]=0,this._shadowColorUniform[1]=0,this._shadowColorUniform[2]=0,this._shadowColorUniform[3]=0):(this._shadowColorUniform[0]=this._shadowColor.r,this._shadowColorUniform[1]=this._shadowColor.g,this._shadowColorUniform[2]=this._shadowColor.b,this._shadowColorUniform[3]=this._shadowColor.a)},t._isWordBoundary=function(e){return Wm.test(e)},t._isValidNextChar=function(e){return null!==e&&!qm.test(e)},t._isNextCJKBoundary=function(e,t){return jm.test(e)&&(Wm.test(t)||Xm.test(t))},t._isNextCJKWholeWord=function(e){return jm.test(e)},t._updateMeshes=function(){var e=this._font.data,t=this,i=Math.min(this._minFontSize,this._maxFontSize),n=this._maxFontSize,s=this._shouldAutoFit();s&&(this._fontSize=this._maxFontSize);var r=this._symbols.length,a=0,o=0,h=0,l=0,c=1,u=0,d=0,f=0,p=0,m=0,_=0,g=Math.abs(this._element.anchor.x-this._element.anchor.z)>=1e-4,v=this._element.calculatedWidth;(this.autoWidth&&!g||!this._wrapLines)&&(v=Number.POSITIVE_INFINITY);var y,x,S,b,w=0,T=0;function A(e,i,n){t._lineWidths.push(Math.abs(n));var s=f>i?i+1:f,r=f>i?f+1:i,h=e.slice(s,r);if(_)for(var l=h.length;l--&&_>0;)Gm.test(h[l])&&(h.splice(l,1),_--);t._lineContents.push(h.join("")),a=0,o-=t._scaledLineHeight,c++,p=0,m=0,_=0,u=0,f=i}for(var C=!0;C;){C=!1,this._scaledLineHeight=s?this._lineHeight*this._fontSize/(this._maxFontSize||1e-4):this._lineHeight,this.width=0,this.height=0,this._lineWidths=[],this._lineContents=[],a=0,o=0,h=0,l=0,c=1,u=0,d=0,f=0,p=0,m=0,_=0;var E=this._fontSize/32;w=this._fontMinY*E,T=this._fontMaxY*E;for(var M=0;M<this._meshInfo.length;M++)this._meshInfo[M].quad=0,this._meshInfo[M].lines={};for(var P=255,R=255,I=255,L=65535,D=65535,O=0,k=65535,F=65535,B=32639,N=0;N<r;N++){if(y=this._symbols[N],b=N+1>=r?null:this._symbols[N+1],Gm.test(y))_++,(!this._wrapLines||this._maxLines<0||c<this._maxLines)&&(A(this._symbols,N,l),d=N+1,f=N+1);else{var U=0,z=0,V=0,H=1,W=void 0;if(!(x=e.chars[y]))if(-1!==Ym.indexOf(y))x=Km;else if(e.chars[" "])x=e.chars[" "];else for(var X in e.chars){x=e.chars[X];break}if(x){var j=0;if(m>0){var q=this._font.data.kerning;if(q){var Y=q[G.getCodePoint(this._symbols[N-1])||0];Y&&(j=Y[G.getCodePoint(this._symbols[N])||0]||0)}}W=x.scale||1,H=E*((x.width+x.height)/2)/W,V=(x.xadvance+j)*E,U=(x.xoffset-j)*E,z=x.yoffset*E}else console.error("Couldn't substitute missing character: '"+y+"'");var K=Hm.test(y),Z=x&&x.map||0,$=-this._font.data.info.maps[Z].width/this._font.data.info.maps[Z].height,Q=this._meshInfo[Z],J=a+this._spacing*V;if(J>v&&m>0&&!K&&(this._maxLines<0||c<this._maxLines)){if(0!==p){var ee=Math.max(N-d,0);if(this._meshInfo.length<=1)Q.lines[c-1]-=ee,Q.quad-=ee;else for(var te=N,ie=d;ie<te;ie++){var ne=this._symbols[ie],se=e.chars[ne],re=this._meshInfo[se&&se.map||0];re.lines[c-1]-=1,re.quad-=1}N-=ee+1,A(this._symbols,d,u);continue}d=N,A(this._symbols,N,l)}S=Q.quad,Q.lines[c-1]=S;var ae=a-U,oe=ae+H,he=o-z,le=he+H;if(this._rtl){var ue=H-U-this._spacing*V-U;ae-=ue,oe-=ue}Q.positions[4*S*3+0]=ae,Q.positions[4*S*3+1]=he,Q.positions[4*S*3+2]=h,Q.positions[4*S*3+3]=oe,Q.positions[4*S*3+4]=he,Q.positions[4*S*3+5]=h,Q.positions[4*S*3+6]=oe,Q.positions[4*S*3+7]=le,Q.positions[4*S*3+8]=h,Q.positions[4*S*3+9]=ae,Q.positions[4*S*3+10]=le,Q.positions[4*S*3+11]=h,this.width=Math.max(this.width,J);var de=void 0;if(this._shouldAutoFitWidth()&&this.width>this._element.calculatedWidth&&(de=Math.floor(this._element.fontSize*this._element.calculatedWidth/(this.width||1e-4)),(de=ce.clamp(de,i,n))!==this._element.fontSize)){this._fontSize=de,C=!0;break}if(this.height=Math.max(this.height,T-(o+w)),this._shouldAutoFitHeight()&&this.height>this._element.calculatedHeight&&(de=ce.clamp(this._fontSize-1,i,n))!==this._element.fontSize){this._fontSize=de,C=!0;break}a+=this._spacing*V,K||(l=a),(this._isWordBoundary(y)||this._isValidNextChar(b)&&(this._isNextCJKBoundary(y,b)||this._isNextCJKWholeWord(b)))&&(p++,u=l,d=N+1),m++;var fe=this._getUv(y);if(Q.uvs[4*S*2+0]=fe[0],Q.uvs[4*S*2+1]=1-fe[1],Q.uvs[4*S*2+2]=fe[2],Q.uvs[4*S*2+3]=1-fe[1],Q.uvs[4*S*2+4]=fe[2],Q.uvs[4*S*2+5]=1-fe[3],Q.uvs[4*S*2+6]=fe[0],Q.uvs[4*S*2+7]=1-fe[3],this._symbolColors){var pe=3*this._symbolColors[N];P=this._colorPalette[pe],R=this._colorPalette[pe+1],I=this._colorPalette[pe+2]}if(Q.colors[4*S*4+0]=P,Q.colors[4*S*4+1]=R,Q.colors[4*S*4+2]=I,Q.colors[4*S*4+3]=255,Q.colors[4*S*4+4]=P,Q.colors[4*S*4+5]=R,Q.colors[4*S*4+6]=I,Q.colors[4*S*4+7]=255,Q.colors[4*S*4+8]=P,Q.colors[4*S*4+9]=R,Q.colors[4*S*4+10]=I,Q.colors[4*S*4+11]=255,Q.colors[4*S*4+12]=P,Q.colors[4*S*4+13]=R,Q.colors[4*S*4+14]=I,Q.colors[4*S*4+15]=255,this._symbolOutlineParams){var me=5*this._symbolOutlineParams[N];L=this._outlinePalette[me]+256*this._outlinePalette[me+1],D=this._outlinePalette[me+2]+256*this._outlinePalette[me+3],O=this._outlinePalette[me+4]}if(Q.outlines[4*S*3+0]=L,Q.outlines[4*S*3+1]=D,Q.outlines[4*S*3+2]=O,Q.outlines[4*S*3+3]=L,Q.outlines[4*S*3+4]=D,Q.outlines[4*S*3+5]=O,Q.outlines[4*S*3+6]=L,Q.outlines[4*S*3+7]=D,Q.outlines[4*S*3+8]=O,Q.outlines[4*S*3+9]=L,Q.outlines[4*S*3+10]=D,Q.outlines[4*S*3+11]=O,this._symbolShadowParams){var _e=6*this._symbolShadowParams[N];k=this._shadowPalette[_e]+256*this._shadowPalette[_e+1],F=this._shadowPalette[_e+2]+256*this._shadowPalette[_e+3],B=this._shadowPalette[_e+4]+127+256*Math.round($*this._shadowPalette[_e+5]+127)}Q.shadows[4*S*3+0]=k,Q.shadows[4*S*3+1]=F,Q.shadows[4*S*3+2]=B,Q.shadows[4*S*3+3]=k,Q.shadows[4*S*3+4]=F,Q.shadows[4*S*3+5]=B,Q.shadows[4*S*3+6]=k,Q.shadows[4*S*3+7]=F,Q.shadows[4*S*3+8]=B,Q.shadows[4*S*3+9]=k,Q.shadows[4*S*3+10]=F,Q.shadows[4*S*3+11]=B,Q.quad++}}C||f<r&&A(this._symbols,r,a)}this._noResize=!0,this.autoWidth=this._autoWidth,this.autoHeight=this._autoHeight,this._noResize=!1;for(var ge=this._element.pivot.x,ve=this._element.pivot.y,ye=this._alignment.x,xe=this._alignment.y,Se=0;Se<this._meshInfo.length;Se++)if(0!==this._meshInfo[Se].count){var be=0;for(var we in this._meshInfo[Se].lines){for(var Te=this._meshInfo[Se].lines[we],Ae=this._lineWidths[parseInt(we,10)],Ce=-ge*this._element.calculatedWidth+ye*(this._element.calculatedWidth-Ae)*(this._rtl?-1:1),Ee=(1-ve)*this._element.calculatedHeight-T-(1-xe)*(this._element.calculatedHeight-this.height),Me=be;Me<=Te;Me++)this._meshInfo[Se].positions[4*Me*3]+=Ce,this._meshInfo[Se].positions[4*Me*3+3]+=Ce,this._meshInfo[Se].positions[4*Me*3+6]+=Ce,this._meshInfo[Se].positions[4*Me*3+9]+=Ce,this._meshInfo[Se].positions[4*Me*3+1]+=Ee,this._meshInfo[Se].positions[4*Me*3+4]+=Ee,this._meshInfo[Se].positions[4*Me*3+7]+=Ee,this._meshInfo[Se].positions[4*Me*3+10]+=Ee;if(this._rtl)for(var Pe=be;Pe<=Te;Pe++){for(var Re=4*Pe*3,Ie=0;Ie<4;++Ie)this._meshInfo[Se].positions[Re+3*Ie]=this._element.calculatedWidth-this._meshInfo[Se].positions[Re+3*Ie]+2*Ce;var Le=this._meshInfo[Se].positions[Re+3],De=this._meshInfo[Se].positions[Re+6];this._meshInfo[Se].positions[Re+3]=this._meshInfo[Se].positions[Re+0],this._meshInfo[Se].positions[Re+6]=this._meshInfo[Se].positions[Re+9],this._meshInfo[Se].positions[Re+0]=Le,this._meshInfo[Se].positions[Re+9]=De}be=Te+1}for(var Oe=4*this._meshInfo[Se].count,ke=4*this._meshInfo[Se].quad,Fe=new zs(this._meshInfo[Se].meshInstance.mesh.vertexBuffer),Be=0;Be<Oe;Be++)Be>=ke?(Fe.element[lt].set(0,0,0),Fe.element[_t].set(0,0),Fe.element[pt].set(0,0,0,0),Fe.element[Dt].set(0,0,0,0),Fe.element[Ot].set(0,0,0,0)):(Fe.element[lt].set(this._meshInfo[Se].positions[3*Be+0],this._meshInfo[Se].positions[3*Be+1],this._meshInfo[Se].positions[3*Be+2]),Fe.element[_t].set(this._meshInfo[Se].uvs[2*Be+0],this._meshInfo[Se].uvs[2*Be+1]),Fe.element[pt].set(this._meshInfo[Se].colors[4*Be+0],this._meshInfo[Se].colors[4*Be+1],this._meshInfo[Se].colors[4*Be+2],this._meshInfo[Se].colors[4*Be+3]),Fe.element[Dt].set(this._meshInfo[Se].outlines[3*Be+0],this._meshInfo[Se].outlines[3*Be+1],this._meshInfo[Se].outlines[3*Be+2]),Fe.element[Ot].set(this._meshInfo[Se].shadows[3*Be+0],this._meshInfo[Se].shadows[3*Be+1],this._meshInfo[Se].shadows[3*Be+2])),Fe.next();Fe.end(),this._meshInfo[Se].meshInstance.mesh.aabb.compute(this._meshInfo[Se].positions),this._meshInfo[Se].meshInstance._aabbVer=-1}this._aabbDirty=!0},t._onFontRender=function(){this.font=this._font},t._onFontLoad=function(e){this.font!==e.resource&&(this.font=e.resource)},t._onFontChange=function(e,t,i,n){if("data"===t){this._font.data=i;for(var s=this._font.data.info.maps.length,r=0;r<s;r++)if(this._meshInfo[r]){var a=this._meshInfo[r].meshInstance;a&&(a.setParameter("font_sdfIntensity",this._font.intensity),a.setParameter("font_pxrange",this._getPxRange(this._font)),a.setParameter("font_textureWidth",this._font.data.info.maps[r].width))}}},t._onFontRemove=function(e){},t._setTextureParams=function(e,t){this._font&&(this._font.type===Im?(e.deleteParameter("texture_emissiveMap"),e.deleteParameter("texture_opacityMap"),e.setParameter("texture_msdfMap",t)):this._font.type===Lm&&(e.deleteParameter("texture_msdfMap"),e.setParameter("texture_emissiveMap",t),e.setParameter("texture_opacityMap",t)))},t._getPxRange=function(e){for(var t=Object.keys(this._font.data.chars),i=0;i<t.length;i++){var n=this._font.data.chars[t[i]];if(n.range)return(n.scale||1)*n.range}return 2},t._getUv=function(e){var t=this._font.data;if(!t.chars[e]){return t.chars[" "]?this._getUv(" "):[0,0,0,0]}var i=t.chars[e].map,n=t.info.maps[i].width,s=t.info.maps[i].height,r=t.chars[e].x,a=t.chars[e].y,o=r,h=a,l=r+t.chars[e].width,c=a-t.chars[e].height,u=1-t.chars[e].height/s;return[o/n,u-h/s,l/n,u-c/s]},t.onEnable=function(){this._fontAsset.autoLoad=!0,this._model&&this._element.addModelToLayers(this._model)},t.onDisable=function(){this._fontAsset.autoLoad=!1,this._model&&this._element.removeModelFromLayers(this._model)},t._setStencil=function(e){if(this._model)for(var t=this._model.meshInstances,i=0;i<t.length;i++)t[i].stencilFront=e,t[i].stencilBack=e},t._shouldAutoFitWidth=function(){return this._autoFitWidth&&!this._autoWidth},t._shouldAutoFitHeight=function(){return this._autoFitHeight&&!this._autoHeight},t._shouldAutoFit=function(){return this._autoFitWidth&&!this._autoWidth||this._autoFitHeight&&!this._autoHeight},t._calculateCharsPerTexture=function(e){var t={};void 0===e&&(e=this._symbols.length);for(var i=0,n=e;i<n;i++){var s=this._symbols[i],r=this._font.data.chars[s];r||(r=this._font.data.chars[" "])||(r=this._font.data.chars[Object.keys(this._font.data.chars)[0]]);var a=r.map;t[a]?t[a]++:t[a]=1}return t},t._updateRenderRange=function(){for(var e=0===this._rangeStart?0:this._calculateCharsPerTexture(this._rangeStart),t=0===this._rangeEnd?0:this._calculateCharsPerTexture(this._rangeEnd),i=0,n=this._meshInfo.length;i<n;i++){var s=e[i]||0,r=t[i]||0,a=this._meshInfo[i].meshInstance;if(a){var o=a.mesh;o&&(o.primitive[0].base=3*s*2,o.primitive[0].count=3*(r-s)*2)}}},Z(e,[{key:"text",get:function(){return this._text},set:function(e){this._i18nKey=null;var t=null!=e&&e.toString()||"";this._setText(t)}},{key:"key",get:function(){return this._i18nKey},set:function(e){var t=null!==e?e.toString():null;this._i18nKey!==t&&(this._i18nKey=t,t?(this._fontAsset.disableLocalization=!1,this._resetLocalizedText()):this._fontAsset.disableLocalization=!0)}},{key:"color",get:function(){return this._color},set:function(e){var t=e.r,i=e.g,n=e.b;if((this._color.r!==t||this._color.g!==i||this._color.b!==n)&&(this._color.r=t,this._color.g=i,this._color.b=n,this._model)){if(this._symbolColors)this._font&&this._updateText();else{this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b;for(var s=0,r=this._model.meshInstances.length;s<r;s++){this._model.meshInstances[s].setParameter("material_emissive",this._colorUniform)}}this._element&&this._element.fire("set:color",this._color)}}},{key:"opacity",get:function(){return this._color.a},set:function(e){if(this._color.a!==e&&(this._color.a=e,this._model))for(var t=0,i=this._model.meshInstances.length;t<i;t++){this._model.meshInstances[t].setParameter("material_opacity",e)}this._element&&this._element.fire("set:opacity",e)}},{key:"lineHeight",get:function(){return this._lineHeight},set:function(e){var t=this._lineHeight;this._lineHeight=e,this._scaledLineHeight=e,t!==e&&this._font&&this._updateText()}},{key:"wrapLines",get:function(){return this._wrapLines},set:function(e){var t=this._wrapLines;this._wrapLines=e,t!==e&&this._font&&this._updateText()}},{key:"lines",get:function(){return this._lineContents}},{key:"spacing",get:function(){return this._spacing},set:function(e){var t=this._spacing;this._spacing=e,t!==e&&this._font&&this._updateText()}},{key:"fontSize",get:function(){return this._fontSize},set:function(e){var t=this._fontSize;this._fontSize=e,this._originalFontSize=e,t!==e&&this._font&&this._updateText()}},{key:"fontAsset",get:function(){return this._fontAsset.localizedAsset},set:function(e){this._fontAsset.defaultAsset=e}},{key:"font",get:function(){return this._font},set:function(e){var t;if(this._font&&(t=this._font.type,this._font.off&&this._font.off("render",this._onFontRender,this)),this._font=e,this._fontMinY=0,this._fontMaxY=0,e){var i=this._font.data;for(var n in i.chars){var s=i.chars[n];s.bounds&&(this._fontMinY=Math.min(this._fontMinY,s.bounds[1]),this._fontMaxY=Math.max(this._fontMaxY,s.bounds[3]))}if(this._font.on&&this._font.on("render",this._onFontRender,this),this._fontAsset.localizedAsset)this._system.app.assets.get(this._fontAsset.localizedAsset).resource!==this._font&&(this._fontAsset.defaultAsset=null);if(e.type!==t){var r=this._element._isScreenSpace();this._updateMaterial(r)}for(var a=0,o=this._font.textures.length;a<o;a++)if(this._meshInfo[a]){var h=this._meshInfo[a].meshInstance;h&&(h.setParameter("font_sdfIntensity",this._font.intensity),h.setParameter("font_pxrange",this._getPxRange(this._font)),h.setParameter("font_textureWidth",this._font.data.info.maps[a].width),this._setTextureParams(h,this._font.textures[a]))}else this._meshInfo[a]=new zm;for(var l=!1,c=this._font.textures.length;c<this._meshInfo.length;c++)this._meshInfo[c].meshInstance&&(l||(this._element.removeModelFromLayers(this._model),l=!0),this._removeMeshInstance(this._meshInfo[c].meshInstance));this._meshInfo.length>this._font.textures.length&&(this._meshInfo.length=this._font.textures.length),this._updateText()}}},{key:"alignment",get:function(){return this._alignment},set:function(e){e instanceof ge?this._alignment.set(e.x,e.y):this._alignment.set(e[0],e[1]),this._font&&this._updateText()}},{key:"autoWidth",get:function(){return this._autoWidth},set:function(e){var t=this._autoWidth;if(this._autoWidth=e,e&&Math.abs(this._element.anchor.x-this._element.anchor.z)<1e-4&&(this._element.width=this.width),t!==e){var i=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;i!==this._fontSize&&(this._fontSize=i,this._font&&this._updateText())}}},{key:"autoHeight",get:function(){return this._autoHeight},set:function(e){var t=this._autoHeight;if(this._autoHeight=e,e&&Math.abs(this._element.anchor.y-this._element.anchor.w)<1e-4&&(this._element.height=this.height),t!==e){var i=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;i!==this._fontSize&&(this._fontSize=i,this._font&&this._updateText())}}},{key:"rtlReorder",get:function(){return this._rtlReorder},set:function(e){this._rtlReorder!==e&&(this._rtlReorder=e,this._font&&this._updateText())}},{key:"unicodeConverter",get:function(){return this._unicodeConverter},set:function(e){this._unicodeConverter!==e&&(this._unicodeConverter=e,this._setText(this._text))}},{key:"aabb",get:function(){if(this._aabbDirty){for(var e=!1,t=0;t<this._meshInfo.length;t++)this._meshInfo[t].meshInstance&&(e?this._aabb.add(this._meshInfo[t].meshInstance.aabb):(this._aabb.copy(this._meshInfo[t].meshInstance.aabb),e=!0));this._aabbDirty=!1}return this._aabb}},{key:"outlineColor",get:function(){return this._outlineColor},set:function(e){var t=e instanceof ue?e.r:e[0],i=e instanceof ue?e.g:e[1],n=e instanceof ue?e.b:e[2],s=e instanceof ue?e.a:e[3];if((this._outlineColor.r!==t||this._outlineColor.g!==i||this._outlineColor.b!==n||this._outlineColor.a!==s)&&(this._outlineColor.r=t,this._outlineColor.g=i,this._outlineColor.b=n,this._outlineColor.a=s,this._model)){if(this._symbolOutlineParams)this._font&&this._updateText();else{this._outlineColorUniform[0]=this._outlineColor.r,this._outlineColorUniform[1]=this._outlineColor.g,this._outlineColorUniform[2]=this._outlineColor.b,this._outlineColorUniform[3]=this._outlineColor.a;for(var r=0,a=this._model.meshInstances.length;r<a;r++){this._model.meshInstances[r].setParameter("outline_color",this._outlineColorUniform)}}this._element&&this._element.fire("set:outline",this._color)}}},{key:"outlineThickness",get:function(){return this._outlineThickness},set:function(e){var t=this._outlineThickness;if(this._outlineThickness=e,t!==e&&this._font){if(!this._model)return;if(this._symbolOutlineParams)this._font&&this._updateText();else for(var i=0,n=this._model.meshInstances.length;i<n;i++){this._model.meshInstances[i].setParameter("outline_thickness",this._outlineThicknessScale*this._outlineThickness)}}}},{key:"shadowColor",get:function(){return this._shadowColor},set:function(e){var t=e instanceof ue?e.r:e[0],i=e instanceof ue?e.g:e[1],n=e instanceof ue?e.b:e[2],s=e instanceof ue?e.a:e[3];if((this._shadowColor.r!==t||this._shadowColor.g!==i||this._shadowColor.b!==n||this._shadowColor.a!==s)&&(this._shadowColor.r=t,this._shadowColor.g=i,this._shadowColor.b=n,this._shadowColor.a=s,this._model))if(this._symbolShadowParams)this._font&&this._updateText();else{this._shadowColorUniform[0]=this._shadowColor.r,this._shadowColorUniform[1]=this._shadowColor.g,this._shadowColorUniform[2]=this._shadowColor.b,this._shadowColorUniform[3]=this._shadowColor.a;for(var r=0,a=this._model.meshInstances.length;r<a;r++){this._model.meshInstances[r].setParameter("shadow_color",this._shadowColorUniform)}}}},{key:"shadowOffset",get:function(){return this._shadowOffset},set:function(e){var t=e instanceof ge?e.x:e[0],i=e instanceof ge?e.y:e[1];if((this._shadowOffset.x!==t||this._shadowOffset.y!==i)&&(this._shadowOffset.set(t,i),this._font&&this._model))if(this._symbolShadowParams)this._updateText();else for(var n=0,s=this._model.meshInstances.length;n<s;n++){var r=-this._font.data.info.maps[n].width/this._font.data.info.maps[n].height;this._shadowOffsetUniform[0]=this._shadowOffsetScale*this._shadowOffset.x,this._shadowOffsetUniform[1]=r*this._shadowOffsetScale*this._shadowOffset.y,this._model.meshInstances[n].setParameter("shadow_offset",this._shadowOffsetUniform)}}},{key:"minFontSize",get:function(){return this._minFontSize},set:function(e){this._minFontSize!==e&&(this._minFontSize=e,this.font&&this._shouldAutoFit()&&this._updateText())}},{key:"maxFontSize",get:function(){return this._maxFontSize},set:function(e){this._maxFontSize!==e&&(this._maxFontSize=e,this.font&&this._shouldAutoFit()&&this._updateText())}},{key:"autoFitWidth",get:function(){return this._autoFitWidth},set:function(e){this._autoFitWidth!==e&&(this._autoFitWidth=e,this._fontSize=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize,this.font&&this._updateText())}},{key:"autoFitHeight",get:function(){return this._autoFitHeight},set:function(e){this._autoFitHeight!==e&&(this._autoFitHeight=e,this._fontSize=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize,this.font&&this._updateText())}},{key:"maxLines",get:function(){return this._maxLines},set:function(e){this._maxLines!==e&&(null===e&&-1===this._maxLines||(this._maxLines=null===e?-1:e,this.font&&this._wrapLines&&this._updateText()))}},{key:"enableMarkup",get:function(){return this._enableMarkup},set:function(e){if(e=!!e,this._enableMarkup!==e){this._enableMarkup=e,this.font&&this._updateText();var t=this._element._isScreenSpace();this._updateMaterial(t)}}},{key:"symbols",get:function(){return this._symbols}},{key:"symbolColors",get:function(){return null===this._symbolColors?null:this._symbolColors.map((function(e){return this._colorPalette.slice(3*e,3*e+3)}),this)}},{key:"symbolOutlineParams",get:function(){return null===this._symbolOutlineParams?null:this._symbolOutlineParams.map((function(e){return this._outlinePalette.slice(5*e,5*e+5)}),this)}},{key:"symbolShadowParams",get:function(){return null===this._symbolShadowParams?null:this._symbolShadowParams.map((function(e){return this._shadowPalette.slice(6*e,6*e+6)}),this)}},{key:"rtl",get:function(){return this._rtl}},{key:"rangeStart",get:function(){return this._rangeStart},set:function(e){(e=Math.max(0,Math.min(e,this._symbols.length)))!==this._rangeStart&&(this._rangeStart=e,this._updateRenderRange())}},{key:"rangeEnd",get:function(){return this._rangeEnd},set:function(e){(e=Math.max(this._rangeStart,Math.min(e,this._symbols.length)))!==this._rangeEnd&&(this._rangeEnd=e,this._updateRenderRange())}}]),e}(),Jm=new me,e_=new Te,t_=new me,i_=new me,n_=new Te,s_=new Te,r_=new Te,a_=new Te,o_=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._beingInitialized=!1,n._anchor=new ve,n._localAnchor=new ve,n._pivot=new ge,n._width=n._calculatedWidth=32,n._height=n._calculatedHeight=32,n._margin=new ve(0,0,-32,-32),n._modelTransform=new Te,n._screenToWorld=new Te,n._anchorTransform=new Te,n._anchorDirty=!0,n._parentWorldTransform=new Te,n._screenTransform=new Te,n._screenCorners=[new me,new me,new me,new me],n._canvasCorners=[new ge,new ge,new ge,new ge],n._worldCorners=[new me,new me,new me,new me],n._cornersDirty=!0,n._canvasCornersDirty=!0,n._worldCornersDirty=!0,n.entity.on("insert",n._onInsert,ee(n)),n._patch(),n.screen=null,n._type=kp,n._image=null,n._text=null,n._group=null,n._drawOrder=0,n._fitMode=Np,n._useInput=!1,n._layers=[4],n._addedModels=[],n._batchGroupId=-1,n._offsetReadAt=0,n._maskOffset=.5,n._maskedBy=null,n}Q(t,e);var i=t.prototype;return i._patch=function(){this.entity._sync=this._sync,this.entity.setPosition=this._setPosition,this.entity.setLocalPosition=this._setLocalPosition},i._unpatch=function(){this.entity._sync=Zd.prototype._sync,this.entity.setPosition=Zd.prototype.setPosition,this.entity.setLocalPosition=Zd.prototype.setLocalPosition},i._setPosition=function(e,t,i){this.element.screen?(e instanceof me?Jm.copy(e):Jm.set(e,t,i),this.getWorldTransform(),e_.copy(this.element._screenToWorld).invert(),e_.transformPoint(Jm,this.localPosition),this._dirtyLocal||this._dirtifyLocal()):Zd.prototype.setPosition.call(this,e,t,i)},i._setLocalPosition=function(e,t,i){e instanceof me?this.localPosition.copy(e):this.localPosition.set(e,t,i);var n=this.element,s=this.localPosition,r=n._pivot;n._margin.x=s.x-n._calculatedWidth*r.x,n._margin.z=n._localAnchor.z-n._localAnchor.x-n._calculatedWidth-n._margin.x,n._margin.y=s.y-n._calculatedHeight*r.y,n._margin.w=n._localAnchor.w-n._localAnchor.y-n._calculatedHeight-n._margin.y,this._dirtyLocal||this._dirtifyLocal()},i._sync=function(){var e=this.element,t=e.screen;if(t){if(e._anchorDirty){var i=0,n=0,s=0,r=1;if(this._parent&&this._parent.element)i=this._parent.element.calculatedWidth,n=this._parent.element.calculatedHeight,s=this._parent.element.pivot.x,r=this._parent.element.pivot.y;else{var a=t.screen.resolution;i=a.x/t.screen.scale,n=a.y/t.screen.scale}e._anchorTransform.setTranslate(i*(e.anchor.x-s),-n*(r-e.anchor.y),0),e._anchorDirty=!1,e._calculateLocalAnchors()}e._sizeDirty&&e._calculateSize(!1,!1)}if(this._dirtyLocal){this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale);var o=this.localPosition,h=e._pivot;e._margin.x=o.x-e._calculatedWidth*h.x,e._margin.z=e._localAnchor.z-e._localAnchor.x-e._calculatedWidth-e._margin.x,e._margin.y=o.y-e._calculatedHeight*h.y,e._margin.w=e._localAnchor.w-e._localAnchor.y-e._calculatedHeight-e._margin.y,this._dirtyLocal=!1}if(!t)return this._dirtyWorld&&(e._cornersDirty=!0,e._canvasCornersDirty=!0,e._worldCornersDirty=!0),Zd.prototype._sync.call(this);if(this._dirtyWorld){if(null===this._parent)this.worldTransform.copy(this.localTransform);else if(this._parent.element?e._screenToWorld.mul2(this._parent.element._modelTransform,e._anchorTransform):e._screenToWorld.copy(e._anchorTransform),e._modelTransform.mul2(e._screenToWorld,this.localTransform),t){e._screenToWorld.mul2(t.screen._screenMatrix,e._screenToWorld),t.screen.screenSpace||e._screenToWorld.mul2(t.worldTransform,e._screenToWorld),this.worldTransform.mul2(e._screenToWorld,this.localTransform);var l=e._parentWorldTransform;l.setIdentity();var c=this._parent;c&&c.element&&c!==t&&(n_.setTRS(me.ZERO,c.getLocalRotation(),c.getLocalScale()),l.mul2(c.element._parentWorldTransform,n_));var u=t_;u.set(0,0,this.localPosition.z);var d=i_;d.set(e._absLeft+e._pivot.x*e.calculatedWidth,e._absBottom+e._pivot.y*e.calculatedHeight,0),n_.setTranslate(-d.x,-d.y,-d.z),s_.setTRS(u,this.getLocalRotation(),this.getLocalScale()),r_.setTranslate(d.x,d.y,d.z),e._screenTransform.mul2(e._parentWorldTransform,r_).mul(s_).mul(n_),e._cornersDirty=!0,e._canvasCornersDirty=!0,e._worldCornersDirty=!0}else this.worldTransform.copy(e._modelTransform);this._dirtyWorld=!1}},i._onInsert=function(e){var t=this._parseUpToScreen();this.entity._dirtifyWorld(),this._updateScreen(t.screen),this._dirtifyMask()},i._dirtifyMask=function(){for(var e=this.entity;e;){var t=e.parent;if((null===t||t.screen)&&e.element){this.system._prerender&&this.system._prerender.length||(this.system._prerender=[],this.system.app.once("prerender",this._onPrerender,this));var i=this.system._prerender.indexOf(this.entity);i>=0&&this.system._prerender.splice(i,1),this.system._prerender.indexOf(e)<0&&this.system._prerender.push(e)}e=t}},i._onPrerender=function(){for(var e=0;e<this.system._prerender.length;e++){var t=this.system._prerender[e];if(t.element){t.element.syncMask(1)}}this.system._prerender.length=0},i._bindScreen=function(e){e._bindElement(this)},i._unbindScreen=function(e){e._unbindElement(this)},i._updateScreen=function(e){this.screen&&this.screen!==e&&this._unbindScreen(this.screen.screen);var t=this.screen;this.screen=e,this.screen&&this._bindScreen(this.screen.screen),this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY),this.fire("set:screen",this.screen,t),this._anchorDirty=!0;for(var i=this.entity.children,n=0,s=i.length;n<s;n++)i[n].element&&i[n].element._updateScreen(e);this.screen&&this.screen.screen.syncDrawOrder()},i.syncMask=function(e){var t=this._parseUpToScreen();this._updateMask(t.mask,e)},i._setMaskedBy=function(e){var t=this._image||this._text;if(e){var i=e.element._image._maskRef;null==t||t._setStencil(new Ri({ref:i,func:2})),this._maskedBy=e}else null==t||t._setStencil(null),this._maskedBy=null},i._updateMask=function(e,t){if(e){if(this._setMaskedBy(e),this.mask){var i=e.element._image._maskRef,n=new Ri({ref:i,func:2,zpass:3});this._image._setStencil(n),this._image._maskRef=t,t++,e=this.entity}for(var s=this.entity.children,r=0,a=s.length;r<a;r++){var o;null==(o=s[r].element)||o._updateMask(e,t)}this.mask&&t--}else{if(this._setMaskedBy(null),this.mask){var h=new Ri({ref:t,func:7,zpass:2});this._image._setStencil(h),this._image._maskRef=t,t++,e=this.entity}for(var l=this.entity.children,c=0,u=l.length;c<u;c++){var d;null==(d=l[c].element)||d._updateMask(e,t)}this.mask&&t--}},i._parseUpToScreen=function(){for(var e={screen:null,mask:null},t=this.entity._parent;t&&!t.screen;)t.element&&t.element.mask&&(e.mask||(e.mask=t)),t=t.parent;return t&&t.screen&&(e.screen=t),e},i._onScreenResize=function(e){this._anchorDirty=!0,this._cornersDirty=!0,this._worldCornersDirty=!0,this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY),this.fire("screen:set:resolution",e)},i._onScreenSpaceChange=function(){this.fire("screen:set:screenspace",this.screen.screen.screenSpace)},i._onScreenRemove=function(){this.screen&&(this.screen._destroying?this.screen=null:this._updateScreen(null))},i._calculateLocalAnchors=function(){var e=1e3,t=1e3,i=this.entity._parent;if(i&&i.element)e=i.element.calculatedWidth,t=i.element.calculatedHeight;else if(this.screen){var n=this.screen.screen.resolution,s=this.screen.screen.scale;e=n.x/s,t=n.y/s}this._localAnchor.set(this._anchor.x*e,this._anchor.y*t,this._anchor.z*e,this._anchor.w*t)},i.getOffsetPosition=function(e,t){var i=this.entity.getLocalPosition().clone();return i.x+=e,i.y+=t,this._screenToWorld.transformPoint(i,i),i},i.onLayersChanged=function(e,t){this.addModelToLayers(this._image?this._image._renderable.model:this._text._model),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(e){this.layers.indexOf(e.id)<0||(this._image?e.addMeshInstances(this._image._renderable.model.meshInstances):this._text&&e.addMeshInstances(this._text._model.meshInstances))},i.onLayerRemoved=function(e){this.layers.indexOf(e.id)<0||(this._image?e.removeMeshInstances(this._image._renderable.model.meshInstances):this._text&&e.removeMeshInstances(this._text._model.meshInstances))},i.onEnable=function(){var e;(this._image&&this._image.onEnable(),this._text&&this._text.onEnable(),this._group&&this._group.onEnable(),this.useInput&&this.system.app.elementInput&&this.system.app.elementInput.addElement(this),this.system.app.scene.on("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.on("add",this.onLayerAdded,this),this.system.app.scene.layers.on("remove",this.onLayerRemoved,this)),this._batchGroupId>=0)&&(null==(e=this.system.app.batcher)||e.insert($a.ELEMENT,this.batchGroupId,this.entity));this.fire("enableelement")},i.onDisable=function(){var e;(this.system.app.scene.off("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.off("add",this.onLayerAdded,this),this.system.app.scene.layers.off("remove",this.onLayerRemoved,this)),this._image&&this._image.onDisable(),this._text&&this._text.onDisable(),this._group&&this._group.onDisable(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this._batchGroupId>=0)&&(null==(e=this.system.app.batcher)||e.remove($a.ELEMENT,this.batchGroupId,this.entity));this.fire("disableelement")},i.onRemove=function(){this.entity.off("insert",this._onInsert,this),this._unpatch(),this._image&&this._image.destroy(),this._text&&this._text.destroy(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this.screen&&this.screen.screen&&(this._unbindScreen(this.screen.screen),this.screen.screen.syncDrawOrder()),this.off()},i._calculateSize=function(e,t){if(this.entity._parent||this.screen){this._calculateLocalAnchors();var i=this._absRight-this._absLeft,n=this._absTop-this._absBottom;e?this._setWidth(i):this._setCalculatedWidth(i,!1),t?this._setHeight(n):this._setCalculatedHeight(n,!1);var s=this.entity.getLocalPosition();s.x=this._margin.x+this._calculatedWidth*this._pivot.x,s.y=this._margin.y+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(s),this._sizeDirty=!1}},i._setWidth=function(e){this._width=e,this._setCalculatedWidth(e,!1),this.fire("set:width",this._width)},i._setHeight=function(e){this._height=e,this._setCalculatedHeight(e,!1),this.fire("set:height",this._height)},i._setCalculatedWidth=function(e,t){if(!(Math.abs(e-this._calculatedWidth)<=1e-4)){if(this._calculatedWidth=e,this.entity._dirtifyLocal(),t){var i=this.entity.getLocalPosition(),n=this._pivot;this._margin.x=i.x-this._calculatedWidth*n.x,this._margin.z=this._localAnchor.z-this._localAnchor.x-this._calculatedWidth-this._margin.x}this._flagChildrenAsDirty(),this.fire("set:calculatedWidth",this._calculatedWidth),this.fire("resize",this._calculatedWidth,this._calculatedHeight)}},i._setCalculatedHeight=function(e,t){if(!(Math.abs(e-this._calculatedHeight)<=1e-4)){if(this._calculatedHeight=e,this.entity._dirtifyLocal(),t){var i=this.entity.getLocalPosition(),n=this._pivot;this._margin.y=i.y-this._calculatedHeight*n.y,this._margin.w=this._localAnchor.w-this._localAnchor.y-this._calculatedHeight-this._margin.y}this._flagChildrenAsDirty(),this.fire("set:calculatedHeight",this._calculatedHeight),this.fire("resize",this._calculatedWidth,this._calculatedHeight)}},i._flagChildrenAsDirty=function(){for(var e=this.entity._children,t=0,i=e.length;t<i;t++)e[t].element&&(e[t].element._anchorDirty=!0,e[t].element._sizeDirty=!0)},i.addModelToLayers=function(e){this._addedModels.push(e);for(var t=0;t<this.layers.length;t++){var i=this.system.app.scene.layers.getLayerById(this.layers[t]);i&&i.addMeshInstances(e.meshInstances)}},i.removeModelFromLayers=function(e){var t=this._addedModels.indexOf(e);t>=0&&this._addedModels.splice(t,1);for(var i=0;i<this.layers.length;i++){var n=this.system.app.scene.layers.getLayerById(this.layers[i]);n&&n.removeMeshInstances(e.meshInstances)}},i.getMaskOffset=function(){var e=this.system.app.frame;this._offsetReadAt!==e&&(this._maskOffset=.5,this._offsetReadAt=e);var t=this._maskOffset;return this._maskOffset-=.001,t},i.isVisibleForCamera=function(e){var t,i,n,s;if(this.maskedBy){var r=this.maskedBy.element.screenCorners;t=Math.min(Math.min(r[0].x,r[1].x),Math.min(r[2].x,r[3].x)),i=Math.max(Math.max(r[0].x,r[1].x),Math.max(r[2].x,r[3].x)),s=Math.min(Math.min(r[0].y,r[1].y),Math.min(r[2].y,r[3].y)),n=Math.max(Math.max(r[0].y,r[1].y),Math.max(r[2].y,r[3].y))}else{var a=this.system.app.graphicsDevice.width,o=this.system.app.graphicsDevice.height,h=e._rect.z*a,l=e._rect.w*o;i=(t=e._rect.x*a)+h,s=(n=(1-e._rect.y)*o)-l}var c=this.screenCorners,u=Math.min(Math.min(c[0].x,c[1].x),Math.min(c[2].x,c[3].x)),d=Math.max(Math.max(c[0].x,c[1].x),Math.max(c[2].x,c[3].x)),f=Math.min(Math.min(c[0].y,c[1].y),Math.min(c[2].y,c[3].y)),p=Math.max(Math.max(c[0].y,c[1].y),Math.max(c[2].y,c[3].y));return!(d<t||u>i||f>n||p<s)},i._isScreenSpace=function(){return!(!this.screen||!this.screen.screen)&&this.screen.screen.screenSpace},i._isScreenCulled=function(){return!(!this.screen||!this.screen.screen)&&this.screen.screen.cull},i._dirtyBatch=function(){var e;-1!==this.batchGroupId&&(null==(e=this.system.app.batcher)||e.markGroupDirty(this.batchGroupId))},Z(t,[{key:"_absLeft",get:function(){return this._localAnchor.x+this._margin.x}},{key:"_absRight",get:function(){return this._localAnchor.z-this._margin.z}},{key:"_absTop",get:function(){return this._localAnchor.w-this._margin.w}},{key:"_absBottom",get:function(){return this._localAnchor.y+this._margin.y}},{key:"_hasSplitAnchorsX",get:function(){return Math.abs(this._anchor.x-this._anchor.z)>.001}},{key:"_hasSplitAnchorsY",get:function(){return Math.abs(this._anchor.y-this._anchor.w)>.001}},{key:"aabb",get:function(){return this._image?this._image.aabb:this._text?this._text.aabb:null}},{key:"anchor",get:function(){return this._anchor},set:function(e){var t;e instanceof ve?this._anchor.copy(e):(t=this._anchor).set.apply(t,e);this.entity._parent||this.screen?this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY):this._calculateLocalAnchors(),this._anchorDirty=!0,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:anchor",this._anchor)}},{key:"batchGroupId",get:function(){return this._batchGroupId},set:function(e){if(this._batchGroupId!==e){var t,i;if(this.entity.enabled&&this._batchGroupId>=0)null==(t=this.system.app.batcher)||t.remove($a.ELEMENT,this.batchGroupId,this.entity);if(this.entity.enabled&&e>=0)null==(i=this.system.app.batcher)||i.insert($a.ELEMENT,e,this.entity);e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&(this._image&&this._image._renderable.model?this.addModelToLayers(this._image._renderable.model):this._text&&this._text._model&&this.addModelToLayers(this._text._model)),this._batchGroupId=e}}},{key:"bottom",get:function(){return this._margin.y},set:function(e){this._margin.y=e;var t=this.entity.getLocalPosition(),i=this._absTop,n=this._localAnchor.y+e;this._setHeight(i-n),t.y=e+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(t)}},{key:"calculatedWidth",get:function(){return this._calculatedWidth},set:function(e){this._setCalculatedWidth(e,!0)}},{key:"calculatedHeight",get:function(){return this._calculatedHeight},set:function(e){this._setCalculatedHeight(e,!0)}},{key:"canvasCorners",get:function(){if(!this._canvasCornersDirty||!this.screen||!this.screen.screen.screenSpace)return this._canvasCorners;for(var e=this.system.app.graphicsDevice,t=this.screenCorners,i=e.canvas.clientWidth/e.width,n=e.canvas.clientHeight/e.height,s=0;s<4;s++)this._canvasCorners[s].set(t[s].x*i,(e.height-t[s].y)*n);return this._canvasCornersDirty=!1,this._canvasCorners}},{key:"drawOrder",get:function(){return this._drawOrder},set:function(e){var t=0;this.screen&&(t=this.screen.screen.priority),e>16777215&&(e=16777215),this._drawOrder=(t<<24)+e,this.fire("set:draworder",this._drawOrder)}},{key:"height",get:function(){return this._height},set:function(e){this._height=e,this._hasSplitAnchorsY||this._setCalculatedHeight(e,!0),this.fire("set:height",this._height)}},{key:"layers",get:function(){return this._layers},set:function(e){if(this._addedModels.length)for(var t=0;t<this._layers.length;t++){var i=this.system.app.scene.layers.getLayerById(this._layers[t]);if(i)for(var n=0;n<this._addedModels.length;n++)i.removeMeshInstances(this._addedModels[n].meshInstances)}if(this._layers=e,this.enabled&&this.entity.enabled&&this._addedModels.length)for(var s=0;s<this._layers.length;s++){var r=this.system.app.scene.layers.getLayerById(this._layers[s]);if(r)for(var a=0;a<this._addedModels.length;a++)r.addMeshInstances(this._addedModels[a].meshInstances)}}},{key:"left",get:function(){return this._margin.x},set:function(e){this._margin.x=e;var t=this.entity.getLocalPosition(),i=this._absRight,n=this._localAnchor.x+e;this._setWidth(i-n),t.x=e+this._calculatedWidth*this._pivot.x,this.entity.setLocalPosition(t)}},{key:"margin",get:function(){return this._margin},set:function(e){this._margin.copy(e),this._calculateSize(!0,!0),this.fire("set:margin",this._margin)}},{key:"maskedBy",get:function(){return this._maskedBy}},{key:"pivot",get:function(){return this._pivot},set:function(e){var t=this.pivot,i=this.margin,n=t.x,s=t.y;e instanceof ge?t.copy(e):t.set.apply(t,e);var r=i.x+i.z,a=t.x-n;i.x+=r*a,i.z-=r*a;var o=i.y+i.w,h=t.y-s;i.y+=o*h,i.w-=o*h,this._anchorDirty=!0,this._cornersDirty=!0,this._worldCornersDirty=!0,this._calculateSize(!1,!1),this._flagChildrenAsDirty(),this.fire("set:pivot",t)}},{key:"right",get:function(){return this._margin.z},set:function(e){this._margin.z=e;var t=this.entity.getLocalPosition(),i=this._absLeft,n=this._localAnchor.z-e;this._setWidth(n-i),t.x=this._localAnchor.z-this._localAnchor.x-e-this._calculatedWidth*(1-this._pivot.x),this.entity.setLocalPosition(t)}},{key:"screenCorners",get:function(){if(!this._cornersDirty||!this.screen)return this._screenCorners;var e=this.entity.parent&&this.entity.parent.element&&this.entity.parent.element.screenCorners[0];this._screenCorners[0].set(this._absLeft,this._absBottom,0),this._screenCorners[1].set(this._absRight,this._absBottom,0),this._screenCorners[2].set(this._absRight,this._absTop,0),this._screenCorners[3].set(this._absLeft,this._absTop,0);for(var t=this.screen.screen.screenSpace,i=0;i<4;i++)this._screenTransform.transformPoint(this._screenCorners[i],this._screenCorners[i]),t&&this._screenCorners[i].mulScalar(this.screen.screen.scale),e&&this._screenCorners[i].add(e);return this._cornersDirty=!1,this._canvasCornersDirty=!0,this._worldCornersDirty=!0,this._screenCorners}},{key:"textWidth",get:function(){return this._text?this._text.width:0}},{key:"textHeight",get:function(){return this._text?this._text.height:0}},{key:"top",get:function(){return this._margin.w},set:function(e){this._margin.w=e;var t=this.entity.getLocalPosition(),i=this._absBottom,n=this._localAnchor.w-e;this._setHeight(n-i),t.y=this._localAnchor.w-this._localAnchor.y-e-this._calculatedHeight*(1-this._pivot.y),this.entity.setLocalPosition(t)}},{key:"type",get:function(){return this._type},set:function(e){e!==this._type&&(this._type=e,this._image&&(this._image.destroy(),this._image=null),this._text&&(this._text.destroy(),this._text=null),e===Fp?this._image=new Pm(this):e===Bp&&(this._text=new Qm(this)))}},{key:"useInput",get:function(){return this._useInput},set:function(e){this._useInput!==e&&(this._useInput=e,this.system.app.elementInput?e?this.enabled&&this.entity.enabled&&this.system.app.elementInput.addElement(this):this.system.app.elementInput.removeElement(this):this._useInput,this.fire("set:useInput",e))}},{key:"fitMode",get:function(){return this._fitMode},set:function(e){this._fitMode=e,this._calculateSize(!0,!0),this._image&&this._image.refreshMesh()}},{key:"width",get:function(){return this._width},set:function(e){this._width=e,this._hasSplitAnchorsX||this._setCalculatedWidth(e,!0),this.fire("set:width",this._width)}},{key:"worldCorners",get:function(){if(!this._worldCornersDirty)return this._worldCorners;if(this.screen){var e=this.screenCorners;if(!this.screen.screen.screenSpace){n_.copy(this.screen.screen._screenMatrix),n_.data[13]=-n_.data[13],n_.mul2(this.screen.getWorldTransform(),n_);for(var t=0;t<4;t++)n_.transformPoint(e[t],this._worldCorners[t])}}else{var i=this.entity.getLocalPosition();n_.setTranslate(-i.x,-i.y,-i.z),s_.setTRS(me.ZERO,this.entity.getLocalRotation(),this.entity.getLocalScale()),r_.setTranslate(i.x,i.y,i.z);var n=this.entity.parent?this.entity.parent:this.entity;a_.copy(n.getWorldTransform()),a_.mul(r_).mul(s_).mul(n_),t_.set(i.x-this.pivot.x*this.calculatedWidth,i.y-this.pivot.y*this.calculatedHeight,i.z),a_.transformPoint(t_,this._worldCorners[0]),t_.set(i.x+(1-this.pivot.x)*this.calculatedWidth,i.y-this.pivot.y*this.calculatedHeight,i.z),a_.transformPoint(t_,this._worldCorners[1]),t_.set(i.x+(1-this.pivot.x)*this.calculatedWidth,i.y+(1-this.pivot.y)*this.calculatedHeight,i.z),a_.transformPoint(t_,this._worldCorners[2]),t_.set(i.x-this.pivot.x*this.calculatedWidth,i.y+(1-this.pivot.y)*this.calculatedHeight,i.z),a_.transformPoint(t_,this._worldCorners[3])}return this._worldCornersDirty=!1,this._worldCorners}}]),t}(gf);function h_(e){Object.defineProperty(o_.prototype,e,{get:function(){return this._text?this._text[e]:this._image?this._image[e]:null},set:function(t){this._text?(this._text[e]!==t&&this._dirtyBatch(),this._text[e]=t):this._image&&(this._image[e]!==t&&this._dirtyBatch(),this._image[e]=t)}})}h_("fontSize"),h_("minFontSize"),h_("maxFontSize"),h_("maxLines"),h_("autoFitWidth"),h_("autoFitHeight"),h_("color"),h_("font"),h_("fontAsset"),h_("spacing"),h_("lineHeight"),h_("wrapLines"),h_("lines"),h_("alignment"),h_("autoWidth"),h_("autoHeight"),h_("rtlReorder"),h_("unicodeConverter"),h_("text"),h_("key"),h_("texture"),h_("textureAsset"),h_("material"),h_("materialAsset"),h_("sprite"),h_("spriteAsset"),h_("spriteFrame"),h_("pixelsPerUnit"),h_("opacity"),h_("rect"),h_("mask"),h_("outlineColor"),h_("outlineThickness"),h_("shadowColor"),h_("shadowOffset"),h_("enableMarkup"),h_("rangeStart"),h_("rangeEnd");var l_=function(){this.enabled=!0},c_=["enabled"],u_=function(e){function t(t){var i;(i=e.call(this,t)||this).id="element",i.ComponentType=o_,i.DataType=l_,i.schema=c_,i._unicodeConverter=null,i._rtlReorder=null,i._defaultTexture=new Yn(t.graphicsDevice,{width:1,height:1,format:7,name:"element-system"});var n=i._defaultTexture.lock(),s=new Uint8Array(4);return s[0]=255,s[1]=255,s[2]=255,s[3]=255,n.set(s),i._defaultTexture.unlock(),i.defaultImageMaterial=null,i.defaultImage9SlicedMaterial=null,i.defaultImage9TiledMaterial=null,i.defaultImageMaskMaterial=null,i.defaultImage9SlicedMaskMaterial=null,i.defaultImage9TiledMaskMaterial=null,i.defaultScreenSpaceImageMaterial=null,i.defaultScreenSpaceImage9SlicedMaterial=null,i.defaultScreenSpaceImage9TiledMaterial=null,i.defaultScreenSpaceImageMask9SlicedMaterial=null,i.defaultScreenSpaceImageMask9TiledMaterial=null,i.defaultScreenSpaceImageMaskMaterial=null,i._defaultTextMaterials={},i.defaultImageMaterials=[],i.on("beforeremove",i.onRemoveComponent,ee(i)),i}Q(t,e);var i=t.prototype;return i.destroy=function(){e.prototype.destroy.call(this),this._defaultTexture.destroy()},i.initializeComponentData=function(t,i,n){t._beingInitialized=!0,void 0!==i.anchor&&(i.anchor instanceof ve?t.anchor.copy(i.anchor):t.anchor.set(i.anchor[0],i.anchor[1],i.anchor[2],i.anchor[3])),void 0!==i.pivot&&(i.pivot instanceof ge?t.pivot.copy(i.pivot):t.pivot.set(i.pivot[0],i.pivot[1]));var s,r=Math.abs(t.anchor.x-t.anchor.z)>.001,a=Math.abs(t.anchor.y-t.anchor.w)>.001,o=!1;void 0!==i.margin&&(i.margin instanceof ve?t.margin.copy(i.margin):t._margin.set(i.margin[0],i.margin[1],i.margin[2],i.margin[3]),o=!0),void 0!==i.left&&(t._margin.x=i.left,o=!0),void 0!==i.bottom&&(t._margin.y=i.bottom,o=!0),void 0!==i.right&&(t._margin.z=i.right,o=!0),void 0!==i.top&&(t._margin.w=i.top,o=!0),o&&(t.margin=t._margin);var h=!1;void 0===i.width||r?r&&(h=!0):t.width=i.width,void 0===i.height||a?a&&(h=!0):t.height=i.height,h&&(t.anchor=t.anchor),void 0!==i.enabled&&(t.enabled=i.enabled),void 0!==i.useInput&&(t.useInput=i.useInput),void 0!==i.fitMode&&(t.fitMode=i.fitMode),t.batchGroupId=void 0===i.batchGroupId||null===i.batchGroupId?-1:i.batchGroupId,i.layers&&Array.isArray(i.layers)&&(t.layers=i.layers.slice(0)),void 0!==i.type&&(t.type=i.type),t.type===Fp?(void 0!==i.rect&&(t.rect=i.rect),void 0!==i.color&&((s=i.color)instanceof ue||(s=new ue(i.color[0],i.color[1],i.color[2])),t.color=s),void 0!==i.opacity&&(t.opacity=i.opacity),void 0!==i.textureAsset&&(t.textureAsset=i.textureAsset),i.texture&&(t.texture=i.texture),void 0!==i.spriteAsset&&(t.spriteAsset=i.spriteAsset),i.sprite&&(t.sprite=i.sprite),void 0!==i.spriteFrame&&(t.spriteFrame=i.spriteFrame),void 0!==i.pixelsPerUnit&&null!==i.pixelsPerUnit&&(t.pixelsPerUnit=i.pixelsPerUnit),void 0!==i.materialAsset&&(t.materialAsset=i.materialAsset),i.material&&(t.material=i.material),void 0!==i.mask&&(t.mask=i.mask)):t.type===Bp&&(void 0!==i.autoWidth&&(t.autoWidth=i.autoWidth),void 0!==i.autoHeight&&(t.autoHeight=i.autoHeight),void 0!==i.rtlReorder&&(t.rtlReorder=i.rtlReorder),void 0!==i.unicodeConverter&&(t.unicodeConverter=i.unicodeConverter),null!==i.text&&void 0!==i.text?t.text=i.text:null!==i.key&&void 0!==i.key&&(t.key=i.key),void 0!==i.color&&((s=i.color)instanceof ue||(s=new ue(s[0],s[1],s[2])),t.color=s),void 0!==i.opacity&&(t.opacity=i.opacity),void 0!==i.spacing&&(t.spacing=i.spacing),void 0!==i.fontSize&&(t.fontSize=i.fontSize,i.lineHeight||(t.lineHeight=i.fontSize)),void 0!==i.lineHeight&&(t.lineHeight=i.lineHeight),void 0!==i.maxLines&&(t.maxLines=i.maxLines),void 0!==i.wrapLines&&(t.wrapLines=i.wrapLines),void 0!==i.minFontSize&&(t.minFontSize=i.minFontSize),void 0!==i.maxFontSize&&(t.maxFontSize=i.maxFontSize),i.autoFitWidth&&(t.autoFitWidth=i.autoFitWidth),i.autoFitHeight&&(t.autoFitHeight=i.autoFitHeight),void 0!==i.fontAsset&&(t.fontAsset=i.fontAsset),void 0!==i.font&&(t.font=i.font),void 0!==i.alignment&&(t.alignment=i.alignment),void 0!==i.outlineColor&&(t.outlineColor=i.outlineColor),void 0!==i.outlineThickness&&(t.outlineThickness=i.outlineThickness),void 0!==i.shadowColor&&(t.shadowColor=i.shadowColor),void 0!==i.shadowOffset&&(t.shadowOffset=i.shadowOffset),void 0!==i.enableMarkup&&(t.enableMarkup=i.enableMarkup));var l=t._parseUpToScreen();l.screen&&t._updateScreen(l.screen),e.prototype.initializeComponentData.call(this,t,i,n),t._beingInitialized=!1,t.type===Fp&&t._image._meshDirty&&t._image._updateMesh(t._image.mesh)},i.onRemoveComponent=function(e,t){t.onRemove()},i.cloneComponent=function(e,t){var i=e.element,n={enabled:i.enabled,width:i.width,height:i.height,anchor:i.anchor.clone(),pivot:i.pivot.clone(),margin:i.margin.clone(),alignment:i.alignment&&i.alignment.clone()||i.alignment,autoWidth:i.autoWidth,autoHeight:i.autoHeight,type:i.type,rect:i.rect&&i.rect.clone()||i.rect,rtlReorder:i.rtlReorder,unicodeConverter:i.unicodeConverter,materialAsset:i.materialAsset,material:i.material,color:i.color&&i.color.clone()||i.color,opacity:i.opacity,textureAsset:i.textureAsset,texture:i.texture,spriteAsset:i.spriteAsset,sprite:i.sprite,spriteFrame:i.spriteFrame,pixelsPerUnit:i.pixelsPerUnit,spacing:i.spacing,lineHeight:i.lineHeight,wrapLines:i.wrapLines,layers:i.layers,fontSize:i.fontSize,minFontSize:i.minFontSize,maxFontSize:i.maxFontSize,autoFitWidth:i.autoFitWidth,autoFitHeight:i.autoFitHeight,maxLines:i.maxLines,fontAsset:i.fontAsset,font:i.font,useInput:i.useInput,fitMode:i.fitMode,batchGroupId:i.batchGroupId,mask:i.mask,outlineColor:i.outlineColor&&i.outlineColor.clone()||i.outlineColor,outlineThickness:i.outlineThickness,shadowColor:i.shadowColor&&i.shadowColor.clone()||i.shadowColor,shadowOffset:i.shadowOffset&&i.shadowOffset.clone()||i.shadowOffset,enableMarkup:i.enableMarkup};return void 0!==i.key&&null!==i.key?n.key=i.key:n.text=i.text,this.addComponent(t,n)},i.getTextElementMaterial=function(e,t,i){var n=(e&&1)|(t&&2)|(i&&4),s=this._defaultTextMaterials[n];if(s)return s;var r="TextMaterial";return s=new Yl,t?(s.msdfMap=this._defaultTexture,s.msdfTextAttribute=i,s.emissive.set(1,1,1)):(r="Bitmap"+r,s.emissive.set(.5,.5,.5),s.emissiveMap=this._defaultTexture,s.emissiveTint=!0,s.opacityMap=this._defaultTexture,s.opacityMapChannel="a"),e&&(r="ScreenSpace"+r,s.depthTest=!1),s.name="default"+r,s.useLighting=!1,s.useGammaTonemap=!1,s.useFog=!1,s.useSkybox=!1,s.diffuse.set(0,0,0),s.opacity=.5,s.blendType=4,s.depthWrite=!1,s.emissiveVertexColor=!0,s.update(),this._defaultTextMaterials[n]=s,s},i._createBaseImageMaterial=function(){var e=new Yl;return e.diffuse.set(0,0,0),e.emissive.set(.5,.5,.5),e.emissiveMap=this._defaultTexture,e.emissiveTint=!0,e.opacityMap=this._defaultTexture,e.opacityMapChannel="a",e.opacityTint=!0,e.opacity=0,e.useLighting=!1,e.useGammaTonemap=!1,e.useFog=!1,e.useSkybox=!1,e.blendType=4,e.depthWrite=!1,e},i.getImageElementMaterial=function(e,t,i,n){return e?t?i?(this.defaultScreenSpaceImageMask9SlicedMaterial||(this.defaultScreenSpaceImageMask9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMask9SlicedMaterial.name="defaultScreenSpaceImageMask9SlicedMaterial",this.defaultScreenSpaceImageMask9SlicedMaterial.nineSlicedMode=1,this.defaultScreenSpaceImageMask9SlicedMaterial.depthTest=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9SlicedMaterial.redWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.greenWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.blueWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9SlicedMaterial)),this.defaultScreenSpaceImageMask9SlicedMaterial):n?(this.defaultScreenSpaceImageMask9TiledMaterial||(this.defaultScreenSpaceImageMask9TiledMaterial=this.defaultScreenSpaceImage9TiledMaterial.clone(),this.defaultScreenSpaceImageMask9TiledMaterial.name="defaultScreenSpaceImageMask9TiledMaterial",this.defaultScreenSpaceImageMask9TiledMaterial.nineSlicedMode=2,this.defaultScreenSpaceImageMask9TiledMaterial.depthTest=!1,this.defaultScreenSpaceImageMask9TiledMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9TiledMaterial.redWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.greenWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.blueWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9TiledMaterial)),this.defaultScreenSpaceImageMask9TiledMaterial):(this.defaultScreenSpaceImageMaskMaterial||(this.defaultScreenSpaceImageMaskMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaskMaterial.name="defaultScreenSpaceImageMaskMaterial",this.defaultScreenSpaceImageMaskMaterial.depthTest=!1,this.defaultScreenSpaceImageMaskMaterial.alphaTest=1,this.defaultScreenSpaceImageMaskMaterial.redWrite=!1,this.defaultScreenSpaceImageMaskMaterial.greenWrite=!1,this.defaultScreenSpaceImageMaskMaterial.blueWrite=!1,this.defaultScreenSpaceImageMaskMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaskMaterial)),this.defaultScreenSpaceImageMaskMaterial):i?(this.defaultScreenSpaceImage9SlicedMaterial||(this.defaultScreenSpaceImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9SlicedMaterial.name="defaultScreenSpaceImage9SlicedMaterial",this.defaultScreenSpaceImage9SlicedMaterial.nineSlicedMode=1,this.defaultScreenSpaceImage9SlicedMaterial.depthTest=!1,this.defaultScreenSpaceImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9SlicedMaterial)),this.defaultScreenSpaceImage9SlicedMaterial):n?(this.defaultScreenSpaceImage9TiledMaterial||(this.defaultScreenSpaceImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9TiledMaterial.name="defaultScreenSpaceImage9TiledMaterial",this.defaultScreenSpaceImage9TiledMaterial.nineSlicedMode=2,this.defaultScreenSpaceImage9TiledMaterial.depthTest=!1,this.defaultScreenSpaceImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9TiledMaterial)),this.defaultScreenSpaceImage9TiledMaterial):(this.defaultScreenSpaceImageMaterial||(this.defaultScreenSpaceImageMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaterial.name="defaultScreenSpaceImageMaterial",this.defaultScreenSpaceImageMaterial.depthTest=!1,this.defaultScreenSpaceImageMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaterial)),this.defaultScreenSpaceImageMaterial):t?i?(this.defaultImage9SlicedMaskMaterial||(this.defaultImage9SlicedMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaskMaterial.name="defaultImage9SlicedMaskMaterial",this.defaultImage9SlicedMaskMaterial.nineSlicedMode=1,this.defaultImage9SlicedMaskMaterial.alphaTest=1,this.defaultImage9SlicedMaskMaterial.redWrite=!1,this.defaultImage9SlicedMaskMaterial.greenWrite=!1,this.defaultImage9SlicedMaskMaterial.blueWrite=!1,this.defaultImage9SlicedMaskMaterial.alphaWrite=!1,this.defaultImage9SlicedMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaskMaterial)),this.defaultImage9SlicedMaskMaterial):n?(this.defaultImage9TiledMaskMaterial||(this.defaultImage9TiledMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaskMaterial.name="defaultImage9TiledMaskMaterial",this.defaultImage9TiledMaskMaterial.nineSlicedMode=2,this.defaultImage9TiledMaskMaterial.alphaTest=1,this.defaultImage9TiledMaskMaterial.redWrite=!1,this.defaultImage9TiledMaskMaterial.greenWrite=!1,this.defaultImage9TiledMaskMaterial.blueWrite=!1,this.defaultImage9TiledMaskMaterial.alphaWrite=!1,this.defaultImage9TiledMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaskMaterial)),this.defaultImage9TiledMaskMaterial):(this.defaultImageMaskMaterial||(this.defaultImageMaskMaterial=this._createBaseImageMaterial(),this.defaultImageMaskMaterial.name="defaultImageMaskMaterial",this.defaultImageMaskMaterial.alphaTest=1,this.defaultImageMaskMaterial.redWrite=!1,this.defaultImageMaskMaterial.greenWrite=!1,this.defaultImageMaskMaterial.blueWrite=!1,this.defaultImageMaskMaterial.alphaWrite=!1,this.defaultImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaskMaterial)),this.defaultImageMaskMaterial):i?(this.defaultImage9SlicedMaterial||(this.defaultImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaterial.name="defaultImage9SlicedMaterial",this.defaultImage9SlicedMaterial.nineSlicedMode=1,this.defaultImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaterial)),this.defaultImage9SlicedMaterial):n?(this.defaultImage9TiledMaterial||(this.defaultImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaterial.name="defaultImage9TiledMaterial",this.defaultImage9TiledMaterial.nineSlicedMode=2,this.defaultImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaterial)),this.defaultImage9TiledMaterial):(this.defaultImageMaterial||(this.defaultImageMaterial=this._createBaseImageMaterial(),this.defaultImageMaterial.name="defaultImageMaterial",this.defaultImageMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaterial)),this.defaultImageMaterial)},i.registerUnicodeConverter=function(e){this._unicodeConverter=e},i.registerRtlReorder=function(e){this._rtlReorder=e},i.getUnicodeConverter=function(){return this._unicodeConverter},i.getRtlReorder=function(){return this._rtlReorder},t}(vf);gf._buildAccessors(o_.prototype,c_);var d_="free",f_="limited",p_="locked",m_=["angularDampingX","angularDampingY","angularDampingZ","angularEquilibriumX","angularEquilibriumY","angularEquilibriumZ","angularLimitsX","angularLimitsY","angularLimitsZ","angularMotionX","angularMotionY","angularMotionZ","angularSpringX","angularSpringY","angularSpringZ","angularStiffnessX","angularStiffnessY","angularStiffnessZ","breakForce","enableCollision","enabled","entityA","entityB","linearDampingX","linearDampingY","linearDampingZ","linearEquilibriumX","linearEquilibriumY","linearEquilibriumZ","linearLimitsX","linearLimitsY","linearLimitsZ","linearMotionX","linearMotionY","linearMotionZ","linearSpringX","linearSpringY","linearSpringZ","linearStiffnessX","linearStiffnessY","linearStiffnessZ"],__=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._constraint=null,n._entityA=null,n._entityB=null,n._breakForce=34e37,n._enableCollision=!0,n._linearMotionX=p_,n._linearLimitsX=new ge(0,0),n._linearSpringX=!1,n._linearStiffnessX=0,n._linearDampingX=1,n._linearEquilibriumX=0,n._linearMotionY=p_,n._linearLimitsY=new ge(0,0),n._linearSpringY=!1,n._linearStiffnessY=0,n._linearDampingY=1,n._linearEquilibriumY=0,n._linearMotionZ=p_,n._linearLimitsZ=new ge(0,0),n._linearSpringZ=!1,n._linearStiffnessZ=0,n._linearDampingZ=1,n._linearEquilibriumZ=0,n._angularMotionX=p_,n._angularLimitsX=new ge(0,0),n._angularSpringX=!1,n._angularStiffnessX=0,n._angularDampingX=1,n._angularEquilibriumX=0,n._angularMotionY=p_,n._angularLimitsY=new ge(0,0),n._angularSpringY=!1,n._angularStiffnessY=0,n._angularDampingY=1,n._angularEquilibriumY=0,n._angularMotionZ=p_,n._angularLimitsZ=new ge(0,0),n._angularSpringZ=!1,n._angularEquilibriumZ=0,n._angularDampingZ=1,n._angularStiffnessZ=0,n.on("set_enabled",n._onSetEnabled,ee(n)),n}Q(t,e);var i=t.prototype;return i._convertTransform=function(e,t){var i=e.getTranslation(),n=new Ae;n.setFromMat4(e);var s=new Ammo.btVector3(i.x,i.y,i.z),r=new Ammo.btQuaternion(n.x,n.y,n.z,n.w);t.setOrigin(s),t.setRotation(r),Ammo.destroy(s),Ammo.destroy(r)},i._updateAngularLimits=function(){var e=this._constraint;if(e){var t,i,n,s,r,a;this._angularMotionX===f_?(t=this._angularLimitsX.x*ce.DEG_TO_RAD,s=this._angularLimitsX.y*ce.DEG_TO_RAD):this._angularMotionX===d_?(t=1,s=0):t=s=0,this._angularMotionY===f_?(i=this._angularLimitsY.x*ce.DEG_TO_RAD,r=this._angularLimitsY.y*ce.DEG_TO_RAD):this._angularMotionY===d_?(i=1,r=0):i=r=0,this._angularMotionZ===f_?(n=this._angularLimitsZ.x*ce.DEG_TO_RAD,a=this._angularLimitsZ.y*ce.DEG_TO_RAD):this._angularMotionZ===d_?(n=1,a=0):n=a=0;var o=new Ammo.btVector3(t,i,n);e.setAngularLowerLimit(o),o.setValue(s,r,a),e.setAngularUpperLimit(o),Ammo.destroy(o)}},i._updateLinearLimits=function(){var e=this._constraint;if(e){var t,i,n,s,r,a;this._linearMotionX===f_?(t=this._linearLimitsX.x,s=this._linearLimitsX.y):this._linearMotionX===d_?(t=1,s=0):t=s=0,this._linearMotionY===f_?(i=this._linearLimitsY.x,r=this._linearLimitsY.y):this._linearMotionY===d_?(i=1,r=0):i=r=0,this._linearMotionZ===f_?(n=this._linearLimitsZ.x,a=this._linearLimitsZ.y):this._linearMotionZ===d_?(n=1,a=0):n=a=0;var o=new Ammo.btVector3(t,i,n);e.setLinearLowerLimit(o),o.setValue(s,r,a),e.setLinearUpperLimit(o),Ammo.destroy(o)}},i._createConstraint=function(){if(this._entityA&&this._entityA.rigidbody){this._destroyConstraint();var e=new Te,t=this._entityA.rigidbody.body;t.activate();var i=this.entity.getWorldTransform(),n=this._entityA.getWorldTransform().clone().invert();e.mul2(n,i);var s=new Ammo.btTransform;if(this._convertTransform(e,s),this._entityB&&this._entityB.rigidbody){var r=this._entityB.rigidbody.body;r.activate();var a=this._entityB.getWorldTransform().clone().invert();e.mul2(a,i);var o=new Ammo.btTransform;this._convertTransform(e,o),this._constraint=new Ammo.btGeneric6DofSpringConstraint(t,r,s,o,!this._enableCollision),Ammo.destroy(o)}else this._constraint=new Ammo.btGeneric6DofSpringConstraint(t,s,!this._enableCollision);Ammo.destroy(s);for(var h=["X","Y","Z","X","Y","Z"],l=0;l<6;l++){var c=l<3?"_linear":"_angular";this._constraint.enableSpring(l,this[c+"Spring"+h[l]]),this._constraint.setDamping(l,this[c+"Damping"+h[l]]),this._constraint.setEquilibriumPoint(l,this[c+"Equilibrium"+h[l]]),this._constraint.setStiffness(l,this[c+"Stiffness"+h[l]])}this._constraint.setBreakingImpulseThreshold(this._breakForce),this._updateLinearLimits(),this._updateAngularLimits(),this.system.app.systems.rigidbody.dynamicsWorld.addConstraint(this._constraint,!this._enableCollision)}},i._destroyConstraint=function(){this._constraint&&(this.system.app.systems.rigidbody.dynamicsWorld.removeConstraint(this._constraint),Ammo.destroy(this._constraint),this._constraint=null)},i.initFromData=function(e){for(var t=0,i=m_;t<i.length;t++){var n=i[t];e.hasOwnProperty(n)&&(e[n]instanceof ge?this["_"+n].copy(e[n]):this["_"+n]=e[n])}this._createConstraint()},i.onEnable=function(){this._createConstraint()},i.onDisable=function(){this._destroyConstraint()},i._onSetEnabled=function(e,t,i){},i._onBeforeRemove=function(){this.fire("remove")},Z(t,[{key:"entityA",get:function(){return this._entityA},set:function(e){this._destroyConstraint(),this._entityA=e,this._createConstraint()}},{key:"entityB",get:function(){return this._entityB},set:function(e){this._destroyConstraint(),this._entityB=e,this._createConstraint()}},{key:"breakForce",get:function(){return this._breakForce},set:function(e){this._constraint&&this._breakForce!==e&&(this._constraint.setBreakingImpulseThreshold(e),this._breakForce=e)}},{key:"enableCollision",get:function(){return this._enableCollision},set:function(e){this._destroyConstraint(),this._enableCollision=e,this._createConstraint()}},{key:"angularLimitsX",get:function(){return this._angularLimitsX},set:function(e){this._angularLimitsX.equals(e)||(this._angularLimitsX.copy(e),this._updateAngularLimits())}},{key:"angularMotionX",get:function(){return this._angularMotionX},set:function(e){this._angularMotionX!==e&&(this._angularMotionX=e,this._updateAngularLimits())}},{key:"angularLimitsY",get:function(){return this._angularLimitsY},set:function(e){this._angularLimitsY.equals(e)||(this._angularLimitsY.copy(e),this._updateAngularLimits())}},{key:"angularMotionY",get:function(){return this._angularMotionY},set:function(e){this._angularMotionY!==e&&(this._angularMotionY=e,this._updateAngularLimits())}},{key:"angularLimitsZ",get:function(){return this._angularLimitsZ},set:function(e){this._angularLimitsZ.equals(e)||(this._angularLimitsZ.copy(e),this._updateAngularLimits())}},{key:"angularMotionZ",get:function(){return this._angularMotionZ},set:function(e){this._angularMotionZ!==e&&(this._angularMotionZ=e,this._updateAngularLimits())}},{key:"linearLimitsX",get:function(){return this._linearLimitsX},set:function(e){this._linearLimitsX.equals(e)||(this._linearLimitsX.copy(e),this._updateLinearLimits())}},{key:"linearMotionX",get:function(){return this._linearMotionX},set:function(e){this._linearMotionX!==e&&(this._linearMotionX=e,this._updateLinearLimits())}},{key:"linearLimitsY",get:function(){return this._linearLimitsY},set:function(e){this._linearLimitsY.equals(e)||(this._linearLimitsY.copy(e),this._updateLinearLimits())}},{key:"linearMotionY",get:function(){return this._linearMotionY},set:function(e){this._linearMotionY!==e&&(this._linearMotionY=e,this._updateLinearLimits())}},{key:"linearLimitsZ",get:function(){return this._linearLimitsZ},set:function(e){this._linearLimitsZ.equals(e)||(this._linearLimitsZ.copy(e),this._updateLinearLimits())}},{key:"linearMotionZ",get:function(){return this._linearMotionZ},set:function(e){this._linearMotionZ!==e&&(this._linearMotionZ=e,this._updateLinearLimits())}}]),t}(gf),g_={Damping:"setDamping",Equilibrium:"setEquilibriumPoint",Spring:"enableSpring",Stiffness:"setStiffness"};["linear","angular"].forEach((function(e){["Damping","Equilibrium","Spring","Stiffness"].forEach((function(t){["X","Y","Z"].forEach((function(i){var n=e+t+i,s="_"+n,r="linear"===e?0:3;"Y"===i&&(r+=1),"Z"===i&&(r+=2),Object.defineProperty(__.prototype,n,{get:function(){return this[s]},set:function(e){this[s]!==e&&(this[s]=e,this._constraint[g_[t]](r,e))}})}))}))}));var v_=function(){this.enabled=!0},y_=["enabled"],x_=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="joint",i.app=t,i.ComponentType=__,i.DataType=v_,i.schema=y_,i}return Q(t,e),t.prototype.initializeComponentData=function(e,t,i){e.initFromData(t)},t}(vf);gf._buildAccessors(__.prototype,y_);var S_=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._minWidth=0,n._minHeight=0,n._maxWidth=null,n._maxHeight=null,n._fitWidthProportion=0,n._fitHeightProportion=0,n._excludeFromLayout=!1,n}return Q(t,e),Z(t,[{key:"minWidth",get:function(){return this._minWidth},set:function(e){e!==this._minWidth&&(this._minWidth=e,this.fire("resize"))}},{key:"minHeight",get:function(){return this._minHeight},set:function(e){e!==this._minHeight&&(this._minHeight=e,this.fire("resize"))}},{key:"maxWidth",get:function(){return this._maxWidth},set:function(e){e!==this._maxWidth&&(this._maxWidth=e,this.fire("resize"))}},{key:"maxHeight",get:function(){return this._maxHeight},set:function(e){e!==this._maxHeight&&(this._maxHeight=e,this.fire("resize"))}},{key:"fitWidthProportion",get:function(){return this._fitWidthProportion},set:function(e){e!==this._fitWidthProportion&&(this._fitWidthProportion=e,this.fire("resize"))}},{key:"fitHeightProportion",get:function(){return this._fitHeightProportion},set:function(e){e!==this._fitHeightProportion&&(this._fitHeightProportion=e,this.fire("resize"))}},{key:"excludeFromLayout",get:function(){return this._excludeFromLayout},set:function(e){e!==this._excludeFromLayout&&(this._excludeFromLayout=e,this.fire("resize"))}}]),t}(gf),b_=function(){this.enabled=!0},w_=["enabled"],T_=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="layoutchild",i.ComponentType=S_,i.DataType=b_,i.schema=w_,i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){void 0!==i.enabled&&(t.enabled=i.enabled),void 0!==i.minWidth&&(t.minWidth=i.minWidth),void 0!==i.minHeight&&(t.minHeight=i.minHeight),void 0!==i.maxWidth&&(t.maxWidth=i.maxWidth),void 0!==i.maxHeight&&(t.maxHeight=i.maxHeight),void 0!==i.fitWidthProportion&&(t.fitWidthProportion=i.fitWidthProportion),void 0!==i.fitHeightProportion&&(t.fitHeightProportion=i.fitHeightProportion),void 0!==i.excludeFromLayout&&(t.excludeFromLayout=i.excludeFromLayout),e.prototype.initializeComponentData.call(this,t,i,n)},i.cloneComponent=function(e,t){var i=e.layoutchild;return this.addComponent(t,{enabled:i.enabled,minWidth:i.minWidth,minHeight:i.minHeight,maxWidth:i.maxWidth,maxHeight:i.maxHeight,fitWidthProportion:i.fitWidthProportion,fitHeightProportion:i.fitHeightProportion,excludeFromLayout:i.excludeFromLayout})},t}(vf);gf._buildAccessors(S_.prototype,w_);var A_={0:{axis:"x",size:"width",calculatedSize:"calculatedWidth",minSize:"minWidth",maxSize:"maxWidth",fitting:"widthFitting",fittingProportion:"fitWidthProportion"},1:{axis:"y",size:"height",calculatedSize:"calculatedHeight",minSize:"minHeight",maxSize:"maxHeight",fitting:"heightFitting",fittingProportion:"fitHeightProportion"}},C_={0:1,1:0},E_={minWidth:0,minHeight:0,maxWidth:Number.POSITIVE_INFINITY,maxHeight:Number.POSITIVE_INFINITY,width:null,height:null,fitWidthProportion:0,fitHeightProportion:0},M_="NONE",P_="APPLY_STRETCHING",R_="APPLY_SHRINKING",I_=new ge;function L_(e){var t,i=A_[e],n=A_[C_[e]];function s(e,t){return-t[i.size]*e.pivot[i.axis]}function r(e,t){return-t[n.size]*e.pivot[n.axis]}function a(e,t){return t[i.size]*(1-e.pivot[i.axis])}function o(e){var t=e.entity.layoutchild;return!t||!t.enabled||!t.excludeFromLayout}function h(e,t,i){switch(e){case 0:return M_;case 1:return t<i?P_:M_;case 2:return t>=i?R_:M_;case 3:return t<i?P_:R_;default:throw new Error("Unrecognized fitting mode: "+e)}}function l(e,i){return _(e,i.size)+(e.length-1)*t.spacing[i.axis]}function c(e,t,i){for(var n=v(e,i.maxSize),s=g(e,i.fittingProportion),r=S(s,n),a=I_[i.axis]-t,o=0;o<e.length;++o){var h=n[o],l=d(h,a,s,r),c=e[h][i.size]+l,u=e[h][i.maxSize],f=Math.min(c,u);e[h][i.size]=f,a-=l-Math.max(c-f,0)}}function u(e,t,i){for(var n=v(e,i.minSize,!0),s=function(e){if(1===e.length)return[1];for(var t=[],i=e.length,n=0;n<i;++n)t.push((1-e[n])/(i-1));return t}(g(e,i.fittingProportion)),r=S(s,n),a=t-I_[i.axis],o=0;o<e.length;++o){var h=n[o],l=d(h,a,s,r),c=e[h][i.size]-l,u=e[h][i.minSize],f=Math.max(c,u);e[h][i.size]=f,a-=l-Math.max(f-c,0)}}function d(e,t,i,n){var s=i[e],r=n[e];return Math.abs(s)<1e-5&&Math.abs(r)<1e-5?t:t*s/r}function f(e){for(var t=[],i=0;i<e.length;++i){var n=e[i],s=Math.max(p(n,"minWidth"),0),r=Math.max(p(n,"minHeight"),0),a=Math.max(p(n,"maxWidth"),s),o=Math.max(p(n,"maxHeight"),r),h=m(p(n,"width"),s,a),l=m(p(n,"height"),r,o),c=p(n,"fitWidthProportion"),u=p(n,"fitHeightProportion");t.push({minWidth:s,minHeight:r,maxWidth:a,maxHeight:o,width:h,height:l,fitWidthProportion:c,fitHeightProportion:u})}return t}function p(e,t){var i=e.entity.layoutchild;return i&&i.enabled&&void 0!==i[t]&&null!==i[t]?i[t]:void 0!==e[t]?e[t]:E_[t]}function m(e,t,i){return Math.min(Math.max(e,t),i)}function _(e,t){return e.reduce((function(e,i){return e+i[t]}),0)}function g(e,t){var i=_(e,t),n=[],s=e.length;if(0===i)for(var r=0;r<s;++r)n.push(1/s);else for(var a=0;a<s;++a)n.push(e[a][t]/i);return n}function v(e,t,i){return e.forEach(y),e.slice().sort((function(e,n){return i?n[t]-e[t]:e[t]-n[t]})).map(x)}function y(e,t){e.index=t}function x(e){return e.index}function S(e,t){var i=[];i[t[e.length-1]]=e[t[e.length-1]];for(var n=e.length-2;n>=0;--n)i[t[n]]=i[t[n+1]]+e[t[n]];return i}return function(e,d){e=e.filter(o),t=d,I_.x=t.containerSize.x-t.padding.x-t.padding.z,I_.y=t.containerSize.y-t.padding.y-t.padding.w,function(e){for(var t=0;t<e.length;++t){var i=e[t],n=i.anchor;0===n.x&&0===n.y&&0===n.z&&0===n.w||(i.anchor=ve.ZERO)}}(e);var p=function(e){var i=0===t.orientation&&t.reverseX||1===t.orientation&&t.reverseY,n=0===t.orientation&&t.reverseY||1===t.orientation&&t.reverseX;if(i)for(var s=0;s<e.length;++s)i&&e[s].reverse();n&&e.reverse();return e}(function(e){if(!t.wrap)return[e];for(var n=[[]],s=f(e),r=0,a=2===t[i.fitting],o=0;o<e.length;++o){n[n.length-1].length>0&&(r+=t.spacing[i.axis]);var h=s[o][i.size];r+=h,!a&&r>I_[i.axis]&&0!==n[n.length-1].length&&(r=h,n.push([])),n[n.length-1].push(e[o]),a&&r>I_[i.axis]&&o!==e.length-1&&(r=0,n.push([]))}return n}(e)),m=function(e,i){for(var s=[],r=[],a=0;a<e.length;++a){var o=e[a];o.largestElement=null,o.largestSize={width:Number.NEGATIVE_INFINITY,height:Number.NEGATIVE_INFINITY};for(var d=0;d<o.length;++d){var f=i[a][d];f[n.size]>o.largestSize[n.size]&&(o.largestElement=o[d],o.largestSize=f)}s.push(o.largestElement),r.push(o.largestSize)}var p=l(r,n),m=h(t[n.fitting],p,I_[n.axis]);m===P_?c(r,p,n):m===R_&&u(r,p,n);for(var _=0;_<e.length;++_)for(var g=e[_],v=0;v<g.length;++v){var y=i[_][v],x=y[n.size],S=1===e.length?I_[n.axis]:g.largestSize[n.size],b=h(t[n.fitting],x,S);b===P_?y[n.size]=Math.min(S,y[n.maxSize]):b===R_&&(y[n.size]=Math.max(S,y[n.minSize]))}return i}(p,function(e){for(var n=[],s=0;s<e.length;++s){var r=f(e[s]),a=l(r,i),o=h(t[i.fitting],a,I_[i.axis]);o===P_?c(r,a,i):o===R_&&u(r,a,i),n.push(r)}return n}(p)),_=function(e,o){var h={};h[i.axis]=0,h[n.axis]=0,e[i.size]=Number.NEGATIVE_INFINITY;for(var l=[],c=0;c<e.length;++c){var u=e[c];if(0!==u.length){for(var d=[],f=o[c],p=0;p<u.length;++p){var m=u[p],_=f[p];h[n.axis]-=r(m,_),h[i.axis]-=s(m,_),d[p]={},d[p][i.axis]=h[i.axis],d[p][n.axis]=h[n.axis],h[n.axis]+=r(m,_),h[i.axis]+=a(m,_)+t.spacing[i.axis]}u[i.size]=h[i.axis]-t.spacing[i.axis],u[n.size]=u.largestSize[n.size],e[i.size]=Math.max(e[i.size],u[i.size]),h[i.axis]=0,h[n.axis]+=u[n.size]+t.spacing[n.axis],l.push(d)}else l.push([])}return e[n.size]=h[n.axis]-t.spacing[n.axis],l}(p,m);return function(e,s,r){for(var a=t.alignment[i.axis],o=t.alignment[n.axis],h=t.padding[i.axis],l=t.padding[n.axis],c=0;c<e.length;++c)for(var u=e[c],d=s[c],f=r[c],p=(I_[i.axis]-u[i.size])*a+h,m=(I_[n.axis]-e[n.size])*o+l,_=0;_<u.length;++_){var g=(u[n.size]-d[_][n.size])*t.alignment[n.axis];f[_][i.axis]+=p,f[_][n.axis]+=m+g}}(p,m,_),function(e,s,r){for(var a=0;a<e.length;++a)for(var o=e[a],h=s[a],l=r[a],c=0;c<o.length;++c){var u=o[c];u[i.calculatedSize]=h[c][i.size],u[n.calculatedSize]=h[c][n.size],0===t.orientation?u.entity.setLocalPosition(l[c][i.axis],l[c][n.axis],u.entity.getLocalPosition().z):u.entity.setLocalPosition(l[c][n.axis],l[c][i.axis],u.entity.getLocalPosition().z)}}(p,m,_),function(e){var i=e.width,n=e.height,s=(I_.x-i)*t.alignment.x+t.padding.x,r=(I_.y-n)*t.alignment.y+t.padding.y;return{bounds:new ve(s,r,i,n)}}(p)}}var D_={};D_[0]=L_(0),D_[1]=L_(1);var O_=function(){function e(){}return e.prototype.calculateLayout=function(e,t){var i=D_[t.orientation];if(i)return i(e,t);throw new Error("Unrecognized orientation value: "+t.orientation)},e}();function k_(e){return e.element}function F_(e){return e.enabled&&e.element&&e.element.enabled}var B_=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._orientation=0,n._reverseX=!1,n._reverseY=!0,n._alignment=new ge(0,1),n._padding=new ve,n._spacing=new ge,n._widthFitting=0,n._heightFitting=0,n._wrap=!1,n._layoutCalculator=new O_,n._listenForReflowEvents(n.entity,"on"),n.entity.children.forEach((function(e){n._listenForReflowEvents(e,"on")})),n.entity.on("childinsert",n._onChildInsert,ee(n)),n.entity.on("childremove",n._onChildRemove,ee(n)),t.app.systems.element.on("add",n._onElementOrLayoutComponentAdd,ee(n)),t.app.systems.element.on("beforeremove",n._onElementOrLayoutComponentRemove,ee(n)),t.app.systems.layoutchild.on("add",n._onElementOrLayoutComponentAdd,ee(n)),t.app.systems.layoutchild.on("beforeremove",n._onElementOrLayoutComponentRemove,ee(n)),n}Q(t,e);var i=t.prototype;return i._isSelfOrChild=function(e){return e===this.entity||-1!==this.entity.children.indexOf(e)},i._listenForReflowEvents=function(e,t){e.element&&(e.element[t]("enableelement",this._scheduleReflow,this),e.element[t]("disableelement",this._scheduleReflow,this),e.element[t]("resize",this._scheduleReflow,this),e.element[t]("set:pivot",this._scheduleReflow,this)),e.layoutchild&&(e.layoutchild[t]("set_enabled",this._scheduleReflow,this),e.layoutchild[t]("resize",this._scheduleReflow,this))},i._onElementOrLayoutComponentAdd=function(e){this._isSelfOrChild(e)&&(this._listenForReflowEvents(e,"on"),this._scheduleReflow())},i._onElementOrLayoutComponentRemove=function(e){this._isSelfOrChild(e)&&(this._listenForReflowEvents(e,"off"),this._scheduleReflow())},i._onChildInsert=function(e){this._listenForReflowEvents(e,"on"),this._scheduleReflow()},i._onChildRemove=function(e){this._listenForReflowEvents(e,"off"),this._scheduleReflow()},i._scheduleReflow=function(){this.enabled&&this.entity&&this.entity.enabled&&!this._isPerformingReflow&&this.system.scheduleReflow(this)},i.reflow=function(){var e=k_(this.entity),t=this.entity.children.filter(F_).map(k_);if(e&&0!==t.length){var i=Math.max(e.calculatedWidth,0),n=Math.max(e.calculatedHeight,0),s={orientation:this._orientation,reverseX:this._reverseX,reverseY:this._reverseY,alignment:this._alignment,padding:this._padding,spacing:this._spacing,widthFitting:this._widthFitting,heightFitting:this._heightFitting,wrap:this._wrap,containerSize:new ge(i,n)};this._isPerformingReflow=!0;var r=this._layoutCalculator.calculateLayout(t,s);this._isPerformingReflow=!1,this.fire("reflow",r)}},i.onEnable=function(){this._scheduleReflow()},i.onRemove=function(){var e=this;this.entity.off("childinsert",this._onChildInsert,this),this.entity.off("childremove",this._onChildRemove,this),this._listenForReflowEvents(this.entity,"off"),this.entity.children.forEach((function(t){e._listenForReflowEvents(t,"off")})),this.system.app.systems.element.off("add",this._onElementOrLayoutComponentAdd,this),this.system.app.systems.element.off("beforeremove",this._onElementOrLayoutComponentRemove,this),this.system.app.systems.layoutchild.off("add",this._onElementOrLayoutComponentAdd,this),this.system.app.systems.layoutchild.off("beforeremove",this._onElementOrLayoutComponentRemove,this)},Z(t,[{key:"orientation",get:function(){return this._orientation},set:function(e){e!==this._orientation&&(this._orientation=e,this._scheduleReflow())}},{key:"reverseX",get:function(){return this._reverseX},set:function(e){e!==this._reverseX&&(this._reverseX=e,this._scheduleReflow())}},{key:"reverseY",get:function(){return this._reverseY},set:function(e){e!==this._reverseY&&(this._reverseY=e,this._scheduleReflow())}},{key:"alignment",get:function(){return this._alignment},set:function(e){e.equals(this._alignment)||(this._alignment.copy(e),this._scheduleReflow())}},{key:"padding",get:function(){return this._padding},set:function(e){e.equals(this._padding)||(this._padding.copy(e),this._scheduleReflow())}},{key:"spacing",get:function(){return this._spacing},set:function(e){e.equals(this._spacing)||(this._spacing.copy(e),this._scheduleReflow())}},{key:"widthFitting",get:function(){return this._widthFitting},set:function(e){e!==this._widthFitting&&(this._widthFitting=e,this._scheduleReflow())}},{key:"heightFitting",get:function(){return this._heightFitting},set:function(e){e!==this._heightFitting&&(this._heightFitting=e,this._scheduleReflow())}},{key:"wrap",get:function(){return this._wrap},set:function(e){e!==this._wrap&&(this._wrap=e,this._scheduleReflow())}}]),t}(gf),N_=function(){this.enabled=!0},U_=["enabled"],z_=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="layoutgroup",i.ComponentType=B_,i.DataType=N_,i.schema=U_,i._reflowQueue=[],i.on("beforeremove",i._onRemoveComponent,ee(i)),i.app.systems.on("postUpdate",i._onPostUpdate,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){void 0!==i.enabled&&(t.enabled=i.enabled),void 0!==i.orientation&&(t.orientation=i.orientation),void 0!==i.reverseX&&(t.reverseX=i.reverseX),void 0!==i.reverseY&&(t.reverseY=i.reverseY),void 0!==i.alignment&&(t.alignment=Array.isArray(i.alignment)?new ge(i.alignment):i.alignment),void 0!==i.padding&&(t.padding=Array.isArray(i.padding)?new ve(i.padding):i.padding),void 0!==i.spacing&&(t.spacing=Array.isArray(i.spacing)?new ge(i.spacing):i.spacing),void 0!==i.widthFitting&&(t.widthFitting=i.widthFitting),void 0!==i.heightFitting&&(t.heightFitting=i.heightFitting),void 0!==i.wrap&&(t.wrap=i.wrap),e.prototype.initializeComponentData.call(this,t,i,n)},i.cloneComponent=function(e,t){var i=e.layoutgroup;return this.addComponent(t,{enabled:i.enabled,orientation:i.orientation,reverseX:i.reverseX,reverseY:i.reverseY,alignment:i.alignment,padding:i.padding,spacing:i.spacing,widthFitting:i.widthFitting,heightFitting:i.heightFitting,wrap:i.wrap})},i.scheduleReflow=function(e){-1===this._reflowQueue.indexOf(e)&&this._reflowQueue.push(e)},i._onPostUpdate=function(){this._processReflowQueue()},i._processReflowQueue=function(){if(0!==this._reflowQueue.length)for(var e=0;this._reflowQueue.length>0;){var t=this._reflowQueue.slice();this._reflowQueue.length=0,t.sort((function(e,t){return e.entity.graphDepth-t.entity.graphDepth}));for(var i=0;i<t.length;++i)t[i].reflow();if(++e>=100){console.warn("Max reflow iterations limit reached, bailing.");break}}},i._onRemoveComponent=function(e,t){t.onRemove()},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("postUpdate",this._onPostUpdate,this)},t}(vf);gf._buildAccessors(B_.prototype,U_);var V_=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._type="asset",n._asset=null,n._model=null,n._mapping={},n._castShadows=!0,n._receiveShadows=!0,n._materialAsset=null,n._material=void 0,n._castShadowsLightmap=!0,n._lightmapped=!1,n._lightmapSizeMultiplier=1,n._isStatic=!1,n._layers=[0],n._batchGroupId=-1,n._customAabb=null,n._area=null,n._materialEvents=null,n._clonedModel=!1,n._material=t.defaultMaterial,i.on("remove",n.onRemoveChild,ee(n)),i.on("removehierarchy",n.onRemoveChild,ee(n)),i.on("insert",n.onInsertChild,ee(n)),i.on("inserthierarchy",n.onInsertChild,ee(n)),n}Q(t,e);var i=t.prototype;return i.addModelToLayers=function(){for(var e=this.system.app.scene.layers,t=0;t<this._layers.length;t++){var i=e.getLayerById(this._layers[t]);i&&i.addMeshInstances(this.meshInstances)}},i.removeModelFromLayers=function(){for(var e=this.system.app.scene.layers,t=0;t<this._layers.length;t++){var i=e.getLayerById(this._layers[t]);i&&i.removeMeshInstances(this.meshInstances)}},i.onRemoveChild=function(){this._model&&this.removeModelFromLayers()},i.onInsertChild=function(){this._model&&this.enabled&&this.entity.enabled&&this.addModelToLayers()},i.onRemove=function(){this.asset=null,this.model=null,this.materialAsset=null,this._unsetMaterialEvents(),this.entity.off("remove",this.onRemoveChild,this),this.entity.off("insert",this.onInsertChild,this)},i.onLayersChanged=function(e,t){this.addModelToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(e){this.layers.indexOf(e.id)<0||e.addMeshInstances(this.meshInstances)},i.onLayerRemoved=function(e){this.layers.indexOf(e.id)<0||e.removeMeshInstances(this.meshInstances)},i._setMaterialEvent=function(e,t,i,n){var s=t+":"+i;this.system.app.assets.on(s,n,this),this._materialEvents||(this._materialEvents=[]),this._materialEvents[e]||(this._materialEvents[e]={}),this._materialEvents[e][s]={id:i,handler:n}},i._unsetMaterialEvents=function(){var e=this.system.app.assets,t=this._materialEvents;if(t){for(var i=0,n=t.length;i<n;i++)if(t[i]){var s=t[i];for(var r in s)e.off(r,s[r].handler,this)}this._materialEvents=null}},i._getAssetByIdOrPath=function(e){var t=null;if(isNaN(parseInt(e,10))){if(this.asset){var i=this._getMaterialAssetUrl(e);i&&(t=this.system.app.assets.getByUrl(i))}}else t=this.system.app.assets.get(e);return t},i._getMaterialAssetUrl=function(e){if(!this.asset)return null;var t=this.system.app.assets.get(this.asset);return t?t.getAbsoluteUrl(e):null},i._loadAndSetMeshInstanceMaterial=function(e,t,i){var n=this.system.app.assets;e&&(e.resource?(t.material=e.resource,this._setMaterialEvent(i,"remove",e.id,(function(){t.material=this.system.defaultMaterial}))):(this._setMaterialEvent(i,"load",e.id,(function(n){t.material=n.resource,this._setMaterialEvent(i,"remove",e.id,(function(){t.material=this.system.defaultMaterial}))})),this.enabled&&this.entity.enabled&&n.load(e)))},i.onEnable=function(){var e=this.system.app,t=e.scene;t.on("set:layers",this.onLayersChanged,this),t.layers&&(t.layers.on("add",this.onLayerAdded,this),t.layers.on("remove",this.onLayerRemoved,this));var i,n,s="asset"===this._type;if(this._model?this.addModelToLayers():s&&this._asset&&(i=e.assets.get(this._asset))&&i.resource!==this._model&&this._bindModelAsset(i),this._materialAsset&&(i=e.assets.get(this._materialAsset))&&i.resource!==this._material&&this._bindMaterialAsset(i),s&&this._mapping)for(var r in this._mapping)this._mapping[r]&&(i=this._getAssetByIdOrPath(this._mapping[r]))&&!i.resource&&e.assets.load(i);this._batchGroupId>=0&&(null==(n=e.batcher)||n.insert($a.MODEL,this.batchGroupId,this.entity))},i.onDisable=function(){var e,t=this.system.app,i=t.scene;(i.off("set:layers",this.onLayersChanged,this),i.layers&&(i.layers.off("add",this.onLayerAdded,this),i.layers.off("remove",this.onLayerRemoved,this)),this._batchGroupId>=0)&&(null==(e=t.batcher)||e.remove($a.MODEL,this.batchGroupId,this.entity));this._model&&this.removeModelFromLayers()},i.hide=function(){if(this._model)for(var e=this._model.meshInstances,t=0,i=e.length;t<i;t++)e[t].visible=!1},i.show=function(){if(this._model)for(var e=this._model.meshInstances,t=0,i=e.length;t<i;t++)e[t].visible=!0},i._bindMaterialAsset=function(e){if(e.on("load",this._onMaterialAssetLoad,this),e.on("unload",this._onMaterialAssetUnload,this),e.on("remove",this._onMaterialAssetRemove,this),e.on("change",this._onMaterialAssetChange,this),e.resource)this._onMaterialAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}},i._unbindMaterialAsset=function(e){e.off("load",this._onMaterialAssetLoad,this),e.off("unload",this._onMaterialAssetUnload,this),e.off("remove",this._onMaterialAssetRemove,this),e.off("change",this._onMaterialAssetChange,this)},i._onMaterialAssetAdd=function(e){this.system.app.assets.off("add:"+e.id,this._onMaterialAssetAdd,this),this._materialAsset===e.id&&this._bindMaterialAsset(e)},i._onMaterialAssetLoad=function(e){this._setMaterial(e.resource)},i._onMaterialAssetUnload=function(e){this._setMaterial(this.system.defaultMaterial)},i._onMaterialAssetRemove=function(e){this._onMaterialAssetUnload(e)},i._onMaterialAssetChange=function(e){},i._bindModelAsset=function(e){if(this._unbindModelAsset(e),e.on("load",this._onModelAssetLoad,this),e.on("unload",this._onModelAssetUnload,this),e.on("change",this._onModelAssetChange,this),e.on("remove",this._onModelAssetRemove,this),e.resource)this._onModelAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}},i._unbindModelAsset=function(e){e.off("load",this._onModelAssetLoad,this),e.off("unload",this._onModelAssetUnload,this),e.off("change",this._onModelAssetChange,this),e.off("remove",this._onModelAssetRemove,this)},i._onModelAssetAdded=function(e){this.system.app.assets.off("add:"+e.id,this._onModelAssetAdded,this),e.id===this._asset&&this._bindModelAsset(e)},i._onModelAssetLoad=function(e){this.model=e.resource.clone(),this._clonedModel=!0},i._onModelAssetUnload=function(e){this.model=null},i._onModelAssetChange=function(e,t,i,n){"data"===t&&(this.mapping=this._mapping)},i._onModelAssetRemove=function(e){this.model=null},i._setMaterial=function(e){if(this._material!==e){this._material=e;var t=this._model;if(t&&"asset"!==this._type)for(var i=t.meshInstances,n=0,s=i.length;n<s;n++)i[n].material=e}},Z(t,[{key:"meshInstances",get:function(){return this._model?this._model.meshInstances:null},set:function(e){this._model&&(this._model.meshInstances=e)}},{key:"customAabb",get:function(){return this._customAabb},set:function(e){if(this._customAabb=e,this._model){var t=this._model.meshInstances;if(t)for(var i=0;i<t.length;i++)t[i].setCustomAabb(this._customAabb)}}},{key:"type",get:function(){return this._type},set:function(e){if(this._type!==e)if(this._area=null,this._type=e,"asset"===e)null!==this._asset?this._bindModelAsset(this._asset):this.model=null;else{var t=pa(this.system.app.graphicsDevice,e);this._area=t.area;var i=t.mesh,n=new go,s=new Uc;s.graph=n,s.meshInstances=[new Co(i,this._material,n)],this.model=s,this._asset=null}}},{key:"asset",get:function(){return this._asset},set:function(e){var t=this.system.app.assets,i=e;if(e instanceof kd&&(i=e.id),this._asset!==i){if(this._asset){t.off("add:"+this._asset,this._onModelAssetAdded,this);var n=t.get(this._asset);n&&this._unbindModelAsset(n)}if(this._asset=i,this._asset){var s=t.get(this._asset);s?this._bindModelAsset(s):(this.model=null,t.on("add:"+this._asset,this._onModelAssetAdded,this))}else this.model=null}}},{key:"model",get:function(){return this._model},set:function(e){if(this._model!==e&&(!e||!e._immutable)&&(this._model&&(this._model._immutable=!1,this.removeModelFromLayers(),this.entity.removeChild(this._model.getGraph()),delete this._model._entity,this._clonedModel&&(this._model.destroy(),this._clonedModel=!1)),this._model=e,this._model)){this._model._immutable=!0;for(var t=this._model.meshInstances,i=0;i<t.length;i++)t[i].castShadow=this._castShadows,t[i].receiveShadow=this._receiveShadows,t[i].isStatic=this._isStatic,t[i].setCustomAabb(this._customAabb);this.lightmapped=this._lightmapped,this.entity.addChild(this._model.graph),this.enabled&&this.entity.enabled&&this.addModelToLayers(),this._model._entity=this.entity,this.entity.animation&&this.entity.animation.setModel(this._model),this.entity.anim&&this.entity.anim.rebind(),"asset"===this.type?this.mapping=this._mapping:this._unsetMaterialEvents()}}},{key:"lightmapped",get:function(){return this._lightmapped},set:function(e){if(e!==this._lightmapped&&(this._lightmapped=e,this._model))for(var t=this._model.meshInstances,i=0;i<t.length;i++)t[i].setLightmapped(e)}},{key:"castShadows",get:function(){return this._castShadows},set:function(e){if(this._castShadows!==e){var t=this._model;if(t){var i=this.layers,n=this.system.app.scene;if(this._castShadows&&!e)for(var s=0;s<i.length;s++){var r=this.system.app.scene.layers.getLayerById(this.layers[s]);r&&r.removeShadowCasters(t.meshInstances)}for(var a=t.meshInstances,o=0;o<a.length;o++)a[o].castShadow=e;if(!this._castShadows&&e)for(var h=0;h<i.length;h++){var l=n.layers.getLayerById(i[h]);l&&l.addShadowCasters(t.meshInstances)}}this._castShadows=e}}},{key:"receiveShadows",get:function(){return this._receiveShadows},set:function(e){if(this._receiveShadows!==e&&(this._receiveShadows=e,this._model))for(var t=this._model.meshInstances,i=0,n=t.length;i<n;i++)t[i].receiveShadow=e}},{key:"castShadowsLightmap",get:function(){return this._castShadowsLightmap},set:function(e){this._castShadowsLightmap=e}},{key:"lightmapSizeMultiplier",get:function(){return this._lightmapSizeMultiplier},set:function(e){this._lightmapSizeMultiplier=e}},{key:"isStatic",get:function(){return this._isStatic},set:function(e){if(this._isStatic!==e&&(this._isStatic=e,this._model))for(var t=this._model.meshInstances,i=0;i<t.length;i++){t[i].isStatic=e}}},{key:"layers",get:function(){return this._layers},set:function(e){var t=this.system.app.scene.layers;if(this.meshInstances)for(var i=0;i<this._layers.length;i++){var n=t.getLayerById(this._layers[i]);n&&n.removeMeshInstances(this.meshInstances)}this._layers.length=0;for(var s=0;s<e.length;s++)this._layers[s]=e[s];if(this.enabled&&this.entity.enabled&&this.meshInstances)for(var r=0;r<this._layers.length;r++){var a=t.getLayerById(this._layers[r]);a&&a.addMeshInstances(this.meshInstances)}}},{key:"batchGroupId",get:function(){return this._batchGroupId},set:function(e){if(this._batchGroupId!==e){var t,i;if(this.entity.enabled&&this._batchGroupId>=0)null==(t=this.system.app.batcher)||t.remove($a.MODEL,this.batchGroupId,this.entity);if(this.entity.enabled&&e>=0)null==(i=this.system.app.batcher)||i.insert($a.MODEL,e,this.entity);e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addModelToLayers(),this._batchGroupId=e}}},{key:"materialAsset",get:function(){return this._materialAsset},set:function(e){var t=e;e instanceof kd&&(t=e.id);var i=this.system.app.assets;if(t!==this._materialAsset){if(this._materialAsset){i.off("add:"+this._materialAsset,this._onMaterialAssetAdd,this);var n=i.get(this._materialAsset);n&&this._unbindMaterialAsset(n)}if(this._materialAsset=t,this._materialAsset){var s=i.get(this._materialAsset);s?this._bindMaterialAsset(s):(this._setMaterial(this.system.defaultMaterial),i.on("add:"+this._materialAsset,this._onMaterialAssetAdd,this))}else this._setMaterial(this.system.defaultMaterial)}}},{key:"material",get:function(){return this._material},set:function(e){this._material!==e&&(this.materialAsset=null,this._setMaterial(e))}},{key:"mapping",get:function(){return this._mapping},set:function(e){if("asset"===this._type&&(this._unsetMaterialEvents(),e||(e={}),this._mapping=e,this._model))for(var t=this._model.meshInstances,i=this.asset?this.system.app.assets.get(this.asset):null,n=i?i.data.mapping:null,s=null,r=0,a=t.length;r<a;r++)if(void 0!==e[r])e[r]?(s=this.system.app.assets.get(e[r]),this._loadAndSetMeshInstanceMaterial(s,t[r],r)):t[r].material=this.system.defaultMaterial;else if(n)if(n[r]&&(n[r].material||n[r].path)){if(void 0!==n[r].material)s=this.system.app.assets.get(n[r].material);else if(void 0!==n[r].path){var o=this._getMaterialAssetUrl(n[r].path);o&&(s=this.system.app.assets.getByUrl(o))}this._loadAndSetMeshInstanceMaterial(s,t[r],r)}else t[r].material=this.system.defaultMaterial}}]),t}(gf),G_=function(){this.enabled=!0},H_=["enabled"],W_=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="model",i.ComponentType=V_,i.DataType=G_,i.schema=H_,i.defaultMaterial=Xa(t.graphicsDevice),i.on("beforeremove",i.onRemove,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){n=["material","materialAsset","asset","castShadows","receiveShadows","castShadowsLightmap","lightmapped","lightmapSizeMultiplier","type","mapping","layers","isStatic","batchGroupId"],null!==i.batchGroupId&&void 0!==i.batchGroupId||(i.batchGroupId=-1),i.layers&&i.layers.length&&(i.layers=i.layers.slice(0));for(var s=0;s<n.length;s++)i.hasOwnProperty(n[s])&&(t[n[s]]=i[n[s]]);i.aabbCenter&&i.aabbHalfExtents&&(t.customAabb=new Ie(new me(i.aabbCenter),new me(i.aabbHalfExtents))),e.prototype.initializeComponentData.call(this,t,i,["enabled"])},i.cloneComponent=function(e,t){var i={type:e.model.type,asset:e.model.asset,castShadows:e.model.castShadows,receiveShadows:e.model.receiveShadows,castShadowsLightmap:e.model.castShadowsLightmap,lightmapped:e.model.lightmapped,lightmapSizeMultiplier:e.model.lightmapSizeMultiplier,isStatic:e.model.isStatic,enabled:e.model.enabled,layers:e.model.layers,batchGroupId:e.model.batchGroupId,mapping:f({},e.model.mapping)},n=e.model.materialAsset;n instanceof kd||null==n||(n=this.app.assets.get(n));var s=e.model.material;s&&s!==this.defaultMaterial&&n&&s!==n.resource||(i.materialAsset=n);var r=this.addComponent(t,i);if(e.model.model&&"asset"===e.model.type&&!e.model.asset&&(r.model=e.model.model.clone(),r._clonedModel=!0),i.materialAsset||(r.material=s),e.model.model)for(var a=e.model.model.meshInstances,o=r.model.meshInstances,h=0;h<a.length;h++)o[h].mask=a[h].mask,o[h].material=a[h].material,o[h].layer=a[h].layer,o[h].receiveShadow=a[h].receiveShadow;return e.model.customAabb&&(r.customAabb=e.model.customAabb.clone()),r},i.onRemove=function(e,t){t.onRemove()},t}(vf);gf._buildAccessors(V_.prototype,H_);var X_,j_=["emitterExtents","emitterRadius","emitterExtentsInner","emitterRadiusInner","loop","initialVelocity","animSpeed","normalMap","particleNormal"],q_=["numParticles","lifetime","rate","rate2","startAngle","startAngle2","lighting","halfLambert","intensity","wrap","wrapBounds","depthWrite","noFog","sort","stretch","alignToMotion","preWarm","emitterShape","animTilesX","animTilesY","animStartFrame","animNumFrames","animNumAnimations","animIndex","randomizeAnimIndex","animLoop","colorMap","localSpace","screenSpace","orientation"],Y_=["scaleGraph","scaleGraph2","colorGraph","colorGraph2","alphaGraph","alphaGraph2","velocityGraph","velocityGraph2","localVelocityGraph","localVelocityGraph2","rotationSpeedGraph","rotationSpeedGraph2","radialSpeedGraph","radialSpeedGraph2"],K_=["colorMapAsset","normalMapAsset","meshAsset","renderAsset"],Z_=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._requestedDepth=!1,n._drawOrder=0,n.on("set_colorMapAsset",n.onSetColorMapAsset,ee(n)),n.on("set_normalMapAsset",n.onSetNormalMapAsset,ee(n)),n.on("set_meshAsset",n.onSetMeshAsset,ee(n)),n.on("set_mesh",n.onSetMesh,ee(n)),n.on("set_renderAsset",n.onSetRenderAsset,ee(n)),n.on("set_loop",n.onSetLoop,ee(n)),n.on("set_blendType",n.onSetBlendType,ee(n)),n.on("set_depthSoftening",n.onSetDepthSoftening,ee(n)),n.on("set_layers",n.onSetLayers,ee(n)),j_.forEach((function(e){n.on("set_"+e,n.onSetSimpleProperty,ee(n))})),q_.forEach((function(e){n.on("set_"+e,n.onSetComplexProperty,ee(n))})),Y_.forEach((function(e){n.on("set_"+e,n.onSetGraphProperty,ee(n))})),n}Q(t,e);var i=t.prototype;return i.addMeshInstanceToLayers=function(){if(this.emitter)for(var e=0;e<this.layers.length;e++){var t=this.system.app.scene.layers.getLayerById(this.layers[e]);t&&(t.addMeshInstances([this.emitter.meshInstance]),this.emitter._layer=t)}},i.removeMeshInstanceFromLayers=function(){if(this.emitter)for(var e=0;e<this.layers.length;e++){var t=this.system.app.scene.layers.getLayerById(this.layers[e]);t&&t.removeMeshInstances([this.emitter.meshInstance])}},i.onSetLayers=function(e,t,i){if(this.emitter){for(var n=0;n<t.length;n++){var s=this.system.app.scene.layers.getLayerById(t[n]);s&&s.removeMeshInstances([this.emitter.meshInstance])}if(this.enabled&&this.entity.enabled)for(var r=0;r<i.length;r++){var a=this.system.app.scene.layers.getLayerById(i[r]);a&&a.addMeshInstances([this.emitter.meshInstance])}}},i.onLayersChanged=function(e,t){this.addMeshInstanceToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(e){this.emitter&&(this.layers.indexOf(e.id)<0||e.addMeshInstances([this.emitter.meshInstance]))},i.onLayerRemoved=function(e){this.emitter&&(this.layers.indexOf(e.id)<0||e.removeMeshInstances([this.emitter.meshInstance]))},i._bindColorMapAsset=function(e){if(e.on("load",this._onColorMapAssetLoad,this),e.on("unload",this._onColorMapAssetUnload,this),e.on("remove",this._onColorMapAssetRemove,this),e.on("change",this._onColorMapAssetChange,this),e.resource)this._onColorMapAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}},i._unbindColorMapAsset=function(e){e.off("load",this._onColorMapAssetLoad,this),e.off("unload",this._onColorMapAssetUnload,this),e.off("remove",this._onColorMapAssetRemove,this),e.off("change",this._onColorMapAssetChange,this)},i._onColorMapAssetLoad=function(e){this.colorMap=e.resource},i._onColorMapAssetUnload=function(e){this.colorMap=null},i._onColorMapAssetRemove=function(e){this._onColorMapAssetUnload(e)},i._onColorMapAssetChange=function(e){},i.onSetColorMapAsset=function(e,t,i){var n=this,s=this.system.app.assets;if(t){var r=s.get(t);r&&this._unbindColorMapAsset(r)}if(i){i instanceof kd&&(this.data.colorMapAsset=i.id,i=i.id);var a=s.get(i);a?this._bindColorMapAsset(a):s.once("add:"+i,(function(e){n._bindColorMapAsset(e)}))}else this.colorMap=null},i._bindNormalMapAsset=function(e){if(e.on("load",this._onNormalMapAssetLoad,this),e.on("unload",this._onNormalMapAssetUnload,this),e.on("remove",this._onNormalMapAssetRemove,this),e.on("change",this._onNormalMapAssetChange,this),e.resource)this._onNormalMapAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}},i._unbindNormalMapAsset=function(e){e.off("load",this._onNormalMapAssetLoad,this),e.off("unload",this._onNormalMapAssetUnload,this),e.off("remove",this._onNormalMapAssetRemove,this),e.off("change",this._onNormalMapAssetChange,this)},i._onNormalMapAssetLoad=function(e){this.normalMap=e.resource},i._onNormalMapAssetUnload=function(e){this.normalMap=null},i._onNormalMapAssetRemove=function(e){this._onNormalMapAssetUnload(e)},i._onNormalMapAssetChange=function(e){},i.onSetNormalMapAsset=function(e,t,i){var n=this,s=this.system.app.assets;if(t){var r=s.get(t);r&&this._unbindNormalMapAsset(r)}if(i){i instanceof kd&&(this.data.normalMapAsset=i.id,i=i.id);var a=s.get(i);a?this._bindNormalMapAsset(a):s.once("add:"+i,(function(e){n._bindNormalMapAsset(e)}))}else this.normalMap=null},i._bindMeshAsset=function(e){if(e.on("load",this._onMeshAssetLoad,this),e.on("unload",this._onMeshAssetUnload,this),e.on("remove",this._onMeshAssetRemove,this),e.on("change",this._onMeshAssetChange,this),e.resource)this._onMeshAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}},i._unbindMeshAsset=function(e){e.off("load",this._onMeshAssetLoad,this),e.off("unload",this._onMeshAssetUnload,this),e.off("remove",this._onMeshAssetRemove,this),e.off("change",this._onMeshAssetChange,this)},i._onMeshAssetLoad=function(e){this._onMeshChanged(e.resource)},i._onMeshAssetUnload=function(e){this.mesh=null},i._onMeshAssetRemove=function(e){this._onMeshAssetUnload(e)},i._onMeshAssetChange=function(e){},i.onSetMeshAsset=function(e,t,i){var n=this.system.app.assets;if(t){var s=n.get(t);s&&this._unbindMeshAsset(s)}if(i){i instanceof kd&&(this.data.meshAsset=i.id,i=i.id);var r=n.get(i);r&&this._bindMeshAsset(r)}else this._onMeshChanged(null)},i.onSetMesh=function(e,t,i){!i||i instanceof kd||"number"==typeof i?this.meshAsset=i:this._onMeshChanged(i)},i._onMeshChanged=function(e){!e||e instanceof Jr||(e=e.meshInstances[0]?e.meshInstances[0].mesh:null),this.data.mesh=e,this.emitter&&(this.emitter.mesh=e,this.emitter.resetMaterial(),this.rebuild())},i.onSetRenderAsset=function(e,t,i){var n=this.system.app.assets;if(t){var s=n.get(t);s&&this._unbindRenderAsset(s)}if(i){i instanceof kd&&(this.data.renderAsset=i.id,i=i.id);var r=n.get(i);r&&this._bindRenderAsset(r)}else this._onRenderChanged(null)},i._bindRenderAsset=function(e){if(e.on("load",this._onRenderAssetLoad,this),e.on("unload",this._onRenderAssetUnload,this),e.on("remove",this._onRenderAssetRemove,this),e.resource)this._onRenderAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}},i._unbindRenderAsset=function(e){e.off("load",this._onRenderAssetLoad,this),e.off("unload",this._onRenderAssetUnload,this),e.off("remove",this._onRenderAssetRemove,this),e.resource&&e.resource.off("set:meshes",this._onRenderSetMeshes,this)},i._onRenderAssetLoad=function(e){this._onRenderChanged(e.resource)},i._onRenderAssetUnload=function(e){this._onRenderChanged(null)},i._onRenderAssetRemove=function(e){this._onRenderAssetUnload(e)},i._onRenderChanged=function(e){e?(e.off("set:meshes",this._onRenderSetMeshes,this),e.on("set:meshes",this._onRenderSetMeshes,this),e.meshes&&this._onRenderSetMeshes(e.meshes)):this._onMeshChanged(null)},i._onRenderSetMeshes=function(e){this._onMeshChanged(e&&e[0])},i.onSetLoop=function(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetTime())},i.onSetBlendType=function(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.material.blendType=i,this.emitter.resetMaterial(),this.rebuild())},i._requestDepth=function(){this._requestedDepth||(X_||(X_=this.system.app.scene.layers.getLayerById(1)),X_&&(X_.incrementCounter(),this._requestedDepth=!0))},i._releaseDepth=function(){this._requestedDepth&&X_&&(X_.decrementCounter(),this._requestedDepth=!1)},i.onSetDepthSoftening=function(e,t,i){t!==i&&(i?(this.enabled&&this.entity.enabled&&this._requestDepth(),this.emitter&&(this.emitter[e]=i)):(this.enabled&&this.entity.enabled&&this._releaseDepth(),this.emitter&&(this.emitter[e]=i)),this.emitter&&(this.reset(),this.emitter.resetMaterial(),this.rebuild()))},i.onSetSimpleProperty=function(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetMaterial())},i.onSetComplexProperty=function(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetMaterial(),this.rebuild(),this.reset())},i.onSetGraphProperty=function(e,t,i){this.emitter&&(this.emitter[e]=i,this.emitter.rebuildGraphs(),this.emitter.resetMaterial())},i.onEnable=function(){for(var e=this.data,t=0,i=K_.length;t<i;t++){var n=e[K_[t]];if(n){if(!(n instanceof kd)){if(!(parseInt(n,10)>=0))continue;n=this.system.app.assets.get(n)}n&&!n.resource&&this.system.app.assets.load(n)}}if(!this.system.app.graphicsDevice.disableParticleSystem){if(!this.emitter){var s=e.mesh;s instanceof Jr||(s=null),this.emitter=new ku(this.system.app.graphicsDevice,{numParticles:e.numParticles,emitterExtents:e.emitterExtents,emitterExtentsInner:e.emitterExtentsInner,emitterRadius:e.emitterRadius,emitterRadiusInner:e.emitterRadiusInner,emitterShape:e.emitterShape,initialVelocity:e.initialVelocity,wrap:e.wrap,localSpace:e.localSpace,screenSpace:e.screenSpace,wrapBounds:e.wrapBounds,lifetime:e.lifetime,rate:e.rate,rate2:e.rate2,orientation:e.orientation,particleNormal:e.particleNormal,animTilesX:e.animTilesX,animTilesY:e.animTilesY,animStartFrame:e.animStartFrame,animNumFrames:e.animNumFrames,animNumAnimations:e.animNumAnimations,animIndex:e.animIndex,randomizeAnimIndex:e.randomizeAnimIndex,animSpeed:e.animSpeed,animLoop:e.animLoop,startAngle:e.startAngle,startAngle2:e.startAngle2,scaleGraph:e.scaleGraph,scaleGraph2:e.scaleGraph2,colorGraph:e.colorGraph,colorGraph2:e.colorGraph2,alphaGraph:e.alphaGraph,alphaGraph2:e.alphaGraph2,localVelocityGraph:e.localVelocityGraph,localVelocityGraph2:e.localVelocityGraph2,velocityGraph:e.velocityGraph,velocityGraph2:e.velocityGraph2,rotationSpeedGraph:e.rotationSpeedGraph,rotationSpeedGraph2:e.rotationSpeedGraph2,radialSpeedGraph:e.radialSpeedGraph,radialSpeedGraph2:e.radialSpeedGraph2,colorMap:e.colorMap,normalMap:e.normalMap,loop:e.loop,preWarm:e.preWarm,sort:e.sort,stretch:e.stretch,alignToMotion:e.alignToMotion,lighting:e.lighting,halfLambert:e.halfLambert,intensity:e.intensity,depthSoftening:e.depthSoftening,scene:this.system.app.scene,mesh:s,depthWrite:e.depthWrite,noFog:e.noFog,node:this.entity,blendType:e.blendType}),this.emitter.meshInstance.node=this.entity,this.emitter.drawOrder=this.drawOrder,e.autoPlay||(this.pause(),this.emitter.meshInstance.visible=!1)}this.emitter.colorMap&&this.addMeshInstanceToLayers(),this.system.app.scene.on("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.on("add",this.onLayerAdded,this),this.system.app.scene.layers.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&e.depthSoftening&&this._requestDepth()}},i.onDisable=function(){this.system.app.scene.off("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.off("add",this.onLayerAdded,this),this.system.app.scene.layers.off("remove",this.onLayerRemoved,this)),this.emitter&&(this.removeMeshInstanceFromLayers(),this.data.depthSoftening&&this._releaseDepth(),this.emitter.camera=null)},i.onBeforeRemove=function(){this.enabled&&(this.enabled=!1),this.emitter&&(this.emitter.destroy(),this.emitter=null);for(var e=0;e<K_.length;e++){var t=K_[e];this.data[t]&&(this[t]=null)}this.off()},i.reset=function(){this.emitter&&this.emitter.reset()},i.stop=function(){this.emitter&&(this.emitter.loop=!1,this.emitter.resetTime(),this.emitter.addTime(0,!0))},i.pause=function(){this.data.paused=!0},i.unpause=function(){this.data.paused=!1},i.play=function(){this.data.paused=!1,this.emitter&&(this.emitter.meshInstance.visible=!0,this.emitter.loop=this.data.loop,this.emitter.resetTime())},i.isPlaying=function(){return!this.data.paused&&(!(!this.emitter||!this.emitter.loop)||Date.now()<=this.emitter.endTime)},i.rebuild=function(){var e=this.enabled;this.enabled=!1,this.emitter&&(this.emitter.rebuild(),this.emitter.meshInstance.node=this.entity),this.enabled=e},Z(t,[{key:"drawOrder",get:function(){return this._drawOrder},set:function(e){this._drawOrder=e,this.emitter&&(this.emitter.drawOrder=e)}}]),t}(gf),$_=function(){this.numParticles=1,this.rate=1,this.rate2=null,this.startAngle=0,this.startAngle2=null,this.lifetime=50,this.emitterExtents=new me,this.emitterExtentsInner=new me,this.emitterRadius=0,this.emitterRadiusInner=0,this.emitterShape=0,this.initialVelocity=0,this.wrapBounds=new me,this.localSpace=!1,this.screenSpace=!1,this.colorMap=null,this.colorMapAsset=null,this.normalMap=null,this.normalMapAsset=null,this.loop=!0,this.preWarm=!1,this.sort=0,this.mode=0,this.scene=null,this.lighting=!1,this.halfLambert=!1,this.intensity=1,this.stretch=0,this.alignToMotion=!1,this.depthSoftening=0,this.meshAsset=null,this.mesh=null,this.depthWrite=!1,this.noFog=!1,this.orientation=0,this.particleNormal=new me(0,1,0),this.animTilesX=1,this.animTilesY=1,this.animStartFrame=0,this.animNumFrames=1,this.animNumAnimations=1,this.animIndex=0,this.randomizeAnimIndex=!1,this.animSpeed=1,this.animLoop=!0,this.scaleGraph=null,this.scaleGraph2=null,this.colorGraph=null,this.colorGraph2=null,this.alphaGraph=null,this.alphaGraph2=null,this.localVelocityGraph=null,this.localVelocityGraph2=null,this.velocityGraph=null,this.velocityGraph2=null,this.rotationSpeedGraph=null,this.rotationSpeedGraph2=null,this.radialSpeedGraph=null,this.radialSpeedGraph2=null,this.blendType=2,this.enabled=!0,this.paused=!1,this.autoPlay=!0,this.layers=[0]},Q_=["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"],J_=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="particlesystem",i.ComponentType=Z_,i.DataType=$_,i.schema=Q_,i.propertyTypes={emitterExtents:"vec3",emitterExtentsInner:"vec3",particleNormal:"vec3",wrapBounds:"vec3",localVelocityGraph:"curveset",localVelocityGraph2:"curveset",velocityGraph:"curveset",velocityGraph2:"curveset",colorGraph:"curveset",colorGraph2:"curveset",alphaGraph:"curve",alphaGraph2:"curve",rotationSpeedGraph:"curve",rotationSpeedGraph2:"curve",radialSpeedGraph:"curve",radialSpeedGraph2:"curve",scaleGraph:"curve",scaleGraph2:"curve"},i.on("beforeremove",i.onBeforeRemove,ee(i)),i.app.systems.on("update",i.onUpdate,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){var s={};n=[];var r=this.propertyTypes;for(var a in(i.mesh instanceof kd||"number"==typeof i.mesh)&&(i.meshAsset=i.mesh,delete i.mesh),i){if(i.hasOwnProperty(a)&&(n.push(a),s[a]=i[a]),"vec3"===r[a])Array.isArray(s[a])&&(s[a]=new me(s[a][0],s[a][1],s[a][2]));else if("curve"===r[a]){if(!(s[a]instanceof fe)){var o=s[a].type;s[a]=new fe(s[a].keys),s[a].type=o}}else if("curveset"===r[a]&&!(s[a]instanceof pe)){var h=s[a].type;s[a]=new pe(s[a].keys),s[a].type=h}s.layers&&Array.isArray(s.layers)&&(s.layers=s.layers.slice(0))}e.prototype.initializeComponentData.call(this,t,s,n)},i.cloneComponent=function(e,t){for(var i=e.particlesystem.data,n=this.schema,s={},r=0,a=n.length;r<a;r++){var o=n[r],h=i[o];h instanceof me||h instanceof fe||h instanceof pe?(h=h.clone(),s[o]=h):"layers"===o?s.layers=i.layers.slice(0):null!=h&&(s[o]=h)}return this.addComponent(t,s)},i.onUpdate=function(e){var t,i=this.store,n=this.app.stats.particles;for(var s in i)if(i.hasOwnProperty(s)){var r=i[s],a=r.entity,o=r.data;if(o.enabled&&a.enabled){var h=a.particlesystem.emitter;if(null==h||!h.meshInstance.visible)continue;if(h.lighting){for(var l=o.layers,c=void 0,u=0;u<l.length;u++){var d=this.app.scene.layers.getLayerById(l[u]);if(d){d._lightCube||(d._lightCube=new Float32Array(18)),c=d._lightCube;for(var f=0;f<6;f++)c[3*f]=this.app.scene.ambientLight.r,c[3*f+1]=this.app.scene.ambientLight.g,c[3*f+2]=this.app.scene.ambientLight.b;for(var p=d._splitLights[0],m=0;m<p.length;m++)for(var _=0;_<6;_++){var g=Math.max(h.lightCubeDir[_].dot(p[m]._direction),0)*p[m]._intensity;c[3*_]+=p[m]._color.r*g,c[3*_+1]+=p[m]._color.g*g,c[3*_+2]+=p[m]._color.b*g}}}h.constantLightCube.setValue(c)}if(!o.paused){if(h.simTime+=e,h.simTime>h.fixedTimeStep&&(t=Math.floor(h.simTime/h.fixedTimeStep),h.simTime-=t*h.fixedTimeStep),t){t=Math.min(t,h.maxSubSteps);for(var v=0;v<t;v++)h.addTime(h.fixedTimeStep,!1);n._updatesPerFrame+=t,n._frameTime+=h._addTimeTime,h._addTimeTime=0}h.finishFrame()}}}},i.onBeforeRemove=function(e,t){t.onBeforeRemove()},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},t}(vf);gf._buildAccessors(Z_.prototype,Q_);var eg=function(e){function t(t,i){var n;return(n=e.call(this)||this).skin=t,n.skinInstance=i,n}return Q(t,e),t}(Yr),tg=function(){function e(){}return e.createCachedSkinInstance=function(t,i,n){var s=e.getCachedSkinInstance(t,i);return s||((s=new Ja(t)).resolve(i,n),e.addCachedSkinInstance(t,i,s)),s},e.getCachedSkinInstance=function(t,i){var n=null,s=e._skinInstanceCache.get(i);if(s){var r=s.find((function(e){return e.skin===t}));r&&(r.incRefCount(),n=r.skinInstance)}return n},e.addCachedSkinInstance=function(t,i,n){var s=e._skinInstanceCache.get(i);s||(s=[],e._skinInstanceCache.set(i,s));var r=s.find((function(e){return e.skin===t}));r||(r=new eg(t,n),s.push(r)),r.incRefCount()},e.removeCachedSkinInstance=function(t){if(t){var i=t.rootBone;if(i){var n=e._skinInstanceCache.get(i);if(n){var s=n.findIndex((function(e){return e.skinInstance===t}));if(s>=0){var r=n[s];r.decRefCount(),0===r.refCount&&(n.splice(s,1),n.length||e._skinInstanceCache.delete(i),t&&(t.destroy(),r.skinInstance=null))}}}}},e}();tg._skinInstanceCache=new Map;var ig=function(){function e(e,t,i,n,s){this.propertyName=e,this.parent=t,this._scope=s,this._registry=i,this.id=null,this.url=null,this.asset=null,this._onAssetLoad=n.load,this._onAssetAdd=n.add,this._onAssetRemove=n.remove,this._onAssetUnload=n.unload}var t=e.prototype;return t._bind=function(){this.id&&(this._onAssetLoad&&this._registry.on("load:"+this.id,this._onLoad,this),this._onAssetAdd&&this._registry.once("add:"+this.id,this._onAdd,this),this._onAssetRemove&&this._registry.on("remove:"+this.id,this._onRemove,this),this._onAssetUnload&&this._registry.on("unload:"+this.id,this._onUnload,this)),this.url&&(this._onAssetLoad&&this._registry.on("load:url:"+this.url,this._onLoad,this),this._onAssetAdd&&this._registry.once("add:url:"+this.url,this._onAdd,this),this._onAssetRemove&&this._registry.on("remove:url:"+this.url,this._onRemove,this))},t._unbind=function(){this.id&&(this._onAssetLoad&&this._registry.off("load:"+this.id,this._onLoad,this),this._onAssetAdd&&this._registry.off("add:"+this.id,this._onAdd,this),this._onAssetRemove&&this._registry.off("remove:"+this.id,this._onRemove,this),this._onAssetUnload&&this._registry.off("unload:"+this.id,this._onUnload,this)),this.url&&(this._onAssetLoad&&this._registry.off("load:"+this.url,this._onLoad,this),this._onAssetAdd&&this._registry.off("add:"+this.url,this._onAdd,this),this._onAssetRemove&&this._registry.off("remove:"+this.url,this._onRemove,this))},t._onLoad=function(e){this._onAssetLoad.call(this._scope,this.propertyName,this.parent,e)},t._onAdd=function(e){this.asset=e,this._onAssetAdd.call(this._scope,this.propertyName,this.parent,e)},t._onRemove=function(e){this._onAssetRemove.call(this._scope,this.propertyName,this.parent,e),this.asset=null},t._onUnload=function(e){this._onAssetUnload.call(this._scope,this.propertyName,this.parent,e)},Z(e,[{key:"id",get:function(){return this._id},set:function(e){if(this.url)throw Error("Can't set id and url");this._unbind(),this._id=e,this.asset=this._registry.get(this._id),this._bind()}},{key:"url",get:function(){return this._url},set:function(e){if(this.id)throw Error("Can't set id and url");this._unbind(),this._url=e,this.asset=this._registry.getByUrl(this._url),this._bind()}}]),e}(),ng=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._type="asset",n._castShadows=!0,n._receiveShadows=!0,n._castShadowsLightmap=!0,n._lightmapped=!1,n._lightmapSizeMultiplier=1,n._isStatic=!1,n._batchGroupId=-1,n._layers=[0],n._renderStyle=0,n._meshInstances=[],n._customAabb=null,n._area=null,n._assetReference=[],n._materialReferences=[],n._material=void 0,n._rootBone=void 0,n._rootBone=new Op(ee(n),"rootBone"),n._rootBone.on("set:entity",n._onSetRootBone,ee(n)),n._assetReference=new ig("asset",ee(n),t.app.assets,{add:n._onRenderAssetAdded,load:n._onRenderAssetLoad,remove:n._onRenderAssetRemove,unload:n._onRenderAssetUnload},ee(n)),n._material=t.defaultMaterial,i.on("remove",n.onRemoveChild,ee(n)),i.on("removehierarchy",n.onRemoveChild,ee(n)),i.on("insert",n.onInsertChild,ee(n)),i.on("inserthierarchy",n.onInsertChild,ee(n)),n}Q(t,e);var i=t.prototype;return i.assignAsset=function(e){var t=e instanceof kd?e.id:e;this._assetReference.id=t},i._onSetRootBone=function(e){e&&this._onRootBoneChanged()},i._onRootBoneChanged=function(){this._clearSkinInstances(),this.enabled&&this.entity.enabled&&this._cloneSkinInstances()},i.destroyMeshInstances=function(){var e=this._meshInstances;if(e){this.removeFromLayers(),this._clearSkinInstances();for(var t=0;t<e.length;t++)e[t].destroy();this._meshInstances.length=0}},i.addToLayers=function(){for(var e=this.system.app.scene.layers,t=0;t<this._layers.length;t++){var i=e.getLayerById(this._layers[t]);i&&i.addMeshInstances(this._meshInstances)}},i.removeFromLayers=function(){if(this._meshInstances&&this._meshInstances.length)for(var e=this.system.app.scene.layers,t=0;t<this._layers.length;t++){var i=e.getLayerById(this._layers[t]);i&&i.removeMeshInstances(this._meshInstances)}},i.onRemoveChild=function(){this.removeFromLayers()},i.onInsertChild=function(){this._meshInstances&&this.enabled&&this.entity.enabled&&this.addToLayers()},i.onRemove=function(){this.destroyMeshInstances(),this.asset=null,this.materialAsset=null,this._assetReference.id=null;for(var e=0;e<this._materialReferences.length;e++)this._materialReferences[e].id=null;this.entity.off("remove",this.onRemoveChild,this),this.entity.off("insert",this.onInsertChild,this)},i.onLayersChanged=function(e,t){this.addToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(e){this.layers.indexOf(e.id)<0||e.addMeshInstances(this._meshInstances)},i.onLayerRemoved=function(e){this.layers.indexOf(e.id)<0||e.removeMeshInstances(this._meshInstances)},i.onEnable=function(){var e=this.system.app,t=e.scene;this._rootBone.onParentComponentEnable(),this._cloneSkinInstances(),t.on("set:layers",this.onLayersChanged,this),t.layers&&(t.layers.on("add",this.onLayerAdded,this),t.layers.on("remove",this.onLayerRemoved,this));var i,n="asset"===this._type;this._meshInstances&&this._meshInstances.length?this.addToLayers():n&&this.asset&&this._onRenderAssetAdded();for(var s=0;s<this._materialReferences.length;s++)this._materialReferences[s].asset&&this.system.app.assets.load(this._materialReferences[s].asset);this._batchGroupId>=0&&(null==(i=e.batcher)||i.insert($a.RENDER,this.batchGroupId,this.entity))},i.onDisable=function(){var e,t=this.system.app,i=t.scene;(i.off("set:layers",this.onLayersChanged,this),i.layers&&(i.layers.off("add",this.onLayerAdded,this),i.layers.off("remove",this.onLayerRemoved,this)),this._batchGroupId>=0)&&(null==(e=t.batcher)||e.remove($a.RENDER,this.batchGroupId,this.entity));this.removeFromLayers()},i.hide=function(){if(this._meshInstances)for(var e=0;e<this._meshInstances.length;e++)this._meshInstances[e].visible=!1},i.show=function(){if(this._meshInstances)for(var e=0;e<this._meshInstances.length;e++)this._meshInstances[e].visible=!0},i._onRenderAssetAdded=function(){this._assetReference.asset&&(this._assetReference.asset.resource?this._onRenderAssetLoad():this.enabled&&this.entity.enabled&&this.system.app.assets.load(this._assetReference.asset))},i._onRenderAssetLoad=function(){if(this.destroyMeshInstances(),this._assetReference.asset){var e=this._assetReference.asset.resource;e.off("set:meshes",this._onSetMeshes,this),e.on("set:meshes",this._onSetMeshes,this),e.meshes&&this._onSetMeshes(e.meshes)}},i._onSetMeshes=function(e){this._cloneMeshes(e)},i._clearSkinInstances=function(){for(var e=0;e<this._meshInstances.length;e++){var t=this._meshInstances[e];tg.removeCachedSkinInstance(t.skinInstance),t.skinInstance=null}},i._cloneSkinInstances=function(){if(this._meshInstances.length&&this._rootBone.entity instanceof go)for(var e=0;e<this._meshInstances.length;e++){var t=this._meshInstances[e],i=t.mesh;i.skin&&!t.skinInstance&&(t.skinInstance=tg.createCachedSkinInstance(i.skin,this._rootBone.entity,this.entity))}},i._cloneMeshes=function(e){if(e&&e.length){for(var t=[],i=0;i<e.length;i++){var n=e[i],s=this._materialReferences[i]&&this._materialReferences[i].asset&&this._materialReferences[i].asset.resource,r=new Co(n,s||this.system.defaultMaterial,this.entity);t.push(r),n.morph&&(r.morphInstance=new Nc(n.morph))}this.meshInstances=t,this._cloneSkinInstances()}},i._onRenderAssetUnload=function(){"asset"===this._type&&this.destroyMeshInstances()},i._onRenderAssetRemove=function(){this._assetReference.asset&&this._assetReference.asset.resource&&this._assetReference.asset.resource.off("set:meshes",this._onSetMeshes,this),this._onRenderAssetUnload()},i._onMaterialAdded=function(e,t,i){i.resource?this._onMaterialLoad(e,t,i):this.enabled&&this.entity.enabled&&this.system.app.assets.load(i)},i._updateMainMaterial=function(e,t){0===e&&(this.material=t)},i._onMaterialLoad=function(e,t,i){this._meshInstances[e]&&(this._meshInstances[e].material=i.resource),this._updateMainMaterial(e,i.resource)},i._onMaterialRemove=function(e,t,i){this._meshInstances[e]&&(this._meshInstances[e].material=this.system.defaultMaterial),this._updateMainMaterial(e,this.system.defaultMaterial)},i._onMaterialUnload=function(e,t,i){this._meshInstances[e]&&(this._meshInstances[e].material=this.system.defaultMaterial),this._updateMainMaterial(e,this.system.defaultMaterial)},i.resolveDuplicatedEntityReferenceProperties=function(e,t){e.rootBone&&t[e.rootBone]&&(this.rootBone=t[e.rootBone]),this._clearSkinInstances()},Z(t,[{key:"renderStyle",get:function(){return this._renderStyle},set:function(e){this._renderStyle!==e&&(this._renderStyle=e,Co._prepareRenderStyleForArray(this._meshInstances,e))}},{key:"customAabb",get:function(){return this._customAabb},set:function(e){this._customAabb=e;var t=this._meshInstances;if(t)for(var i=0;i<t.length;i++)t[i].setCustomAabb(this._customAabb)}},{key:"type",get:function(){return this._type},set:function(e){if(this._type!==e&&(this._area=null,this._type=e,this.destroyMeshInstances(),"asset"!==e)){var t=this._material;t&&t!==this.system.defaultMaterial||(t=this._materialReferences[0]&&this._materialReferences[0].asset&&this._materialReferences[0].asset.resource);var i=pa(this.system.app.graphicsDevice,e);this._area=i.area,this.meshInstances=[new Co(i.mesh,t||this.system.defaultMaterial,this.entity)]}}},{key:"meshInstances",get:function(){return this._meshInstances},set:function(e){if(this.destroyMeshInstances(),this._meshInstances=e,this._meshInstances){for(var t=this._meshInstances,i=0;i<t.length;i++)t[i].node||(t[i].node=this.entity),t[i].castShadow=this._castShadows,t[i].receiveShadow=this._receiveShadows,t[i].isStatic=this._isStatic,t[i].renderStyle=this._renderStyle,t[i].setLightmapped(this._lightmapped),t[i].setCustomAabb(this._customAabb);this.enabled&&this.entity.enabled&&this.addToLayers()}}},{key:"lightmapped",get:function(){return this._lightmapped},set:function(e){if(e!==this._lightmapped){this._lightmapped=e;var t=this._meshInstances;if(t)for(var i=0;i<t.length;i++)t[i].setLightmapped(e)}}},{key:"castShadows",get:function(){return this._castShadows},set:function(e){if(this._castShadows!==e){var t=this._meshInstances;if(t){var i=this.layers,n=this.system.app.scene;if(this._castShadows&&!e)for(var s=0;s<i.length;s++){var r=n.layers.getLayerById(this.layers[s]);r&&r.removeShadowCasters(t)}for(var a=0;a<t.length;a++)t[a].castShadow=e;if(!this._castShadows&&e)for(var o=0;o<i.length;o++){var h=n.layers.getLayerById(i[o]);h&&h.addShadowCasters(t)}}this._castShadows=e}}},{key:"receiveShadows",get:function(){return this._receiveShadows},set:function(e){if(this._receiveShadows!==e){this._receiveShadows=e;var t=this._meshInstances;if(t)for(var i=0;i<t.length;i++)t[i].receiveShadow=e}}},{key:"castShadowsLightmap",get:function(){return this._castShadowsLightmap},set:function(e){this._castShadowsLightmap=e}},{key:"lightmapSizeMultiplier",get:function(){return this._lightmapSizeMultiplier},set:function(e){this._lightmapSizeMultiplier=e}},{key:"isStatic",get:function(){return this._isStatic},set:function(e){if(this._isStatic!==e){this._isStatic=e;var t=this._meshInstances;if(t)for(var i=0;i<t.length;i++)t[i].isStatic=e}}},{key:"layers",get:function(){return this._layers},set:function(e){var t,i=this.system.app.scene.layers;if(this._meshInstances)for(var n=0;n<this._layers.length;n++)(t=i.getLayerById(this._layers[n]))&&t.removeMeshInstances(this._meshInstances);this._layers.length=0;for(var s=0;s<e.length;s++)this._layers[s]=e[s];if(this.enabled&&this.entity.enabled&&this._meshInstances)for(var r=0;r<this._layers.length;r++)(t=i.getLayerById(this._layers[r]))&&t.addMeshInstances(this._meshInstances)}},{key:"batchGroupId",get:function(){return this._batchGroupId},set:function(e){if(this._batchGroupId!==e){var t,i;if(this.entity.enabled&&this._batchGroupId>=0)null==(t=this.system.app.batcher)||t.remove($a.RENDER,this.batchGroupId,this.entity);if(this.entity.enabled&&e>=0)null==(i=this.system.app.batcher)||i.insert($a.RENDER,e,this.entity);e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addToLayers(),this._batchGroupId=e}}},{key:"material",get:function(){return this._material},set:function(e){if(this._material!==e&&(this._material=e,this._meshInstances&&"asset"!==this._type))for(var t=0;t<this._meshInstances.length;t++)this._meshInstances[t].material=e}},{key:"materialAssets",get:function(){return this._materialReferences.map((function(e){return e.id}))},set:function(e){if(void 0===e&&(e=[]),this._materialReferences.length>e.length){for(var t=e.length;t<this._materialReferences.length;t++)this._materialReferences[t].id=null;this._materialReferences.length=e.length}for(var i=0;i<e.length;i++)if(this._materialReferences[i]||this._materialReferences.push(new ig(i,this,this.system.app.assets,{add:this._onMaterialAdded,load:this._onMaterialLoad,remove:this._onMaterialRemove,unload:this._onMaterialUnload},this)),e[i]){var n=e[i]instanceof kd?e[i].id:e[i];this._materialReferences[i].id!==n&&(this._materialReferences[i].id=n),this._materialReferences[i].asset&&this._onMaterialAdded(i,this,this._materialReferences[i].asset)}else this._materialReferences[i].id=null,this._meshInstances[i]&&(this._meshInstances[i].material=this.system.defaultMaterial)}},{key:"asset",get:function(){return this._assetReference.id},set:function(e){var t=e instanceof kd?e.id:e;this._assetReference.id!==t&&(this._assetReference.asset&&this._assetReference.asset.resource&&this._onRenderAssetRemove(),this._assetReference.id=t,this._assetReference.asset&&this._onRenderAssetAdded())}}]),t}(gf),sg=function(){this.enabled=!0,this.rootBone=null},rg=[{name:"rootBone",type:"entity"},"enabled"],ag=["material","meshInstances","asset","materialAssets","castShadows","receiveShadows","castShadowsLightmap","lightmapped","lightmapSizeMultiplier","renderStyle","type","layers","isStatic","batchGroupId"],og=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="render",i.ComponentType=ng,i.DataType=sg,i.schema=rg,i.defaultMaterial=Xa(t.graphicsDevice),i.on("beforeremove",i.onRemove,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){null!==i.batchGroupId&&void 0!==i.batchGroupId||(i.batchGroupId=-1),i.layers&&i.layers.length&&(i.layers=i.layers.slice(0));for(var s=0;s<ag.length;s++)i.hasOwnProperty(ag[s])&&(t[ag[s]]=i[ag[s]]);i.aabbCenter&&i.aabbHalfExtents&&(t.customAabb=new Ie(new me(i.aabbCenter),new me(i.aabbHalfExtents))),e.prototype.initializeComponentData.call(this,t,i,rg)},i.cloneComponent=function(e,t){for(var i={},n=0;n<ag.length;n++)i[ag[n]]=e.render[ag[n]];i.enabled=e.render.enabled,delete i.meshInstances;var s=this.addComponent(t,i),r=e.render.meshInstances,a=r.map((function(e){return e.mesh}));s._onSetMeshes(a);for(var o=0;o<r.length;o++)s.meshInstances[o].material=r[o].material;return e.render.customAabb&&(s.customAabb=e.render.customAabb.clone()),s},i.onRemove=function(e,t){t.onRemove()},t}(vf);gf._buildAccessors(ng.prototype,rg);var hg,lg,cg,ug,dg,fg,pg=function(){function e(e,t){this._pool=[],this._count=0,this._constructor=e,this._resize(t)}var t=e.prototype;return t._resize=function(e){if(e>this._pool.length)for(var t=this._pool.length;t<e;t++)this._pool[t]=new this._constructor},t.allocate=function(){return this._count>=this._pool.length&&this._resize(2*this._pool.length),this._pool[this._count++]},t.freeAll=function(){this._count=0},e}(),mg=new Ae,_g=new Ae,gg=new me,vg=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._angularDamping=0,n._angularFactor=new me(1,1,1),n._angularVelocity=new me,n._body=null,n._friction=.5,n._group=2,n._linearDamping=0,n._linearFactor=new me(1,1,1),n._linearVelocity=new me,n._mask=cm,n._mass=1,n._restitution=0,n._rollingFriction=0,n._simulationEnabled=!1,n._type=am,n}Q(t,e),t.onLibraryLoaded=function(){"undefined"!=typeof Ammo&&(hg=new Ammo.btTransform,lg=new Ammo.btVector3,cg=new Ammo.btVector3,ug=new Ammo.btQuaternion)};var i=t.prototype;return i.createBody=function(){var e,t=this.entity;if(t.collision&&(e=t.collision.shape,t.trigger&&(t.trigger.destroy(),delete t.trigger)),e){this._body&&this.system.onRemove(t,this);var i=this._type===om?this._mass:0;this._getEntityTransform(hg);var n=this.system.createBody(i,e,hg);if(n.setRestitution(this._restitution),n.setFriction(this._friction),n.setRollingFriction(this._rollingFriction),n.setDamping(this._linearDamping,this._angularDamping),this._type===om){var s=this._linearFactor;lg.setValue(s.x,s.y,s.z),n.setLinearFactor(lg);var r=this._angularFactor;lg.setValue(r.x,r.y,r.z),n.setAngularFactor(lg)}else this._type===hm&&(n.setCollisionFlags(2|n.getCollisionFlags()),n.setActivationState(4));n.entity=t,this.body=n,this.enabled&&t.enabled&&this.enableSimulation()}},i.isActive=function(){return!!this._body&&this._body.isActive()},i.activate=function(){this._body&&this._body.activate()},i.enableSimulation=function(){var e=this.entity;if(e.collision&&e.collision.enabled&&!this._simulationEnabled){var t=this._body;if(t){switch(this.system.addBody(t,this._group,this._mask),this._type){case om:this.system._dynamic.push(this),t.forceActivationState(1),this.syncEntityToBody();break;case hm:this.system._kinematic.push(this),t.forceActivationState(4);break;case am:t.forceActivationState(1),this.syncEntityToBody()}"compound"===e.collision.type&&this.system._compounds.push(e.collision),t.activate(),this._simulationEnabled=!0}}},i.disableSimulation=function(){var e=this._body;if(e&&this._simulationEnabled){var t=this.system,i=t._compounds.indexOf(this.entity.collision);i>-1&&t._compounds.splice(i,1),(i=t._dynamic.indexOf(this))>-1&&t._dynamic.splice(i,1),(i=t._kinematic.indexOf(this))>-1&&t._kinematic.splice(i,1),t.removeBody(e),e.forceActivationState(5),this._simulationEnabled=!1}},i.applyForce=function(e,t,i,n,s,r){var a=this._body;a&&(a.activate(),e instanceof me?lg.setValue(e.x,e.y,e.z):lg.setValue(e,t,i),t instanceof me?cg.setValue(t.x,t.y,t.z):void 0!==n?cg.setValue(n,s,r):cg.setValue(0,0,0),a.applyForce(lg,cg))},i.applyTorque=function(e,t,i){var n=this._body;n&&(n.activate(),e instanceof me?lg.setValue(e.x,e.y,e.z):lg.setValue(e,t,i),n.applyTorque(lg))},i.applyImpulse=function(e,t,i,n,s,r){var a=this._body;a&&(a.activate(),e instanceof me?lg.setValue(e.x,e.y,e.z):lg.setValue(e,t,i),t instanceof me?cg.setValue(t.x,t.y,t.z):void 0!==n?cg.setValue(n,s,r):cg.setValue(0,0,0),a.applyImpulse(lg,cg))},i.applyTorqueImpulse=function(e,t,i){var n=this._body;n&&(n.activate(),e instanceof me?lg.setValue(e.x,e.y,e.z):lg.setValue(e,t,i),n.applyTorqueImpulse(lg))},i.isStatic=function(){return this._type===am},i.isStaticOrKinematic=function(){return this._type===am||this._type===hm},i.isKinematic=function(){return this._type===hm},i._getEntityTransform=function(e){var t=this.entity,i=t.collision;if(i){var n=i.getShapePosition(),s=i.getShapeRotation();lg.setValue(n.x,n.y,n.z),ug.setValue(s.x,s.y,s.z,s.w)}else{var r=t.getPosition(),a=t.getRotation();lg.setValue(r.x,r.y,r.z),ug.setValue(a.x,a.y,a.z,a.w)}e.setOrigin(lg),e.setRotation(ug)},i.syncEntityToBody=function(){var e=this._body;if(e){if(this._getEntityTransform(hg),e.setWorldTransform(hg),this._type===hm){var t=e.getMotionState();t&&t.setWorldTransform(hg)}e.activate()}},i._updateDynamic=function(){var e=this._body;if(e.isActive()){var t=e.getMotionState();if(t){var i=this.entity;t.getWorldTransform(hg);var n=hg.getOrigin(),s=hg.getRotation(),r=i.collision;if(r&&r._hasOffset){var a=r.data.linearOffset,o=r.data.angularOffset,h=_g.copy(o).invert(),l=mg.set(s.x(),s.y(),s.z(),s.w()).mul(h);l.transformVector(a,gg),i.setPosition(n.x()-gg.x,n.y()-gg.y,n.z()-gg.z),i.setRotation(l)}else i.setPosition(n.x(),n.y(),n.z()),i.setRotation(s.x(),s.y(),s.z(),s.w())}}},i._updateKinematic=function(){var e=this._body.getMotionState();e&&(this._getEntityTransform(hg),e.setWorldTransform(hg))},i.teleport=function(e,t,i,n,s,r){e instanceof me?this.entity.setPosition(e):this.entity.setPosition(e,t,i),t instanceof Ae?this.entity.setRotation(t):t instanceof me?this.entity.setEulerAngles(t):void 0!==n&&this.entity.setEulerAngles(n,s,r),this.syncEntityToBody()},i.onEnable=function(){this._body||this.createBody(),this.enableSimulation()},i.onDisable=function(){this.disableSimulation()},Z(t,[{key:"angularDamping",get:function(){return this._angularDamping},set:function(e){this._angularDamping!==e&&(this._angularDamping=e,this._body&&this._body.setDamping(this._linearDamping,e))}},{key:"angularFactor",get:function(){return this._angularFactor},set:function(e){this._angularFactor.equals(e)||(this._angularFactor.copy(e),this._body&&this._type===om&&(lg.setValue(e.x,e.y,e.z),this._body.setAngularFactor(lg)))}},{key:"angularVelocity",get:function(){if(this._body&&this._type===om){var e=this._body.getAngularVelocity();this._angularVelocity.set(e.x(),e.y(),e.z())}return this._angularVelocity},set:function(e){this._body&&this._type===om&&(this._body.activate(),lg.setValue(e.x,e.y,e.z),this._body.setAngularVelocity(lg),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===om&&(lg.setValue(e.x,e.y,e.z),this._body.setLinearFactor(lg)))}},{key:"linearVelocity",get:function(){if(this._body&&this._type===om){var e=this._body.getLinearVelocity();this._linearVelocity.set(e.x(),e.y(),e.z())}return this._linearVelocity},set:function(e){this._body&&this._type===om&&(this._body.activate(),lg.setValue(e.x,e.y,e.z),this._body.setLinearVelocity(lg),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===om)){var t=this.enabled&&this.entity.enabled;t&&this.disableSimulation(),this._body.getCollisionShape().calculateLocalInertia(e,lg),this._body.setMassProps(e,lg),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 om:this._group=1,this._mask=lm;break;case hm:this._group=4,this._mask=lm;break;default:this._group=2,this._mask=cm}this.createBody()}}}]),t}(gf),yg=function(){this.enabled=!0},xg=function(e,t,i,n){this.entity=e,this.point=t,this.normal=i,this.hitFraction=n},Sg=function(e,t,i){0===arguments.length?(this.a=null,this.b=null,this.impulse=0,this.localPointA=new me,this.localPointB=new me,this.pointA=new me,this.pointB=new me,this.normal=new me):(this.a=e,this.b=t,this.impulse=i.impulse,this.localPointA=i.localPoint,this.localPointB=i.localPointOther,this.pointA=i.point,this.pointB=i.pointOther,this.normal=i.normal)},bg=function(e,t,i,n,s,r){void 0===e&&(e=new me),void 0===t&&(t=new me),void 0===i&&(i=new me),void 0===n&&(n=new me),void 0===s&&(s=new me),void 0===r&&(r=0),this.localPoint=e,this.localPointOther=t,this.point=i,this.pointOther=n,this.normal=s,this.impulse=r},wg=function(e,t){this.other=e,this.contacts=t},Tg=["enabled"],Ag=function(e){function t(t){var i;return(i=e.call(this,t)||this).maxSubSteps=10,i.fixedTimeStep=1/60,i.gravity=new me(0,-9.81,0),i._gravityFloat32=new Float32Array(3),i._dynamic=[],i._kinematic=[],i._triggers=[],i._compounds=[],i.id="rigidbody",i._stats=t.stats.frame,i.ComponentType=vg,i.DataType=yg,i.contactPointPool=null,i.contactResultPool=null,i.singleContactResultPool=null,i.schema=Tg,i.collisions={},i.frameCollisions={},i.on("beforeremove",i.onBeforeRemove,ee(i)),i.on("remove",i.onRemove,ee(i)),i}Q(t,e);var i=t.prototype;return i.onLibraryLoaded=function(){if("undefined"!=typeof Ammo){if(this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.overlappingPairCache=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.dynamicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.overlappingPairCache,this.solver,this.collisionConfiguration),this.dynamicsWorld.setInternalTickCallback){var e=Ammo.addFunction(this._checkForCollisions.bind(this),"vif");this.dynamicsWorld.setInternalTickCallback(e)}dg=new Ammo.btVector3,fg=new Ammo.btVector3,vg.onLibraryLoaded(),this.contactPointPool=new pg(bg,1),this.contactResultPool=new pg(wg,1),this.singleContactResultPool=new pg(Sg,1),this.app.systems.on("update",this.onUpdate,this)}else this.app.systems.off("update",this.onUpdate,this)},i.initializeComponentData=function(t,i,n){for(var s=0,r=["mass","linearDamping","angularDamping","linearFactor","angularFactor","friction","rollingFriction","restitution","type","group","mask"];s<r.length;s++){var a=r[s];if(i.hasOwnProperty(a)){var o=i[a];Array.isArray(o)?t[a]=new me(o[0],o[1],o[2]):t[a]=o}}e.prototype.initializeComponentData.call(this,t,i,["enabled"])},i.cloneComponent=function(e,t){var i=e.rigidbody,n={enabled:i.enabled,mass:i.mass,linearDamping:i.linearDamping,angularDamping:i.angularDamping,linearFactor:[i.linearFactor.x,i.linearFactor.y,i.linearFactor.z],angularFactor:[i.angularFactor.x,i.angularFactor.y,i.angularFactor.z],friction:i.friction,rollingFriction:i.rollingFriction,restitution:i.restitution,type:i.type,group:i.group,mask:i.mask};return this.addComponent(t,n)},i.onBeforeRemove=function(e,t){t.enabled&&(t.enabled=!1)},i.onRemove=function(e,t){var i=t.body;i&&(this.removeBody(i),this.destroyBody(i),t.body=null)},i.addBody=function(e,t,i){void 0!==t&&void 0!==i?this.dynamicsWorld.addRigidBody(e,t,i):this.dynamicsWorld.addRigidBody(e)},i.removeBody=function(e){this.dynamicsWorld.removeRigidBody(e)},i.createBody=function(e,t,i){var n=new Ammo.btVector3(0,0,0);0!==e&&t.calculateLocalInertia(e,n);var s=new Ammo.btDefaultMotionState(i),r=new Ammo.btRigidBodyConstructionInfo(e,s,t,n),a=new Ammo.btRigidBody(r);return Ammo.destroy(r),Ammo.destroy(n),a},i.destroyBody=function(e){var t=e.getMotionState();t&&Ammo.destroy(t),Ammo.destroy(e)},i.raycastFirst=function(e,t,i){if(void 0===i&&(i={}),i.filterTags||i.filterCallback)return i.sort=!0,this.raycastAll(e,t,i)[0]||null;var n=null;dg.setValue(e.x,e.y,e.z),fg.setValue(t.x,t.y,t.z);var s=new Ammo.ClosestRayResultCallback(dg,fg);if("number"==typeof i.filterCollisionGroup&&s.set_m_collisionFilterGroup(i.filterCollisionGroup),"number"==typeof i.filterCollisionMask&&s.set_m_collisionFilterMask(i.filterCollisionMask),this.dynamicsWorld.rayTest(dg,fg,s),s.hasHit()){var r=s.get_m_collisionObject(),a=Ammo.castObject(r,Ammo.btRigidBody);if(a){var o=s.get_m_hitPointWorld(),h=s.get_m_hitNormalWorld();n=new xg(a.entity,new me(o.x(),o.y(),o.z()),new me(h.x(),h.y(),h.z()),s.get_m_closestHitFraction())}}return Ammo.destroy(s),n},i.raycastAll=function(e,t,i){void 0===i&&(i={});var n=[];dg.setValue(e.x,e.y,e.z),fg.setValue(t.x,t.y,t.z);var s=new Ammo.AllHitsRayResultCallback(dg,fg);if("number"==typeof i.filterCollisionGroup&&s.set_m_collisionFilterGroup(i.filterCollisionGroup),"number"==typeof i.filterCollisionMask&&s.set_m_collisionFilterMask(i.filterCollisionMask),this.dynamicsWorld.rayTest(dg,fg,s),s.hasHit()){for(var r=s.get_m_collisionObjects(),a=s.get_m_hitPointWorld(),o=s.get_m_hitNormalWorld(),h=s.get_m_hitFractions(),l=r.size(),c=0;c<l;c++){var u=Ammo.castObject(r.at(c),Ammo.btRigidBody);if(u&&u.entity){var d;if(i.filterTags&&!(d=u.entity.tags).has.apply(d,i.filterTags)||i.filterCallback&&!i.filterCallback(u.entity))continue;var f=a.at(c),p=o.at(c),m=new xg(u.entity,new me(f.x(),f.y(),f.z()),new me(p.x(),p.y(),p.z()),h.at(c));n.push(m)}}i.sort&&n.sort((function(e,t){return e.hitFraction-t.hitFraction}))}return Ammo.destroy(s),n},i._storeCollision=function(e,t){var i=!1,n=e.getGuid();return this.collisions[n]=this.collisions[n]||{others:[],entity:e},this.collisions[n].others.indexOf(t)<0&&(this.collisions[n].others.push(t),i=!0),this.frameCollisions[n]=this.frameCollisions[n]||{others:[],entity:e},this.frameCollisions[n].others.push(t),i},i._createContactPointFromAmmo=function(e){var t=e.get_m_localPointA(),i=e.get_m_localPointB(),n=e.getPositionWorldOnA(),s=e.getPositionWorldOnB(),r=e.get_m_normalWorldOnB(),a=this.contactPointPool.allocate();return a.localPoint.set(t.x(),t.y(),t.z()),a.localPointOther.set(i.x(),i.y(),i.z()),a.point.set(n.x(),n.y(),n.z()),a.pointOther.set(s.x(),s.y(),s.z()),a.normal.set(r.x(),r.y(),r.z()),a.impulse=e.getAppliedImpulse(),a},i._createReverseContactPointFromAmmo=function(e){var t=e.get_m_localPointA(),i=e.get_m_localPointB(),n=e.getPositionWorldOnA(),s=e.getPositionWorldOnB(),r=e.get_m_normalWorldOnB(),a=this.contactPointPool.allocate();return a.localPointOther.set(t.x(),t.y(),t.z()),a.localPoint.set(i.x(),i.y(),i.z()),a.pointOther.set(n.x(),n.y(),n.z()),a.point.set(s.x(),s.y(),s.z()),a.normal.set(r.x(),r.y(),r.z()),a.impulse=e.getAppliedImpulse(),a},i._createSingleContactResult=function(e,t,i){var n=this.singleContactResultPool.allocate();return n.a=e,n.b=t,n.localPointA=i.localPoint,n.localPointB=i.localPointOther,n.pointA=i.point,n.pointB=i.pointOther,n.normal=i.normal,n.impulse=i.impulse,n},i._createContactResult=function(e,t){var i=this.contactResultPool.allocate();return i.other=e,i.contacts=t,i},i._cleanOldCollisions=function(){for(var e in this.collisions)if(this.collisions.hasOwnProperty(e)){for(var t=this.frameCollisions[e],i=this.collisions[e],n=i.entity,s=n.collision,r=n.rigidbody,a=i.others,o=a.length;o--;){var h=a[o];(!t||t.others.indexOf(h)<0)&&(a.splice(o,1),n.trigger?(s&&s.fire("triggerleave",h),h.rigidbody&&h.rigidbody.fire("triggerleave",n)):h.trigger||(r&&r.fire("collisionend",h),s&&s.fire("collisionend",h)))}0===a.length&&delete this.collisions[e]}},i._hasContactEvent=function(e){var t=e.collision;if(t&&(t.hasEvent("collisionstart")||t.hasEvent("collisionend")||t.hasEvent("contact")))return!0;var i=e.rigidbody;return i&&(i.hasEvent("collisionstart")||i.hasEvent("collisionend")||i.hasEvent("contact"))},i._checkForCollisions=function(e,t){var i=Ammo.wrapPointer(e,Ammo.btDynamicsWorld).getDispatcher(),n=i.getNumManifolds();this.frameCollisions={};for(var s=0;s<n;s++){var r=i.getManifoldByIndexInternal(s),a=r.getBody0(),o=r.getBody1(),h=Ammo.castObject(a,Ammo.btRigidBody),l=Ammo.castObject(o,Ammo.btRigidBody),c=h.entity,u=l.entity;if(c&&u){var d=h.getCollisionFlags(),f=l.getCollisionFlags(),p=r.getNumContacts(),m=[],_=[],g=void 0;if(p>0)if(4&d||4&f){var v=c.collision&&(c.collision.hasEvent("triggerenter")||c.collision.hasEvent("triggerleave")),y=u.collision&&(u.collision.hasEvent("triggerenter")||u.collision.hasEvent("triggerleave")),x=c.rigidbody&&(c.rigidbody.hasEvent("triggerenter")||c.rigidbody.hasEvent("triggerleave")),S=u.rigidbody&&(u.rigidbody.hasEvent("triggerenter")||u.rigidbody.hasEvent("triggerleave"));v&&(!(g=this._storeCollision(c,u))||4&f||c.collision.fire("triggerenter",u)),y&&(!(g=this._storeCollision(u,c))||4&d||u.collision.fire("triggerenter",c)),x&&(g||(g=this._storeCollision(u,c)),g&&c.rigidbody.fire("triggerenter",u)),S&&(g||(g=this._storeCollision(c,u)),g&&u.rigidbody.fire("triggerenter",c))}else{var b=this._hasContactEvent(c),w=this._hasContactEvent(u),T=this.hasEvent("contact");if(T||b||w){for(var A=0;A<p;A++){var C=r.getContactPoint(A),E=this._createContactPointFromAmmo(C);if(b||w){m.push(E);var M=this._createReverseContactPointFromAmmo(C);_.push(M)}if(T){var P=this._createSingleContactResult(c,u,E);this.fire("contact",P)}}if(b){var R=this._createContactResult(u,m);g=this._storeCollision(c,u),c.collision&&(c.collision.fire("contact",R),g&&c.collision.fire("collisionstart",R)),c.rigidbody&&(c.rigidbody.fire("contact",R),g&&c.rigidbody.fire("collisionstart",R))}if(w){var I=this._createContactResult(c,_);g=this._storeCollision(u,c),u.collision&&(u.collision.fire("contact",I),g&&u.collision.fire("collisionstart",I)),u.rigidbody&&(u.rigidbody.fire("contact",I),g&&u.rigidbody.fire("collisionstart",I))}}}}}this._cleanOldCollisions(),this.contactPointPool.freeAll(),this.contactResultPool.freeAll(),this.singleContactResultPool.freeAll()},i.onUpdate=function(e){var t,i;this._gravityFloat32[0]=this.gravity.x,this._gravityFloat32[1]=this.gravity.y,this._gravityFloat32[2]=this.gravity.z;var n=this.dynamicsWorld.getGravity();n.x()===this._gravityFloat32[0]&&n.y()===this._gravityFloat32[1]&&n.z()===this._gravityFloat32[2]||(n.setValue(this.gravity.x,this.gravity.y,this.gravity.z),this.dynamicsWorld.setGravity(n));var s=this._triggers;for(t=0,i=s.length;t<i;t++)s[t].updateTransform();var r=this._compounds;for(t=0,i=r.length;t<i;t++)r[t]._updateCompound();var a=this._kinematic;for(t=0,i=a.length;t<i;t++)a[t]._updateKinematic();this.dynamicsWorld.stepSimulation(e,this.maxSubSteps,this.fixedTimeStep);var o=this._dynamic;for(t=0,i=o.length;t<i;t++)o[t]._updateDynamic();this.dynamicsWorld.setInternalTickCallback||this._checkForCollisions(Ammo.getPointer(this.dynamicsWorld),e)},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this),"undefined"!=typeof Ammo&&(Ammo.destroy(this.dynamicsWorld),Ammo.destroy(this.solver),Ammo.destroy(this.overlappingPairCache),Ammo.destroy(this.dispatcher),Ammo.destroy(this.collisionConfiguration),this.dynamicsWorld=null,this.solver=null,this.overlappingPairCache=null,this.dispatcher=null,this.collisionConfiguration=null)},t}(vf);gf._buildAccessors(vg.prototype,Tg);var Cg="none",Eg="blend",Mg=new Te,Pg=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._resolution=new ge(640,320),n._referenceResolution=new ge(640,320),n._scaleMode=Cg,n.scale=1,n._scaleBlend=.5,n._priority=0,n._screenSpace=!1,n.cull=n._screenSpace,n._screenMatrix=new Te,n._elements=new Set,t.app.graphicsDevice.on("resizecanvas",n._onResize,ee(n)),n}Q(t,e);var i=t.prototype;return i.syncDrawOrder=function(){this.system.queueDrawOrderSync(this.entity.getGuid(),this._processDrawOrderSync,this)},i._recurseDrawOrderSync=function(e,t){if(!(e instanceof Zd))return t;if(e.element){var i,n=e.element.drawOrder;if(e.element.drawOrder=t++,e.element._batchGroupId>=0&&n!==e.element.drawOrder)null==(i=this.system.app.batcher)||i.markGroupDirty(e.element._batchGroupId)}e.particlesystem&&(e.particlesystem.drawOrder=t++);for(var s=e.children,r=0;r<s.length;r++)t=this._recurseDrawOrderSync(s[r],t);return t},i._processDrawOrderSync=function(){this._recurseDrawOrderSync(this.entity,1),this.fire("syncdraworder")},i._calcProjectionMatrix=function(){var e=this._resolution.x/this.scale,t=this._resolution.y/this.scale,i=e,n=-t;this._screenMatrix.setOrtho(0,i,n,0,1,-1),this._screenSpace||(Mg.setScale(.5*e,.5*t,1),this._screenMatrix.mul2(Mg,this._screenMatrix))},i._updateScale=function(){this.scale=this._calcScale(this._resolution,this.referenceResolution)},i._calcScale=function(e,t){var i=Math.log2(e.x/t.x),n=Math.log2(e.y/t.y);return Math.pow(2,i*(1-this._scaleBlend)+n*this._scaleBlend)},i._onResize=function(e,t){this._screenSpace&&(this._resolution.set(e,t),this.resolution=this._resolution)},i._bindElement=function(e){this._elements.add(e)},i._unbindElement=function(e){this._elements.delete(e)},i.onRemove=function(){this.system.app.graphicsDevice.off("resizecanvas",this._onResize,this),this.fire("remove"),this._elements.forEach((function(e){return e._onScreenRemove()})),this._elements.clear(),this.off()},Z(t,[{key:"resolution",get:function(){return this._resolution},set:function(e){var t=this;this._screenSpace?this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height):this._resolution.set(e.x,e.y),this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:resolution",this._resolution),this._elements.forEach((function(e){return e._onScreenResize(t._resolution)}))}},{key:"referenceResolution",get:function(){return this._scaleMode===Cg?this._resolution:this._referenceResolution},set:function(e){var t=this;this._referenceResolution.set(e.x,e.y),this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:referenceresolution",this._resolution),this._elements.forEach((function(e){return e._onScreenResize(t._resolution)}))}},{key:"screenSpace",get:function(){return this._screenSpace},set:function(e){this._screenSpace=e,this._screenSpace&&this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height),this.resolution=this._resolution,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:screenspace",this._screenSpace),this._elements.forEach((function(e){return e._onScreenSpaceChange()}))}},{key:"scaleMode",get:function(){return this._scaleMode},set:function(e){e!==Cg&&e!==Eg&&(e=Cg),this._screenSpace||e===Cg||(e=Cg),this._scaleMode=e,this.resolution=this._resolution,this.fire("set:scalemode",this._scaleMode)}},{key:"scaleBlend",get:function(){return this._scaleBlend},set:function(e){var t=this;this._scaleBlend=e,this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:scaleblend",this._scaleBlend),this._elements.forEach((function(e){return e._onScreenResize(t._resolution)}))}},{key:"priority",get:function(){return this._priority},set:function(e){e>255&&(e=255),this._priority!==e&&(this._priority=e,this.syncDrawOrder())}}]),t}(gf),Rg=function(){this.enabled=!0},Ig=["enabled"],Lg=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="screen",i.ComponentType=Pg,i.DataType=Rg,i.schema=Ig,i.windowResolution=new ge,i._drawOrderSyncQueue=new H,i.app.graphicsDevice.on("resizecanvas",i._onResize,ee(i)),i.app.systems.on("update",i._onUpdate,ee(i)),i.on("beforeremove",i.onRemoveComponent,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){void 0!==i.priority&&(t.priority=i.priority),void 0!==i.screenSpace&&(t.screenSpace=i.screenSpace),t.cull=t.screenSpace,void 0!==i.scaleMode&&(t.scaleMode=i.scaleMode),void 0!==i.scaleBlend&&(t.scaleBlend=i.scaleBlend),void 0!==i.resolution&&(i.resolution instanceof ge?t._resolution.copy(i.resolution):t._resolution.set(i.resolution[0],i.resolution[1]),t.resolution=t._resolution),void 0!==i.referenceResolution&&(i.referenceResolution instanceof ge?t._referenceResolution.copy(i.referenceResolution):t._referenceResolution.set(i.referenceResolution[0],i.referenceResolution[1]),t.referenceResolution=t._referenceResolution),t.syncDrawOrder(),e.prototype.initializeComponentData.call(this,t,i,n)},i.destroy=function(){e.prototype.destroy.call(this),this.app.graphicsDevice.off("resizecanvas",this._onResize,this),this.app.systems.off("update",this._onUpdate,this)},i._onUpdate=function(e){var t=this.store;for(var i in t)t[i].entity.screen.update&&t[i].entity.screen.update(e)},i._onResize=function(e,t){this.windowResolution.x=e,this.windowResolution.y=t},i.cloneComponent=function(e,t){var i=e.screen;return this.addComponent(t,{enabled:i.enabled,screenSpace:i.screenSpace,scaleMode:i.scaleMode,resolution:i.resolution.clone(),referenceResolution:i.referenceResolution.clone()})},i.onRemoveComponent=function(e,t){t.onRemove()},i.processDrawOrderSyncQueue=function(){for(var e=this._drawOrderSyncQueue.list(),t=0;t<e.length;t++){var i=e[t];i.callback.call(i.scope)}this._drawOrderSyncQueue.clear()},i.queueDrawOrderSync=function(e,t,i){this._drawOrderSyncQueue.list().length||this.app.once("prerender",this.processDrawOrderSyncQueue,this),this._drawOrderSyncQueue.has(e)||this._drawOrderSyncQueue.push(e,{callback:t,scope:i})},t}(vf);gf._buildAccessors(Pg.prototype,Ig);var Dg=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this).on("set_scripts",n.onSetScripts,ee(n)),n}Q(t,e);var i=t.prototype;return i.send=function(e,t){var i,n=Array.prototype.slice.call(arguments,2),s=this.entity.script.instances;if(s&&s[e]&&(i=s[e].instance[t]))return i.apply(s[e].instance,n)},i.onEnable=function(){this.data.areScriptsLoaded&&!this.system.preloading&&(this.data.initialized?this.system._enableScriptComponent(this):this.system._initializeScriptComponent(this),this.data.postInitialized||this.system._postInitializeScriptComponent(this))},i.onDisable=function(){this.system._disableScriptComponent(this)},i.onSetScripts=function(e,t,i){if(!this.system._inTools||this.runInTools){if(this._updateScriptAttributes(t,i))return;this.enabled&&this.system._disableScriptComponent(this),this.system._destroyScriptComponent(this),this.data.areScriptsLoaded=!1;var n=i.map((function(e){return e.url}));if(this._loadFromCache(n))return;this._loadScripts(n)}},i._updateScriptAttributes=function(e,t){var i=!0;if(e.length!==t.length)i=!1;else for(var n=0,s=t.length;n<s;n++)if(e[n].url!==t[n].url){i=!1;break}if(i)for(var r in this.instances)this.instances.hasOwnProperty(r)&&this.system._updateAccessors(this.entity,this.instances[r]);return i},i._loadFromCache=function(e){for(var t=[],i=this.system.app._scriptPrefix||"",n=/^http(s)?:\/\//i,s=0,r=e.length;s<r;s++){var a=e[s];n.test(a)||(a=v.join(i,a));var o=this.system.app.loader.getFromCache(a,"script");if(!o)return!1;t.push(o)}for(var h=0,l=t.length;h<l;h++){var c=t[h];if(!0!==c&&(c&&this.entity.script&&!this.entity.script.instances[c._pcScriptName])){var u=new c(this.entity);this.system._preRegisterInstance(this.entity,e[h],c._pcScriptName,u)}}return this.data&&(this.data.areScriptsLoaded=!0),this.system.preloading||(this.system.onInitialize(this.entity),this.system.onPostInitialize(this.entity)),!0},i._loadScripts=function(e){var t=this,i=e.length,n=this.system.app._scriptPrefix||"";e.forEach((function(e){var s=null,r=null;e.toLowerCase().startsWith("http://")||e.toLowerCase().startsWith("https://")?(r=e,s=e):(r=e,s=v.join(n,e)),t.system.app.loader.load(s,"script",(function(e,n){if(i--,e)console.error(e);else if(n&&t.entity.script&&!t.entity.script.instances[n._pcScriptName]){var s=new n(t.entity);t.system._preRegisterInstance(t.entity,r,n._pcScriptName,s)}0===i&&(t.data.areScriptsLoaded=!0,t.system.preloading||(t.system.onInitialize(t.entity),t.system.onPostInitialize(t.entity)))}))}))},t}(gf),Og=function(){this.scripts=[],this.enabled=!0,this.instances={},this._instances={},this.runInTools=!1,this.attributes={},this.initialized=!1,this.postInitialized=!1,this.areScriptsLoaded=!1},kg=["enabled","scripts","instances","runInTools"],Fg="initialize",Bg="postInitialize",Ng="update",Ug="postUpdate",zg="fixedUpdate",Vg="toolsUpdate",Gg=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="script",i.ComponentType=Dg,i.DataType=Og,i.schema=kg,i.preloading=!1,i.instancesWithUpdate=[],i.instancesWithFixedUpdate=[],i.instancesWithPostUpdate=[],i.instancesWithToolsUpdate=[],i.on("beforeremove",i.onBeforeRemove,ee(i)),i.app.systems.on(Fg,i.onInitialize,ee(i)),i.app.systems.on(Bg,i.onPostInitialize,ee(i)),i.app.systems.on(Ng,i.onUpdate,ee(i)),i.app.systems.on(zg,i.onFixedUpdate,ee(i)),i.app.systems.on(Ug,i.onPostUpdate,ee(i)),i.app.systems.on(Vg,i.onToolsUpdate,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){n=["runInTools","enabled","scripts"],i.scripts&&i.scripts.length&&i.scripts.forEach((function(e){if(e.attributes&&Array.isArray(e.attributes)){for(var t={},i=0;i<e.attributes.length;i++)t[e.attributes[i].name]=e.attributes[i];e.attributes=t}})),e.prototype.initializeComponentData.call(this,t,i,n)},i.cloneComponent=function(e,t){for(var i=this.store[e.getGuid()],n={runInTools:i.data.runInTools,scripts:[],enabled:i.data.enabled},s=i.data.scripts,r=0,a=s.length;r<a;r++){var o=s[r].attributes;o&&delete s[r].attributes,n.scripts.push(f({},s[r])),o&&(n.scripts[r].attributes=this._cloneAttributes(o),s[r].attributes=o)}return this.addComponent(t,n)},i.onBeforeRemove=function(e,t){t.enabled&&this._disableScriptComponent(t),this._destroyScriptComponent(t)},i.onInitialize=function(e){if(this._registerInstances(e),e.enabled){e.script&&e.script.enabled&&this._initializeScriptComponent(e.script);for(var t=e._children,i=0,n=t.length;i<n;i++)t[i]instanceof Zd&&this.onInitialize(t[i])}},i.onPostInitialize=function(e){if(e.enabled){e.script&&e.script.enabled&&this._postInitializeScriptComponent(e.script);for(var t=e._children,i=0,n=t.length;i<n;i++)t[i]instanceof Zd&&this.onPostInitialize(t[i])}},i._callInstancesMethod=function(e,t){var i=e.data.instances;for(var n in i)if(i.hasOwnProperty(n)){var s=i[n].instance;s[t]&&s[t]()}},i._initializeScriptComponent=function(e){this._callInstancesMethod(e,Fg),e.data.initialized=!0,e.enabled&&e.entity.enabled&&this._enableScriptComponent(e)},i._enableScriptComponent=function(e){this._callInstancesMethod(e,"onEnable")},i._disableScriptComponent=function(e){this._callInstancesMethod(e,"onDisable")},i._destroyScriptComponent=function(e){var t=e.data.instances;for(var i in t)if(t.hasOwnProperty(i)){var n=t[i].instance;if(n.destroy&&n.destroy(),n.update){var s=this.instancesWithUpdate.indexOf(n);s>=0&&this.instancesWithUpdate.splice(s,1)}if(n.fixedUpdate){var r=this.instancesWithFixedUpdate.indexOf(n);r>=0&&this.instancesWithFixedUpdate.splice(r,1)}if(n.postUpdate){var a=this.instancesWithPostUpdate.indexOf(n);a>=0&&this.instancesWithPostUpdate.splice(a,1)}if(n.toolsUpdate){var o=this.instancesWithToolsUpdate.indexOf(n);o>=0&&this.instancesWithToolsUpdate.splice(o,1)}e.instances[i].instance===e[i]&&delete e[i],delete e.instances[i]}},i._postInitializeScriptComponent=function(e){this._callInstancesMethod(e,Bg),e.data.postInitialized=!0},i._updateInstances=function(e,t,i){for(var n=0,s=t.length;n<s;n++){var r=t[n];r&&r.entity&&r.entity.enabled&&r.entity.script.enabled&&r[e](i)}},i.onUpdate=function(e){this._updateInstances(Ng,this.instancesWithUpdate,e)},i.onFixedUpdate=function(e){this._updateInstances(zg,this.instancesWithFixedUpdate,e)},i.onPostUpdate=function(e){this._updateInstances(Ug,this.instancesWithPostUpdate,e)},i.onToolsUpdate=function(e){this._updateInstances(Vg,this.instancesWithToolsUpdate,e)},i.broadcast=function(e,t){var i=Array.prototype.slice.call(arguments,2),n=this.store;for(var s in n)if(n.hasOwnProperty(s)){var r=n[s].data;if(r.instances[e]){var a=r.instances[e].instance[t];a&&a.apply(r.instances[e].instance,i)}}},i._preRegisterInstance=function(e,t,i,n){if(e.script){if(e.script.data._instances=e.script.data._instances||{},e.script.data._instances[i])throw Error("Script name collision '"+i+"'. Scripts from '"+t+"' and '"+e.script.data._instances[i].url+"' {"+e.getGuid()+"}");e.script.data._instances[i]={url:t,name:i,instance:n}}},i._registerInstances=function(e){if(e.script&&e.script.data._instances){for(var t in e.script.instances=e.script.data._instances,e.script.instances){var i=e.script.instances[t],n=i.instance;if(m.attach(n),n.update&&this.instancesWithUpdate.push(n),n.fixedUpdate&&this.instancesWithFixedUpdate.push(n),n.postUpdate&&this.instancesWithPostUpdate.push(n),n.toolsUpdate&&this.instancesWithToolsUpdate.push(n),e.script.scripts&&this._createAccessors(e,i),e.script[t])throw Error("Script with name '"+t+"' is already attached to Script Component");e.script[t]=n}delete e.script.data._instances}for(var s=e._children,r=0,a=s.length;r<a;r++)s[r]instanceof Zd&&this._registerInstances(s[r])},i._cloneAttributes=function(e){var t={};for(var i in e)if(e.hasOwnProperty(i))if("entity"!==e[i].type)t[i]=f({},e[i]);else{var n=e[i].value;delete e[i].value,t[i]=f({},e[i]),t[i].value=n,e[i].value=n}return t},i._createAccessors=function(e,t){for(var i=e.script.scripts.length,n=t.url,s=0;s<i;s++){var r=e.script.scripts[s];if(r.url===n){var a=r.attributes;if(r.name&&a){for(var o in a)a.hasOwnProperty(o)&&this._createAccessor(a[o],t);e.script.data.attributes[r.name]=this._cloneAttributes(a)}break}}},i._createAccessor=function(e,t){var i=this;e={name:e.name,value:e.value,type:e.type},this._convertAttributeValue(e),Object.defineProperty(t.instance,e.name,{get:function(){return e.value},set:function(n){var s=e.value;e.value=n,i._convertAttributeValue(e),t.instance.fire("set",e.name,s,e.value)},configurable:!0})},i._updateAccessors=function(e,t){for(var i=e.script.scripts.length,n=t.url,s=0;s<i;s++){var r=e.script,a=r.scripts[s];if(a.url===n){var o=a.name,h=a.attributes;if(o){if(h)for(var l in h)h.hasOwnProperty(l)&&this._createAccessor(h[l],t);var c=r.data.attributes[o];if(c)for(var u in c){var d=c[u];u in h?h[u].value!==d.value&&t.instance.onAttributeChanged&&t.instance.onAttributeChanged(d.name,d.value,h[u].value):delete t.instance[d.name]}h?r.data.attributes[o]=this._cloneAttributes(h):delete r.data.attributes[o]}break}}},i._convertAttributeValue=function(e){if("rgb"===e.type||"rgba"===e.type)Array.isArray(e.value)&&(e.value=3===e.value.length?new ue(e.value[0],e.value[1],e.value[2]):new ue(e.value[0],e.value[1],e.value[2],e.value[3]));else if("vec2"===e.type)Array.isArray(e.value)&&(e.value=new ge(e.value[0],e.value[1]));else if("vec3"===e.type||"vector"===e.type)Array.isArray(e.value)&&(e.value=new me(e.value[0],e.value[1],e.value[2]));else if("vec4"===e.type)Array.isArray(e.value)&&(e.value=new ve(e.value[0],e.value[1],e.value[2],e.value[3]));else if("entity"===e.type)null!==e.value&&"string"==typeof e.value&&(e.value=this.app.root.findByGuid(e.value));else if("curve"===e.type||"colorcurve"===e.type){var t=e.value.keys[0]instanceof Array?pe:fe;e.value=new t(e.value.keys),e.value.type=e.value.type}},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off(Fg,this.onInitialize,this),this.app.systems.off(Bg,this.onPostInitialize,this),this.app.systems.off(Ng,this.onUpdate,this),this.app.systems.off(zg,this.onFixedUpdate,this),this.app.systems.off(Ug,this.onPostUpdate,this),this.app.systems.off(Vg,this.onToolsUpdate,this)},t}(vf);gf._buildAccessors(Dg.prototype,kg);var Hg=new ge,Wg=new me,Xg=new Fe,jg=new Ge,qg=new me,Yg=new me,Kg=new Ae,Zg={x:"y",y:"x"},$g=function(e){function t(t,i){var n;if(n=e.call(this)||this,!(t&&t instanceof o_))throw new Error("Element was null or not an ElementComponent");if(i&&"x"!==i&&"y"!==i)throw new Error("Unrecognized axis: "+i);return n._element=t,n._app=t.system.app,n._axis=i||null,n._enabled=!0,n._dragScale=new me,n._dragStartMousePosition=new me,n._dragStartHandlePosition=new me,n._deltaMousePosition=new me,n._deltaHandlePosition=new me,n._isDragging=!1,n._toggleLifecycleListeners("on"),n}Q(t,e);var i=t.prototype;return i._toggleLifecycleListeners=function(e){this._element[e]("mousedown",this._onMouseDownOrTouchStart,this),this._element[e]("touchstart",this._onMouseDownOrTouchStart,this),this._element[e]("selectstart",this._onMouseDownOrTouchStart,this)},i._toggleDragListeners=function(e){var t="on"===e;this._hasDragListeners&&t||(this._app.mouse&&(this._element[e]("mousemove",this._onMove,this),this._element[e]("mouseup",this._onMouseUpOrTouchEnd,this)),M.touch&&(this._element[e]("touchmove",this._onMove,this),this._element[e]("touchend",this._onMouseUpOrTouchEnd,this),this._element[e]("touchcancel",this._onMouseUpOrTouchEnd,this)),this._element[e]("selectmove",this._onMove,this),this._element[e]("selectend",this._onMouseUpOrTouchEnd,this),this._hasDragListeners=t)},i._onMouseDownOrTouchStart=function(e){if(this._element&&!this._isDragging&&this.enabled){this._dragCamera=e.camera,this._calculateDragScale();var t=this._screenToLocal(e);t&&(this._toggleDragListeners("on"),this._isDragging=!0,this._dragStartMousePosition.copy(t),this._dragStartHandlePosition.copy(this._element.entity.getLocalPosition()),this.fire("drag:start"))}},i._onMouseUpOrTouchEnd=function(){this._isDragging&&(this._isDragging=!1,this._toggleDragListeners("off"),this.fire("drag:end"))},i._screenToLocal=function(e){return e.inputSource?Xg.set(e.inputSource.getOrigin(),e.inputSource.getDirection()):(this._determineInputPosition(e),this._chooseRayOriginAndDirection()),qg.copy(this._element.entity.forward).mulScalar(-1),jg.setFromPointNormal(this._element.entity.getPosition(),qg),jg.intersectsRay(Xg,Yg)?(Kg.copy(this._element.entity.getRotation()).invert().transformVector(Yg,Yg),Yg.mul(this._dragScale),Yg):null},i._determineInputPosition=function(e){var t=this._app.graphicsDevice.maxPixelRatio;void 0!==e.x&&void 0!==e.y?(Hg.x=e.x*t,Hg.y=e.y*t):e.changedTouches?(Hg.x=e.changedTouches[0].x*t,Hg.y=e.changedTouches[0].y*t):console.warn("Could not determine position from input event")},i._chooseRayOriginAndDirection=function(){this._element.screen&&this._element.screen.screen.screenSpace?(Xg.origin.set(Hg.x,-Hg.y,0),Xg.direction.copy(me.FORWARD)):(Wg.copy(this._dragCamera.screenToWorld(Hg.x,Hg.y,1)),Xg.origin.copy(this._dragCamera.entity.getPosition()),Xg.direction.copy(Wg).sub(Xg.origin).normalize())},i._calculateDragScale=function(){var e=this._element.entity.parent,t=this._element.screen&&this._element.screen.screen,i=t&&t.screenSpace,n=i?t.scale:1,s=this._dragScale;for(s.set(n,n,n);e&&(s.mul(e.getLocalScale()),e=e.parent,!i||!e.screen););s.x=1/s.x,s.y=1/s.y,s.z=0},i._onMove=function(e){var t=this._element,i=this._deltaMousePosition,n=this._deltaHandlePosition,s=this._axis;if(t&&this._isDragging&&this.enabled&&t.enabled&&t.entity.enabled){var r=this._screenToLocal(e);if(r){if(i.sub2(r,this._dragStartMousePosition),n.add2(this._dragStartHandlePosition,i),s){var a=t.entity.getLocalPosition(),o=Zg[s];n[o]=a[o]}t.entity.setLocalPosition(n),this.fire("drag:move",n)}}},i.destroy=function(){this._toggleLifecycleListeners("off"),this._toggleDragListeners("off")},Z(t,[{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"isDragging",get:function(){return this._isDragging}}]),t}(p),Qg=new ge,Jg=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._viewportReference=new Op(ee(n),"viewportEntity",{"element#gain":n._onViewportElementGain,"element#resize":n._onSetContentOrViewportSize}),n._contentReference=new Op(ee(n),"contentEntity",{"element#gain":n._onContentElementGain,"element#lose":n._onContentElementLose,"element#resize":n._onSetContentOrViewportSize}),n._scrollbarUpdateFlags={},n._scrollbarReferences={},n._scrollbarReferences[0]=new Op(ee(n),"horizontalScrollbarEntity",{"scrollbar#set:value":n._onSetHorizontalScrollbarValue,"scrollbar#gain":n._onHorizontalScrollbarGain}),n._scrollbarReferences[1]=new Op(ee(n),"verticalScrollbarEntity",{"scrollbar#set:value":n._onSetVerticalScrollbarValue,"scrollbar#gain":n._onVerticalScrollbarGain}),n._prevContentSizes={},n._prevContentSizes[0]=null,n._prevContentSizes[1]=null,n._scroll=new ge,n._velocity=new me,n._dragStartPosition=new me,n._disabledContentInput=!1,n._disabledContentInputEntities=[],n._toggleLifecycleListeners("on",t),n._toggleElementListeners("on"),n}Q(t,e);var i=t.prototype;return i._toggleLifecycleListeners=function(e,t){this[e]("set_horizontal",this._onSetHorizontalScrollingEnabled,this),this[e]("set_vertical",this._onSetVerticalScrollingEnabled,this),t.app.systems.element[e]("add",this._onElementComponentAdd,this),t.app.systems.element[e]("beforeremove",this._onElementComponentRemove,this)},i._toggleElementListeners=function(e){if(this.entity.element){if("on"===e&&this._hasElementListeners)return;this.entity.element[e]("resize",this._onSetContentOrViewportSize,this),this.entity.element[e](qs,this._onMouseWheel,this),this._hasElementListeners="on"===e}},i._onElementComponentAdd=function(e){this.entity===e&&this._toggleElementListeners("on")},i._onElementComponentRemove=function(e){this.entity===e&&this._toggleElementListeners("off")},i._onViewportElementGain=function(){this._syncAll()},i._onContentElementGain=function(){this._destroyDragHelper(),this._contentDragHelper=new $g(this._contentReference.entity.element),this._contentDragHelper.on("drag:start",this._onContentDragStart,this),this._contentDragHelper.on("drag:end",this._onContentDragEnd,this),this._contentDragHelper.on("drag:move",this._onContentDragMove,this),this._prevContentSizes[0]=null,this._prevContentSizes[1]=null,this._syncAll()},i._onContentElementLose=function(){this._destroyDragHelper()},i._onContentDragStart=function(){this._contentReference.entity&&this.enabled&&this.entity.enabled&&this._dragStartPosition.copy(this._contentReference.entity.getLocalPosition())},i._onContentDragEnd=function(){this._prevContentDragPosition=null,this._enableContentInput()},i._onContentDragMove=function(e){if(this._contentReference.entity&&this.enabled&&this.entity.enabled&&(this._wasDragged=!0,this._setScrollFromContentPosition(e),this._setVelocityFromContentPositionDelta(e),!this._disabledContentInput)){var t=e.x-this._dragStartPosition.x,i=e.y-this._dragStartPosition.y;(Math.abs(t)>this.dragThreshold||Math.abs(i)>this.dragThreshold)&&this._disableContentInput()}},i._onSetContentOrViewportSize=function(){this._syncAll()},i._onSetHorizontalScrollbarValue=function(e){!this._scrollbarUpdateFlags[0]&&this.enabled&&this.entity.enabled&&this._onSetScroll(e,null)},i._onSetVerticalScrollbarValue=function(e){!this._scrollbarUpdateFlags[1]&&this.enabled&&this.entity.enabled&&this._onSetScroll(null,e)},i._onSetHorizontalScrollingEnabled=function(){this._syncScrollbarEnabledState(0)},i._onSetVerticalScrollingEnabled=function(){this._syncScrollbarEnabledState(1)},i._onHorizontalScrollbarGain=function(){this._syncScrollbarEnabledState(0),this._syncScrollbarPosition(0)},i._onVerticalScrollbarGain=function(){this._syncScrollbarEnabledState(1),this._syncScrollbarPosition(1)},i._onSetScroll=function(e,t,i){!1!==i&&this._velocity.set(0,0,0);var n=this._updateAxis(e,"x",0),s=this._updateAxis(t,"y",1);(n||s)&&this.fire("set:scroll",this._scroll)},i._updateAxis=function(e,t,i){var n=null!==e&&Math.abs(e-this._scroll[t])>1e-5;return(n||this._isDragging()||0===e)&&(this._scroll[t]=this._determineNewScrollValue(e,t,i),this._syncContentPosition(i),this._syncScrollbarPosition(i)),n},i._determineNewScrollValue=function(e,t,i){if(!this._getScrollingEnabled(i))return this._scroll[t];switch(this.scrollMode){case 0:return ce.clamp(e,0,this._getMaxScrollValue(i));case 1:return this._setVelocityFromOvershoot(e,t,i),e;case 2:return e;default:return console.warn("Unhandled scroll mode:"+this.scrollMode),e}},i._syncAll=function(){this._syncContentPosition(0),this._syncContentPosition(1),this._syncScrollbarPosition(0),this._syncScrollbarPosition(1),this._syncScrollbarEnabledState(0),this._syncScrollbarEnabledState(1)},i._syncContentPosition=function(e){var t=this._getAxis(e),i=this._getSign(e),n=this._contentReference.entity;if(n){var s=this._prevContentSizes[e],r=this._getContentSize(e);if(null!==s&&Math.abs(s-r)>1e-4){var a=this._getMaxOffset(e,s),o=this._getMaxOffset(e,r);this._scroll[t]=0===o?1:ce.clamp(this._scroll[t]*a/o,0,1)}var h=this._scroll[t]*this._getMaxOffset(e),l=n.getLocalPosition();l[t]=h*i,n.setLocalPosition(l),this._prevContentSizes[e]=r}},i._syncScrollbarPosition=function(e){var t=this._getAxis(e),i=this._scrollbarReferences[e].entity;i&&i.scrollbar&&(this._scrollbarUpdateFlags[e]=!0,i.scrollbar.value=this._scroll[t],i.scrollbar.handleSize=this._getScrollbarHandleSize(t,e),this._scrollbarUpdateFlags[e]=!1)},i._syncScrollbarEnabledState=function(e){var t=this._scrollbarReferences[e].entity;if(t){var i=this._getScrollingEnabled(e),n=this._getScrollbarVisibility(e);switch(n){case 0:return void(t.enabled=i);case 1:return void(t.enabled=i&&this._contentIsLargerThanViewport(e));default:console.warn("Unhandled scrollbar visibility:"+n),t.enabled=i}}},i._contentIsLargerThanViewport=function(e){return this._getContentSize(e)>this._getViewportSize(e)},i._contentPositionToScrollValue=function(e){var t=this._getMaxOffset(0),i=this._getMaxOffset(1);return Qg.x=0===t?0:e.x/t,Qg.y=0===i?0:e.y/-i,Qg},i._getMaxOffset=function(e,t){t=void 0===t?this._getContentSize(e):t;var i=this._getViewportSize(e);return t<i?-this._getViewportSize(e):i-t},i._getMaxScrollValue=function(e){return this._contentIsLargerThanViewport(e)?1:0},i._getScrollbarHandleSize=function(e,t){var i=this._getViewportSize(t),n=this._getContentSize(t);if(Math.abs(n)<.001)return 1;var s=Math.min(i/n,1),r=this._toOvershoot(this._scroll[e],t);return 0===r?s:s/(1+Math.abs(r))},i._getViewportSize=function(e){return this._getSize(e,this._viewportReference)},i._getContentSize=function(e){return this._getSize(e,this._contentReference)},i._getSize=function(e,t){return t.entity&&t.entity.element?t.entity.element[this._getCalculatedDimension(e)]:0},i._getScrollingEnabled=function(e){return 0===e?this.horizontal:1===e?this.vertical:void 0},i._getScrollbarVisibility=function(e){return 0===e?this.horizontalScrollbarVisibility:1===e?this.verticalScrollbarVisibility:void 0},i._getSign=function(e){return 0===e?1:-1},i._getAxis=function(e){return 0===e?"x":"y"},i._getCalculatedDimension=function(e){return 0===e?"calculatedWidth":"calculatedHeight"},i._destroyDragHelper=function(){this._contentDragHelper&&this._contentDragHelper.destroy()},i.onUpdate=function(){this._contentReference.entity&&(this._updateVelocity(),this._syncScrollbarEnabledState(0),this._syncScrollbarEnabledState(1))},i._updateVelocity=function(){if(!this._isDragging()){if(1===this.scrollMode&&(this._hasOvershoot("x",0)&&this._setVelocityFromOvershoot(this.scroll.x,"x",0),this._hasOvershoot("y",1)&&this._setVelocityFromOvershoot(this.scroll.y,"y",1)),Math.abs(this._velocity.x)>1e-4||Math.abs(this._velocity.y)>1e-4){var e=this._contentReference.entity.getLocalPosition();e.x+=this._velocity.x,e.y+=this._velocity.y,this._contentReference.entity.setLocalPosition(e),this._setScrollFromContentPosition(e)}this._velocity.x*=1-this.friction,this._velocity.y*=1-this.friction}},i._hasOvershoot=function(e,t){return Math.abs(this._toOvershoot(this.scroll[e],t))>.001},i._toOvershoot=function(e,t){var i=this._getMaxScrollValue(t);return e<0?e:e>i?e-i:0},i._setVelocityFromOvershoot=function(e,t,i){var n=this._toOvershoot(e,i)*this._getMaxOffset(i)*this._getSign(i);Math.abs(n)>0&&(this._velocity[t]=-n/(50*this.bounceAmount+1))},i._setVelocityFromContentPositionDelta=function(e){this._prevContentDragPosition?(this._velocity.sub2(e,this._prevContentDragPosition),this._prevContentDragPosition.copy(e)):(this._velocity.set(0,0,0),this._prevContentDragPosition=e.clone())},i._setScrollFromContentPosition=function(e){var t=this._contentPositionToScrollValue(e);this._isDragging()&&(t=this._applyScrollValueTension(t)),this._onSetScroll(t.x,t.y,!1)},i._applyScrollValueTension=function(e){var t=this._getMaxScrollValue(0),i=this._toOvershoot(e.x,0);return i>0?e.x=t+1*Math.log10(1+i):i<0&&(e.x=-1*Math.log10(1-i)),t=this._getMaxScrollValue(1),(i=this._toOvershoot(e.y,1))>0?e.y=t+1*Math.log10(1+i):i<0&&(e.y=-1*Math.log10(1-i)),e},i._isDragging=function(){return this._contentDragHelper&&this._contentDragHelper.isDragging},i._setScrollbarComponentsEnabled=function(e){this._scrollbarReferences[0].hasComponent("scrollbar")&&(this._scrollbarReferences[0].entity.scrollbar.enabled=e),this._scrollbarReferences[1].hasComponent("scrollbar")&&(this._scrollbarReferences[1].entity.scrollbar.enabled=e)},i._setContentDraggingEnabled=function(e){this._contentDragHelper&&(this._contentDragHelper.enabled=e)},i._onMouseWheel=function(e){if(this.useMouseWheel){var t=e.event,i=t.deltaX/this._contentReference.entity.element.calculatedWidth*this.mouseWheelSensitivity.x,n=t.deltaY/this._contentReference.entity.element.calculatedHeight*this.mouseWheelSensitivity.y,s=ce.clamp(this._scroll.x+i,0,this._getMaxScrollValue(0)),r=ce.clamp(this._scroll.y+n,0,this._getMaxScrollValue(1));this.scroll=new ge(s,r)}},i._enableContentInput=function(){for(;this._disabledContentInputEntities.length;){var e=this._disabledContentInputEntities.pop();e.element&&(e.element.useInput=!0)}this._disabledContentInput=!1},i._disableContentInput=function(){var e=this,t=function t(i){i.element&&i.element.useInput&&(e._disabledContentInputEntities.push(i),i.element.useInput=!1);for(var n=i.children,s=0,r=n.length;s<r;s++)t(n[s])},i=this._contentReference.entity;if(i)for(var n=i.children,s=0,r=n.length;s<r;s++)t(n[s]);this._disabledContentInput=!0},i.onEnable=function(){this._viewportReference.onParentComponentEnable(),this._contentReference.onParentComponentEnable(),this._scrollbarReferences[0].onParentComponentEnable(),this._scrollbarReferences[1].onParentComponentEnable(),this._setScrollbarComponentsEnabled(!0),this._setContentDraggingEnabled(!0),this._syncAll()},i.onDisable=function(){this._setScrollbarComponentsEnabled(!1),this._setContentDraggingEnabled(!1)},i.onRemove=function(){this._toggleLifecycleListeners("off",this.system),this._toggleElementListeners("off"),this._destroyDragHelper()},Z(t,[{key:"scroll",get:function(){return this._scroll},set:function(e){this._onSetScroll(e.x,e.y)}}]),t}(gf),ev=function(){this.enabled=!0},tv=[{name:"enabled",type:"boolean"},{name:"horizontal",type:"boolean"},{name:"vertical",type:"boolean"},{name:"scrollMode",type:"number"},{name:"bounceAmount",type:"number"},{name:"friction",type:"number"},{name:"dragThreshold",type:"number"},{name:"useMouseWheel",type:"boolean"},{name:"mouseWheelSensitivity",type:"vec2"},{name:"horizontalScrollbarVisibility",type:"number"},{name:"verticalScrollbarVisibility",type:"number"},{name:"viewportEntity",type:"entity"},{name:"contentEntity",type:"entity"},{name:"horizontalScrollbarEntity",type:"entity"},{name:"verticalScrollbarEntity",type:"entity"}],iv=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="scrollview",i.ComponentType=Jg,i.DataType=ev,i.schema=tv,i.on("beforeremove",i._onRemoveComponent,ee(i)),i.app.systems.on("update",i.onUpdate,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){void 0===i.dragThreshold&&(i.dragThreshold=10),void 0===i.useMouseWheel&&(i.useMouseWheel=!0),void 0===i.mouseWheelSensitivity&&(i.mouseWheelSensitivity=new ge(1,1)),e.prototype.initializeComponentData.call(this,t,i,tv)},i.onUpdate=function(e){var t=this.store;for(var i in t){var n=t[i].entity,s=n.scrollview;s.enabled&&n.enabled&&s.onUpdate()}},i._onRemoveComponent=function(e,t){t.onRemove()},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},t}(vf);gf._buildAccessors(Jg.prototype,tv);var nv=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._handleReference=new Op(ee(n),"handleEntity",{"element#gain":n._onHandleElementGain,"element#lose":n._onHandleElementLose,"element#set:anchor":n._onSetHandleAlignment,"element#set:margin":n._onSetHandleAlignment,"element#set:pivot":n._onSetHandleAlignment}),n._toggleLifecycleListeners("on"),n}Q(t,e);var i=t.prototype;return i._toggleLifecycleListeners=function(e){this[e]("set_value",this._onSetValue,this),this[e]("set_handleSize",this._onSetHandleSize,this),this[e]("set_orientation",this._onSetOrientation,this)},i._onHandleElementGain=function(){this._destroyDragHelper(),this._handleDragHelper=new $g(this._handleReference.entity.element,this._getAxis()),this._handleDragHelper.on("drag:move",this._onHandleDrag,this),this._updateHandlePositionAndSize()},i._onHandleElementLose=function(){this._destroyDragHelper()},i._onHandleDrag=function(e){this._handleReference.entity&&this.enabled&&this.entity.enabled&&(this.value=this._handlePositionToScrollValue(e[this._getAxis()]))},i._onSetValue=function(e,t,i){Math.abs(i-t)>1e-5&&(this.data.value=ce.clamp(i,0,1),this._updateHandlePositionAndSize(),this.fire("set:value",this.data.value))},i._onSetHandleSize=function(e,t,i){Math.abs(i-t)>1e-5&&(this.data.handleSize=ce.clamp(i,0,1),this._updateHandlePositionAndSize())},i._onSetHandleAlignment=function(){this._updateHandlePositionAndSize()},i._onSetOrientation=function(e,t,i){i!==t&&this._handleReference.hasComponent("element")&&(this._handleReference.entity.element[this._getOppositeDimension()]=0)},i._updateHandlePositionAndSize=function(){var e=this._handleReference.entity,t=e&&e.element;if(e){var i=e.getLocalPosition();i[this._getAxis()]=this._getHandlePosition(),this._handleReference.entity.setLocalPosition(i)}t&&(t[this._getDimension()]=this._getHandleLength())},i._handlePositionToScrollValue=function(e){return e*this._getSign()/this._getUsableTrackLength()},i._scrollValueToHandlePosition=function(e){return e*this._getSign()*this._getUsableTrackLength()},i._getUsableTrackLength=function(){return Math.max(this._getTrackLength()-this._getHandleLength(),.001)},i._getTrackLength=function(){return this.entity.element?0===this.orientation?this.entity.element.calculatedWidth:this.entity.element.calculatedHeight:0},i._getHandleLength=function(){return this._getTrackLength()*this.handleSize},i._getHandlePosition=function(){return this._scrollValueToHandlePosition(this.value)},i._getSign=function(){return 0===this.orientation?1:-1},i._getAxis=function(){return 0===this.orientation?"x":"y"},i._getDimension=function(){return 0===this.orientation?"width":"height"},i._getOppositeDimension=function(){return 0===this.orientation?"height":"width"},i._destroyDragHelper=function(){this._handleDragHelper&&this._handleDragHelper.destroy()},i._setHandleDraggingEnabled=function(e){this._handleDragHelper&&(this._handleDragHelper.enabled=e)},i.onEnable=function(){this._handleReference.onParentComponentEnable(),this._setHandleDraggingEnabled(!0)},i.onDisable=function(){this._setHandleDraggingEnabled(!1)},i.onRemove=function(){this._destroyDragHelper(),this._toggleLifecycleListeners("off")},t}(gf),sv=function(){this.enabled=!0},rv=[{name:"enabled",type:"boolean"},{name:"orientation",type:"number"},{name:"value",type:"number"},{name:"handleSize",type:"number"},{name:"handleEntity",type:"entity"}],av=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="scrollbar",i.ComponentType=nv,i.DataType=sv,i.schema=rv,i.on("beforeremove",i._onRemoveComponent,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){e.prototype.initializeComponentData.call(this,t,i,rv)},i._onRemoveComponent=function(e,t){t.onRemove()},t}(vf);gf._buildAccessors(nv.prototype,rv);var ov={volume:0,pitch:0,loop:!1,startTime:0,duration:0,position:new me,maxDistance:0,refDistance:0,rollOffFactor:0,distanceModel:0,onPlay:null,onPause:null,onResume:null,onStop:null,onEnd:null},hv=function(e){function t(t,i,n){var s;return void 0===i&&(i="Untitled"),void 0===n&&(n={}),(s=e.call(this)||this).name=void 0,s.instances=[],s._component=t,s._assets=t.system.app.assets,s._manager=t.system.manager,s.name=i,s._volume=void 0!==n.volume?ce.clamp(Number(n.volume)||0,0,1):1,s._pitch=void 0!==n.pitch?Math.max(.01,Number(n.pitch)||0):1,s._loop=!(void 0===n.loop||!n.loop),s._duration=n.duration>0?n.duration:null,s._startTime=Math.max(0,Number(n.startTime)||0),s._overlap=!!n.overlap,s._autoPlay=!!n.autoPlay,s._firstNode=null,s._lastNode=null,s._asset=n.asset,s._asset instanceof kd&&(s._asset=s._asset.id),s._onInstancePlayHandler=s._onInstancePlay.bind(ee(s)),s._onInstancePauseHandler=s._onInstancePause.bind(ee(s)),s._onInstanceResumeHandler=s._onInstanceResume.bind(ee(s)),s._onInstanceStopHandler=s._onInstanceStop.bind(ee(s)),s._onInstanceEndHandler=s._onInstanceEnd.bind(ee(s)),s}Q(t,e);var i=t.prototype;return i.play=function(){if(this.overlap||this.stop(),this.isLoaded||this._hasAsset()){var e=this._createInstance();if(this.instances.push(e),this.isLoaded)e.play();else{var t=function(t){var i=e._playWhenLoaded;e.sound=t,i&&e.play()};this.off("load",t),this.once("load",t),this.load()}return e}},i.pause=function(){for(var e=!1,t=this.instances,i=0,n=t.length;i<n;i++)t[i].pause()&&(e=!0);return e},i.resume=function(){for(var e=!1,t=this.instances,i=0,n=t.length;i<n;i++)t[i].resume()&&(e=!0);return e},i.stop=function(){for(var e=!1,t=this.instances,i=t.length;i--;)t[i].stop(),e=!0;return t.length=0,e},i.load=function(){if(this._hasAsset()){var e=this._assets.get(this._asset);if(!e)return this._assets.off("add:"+this._asset,this._onAssetAdd,this),void this._assets.once("add:"+this._asset,this._onAssetAdd,this);if(e.off("remove",this._onAssetRemoved,this),e.on("remove",this._onAssetRemoved,this),!e.resource)return e.off("load",this._onAssetLoad,this),e.once("load",this._onAssetLoad,this),void this._assets.load(e);this.fire("load",e.resource)}},i.setExternalNodes=function(e,t){if(e){if(t||(t=e),this._firstNode=e,this._lastNode=t,!this._overlap)for(var i=this.instances,n=0,s=i.length;n<s;n++)i[n].setExternalNodes(e,t)}else console.error("The firstNode must have a valid AudioNode")},i.clearExternalNodes=function(){if(this._firstNode=null,this._lastNode=null,!this._overlap)for(var e=this.instances,t=0,i=e.length;t<i;t++)e[t].clearExternalNodes()},i.getExternalNodes=function(){return[this._firstNode,this._lastNode]},i._hasAsset=function(){return null!=this._asset},i._createInstance=function(){var e=null,t=this._component,i=null;if(this._hasAsset()){var n=this._assets.get(this._asset);n&&(i=n.resource)}var s=ov;return s.volume=this._volume*t.volume,s.pitch=this._pitch*t.pitch,s.loop=this._loop,s.startTime=this._startTime,s.duration=this._duration,s.onPlay=this._onInstancePlayHandler,s.onPause=this._onInstancePauseHandler,s.onResume=this._onInstanceResumeHandler,s.onStop=this._onInstanceStopHandler,s.onEnd=this._onInstanceEndHandler,t.positional?(s.position.copy(t.entity.getPosition()),s.maxDistance=t.maxDistance,s.refDistance=t.refDistance,s.rollOffFactor=t.rollOffFactor,s.distanceModel=t.distanceModel,e=new Fr(this._manager,i,s)):e=new kr(this._manager,i,s),this._firstNode&&e.setExternalNodes(this._firstNode,this._lastNode),e},i._onInstancePlay=function(e){this.fire("play",e),this._component.fire("play",this,e)},i._onInstancePause=function(e){this.fire("pause",e),this._component.fire("pause",this,e)},i._onInstanceResume=function(e){this.fire("resume",e),this._component.fire("resume",this,e)},i._onInstanceStop=function(e){var t=this.instances.indexOf(e);-1!==t&&this.instances.splice(t,1),this.fire("stop",e),this._component.fire("stop",this,e)},i._onInstanceEnd=function(e){var t=this.instances.indexOf(e);-1!==t&&this.instances.splice(t,1),this.fire("end",e),this._component.fire("end",this,e)},i._onAssetAdd=function(e){this.load()},i._onAssetLoad=function(e){this.load()},i._onAssetRemoved=function(e){e.off("remove",this._onAssetRemoved,this),this._assets.off("add:"+e.id,this._onAssetAdd,this),this.stop()},i.updatePosition=function(e){for(var t=this.instances,i=0,n=t.length;i<n;i++)t[i].position=e},Z(t,[{key:"asset",get:function(){return this._asset},set:function(e){var t=this._asset;if(t){this._assets.off("add:"+t,this._onAssetAdd,this);var i=this._assets.get(t);i&&i.off("remove",this._onAssetRemoved,this)}this._asset=e,this._asset instanceof kd&&(this._asset=this._asset.id),this._hasAsset()&&this._component.enabled&&this._component.entity.enabled&&this.load()}},{key:"autoPlay",get:function(){return this._autoPlay},set:function(e){this._autoPlay=!!e}},{key:"duration",get:function(){var e=0;if(this._hasAsset()){var t=this._assets.get(this._asset);e=null!=t&&t.resource?t.resource.duration:0}return null!=this._duration?this._duration%(e||1):e},set:function(e){if(this._duration=Math.max(0,Number(e)||0)||null,!this._overlap)for(var t=this.instances,i=0,n=t.length;i<n;i++)t[i].duration=this._duration}},{key:"isLoaded",get:function(){if(this._hasAsset()){var e=this._assets.get(this._asset);if(e)return!!e.resource}return!1}},{key:"isPaused",get:function(){var e=this.instances,t=e.length;if(0===t)return!1;for(var i=0;i<t;i++)if(!e[i].isPaused)return!1;return!0}},{key:"isPlaying",get:function(){for(var e=this.instances,t=0,i=e.length;t<i;t++)if(e[t].isPlaying)return!0;return!1}},{key:"isStopped",get:function(){for(var e=this.instances,t=0,i=e.length;t<i;t++)if(!e[t].isStopped)return!1;return!0}},{key:"loop",get:function(){return this._loop},set:function(e){this._loop=!!e;for(var t=this.instances,i=0,n=t.length;i<n;i++)t[i].loop=this._loop}},{key:"overlap",get:function(){return this._overlap},set:function(e){this._overlap=!!e}},{key:"pitch",get:function(){return this._pitch},set:function(e){if(this._pitch=Math.max(Number(e)||0,.01),!this._overlap)for(var t=this.instances,i=0,n=t.length;i<n;i++)t[i].pitch=this.pitch*this._component.pitch}},{key:"startTime",get:function(){return this._startTime},set:function(e){if(this._startTime=Math.max(0,Number(e)||0),!this._overlap)for(var t=this.instances,i=0,n=t.length;i<n;i++)t[i].startTime=this._startTime}},{key:"volume",get:function(){return this._volume},set:function(e){if(this._volume=ce.clamp(Number(e)||0,0,1),!this._overlap)for(var t=this.instances,i=0,n=t.length;i<n;i++)t[i].volume=this._volume*this._component.volume}}]),t}(p),lv=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._volume=1,n._pitch=1,n._positional=!0,n._refDistance=1,n._maxDistance=1e4,n._rollOffFactor=1,n._distanceModel=He,n._slots={},n._playingBeforeDisable={},n}Q(t,e);var i=t.prototype;return i._updateSoundInstances=function(e,t,i){var n=this._slots;for(var s in n){var r=n[s];if(!r.overlap)for(var a=r.instances,o=0,h=a.length;o<h;o++)a[o][e]=i?r[e]*t:t}},i.onEnable=function(){if(!this.system._inTools){var e=this._slots,t=this._playingBeforeDisable;for(var i in e){var n=e[i];n.autoPlay&&n.isStopped?n.play():t[i]?n.resume():n.isLoaded||n.load()}}},i.onDisable=function(){var e=this._slots,t={};for(var i in e)e[i].overlap||e[i].isPlaying&&(e[i].pause(),t[i]=!0);this._playingBeforeDisable=t},i.onRemove=function(){this.off()},i.addSlot=function(e,t){var i=this._slots;if(i[e])return null;var n=new hv(this,e,t);return i[e]=n,n.autoPlay&&this.enabled&&this.entity.enabled&&n.play(),n},i.removeSlot=function(e){var t=this._slots;t[e]&&(t[e].stop(),delete t[e])},i.slot=function(e){return this._slots[e]},i._getSlotProperty=function(e,t){if(this.enabled&&this.entity.enabled){var i=this._slots[e];if(i)return i[t]}},i.isPlaying=function(e){return this._getSlotProperty(e,"isPlaying")||!1},i.isLoaded=function(e){return this._getSlotProperty(e,"isLoaded")||!1},i.isPaused=function(e){return this._getSlotProperty(e,"isPaused")||!1},i.isStopped=function(e){return this._getSlotProperty(e,"isStopped")||!1},i.play=function(e){if(!this.enabled||!this.entity.enabled)return null;var t=this._slots[e];return t?t.play():null},i.pause=function(e){var t=this._slots;if(e){var i=t[e];if(!i)return;i.pause()}else for(var n in t)t[n].pause()},i.resume=function(e){var t=this._slots;if(e){var i=t[e];if(!i)return;i.isPaused&&i.resume()}else for(var n in t)t[n].resume()},i.stop=function(e){var t=this._slots;if(e){var i=t[e];if(!i)return;i.stop()}else for(var n in t)t[n].stop()},Z(t,[{key:"distanceModel",get:function(){return this._distanceModel},set:function(e){this._distanceModel=e,this._updateSoundInstances("distanceModel",e,!1)}},{key:"maxDistance",get:function(){return this._maxDistance},set:function(e){this._maxDistance=e,this._updateSoundInstances("maxDistance",e,!1)}},{key:"refDistance",get:function(){return this._refDistance},set:function(e){this._refDistance=e,this._updateSoundInstances("refDistance",e,!1)}},{key:"rollOffFactor",get:function(){return this._rollOffFactor},set:function(e){this._rollOffFactor=e,this._updateSoundInstances("rollOffFactor",e,!1)}},{key:"pitch",get:function(){return this._pitch},set:function(e){this._pitch=e,this._updateSoundInstances("pitch",e,!0)}},{key:"volume",get:function(){return this._volume},set:function(e){this._volume=e,this._updateSoundInstances("volume",e,!0)}},{key:"positional",get:function(){return this._positional},set:function(e){this._positional=e;var t=this._slots;for(var i in t){var n=t[i];if(!n.overlap)for(var s=n.instances,r=s.length-1;r>=0;r--){var a=s[r].isPlaying||s[r].isSuspended,o=s[r].currentTime;a&&s[r].stop();var h=n._createInstance();a&&(h.play(),h.currentTime=o),s.push(h)}}}},{key:"slots",get:function(){return this._slots},set:function(e){var t=this._slots;if(t)for(var i in t)t[i].stop();var n={};for(var s in e)e[s]instanceof hv?n[e[s].name]=e[s]:e[s].name&&(n[e[s].name]=new hv(this,e[s].name,e[s]));this._slots=n,this.enabled&&this.entity.enabled&&this.onEnable()}}]),t}(gf),cv=function(){this.enabled=!0},uv=["enabled"],dv=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="sound",i.ComponentType=lv,i.DataType=cv,i.schema=uv,i.manager=t.soundManager,i.app.systems.on("update",i.onUpdate,ee(i)),i.on("beforeremove",i.onBeforeRemove,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){n=["volume","pitch","positional","refDistance","maxDistance","rollOffFactor","distanceModel","slots"];for(var s=0;s<n.length;s++)i.hasOwnProperty(n[s])&&(t[n[s]]=i[n[s]]);e.prototype.initializeComponentData.call(this,t,i,["enabled"])},i.cloneComponent=function(e,t){var i=e.sound,n=i.slots,s={};for(var r in n){var a=n[r];s[r]={name:a.name,volume:a.volume,pitch:a.pitch,loop:a.loop,duration:a.duration,startTime:a.startTime,overlap:a.overlap,autoPlay:a.autoPlay,asset:a.asset}}var o={distanceModel:i.distanceModel,enabled:i.enabled,maxDistance:i.maxDistance,pitch:i.pitch,positional:i.positional,refDistance:i.refDistance,rollOffFactor:i.rollOffFactor,slots:s,volume:i.volume};return this.addComponent(t,o)},i.onUpdate=function(e){var t=this.store;for(var i in t)if(t.hasOwnProperty(i)){var n=t[i].entity;if(n.enabled){var s=n.sound;if(s.enabled&&s.positional){var r=n.getPosition(),a=s.slots;for(var o in a)a[o].updatePosition(r)}}}},i.onBeforeRemove=function(e,t){var i=t.slots;for(var n in i)i[n].overlap||i[n].stop();t.onRemove()},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},Z(t,[{key:"volume",get:function(){return this.manager.volume},set:function(e){this.manager.volume=e}},{key:"context",get:function(){return Ar()?this.manager.context:null}}]),t}(vf);gf._buildAccessors(lv.prototype,uv);var fv="simple",pv="animated",mv=function(e){function t(t,i){var n;return(n=e.call(this)||this)._component=t,n._frame=0,n._sprite=null,n._spriteAsset=null,n.spriteAsset=i.spriteAsset,n.name=i.name,n.fps=i.fps||0,n.loop=i.loop||!1,n._playing=!1,n._paused=!1,n._time=0,n}Q(t,e);var i=t.prototype;return i._onSpriteAssetAdded=function(e){this._component.system.app.assets.off("add:"+e.id,this._onSpriteAssetAdded,this),this._spriteAsset===e.id&&this._bindSpriteAsset(e)},i._bindSpriteAsset=function(e){e.on("load",this._onSpriteAssetLoad,this),e.on("remove",this._onSpriteAssetRemove,this),e.resource?this._onSpriteAssetLoad(e):this._component.system.app.assets.load(e)},i._unbindSpriteAsset=function(e){e&&(e.off("load",this._onSpriteAssetLoad,this),e.off("remove",this._onSpriteAssetRemove,this),e.resource&&!e.resource.atlas&&this._component.system.app.assets.off("load:"+e.data.textureAtlasAsset,this._onTextureAtlasLoad,this))},i._onSpriteAssetLoad=function(e){if(e.resource)if(e.resource.atlas)this.sprite=e.resource;else{var t=e.data.textureAtlasAsset,i=this._component.system.app.assets;i.off("load:"+t,this._onTextureAtlasLoad,this),i.once("load:"+t,this._onTextureAtlasLoad,this)}else this.sprite=null},i._onTextureAtlasLoad=function(e){var t=this._spriteAsset;t instanceof kd?this._onSpriteAssetLoad(t):this._onSpriteAssetLoad(this._component.system.app.assets.get(t))},i._onSpriteAssetRemove=function(e){this.sprite=null},i._onSpriteMeshesChange=function(){this._component.currentClip===this&&this._component._showFrame(this.frame)},i._onSpritePpuChanged=function(){this._component.currentClip===this&&0!==this.sprite.renderMode&&this._component._showFrame(this.frame)},i._update=function(e){if(0!==this.fps&&this._playing&&!this._paused&&this._sprite){var t=this.fps<0?-1:1,i=this._time+e*this._component.speed*t,n=this.duration,s=i>n||i<0;this._setTime(i);var r=this.frame;(r=this._sprite?Math.floor(this._sprite.frameKeys.length*this._time/n):0)!==this._frame&&this._setFrame(r),s&&(this.loop?(this.fire("loop"),this._component.fire("loop",this)):(this._playing=!1,this._paused=!1,this.fire("end"),this._component.fire("end",this)))}},i._setTime=function(e){this._time=e;var t=this.duration;this._time<0?this.loop?this._time=this._time%t+t:this._time=0:this._time>t&&(this.loop?this._time%=t:this._time=t)},i._setFrame=function(e){this._sprite?this._frame=ce.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=!0,this._paused=!1,this.frame=0,this.fire("play"),this._component.fire("play",this))},i.pause=function(){this._playing&&!this._paused&&(this._paused=!0,this.fire("pause"),this._component.fire("pause",this))},i.resume=function(){this._paused&&(this._paused=!1,this.fire("resume"),this._component.fire("resume",this))},i.stop=function(){this._playing&&(this._playing=!1,this._paused=!1,this._time=0,this.frame=0,this.fire("stop"),this._component.fire("stop",this))},Z(t,[{key:"duration",get:function(){if(this._sprite){var e=this.fps||Number.MIN_VALUE;return this._sprite.frameKeys.length/Math.abs(e)}return 0}},{key:"frame",get:function(){return this._frame},set:function(e){this._setFrame(e);var t=this.fps||Number.MIN_VALUE;this._setTime(this._frame/t)}},{key:"isPaused",get:function(){return this._paused}},{key:"isPlaying",get:function(){return this._playing}},{key:"sprite",get:function(){return this._sprite},set:function(e){var t;(this._sprite&&(this._sprite.off("set:meshes",this._onSpriteMeshesChange,this),this._sprite.off("set:pixelsPerUnit",this._onSpritePpuChanged,this),this._sprite.off("set:atlas",this._onSpriteMeshesChange,this),this._sprite.atlas&&this._sprite.atlas.off("set:texture",this._onSpriteMeshesChange,this)),this._sprite=e,this._sprite&&(this._sprite.on("set:meshes",this._onSpriteMeshesChange,this),this._sprite.on("set:pixelsPerUnit",this._onSpritePpuChanged,this),this._sprite.on("set:atlas",this._onSpriteMeshesChange,this),this._sprite.atlas&&this._sprite.atlas.on("set:texture",this._onSpriteMeshesChange,this)),this._component.currentClip===this)&&(e&&e.atlas?(e.atlas.texture&&((t=this._component._meshInstance)&&(t.setParameter("texture_emissiveMap",e.atlas.texture),t.setParameter("texture_opacityMap",e.atlas.texture)),this._component.enabled&&this._component.entity.enabled&&this._component._showModel()),this.time&&this.fps?this.time=this.time:this.frame=this.frame):((t=this._component._meshInstance)&&(t.deleteParameter("texture_emissiveMap"),t.deleteParameter("texture_opacityMap")),this._component._hideModel()))}},{key:"spriteAsset",get:function(){return this._spriteAsset},set:function(e){var t=this._component.system.app.assets,i=e;if(e instanceof kd&&(i=e.id),this._spriteAsset!==i){if(this._spriteAsset){var n=t.get(this._spriteAsset);n&&this._unbindSpriteAsset(n)}if(this._spriteAsset=i,this._spriteAsset){var s=t.get(this._spriteAsset);s?this._bindSpriteAsset(s):(this.sprite=null,t.on("add:"+this._spriteAsset,this._onSpriteAssetAdded,this))}else this.sprite=null}}},{key:"time",get:function(){return this._time},set:function(e){this._setTime(e),this._sprite?this.frame=Math.min(this._sprite.frameKeys.length-1,Math.floor(this._time*Math.abs(this.fps))):this.frame=0}}]),t}(p),_v="texture_emissiveMap",gv="texture_opacityMap",vv="material_emissive",yv="material_opacity",xv=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._type=fv,n._material=t.defaultMaterial,n._color=new ue(1,1,1,1),n._colorUniform=new Float32Array(3),n._speed=1,n._flipX=!1,n._flipY=!1,n._width=1,n._height=1,n._drawOrder=0,n._layers=[0],n._outerScale=new ge(1,1),n._outerScaleUniform=new Float32Array(2),n._innerOffset=new ve,n._innerOffsetUniform=new Float32Array(4),n._atlasRect=new ve,n._atlasRectUniform=new Float32Array(4),n._batchGroupId=-1,n._batchGroup=null,n._node=new go,n._model=new Uc,n._model.graph=n._node,n._meshInstance=null,i.addChild(n._model.graph),n._model._entity=i,n._updateAabbFunc=n._updateAabb.bind(ee(n)),n._addedModel=!1,n._autoPlayClip=null,n._clips={},n._defaultClip=new mv(ee(n),{name:n.entity.name,fps:0,loop:!1,spriteAsset:null}),n._currentClip=n._defaultClip,n}Q(t,e);var i=t.prototype;return i.onEnable=function(){var e,t=this.system.app,i=t.scene;(i.on("set:layers",this._onLayersChanged,this),i.layers&&(i.layers.on("add",this._onLayerAdded,this),i.layers.on("remove",this._onLayerRemoved,this)),this._showModel(),this._autoPlayClip&&this._tryAutoPlay(),this._batchGroupId>=0)&&(null==(e=t.batcher)||e.insert($a.SPRITE,this._batchGroupId,this.entity))},i.onDisable=function(){var e,t=this.system.app,i=t.scene;(i.off("set:layers",this._onLayersChanged,this),i.layers&&(i.layers.off("add",this._onLayerAdded,this),i.layers.off("remove",this._onLayerRemoved,this)),this.stop(),this._hideModel(),this._batchGroupId>=0)&&(null==(e=t.batcher)||e.remove($a.SPRITE,this._batchGroupId,this.entity))},i.onDestroy=function(){for(var e in this._currentClip=null,this._defaultClip&&(this._defaultClip._destroy(),this._defaultClip=null),this._clips)this._clips[e]._destroy();this._clips=null,this._hideModel(),this._model=null,this._node&&(this._node.parent&&this._node.parent.removeChild(this._node),this._node=null),this._meshInstance&&(this._meshInstance.material=null,this._meshInstance.mesh=null,this._meshInstance=null)},i._showModel=function(){if(!this._addedModel&&this._meshInstance){for(var e=[this._meshInstance],t=0,i=this._layers.length;t<i;t++){var n=this.system.app.scene.layers.getLayerById(this._layers[t]);n&&n.addMeshInstances(e)}this._addedModel=!0}},i._hideModel=function(){if(this._addedModel&&this._meshInstance){for(var e=[this._meshInstance],t=0,i=this._layers.length;t<i;t++){var n=this.system.app.scene.layers.getLayerById(this._layers[t]);n&&n.removeMeshInstances(e)}this._addedModel=!1}},i._showFrame=function(e){if(this.sprite){var t=this.sprite.meshes[e];if(t){var i;if(i=1===this.sprite.renderMode?this.system.default9SlicedMaterialSlicedMode:2===this.sprite.renderMode?this.system.default9SlicedMaterialTiledMode:this.system.defaultMaterial,this._meshInstance||(this._meshInstance=new Co(t,this._material,this._node),this._meshInstance.castShadow=!1,this._meshInstance.receiveShadow=!1,this._meshInstance.drawOrder=this._drawOrder,this._model.meshInstances.push(this._meshInstance),this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._meshInstance.setParameter(vv,this._colorUniform),this._meshInstance.setParameter(yv,this._color.a),this.enabled&&this.entity.enabled&&this._showModel()),this._meshInstance.material!==i&&(this._meshInstance.material=i),this._meshInstance.mesh!==t&&(this._meshInstance.mesh=t,this._meshInstance.visible=!0,this._meshInstance._aabbVer=-1),this.sprite.atlas&&this.sprite.atlas.texture?(this._meshInstance.setParameter(_v,this.sprite.atlas.texture),this._meshInstance.setParameter(gv,this.sprite.atlas.texture)):(this._meshInstance.deleteParameter(_v),this._meshInstance.deleteParameter(gv)),!this.sprite.atlas||1!==this.sprite.renderMode&&2!==this.sprite.renderMode)this._meshInstance._updateAabbFunc=null;else{this._meshInstance._updateAabbFunc=this._updateAabbFunc;var n=this.sprite.atlas.frames[this.sprite.frameKeys[e]];if(n){var s=2/n.rect.z,r=2/n.rect.w;this._innerOffset.set(n.border.x*s,n.border.y*r,n.border.z*s,n.border.w*r);var a=this.sprite.atlas.texture;this._atlasRect.set(n.rect.x/a.width,n.rect.y/a.height,n.rect.z/a.width,n.rect.w/a.height)}else this._innerOffset.set(0,0,0,0);this._innerOffsetUniform[0]=this._innerOffset.x,this._innerOffsetUniform[1]=this._innerOffset.y,this._innerOffsetUniform[2]=this._innerOffset.z,this._innerOffsetUniform[3]=this._innerOffset.w,this._meshInstance.setParameter("innerOffset",this._innerOffsetUniform),this._atlasRectUniform[0]=this._atlasRect.x,this._atlasRectUniform[1]=this._atlasRect.y,this._atlasRectUniform[2]=this._atlasRect.z,this._atlasRectUniform[3]=this._atlasRect.w,this._meshInstance.setParameter("atlasRect",this._atlasRectUniform)}this._updateTransform()}else this._meshInstance&&(this._meshInstance.mesh=null,this._meshInstance.visible=!1)}},i._updateTransform=function(){var e=this.flipX?-1:1,t=this.flipY?-1:1,i=0,n=0;if(this.sprite&&(1===this.sprite.renderMode||2===this.sprite.renderMode)){var s=1,r=1;if(this.sprite.atlas){var a=this.sprite.atlas.frames[this.sprite.frameKeys[this.frame]];a&&(s=a.rect.z,r=a.rect.w,i=(.5-a.pivot.x)*this._width,n=(.5-a.pivot.y)*this._height)}var o=s/this.sprite.pixelsPerUnit,h=r/this.sprite.pixelsPerUnit;this._outerScale.set(Math.max(this._width,this._innerOffset.x*o),Math.max(this._height,this._innerOffset.y*h)),e*=o,t*=h,this._outerScale.x/=o,this._outerScale.y/=h,e*=ce.clamp(this._width/(this._innerOffset.x*o),1e-4,1),t*=ce.clamp(this._height/(this._innerOffset.y*h),1e-4,1),this._meshInstance&&(this._outerScaleUniform[0]=this._outerScale.x,this._outerScaleUniform[1]=this._outerScale.y,this._meshInstance.setParameter("outerScale",this._outerScaleUniform))}this._node.setLocalScale(e,t,1),this._node.setLocalPosition(i,n,0)},i._updateAabb=function(e){return e.center.set(0,0,0),e.halfExtents.set(.5*this._outerScale.x,.5*this._outerScale.y,.001),e.setFromTransformedAabb(e,this._node.getWorldTransform()),e},i._tryAutoPlay=function(){if(this._autoPlayClip&&this.type===pv){var e=this._clips[this._autoPlayClip];!e||e.isPlaying||this._currentClip&&this._currentClip.isPlaying||this.enabled&&this.entity.enabled&&this.play(e.name)}},i._onLayersChanged=function(e,t){e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this),this.enabled&&this.entity.enabled&&this._showModel()},i._onLayerAdded=function(e){this.layers.indexOf(e.id)<0||this._addedModel&&this.enabled&&this.entity.enabled&&this._meshInstance&&e.addMeshInstances([this._meshInstance])},i._onLayerRemoved=function(e){this._meshInstance&&(this.layers.indexOf(e.id)<0||e.removeMeshInstances([this._meshInstance]))},i.removeModelFromLayers=function(){for(var e=0;e<this.layers.length;e++){var t=this.system.app.scene.layers.getLayerById(this.layers[e]);t&&t.removeMeshInstances([this._meshInstance])}},i.addClip=function(e){var t=new mv(this,{name:e.name,fps:e.fps,loop:e.loop,spriteAsset:e.spriteAsset});return this._clips[e.name]=t,t.name&&t.name===this._autoPlayClip&&this._tryAutoPlay(),t},i.removeClip=function(e){delete this._clips[e]},i.clip=function(e){return this._clips[e]},i.play=function(e){var t=this._clips[e],i=this._currentClip;return i&&i!==t&&(i._playing=!1),this._currentClip=t,this._currentClip&&(this._currentClip=t,this._currentClip.play()),t},i.pause=function(){this._currentClip!==this._defaultClip&&this._currentClip.isPlaying&&this._currentClip.pause()},i.resume=function(){this._currentClip!==this._defaultClip&&this._currentClip.isPaused&&this._currentClip.resume()},i.stop=function(){this._currentClip!==this._defaultClip&&this._currentClip.stop()},Z(t,[{key:"type",get:function(){return this._type},set:function(e){this._type!==e&&(this._type=e,this._type===fv?(this.stop(),this._currentClip=this._defaultClip,this.enabled&&this.entity.enabled&&(this._currentClip.frame=this.frame,this._currentClip.sprite?this._showModel():this._hideModel())):this._type===pv&&(this.stop(),this._autoPlayClip&&this._tryAutoPlay(),this._currentClip&&this._currentClip.isPlaying&&this.enabled&&this.entity.enabled?this._showModel():this._hideModel()))}},{key:"frame",get:function(){return this._currentClip.frame},set:function(e){this._currentClip.frame=e}},{key:"spriteAsset",get:function(){return this._defaultClip._spriteAsset},set:function(e){this._defaultClip.spriteAsset=e}},{key:"sprite",get:function(){return this._currentClip.sprite},set:function(e){this._currentClip.sprite=e}},{key:"material",get:function(){return this._material},set:function(e){this._material=e,this._meshInstance&&(this._meshInstance.material=e)}},{key:"color",get:function(){return this._color},set:function(e){this._color.r=e.r,this._color.g=e.g,this._color.b=e.b,this._meshInstance&&(this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._meshInstance.setParameter(vv,this._colorUniform))}},{key:"opacity",get:function(){return this._color.a},set:function(e){this._color.a=e,this._meshInstance&&this._meshInstance.setParameter(yv,e)}},{key:"clips",get:function(){return this._clips},set:function(e){if(e){for(var t in this._clips){var i=!1;for(var n in e)if(e[n].name===t){i=!0,this._clips[t].fps=e[n].fps,this._clips[t].loop=e[n].loop,e[n].hasOwnProperty("sprite")?this._clips[t].sprite=e[n].sprite:e[n].hasOwnProperty("spriteAsset")&&(this._clips[t].spriteAsset=e[n].spriteAsset);break}i||this.removeClip(t)}for(var s in e)this._clips[e[s].name]||this.addClip(e[s]);this._autoPlayClip&&this._tryAutoPlay(),this._currentClip&&this._currentClip.sprite||this._hideModel()}else for(var r in this._clips)this.removeClip(r)}},{key:"currentClip",get:function(){return this._currentClip}},{key:"speed",get:function(){return this._speed},set:function(e){this._speed=e}},{key:"flipX",get:function(){return this._flipX},set:function(e){this._flipX!==e&&(this._flipX=e,this._updateTransform())}},{key:"flipY",get:function(){return this._flipY},set:function(e){this._flipY!==e&&(this._flipY=e,this._updateTransform())}},{key:"width",get:function(){return this._width},set:function(e){e!==this._width&&(this._width=e,this._outerScale.x=this._width,!this.sprite||2!==this.sprite.renderMode&&1!==this.sprite.renderMode||this._updateTransform())}},{key:"height",get:function(){return this._height},set:function(e){e!==this._height&&(this._height=e,this._outerScale.y=this.height,!this.sprite||2!==this.sprite.renderMode&&1!==this.sprite.renderMode||this._updateTransform())}},{key:"batchGroupId",get:function(){return this._batchGroupId},set:function(e){if(this._batchGroupId!==e){var t,i,n=this._batchGroupId;if(this._batchGroupId=e,this.entity.enabled&&n>=0)null==(t=this.system.app.batcher)||t.remove($a.SPRITE,n,this.entity);if(this.entity.enabled&&e>=0)null==(i=this.system.app.batcher)||i.insert($a.SPRITE,e,this.entity);else n>=0&&this._currentClip&&this._currentClip.sprite&&this.enabled&&this.entity.enabled&&this._showModel()}}},{key:"autoPlayClip",get:function(){return this._autoPlayClip},set:function(e){this._autoPlayClip=e instanceof mv?e.name:e,this._tryAutoPlay()}},{key:"drawOrder",get:function(){return this._drawOrder},set:function(e){this._drawOrder=e,this._meshInstance&&(this._meshInstance.drawOrder=e)}},{key:"layers",get:function(){return this._layers},set:function(e){this._addedModel&&this._hideModel(),this._layers=e,this._meshInstance&&this.enabled&&this.entity.enabled&&this._showModel()}},{key:"aabb",get:function(){return this._meshInstance?this._meshInstance.aabb:null}}]),t}(gf),Sv=function(){this.enabled=!0},bv=["enabled"],wv=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="sprite",i.ComponentType=xv,i.DataType=Sv,i.schema=bv,i._defaultTexture=null,i._defaultMaterial=null,i._default9SlicedMaterialSlicedMode=null,i._default9SlicedMaterialTiledMode=null,i.app.systems.on("update",i.onUpdate,ee(i)),i.on("beforeremove",i.onBeforeRemove,ee(i)),i}Q(t,e);var i=t.prototype;return i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this),this._defaultTexture&&(this._defaultTexture.destroy(),this._defaultTexture=null)},i.initializeComponentData=function(t,i,n){if(void 0!==i.enabled&&(t.enabled=i.enabled),t.type=i.type,i.layers&&Array.isArray(i.layers)&&(t.layers=i.layers.slice(0)),void 0!==i.drawOrder&&(t.drawOrder=i.drawOrder),void 0!==i.color){var s,r;if(i.color instanceof ue)t.color.set(i.color.r,i.color.g,i.color.b,null!=(s=i.opacity)?s:1);else t.color.set(i.color[0],i.color[1],i.color[2],null!=(r=i.opacity)?r:1);t.color=t.color}if(void 0!==i.opacity&&(t.opacity=i.opacity),void 0!==i.flipX&&(t.flipX=i.flipX),void 0!==i.flipY&&(t.flipY=i.flipY),void 0!==i.width&&(t.width=i.width),void 0!==i.height&&(t.height=i.height),void 0!==i.spriteAsset&&(t.spriteAsset=i.spriteAsset),i.sprite&&(t.sprite=i.sprite),void 0!==i.frame&&(t.frame=i.frame),i.clips)for(var a in i.clips)t.addClip(i.clips[a]);void 0!==i.speed&&(t.speed=i.speed),i.autoPlayClip&&(t.autoPlayClip=i.autoPlayClip),t.batchGroupId=void 0===i.batchGroupId||null===i.batchGroupId?-1:i.batchGroupId,e.prototype.initializeComponentData.call(this,t,i,n)},i.cloneComponent=function(e,t){var i=e.sprite;return this.addComponent(t,{enabled:i.enabled,type:i.type,spriteAsset:i.spriteAsset,sprite:i.sprite,frame:i.frame,color:i.color.clone(),opacity:i.opacity,flipX:i.flipX,flipY:i.flipY,speed:i.speed,clips:i.clips,autoPlayClip:i.autoPlayClip,batchGroupId:i.batchGroupId,drawOrder:i.drawOrder,layers:i.layers.slice(0)})},i.onUpdate=function(e){var t=this.store;for(var i in t)if(t.hasOwnProperty(i)){var n=t[i];if(n.data.enabled&&n.entity.enabled){var s=n.entity.sprite;s._currentClip&&s._currentClip._update(e)}}},i.onBeforeRemove=function(e,t){t.onDestroy()},Z(t,[{key:"defaultMaterial",get:function(){if(!this._defaultMaterial){var e=new Yn(this.app.graphicsDevice,{width:1,height:1,format:7,name:"sprite"}),t=new Uint8Array(e.lock());t[0]=t[1]=t[2]=t[3]=255,e.unlock();var i=new Yl;i.diffuse.set(0,0,0),i.emissive.set(.5,.5,.5),i.emissiveMap=e,i.emissiveTint=!0,i.opacityMap=e,i.opacityMapChannel="a",i.opacityTint=!0,i.opacity=0,i.useLighting=!1,i.useGammaTonemap=!1,i.useFog=!1,i.useSkybox=!1,i.blendType=4,i.depthWrite=!1,i.pixelSnap=!1,i.cull=0,i.update(),this._defaultTexture=e,this._defaultMaterial=i}return this._defaultMaterial},set:function(e){this._defaultMaterial=e}},{key:"default9SlicedMaterialSlicedMode",get:function(){if(!this._default9SlicedMaterialSlicedMode){var e=this.defaultMaterial.clone();e.nineSlicedMode=1,e.update(),this._default9SlicedMaterialSlicedMode=e}return this._default9SlicedMaterialSlicedMode},set:function(e){this._default9SlicedMaterialSlicedMode=e}},{key:"default9SlicedMaterialTiledMode",get:function(){if(!this._default9SlicedMaterialTiledMode){var e=this.defaultMaterial.clone();e.nineSlicedMode=2,e.update(),this._default9SlicedMaterialTiledMode=e}return this._default9SlicedMaterialTiledMode},set:function(e){this._default9SlicedMaterialTiledMode=e}}]),t}(vf);gf._buildAccessors(xv.prototype,bv);var Tv=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._oldState=!0,n._size=new me,n.on("set_enabled",n._onSetEnabled,ee(n)),n}Q(t,e);var i=t.prototype;return i.onEnable=function(){this._checkState()},i.onDisable=function(){this._checkState()},i._onSetEnabled=function(e,t,i){this._checkState()},i._checkState=function(){var e=this.enabled&&this.entity.enabled;e!==this._oldState&&(this._oldState=e,this.fire("enable"),this.fire("state",this.enabled))},i._onBeforeRemove=function(){this.fire("remove")},Z(t,[{key:"size",get:function(){return this._size},set:function(e){e instanceof me?this._size.copy(e):e instanceof Array&&e.length>=3&&this.size.set(e[0],e[1],e[2])}}]),t}(gf),Av=function(){this.enabled=!0},Cv=["enabled"],Ev=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="zone",i.ComponentType=Tv,i.DataType=Av,i.schema=Cv,i.on("beforeremove",i._onBeforeRemove,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(e,t,i){e.enabled=!t.hasOwnProperty("enabled")||!!t.enabled,t.size&&(t.size instanceof me?e.size.copy(t.size):t.size instanceof Array&&t.size.length>=3&&e.size.set(t.size[0],t.size[1],t.size[2]))},i.cloneComponent=function(e,t){var i={size:e.zone.size};return this.addComponent(t,i)},i._onBeforeRemove=function(e,t){t._onBeforeRemove()},t}(vf);gf._buildAccessors(Tv.prototype,Cv);var Mv=function(e,t){this.effect=e,this.inputTarget=t,this.outputTarget=null,this.name=e.constructor.name},Pv=function(){function e(e,t){this.app=e,this.camera=t,this.destinationRenderTarget=null,this.effects=[],this.enabled=!1,this.depthTarget=null,t.on("set:rect",this.onCameraRectChanged,this)}var t=e.prototype;return t._allocateColorBuffer=function(e,t){var i,n,s,r,a=this.camera.rect,o=Math.floor(a.z*(null!=(i=null==(n=this.camera.renderTarget)?void 0:n.width)?i:this.app.graphicsDevice.width)),h=Math.floor(a.w*(null!=(s=null==(r=this.camera.renderTarget)?void 0:r.height)?s:this.app.graphicsDevice.height));return new Yn(this.app.graphicsDevice,{name:t,format:e,width:o,height:h,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1})},t._createOffscreenTarget=function(e,t){var i=this.app.graphicsDevice,n=t&&i.getHdrFormat(!1,!0,!1,!1)||7,s=this.camera.entity.name+"-posteffect-"+this.effects.length,r=this._allocateColorBuffer(n,s);return new Di({colorBuffer:r,depth:e,stencil:e&&this.app.graphicsDevice.supportsStencil,samples:e?i.samples:1})},t._resizeOffscreenTarget=function(e){var t=e.colorBuffer.format,i=e.colorBuffer.name;e.destroyFrameBuffers(),e.destroyTextureBuffers(),e._colorBuffer=this._allocateColorBuffer(t,i),e._colorBuffers=[e._colorBuffer]},t._destroyOffscreenTarget=function(e){e.destroyTextureBuffers(),e.destroy()},t.addEffect=function(e){var t=this.effects,i=0===t.length,n=this._createOffscreenTarget(i,e.hdr),s=new Mv(e,n);t.push(s),this._sourceTarget=s.inputTarget,t.length>1&&(t[t.length-2].outputTarget=s.inputTarget),this._newPostEffect=e,e.needsDepthBuffer&&this._requestDepthMap(),this.enable(),this._newPostEffect=void 0},t.removeEffect=function(e){for(var t=-1,i=0,n=this.effects.length;i<n;i++)if(this.effects[i].effect===e){t=i;break}t>=0&&(t>0?this.effects[t-1].outputTarget=t+1<this.effects.length?this.effects[t+1].inputTarget:null:this.effects.length>1&&(this.effects[1].inputTarget._depth||(this._destroyOffscreenTarget(this.effects[1].inputTarget),this.effects[1].inputTarget=this._createOffscreenTarget(!0,this.effects[1].hdr),this._sourceTarget=this.effects[1].inputTarget),this.camera.renderTarget=this.effects[1].inputTarget),this._destroyOffscreenTarget(this.effects[t].inputTarget),this.effects.splice(t,1)),this.enabled&&e.needsDepthBuffer&&this._releaseDepthMap(),0===this.effects.length&&this.disable()},t._requestDepthMaps=function(){for(var e=0,t=this.effects.length;e<t;e++){var i=this.effects[e].effect;this._newPostEffect!==i&&(i.needsDepthBuffer&&this._requestDepthMap())}},t._releaseDepthMaps=function(){for(var e=0,t=this.effects.length;e<t;e++){this.effects[e].effect.needsDepthBuffer&&this._releaseDepthMap()}},t._requestDepthMap=function(){var e=this.app.scene.layers.getLayerById(1);e&&(e.incrementCounter(),this.camera.requestSceneDepthMap(!0))},t._releaseDepthMap=function(){var e=this.app.scene.layers.getLayerById(1);e&&(e.decrementCounter(),this.camera.requestSceneDepthMap(!1))},t.destroy=function(){for(var e=0,t=this.effects.length;e<t;e++)this.effects[e].inputTarget.destroy();this.effects.length=0,this.disable()},t.enable=function(){var e=this;!this.enabled&&this.effects.length&&(this.enabled=!0,this._requestDepthMaps(),this.app.graphicsDevice.on("resizecanvas",this._onCanvasResized,this),this.destinationRenderTarget=this.camera.renderTarget,this.camera.renderTarget=this.effects[0].inputTarget,this.camera.onPostprocessing=function(){if(e.enabled){var t=null,i=e.effects.length;if(i)for(var n=0;n<i;n++){var s=e.effects[n],r=s.outputTarget;n===i-1&&(t=e.camera.rect,e.destinationRenderTarget&&(r=e.destinationRenderTarget)),s.effect.render(s.inputTarget,r,t)}}})},t.disable=function(){this.enabled&&(this.enabled=!1,this.app.graphicsDevice.off("resizecanvas",this._onCanvasResized,this),this._releaseDepthMaps(),this._destroyOffscreenTarget(this._sourceTarget),this.camera.renderTarget=null,this.camera.onPostprocessing=null)},t._onCanvasResized=function(e,t){var i=this.camera.rect,n=this.app.graphicsDevice;this.camera.camera.aspectRatio=n.width*i.z/(n.height*i.w),this.resizeRenderTargets()},t.resizeRenderTargets=function(){for(var e=this.camera.rect,t=Math.floor(e.z*this.app.graphicsDevice.width),i=Math.floor(e.w*this.app.graphicsDevice.height),n=this.effects,s=0,r=n.length;s<r;s++){var a=n[s];a.inputTarget.width===t&&a.inputTarget.height===i||this._resizeOffscreenTarget(a.inputTarget)}},t.onCameraRectChanged=function(e,t,i){this.enabled&&this.resizeRenderTargets()},e}(),Rv=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this).onPostprocessing=null,n.onPreRender=null,n.onPostRender=null,n._renderSceneDepthMap=0,n._renderSceneColorMap=0,n._sceneDepthMapRequested=!1,n._sceneColorMapRequested=!1,n._priority=0,n._disablePostEffectsLayer=4,n._camera=new Vo,n._camera.node=i,n._postEffects=new Pv(t.app,ee(n)),n}Q(t,e);var i=t.prototype;return i.setShaderPass=function(e){var t=Fa.get(this.system.app.graphicsDevice),i=e?t.allocate(e,{isForward:!0}):null;return this._camera.shaderPassInfo=i,i.index},i.getShaderPass=function(){var e;return null==(e=this._camera.shaderPassInfo)?void 0:e.name},i._enableDepthLayer=function(e){if(this.layers.find((function(e){return 1===e}))){var t=this.system.app.scene.layers.getLayerById(1);e?null==t||t.incrementCounter():null==t||t.decrementCounter()}else if(e)return!1;return!0},i.requestSceneColorMap=function(e){this._renderSceneColorMap+=e?1:-1,this._enableDepthLayer(e)},i.requestSceneDepthMap=function(e){this._renderSceneDepthMap+=e?1:-1,this._enableDepthLayer(e)},i.dirtyLayerCompositionCameras=function(){this.system.app.scene.layers._dirtyCameras=!0},i.screenToWorld=function(e,t,i,n){var s=this.system.app.graphicsDevice,r=s.clientRect.width,a=s.clientRect.height;return this._camera.screenToWorld(e,t,i,r,a,n)},i.worldToScreen=function(e,t){var i=this.system.app.graphicsDevice,n=i.clientRect.width,s=i.clientRect.height;return this._camera.worldToScreen(e,n,s,t)},i.onAppPrerender=function(){this._camera._viewMatDirty=!0,this._camera._viewProjMatDirty=!0},i.addCameraToLayers=function(){for(var e=this.layers,t=0;t<e.length;t++){var i=this.system.app.scene.layers.getLayerById(e[t]);i&&i.addCamera(this)}},i.removeCameraFromLayers=function(){for(var e=this.layers,t=0;t<e.length;t++){var i=this.system.app.scene.layers.getLayerById(e[t]);i&&i.removeCamera(this)}},i.onLayersChanged=function(e,t){this.addCameraToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(e){this.layers.indexOf(e.id)<0||e.addCamera(this)},i.onLayerRemoved=function(e){this.layers.indexOf(e.id)<0||e.removeCamera(this)},i.onEnable=function(){var e=this.system,t=e.app.scene,i=t.layers;e.addCamera(this),t.on("set:layers",this.onLayersChanged,this),i&&(i.on("add",this.onLayerAdded,this),i.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&this.addCameraToLayers(),this.postEffects.enable()},i.onDisable=function(){var e=this.system,t=e.app.scene,i=t.layers;this.postEffects.disable(),this.removeCameraFromLayers(),t.off("set:layers",this.onLayersChanged,this),i&&(i.off("add",this.onLayerAdded,this),i.off("remove",this.onLayerRemoved,this)),e.removeCamera(this)},i.onRemove=function(){this.onDisable(),this.off()},i.calculateAspectRatio=function(e){var t=this.system.app.graphicsDevice,i=e?e.width:t.width,n=e?e.height:t.height;return i*this.rect.z/(n*this.rect.w)},i.frameUpdate=function(e){0===this.aspectRatioMode&&(this.aspectRatio=this.calculateAspectRatio(e))},i.startXr=function(e,t,i){this.system.app.xr.start(this,e,t,i)},i.endXr=function(e){this._camera.xr?this._camera.xr.end(e):e&&e(new Error("Camera is not in XR"))},i.copy=function(e){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},Z(t,[{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){for(var t=this._camera.layers,i=0;i<t.length;i++){var n=this.system.app.scene.layers.getLayerById(t[i]);n&&n.removeCamera(this)}if(this._camera.layers=e,this.enabled&&this.entity.enabled)for(var s=0;s<e.length;s++){var r=this.system.app.scene.layers.getLayerById(e[s]);r&&r.addCamera(this)}}},{key:"layersSet",get:function(){return this._camera.layersSet}},{key:"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(!0),this._sceneColorMapRequested=!0):this._sceneColorMapRequested&&(this.requestSceneColorMap(!1),this._sceneColorMapRequested=!1)}},{key:"renderSceneDepthMap",get:function(){return this._renderSceneDepthMap>0},set:function(e){e&&!this._sceneDepthMapRequested?(this.requestSceneDepthMap(!0),this._sceneDepthMapRequested=!0):this._sceneDepthMapRequested&&(this.requestSceneDepthMap(!1),this._sceneDepthMapRequested=!1)}},{key:"renderTarget",get:function(){return this._camera.renderTarget},set:function(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}}]),t}(gf),Iv=function(){this.enabled=!0},Lv=["enabled"],Dv=function(e){function t(t){var i;return(i=e.call(this,t)||this).cameras=[],i.id="camera",i.ComponentType=Rv,i.DataType=Iv,i.schema=Lv,i.on("beforeremove",i.onBeforeRemove,ee(i)),i.app.on("prerender",i.onAppPrerender,ee(i)),i.app.systems.on("update",i.onUpdate,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i,n){n=["aspectRatio","aspectRatioMode","calculateProjection","calculateTransform","clearColor","clearColorBuffer","clearDepthBuffer","clearStencilBuffer","renderSceneColorMap","renderSceneDepthMap","cullFaces","farClip","flipFaces","fov","frustumCulling","horizontalFov","layers","renderTarget","nearClip","orthoHeight","projection","priority","rect","scissorRect","aperture","shutter","sensitivity"];for(var s=0;s<n.length;s++){var r=n[s];if(i.hasOwnProperty(r)){var a=i[r];switch(r){case"rect":case"scissorRect":Array.isArray(a)?t[r]=new ve(a[0],a[1],a[2],a[3]):t[r]=a;break;case"clearColor":Array.isArray(a)?t[r]=new ue(a[0],a[1],a[2],a[3]):t[r]=a;break;default:t[r]=a}}}e.prototype.initializeComponentData.call(this,t,i,["enabled"])},i.cloneComponent=function(e,t){var i=e.camera;return this.addComponent(t,{aspectRatio:i.aspectRatio,aspectRatioMode:i.aspectRatioMode,calculateProjection:i.calculateProjection,calculateTransform:i.calculateTransform,clearColor:i.clearColor,clearColorBuffer:i.clearColorBuffer,clearDepthBuffer:i.clearDepthBuffer,clearStencilBuffer:i.clearStencilBuffer,renderSceneDepthMap:i.renderSceneDepthMap,renderSceneColorMap:i.renderSceneColorMap,cullFaces:i.cullFaces,enabled:i.enabled,farClip:i.farClip,flipFaces:i.flipFaces,fov:i.fov,frustumCulling:i.frustumCulling,horizontalFov:i.horizontalFov,layers:i.layers,renderTarget:i.renderTarget,nearClip:i.nearClip,orthoHeight:i.orthoHeight,projection:i.projection,priority:i.priority,rect:i.rect,scissorRect:i.scissorRect,aperture:i.aperture,sensitivity:i.sensitivity,shutter:i.shutter})},i.onBeforeRemove=function(e,t){this.removeCamera(t)},i.onUpdate=function(e){},i.onAppPrerender=function(){for(var e=0,t=this.cameras.length;e<t;e++)this.cameras[e].onAppPrerender()},i.addCamera=function(e){this.cameras.push(e),bc(this.cameras)},i.removeCamera=function(e){var t=this.cameras.indexOf(e);t>=0&&(this.cameras.splice(t,1),bc(this.cameras))},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("update",this.onUpdate,this)},t}(vf);gf._buildAccessors(Rv.prototype,Lv);var Ov=[],kv=[],Fv=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._cookieAsset=null,n._cookieAssetId=null,n._cookieAssetAdd=!1,n._cookieMatrix=null,n}Q(t,e);var i=t.prototype;return i.addLightToLayers=function(){for(var e=0;e<this.layers.length;e++){var t=this.system.app.scene.layers.getLayerById(this.layers[e]);t&&t.addLight(this)}},i.removeLightFromLayers=function(){for(var e=0;e<this.layers.length;e++){var t=this.system.app.scene.layers.getLayerById(this.layers[e]);t&&t.removeLight(this)}},i.onLayersChanged=function(e,t){this.enabled&&this.entity.enabled&&this.addLightToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)},i.onLayerAdded=function(e){this.layers.indexOf(e.id)>=0&&this.enabled&&this.entity.enabled&&e.addLight(this)},i.onLayerRemoved=function(e){this.layers.indexOf(e.id)>=0&&e.removeLight(this)},i.refreshProperties=function(){for(var e=0;e<Ov.length;e++){var t=Ov[e];this[t]=this[t]}this.enabled&&this.entity.enabled&&this.onEnable()},i.onCookieAssetSet=function(){var e=!1;"cubemap"!==this._cookieAsset.type||this._cookieAsset.loadFaces||(this._cookieAsset.loadFaces=!0,e=!0),this._cookieAsset.resource&&!e||this.system.app.assets.load(this._cookieAsset),this._cookieAsset.resource&&this.onCookieAssetLoad()},i.onCookieAssetAdd=function(e){this._cookieAssetId===e.id&&(this._cookieAsset=e,this.light.enabled&&this.onCookieAssetSet(),this._cookieAsset.on("load",this.onCookieAssetLoad,this),this._cookieAsset.on("remove",this.onCookieAssetRemove,this))},i.onCookieAssetLoad=function(){this._cookieAsset&&this._cookieAsset.resource&&(this.cookie=this._cookieAsset.resource)},i.onCookieAssetRemove=function(){this._cookieAssetId&&(this._cookieAssetAdd&&(this.system.app.assets.off("add:"+this._cookieAssetId,this.onCookieAssetAdd,this),this._cookieAssetAdd=!1),this._cookieAsset&&(this._cookieAsset.off("load",this.onCookieAssetLoad,this),this._cookieAsset.off("remove",this.onCookieAssetRemove,this),this._cookieAsset=null),this.cookie=null)},i.onEnable=function(){this.light.enabled=!0,this.system.app.scene.on("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.on("add",this.onLayerAdded,this),this.system.app.scene.layers.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&this.addLightToLayers(),this._cookieAsset&&!this.cookie&&this.onCookieAssetSet()},i.onDisable=function(){this.light.enabled=!1,this.system.app.scene.off("set:layers",this.onLayersChanged,this),this.system.app.scene.layers&&(this.system.app.scene.layers.off("add",this.onLayerAdded,this),this.system.app.scene.layers.off("remove",this.onLayerRemoved,this)),this.removeLightFromLayers()},i.onRemove=function(){this.onDisable(),this.light.destroy(),this.cookieAsset=null},Z(t,[{key:"shadowUpdateOverrides",get:function(){return this.light.shadowUpdateOverrides},set:function(e){this.light.shadowUpdateOverrides=e}},{key:"penumbraSize",get:function(){return this.light.penumbraSize},set:function(e){this.light.penumbraSize=e}}]),t}(gf);function Bv(e,t,i,n){var s=Fv.prototype;Ov.push(e),kv.push(t),Object.defineProperty(s,e,{get:function(){return this.data[e]},set:function(t){var s=this.data,r=s[e];(n||r!==t)&&(s[e]=t,i&&i.call(this,t,r))},configurable:!0})}Bv("enabled",!0,(function(e,t){this.onSetEnabled(null,t,e)})),Bv("light",null),Bv("type","directional",(function(e,t){this.system.changeType(this,t,e),this.refreshProperties()})),Bv("color",new ue(1,1,1),(function(e,t){this.light.setColor(e)}),!0),Bv("intensity",1,(function(e,t){this.light.intensity=e})),Bv("luminance",0,(function(e,t){this.light.luminance=e})),Bv("shape",0,(function(e,t){this.light.shape=e})),Bv("affectSpecularity",!0,(function(e,t){this.light.affectSpecularity=e})),Bv("castShadows",!1,(function(e,t){this.light.castShadows=e})),Bv("shadowDistance",40,(function(e,t){this.light.shadowDistance=e})),Bv("shadowIntensity",1,(function(e,t){this.light.shadowIntensity=e})),Bv("shadowResolution",1024,(function(e,t){this.light.shadowResolution=e})),Bv("shadowBias",.05,(function(e,t){this.light.shadowBias=-.01*ce.clamp(e,0,1)})),Bv("numCascades",1,(function(e,t){this.light.numCascades=ce.clamp(Math.floor(e),1,4)})),Bv("bakeNumSamples",1,(function(e,t){this.light.bakeNumSamples=ce.clamp(Math.floor(e),1,255)})),Bv("bakeArea",0,(function(e,t){this.light.bakeArea=ce.clamp(e,0,180)})),Bv("cascadeDistribution",.5,(function(e,t){this.light.cascadeDistribution=ce.clamp(e,0,1)})),Bv("normalOffsetBias",0,(function(e,t){this.light.normalOffsetBias=ce.clamp(e,0,1)})),Bv("range",10,(function(e,t){this.light.attenuationEnd=e})),Bv("innerConeAngle",40,(function(e,t){this.light.innerConeAngle=e})),Bv("outerConeAngle",45,(function(e,t){this.light.outerConeAngle=e})),Bv("falloffMode",0,(function(e,t){this.light.falloffMode=e})),Bv("shadowType",0,(function(e,t){this.light.shadowType=e})),Bv("vsmBlurSize",11,(function(e,t){this.light.vsmBlurSize=e})),Bv("vsmBlurMode",1,(function(e,t){this.light.vsmBlurMode=e})),Bv("vsmBias",.0025,(function(e,t){this.light.vsmBias=ce.clamp(e,0,1)})),Bv("cookieAsset",null,(function(e,t){if(!this._cookieAssetId||!(e instanceof kd&&e.id===this._cookieAssetId||e===this._cookieAssetId))if(this.onCookieAssetRemove(),this._cookieAssetId=null,e instanceof kd)this.data.cookieAsset=e.id,this._cookieAssetId=e.id,this.onCookieAssetAdd(e);else if("number"==typeof e){this._cookieAssetId=e;var i=this.system.app.assets.get(e);i?this.onCookieAssetAdd(i):(this._cookieAssetAdd=!0,this.system.app.assets.on("add:"+this._cookieAssetId,this.onCookieAssetAdd,this))}})),Bv("cookie",null,(function(e,t){this.light.cookie=e})),Bv("cookieIntensity",1,(function(e,t){this.light.cookieIntensity=ce.clamp(e,0,1)})),Bv("cookieFalloff",!0,(function(e,t){this.light.cookieFalloff=e})),Bv("cookieChannel","rgb",(function(e,t){this.light.cookieChannel=e})),Bv("cookieAngle",0,(function(e,t){if(0!==e||null!==this.cookieScale){this._cookieMatrix||(this._cookieMatrix=new ve);var i=1,n=1;this.cookieScale&&(i=this.cookieScale.x,n=this.cookieScale.y);var s=Math.cos(e*ce.DEG_TO_RAD),r=Math.sin(e*ce.DEG_TO_RAD);this._cookieMatrix.set(s/i,-r/i,r/n,s/n),this.light.cookieTransform=this._cookieMatrix}else this.light.cookieTransform=null})),Bv("cookieScale",null,(function(e,t){if(null!==e||0!==this.cookieAngle){this._cookieMatrix||(this._cookieMatrix=new ve);var i=e.x,n=e.y,s=Math.cos(this.cookieAngle*ce.DEG_TO_RAD),r=Math.sin(this.cookieAngle*ce.DEG_TO_RAD);this._cookieMatrix.set(s/i,-r/i,r/n,s/n),this.light.cookieTransform=this._cookieMatrix}else this.light.cookieTransform=null}),!0),Bv("cookieOffset",null,(function(e,t){this.light.cookieOffset=e}),!0),Bv("shadowUpdateMode",2,(function(e,t){this.light.shadowUpdateMode=e}),!0),Bv("mask",1,(function(e,t){this.light.mask=e})),Bv("affectDynamic",!0,(function(e,t){e?this.light.mask|=1:this.light.mask&=-2,this.light.layersDirty()})),Bv("affectLightmapped",!1,(function(e,t){e?(this.light.mask|=2,this.bake&&(this.light.mask&=-5)):(this.light.mask&=-3,this.bake&&(this.light.mask|=4))})),Bv("bake",!1,(function(e,t){e?(this.light.mask|=4,this.affectLightmapped&&(this.light.mask&=-3)):(this.light.mask&=-5,this.affectLightmapped&&(this.light.mask|=2)),this.light.layersDirty()})),Bv("bakeDir",!0,(function(e,t){this.light.bakeDir=e})),Bv("isStatic",!1,(function(e,t){this.light.isStatic=e})),Bv("layers",[0],(function(e,t){for(var i=0;i<t.length;i++){var n=this.system.app.scene.layers.getLayerById(t[i]);n&&n.removeLight(this)}for(var s=0;s<e.length;s++){var r=this.system.app.scene.layers.getLayerById(e[s]);r&&this.enabled&&this.entity.enabled&&r.addLight(this)}})),Ov.push("penumbraSize"),kv.push(1);var Nv=function(){for(var e=Ov,t=kv,i=0;i<e.length;i++){var n=t[i];n&&n.clone?this[e[i]]=n.clone():this[e[i]]=n}},Uv=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="light",i.ComponentType=Fv,i.DataType=Nv,i.on("beforeremove",i._onRemoveComponent,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(t,i){for(var n=Ov,s={},r=0,a=n.length;r<a;r++){var o=n[r];s[o]=i[o]}s.type||(s.type=t.data.type),t.data.type=s.type,s.layers&&Array.isArray(s.layers)&&(s.layers=s.layers.slice(0)),s.color&&Array.isArray(s.color)&&(s.color=new ue(s.color[0],s.color[1],s.color[2])),s.cookieOffset&&s.cookieOffset instanceof Array&&(s.cookieOffset=new ge(s.cookieOffset[0],s.cookieOffset[1])),s.cookieScale&&s.cookieScale instanceof Array&&(s.cookieScale=new ge(s.cookieScale[0],s.cookieScale[1])),s.enable&&(console.warn("WARNING: enable: Property is deprecated. Set enabled property instead."),s.enabled=s.enable),s.shape||(s.shape=0);var h=new kc(this.app.graphicsDevice);h.type=Ic[s.type],h._node=t.entity,h._scene=this.app.scene,t.data.light=h,e.prototype.initializeComponentData.call(this,t,s,n)},i._onRemoveComponent=function(e,t){t.onRemove()},i.cloneComponent=function(e,t){for(var i,n=e.light,s=[],r=Ov,a=0;a<r.length;a++)"light"!==(i=r[a])&&(n[i]&&n[i].clone?s[i]=n[i].clone():s[i]=n[i]);return this.addComponent(t,s)},i.changeType=function(e,t,i){t!==i&&(e.light.type=Ic[i])},t}(vf),zv=["x","y","z","w"],Vv=[void 0,void 0,ge,me,ve];function Gv(e,t,i,n){switch(t.type){case"boolean":return!!i;case"number":if("number"==typeof i)return i;if("string"==typeof i){var s=parseInt(i,10);return isNaN(s)?null:s}return"boolean"==typeof i?0+i:null;case"json":var r={};if(Array.isArray(t.schema)){i&&"object"==typeof i||(i={});for(var a=0;a<t.schema.length;a++){var o=t.schema[a];if(o.name)if(o.array){r[o.name]=[];for(var h=Array.isArray(i[o.name])?i[o.name]:[],l=0;l<h.length;l++)r[o.name].push(Gv(e,o,h[l]))}else{var c=i.hasOwnProperty(o.name)?i[o.name]:o.default;r[o.name]=Gv(e,o,c)}}}return r;case"asset":return i instanceof kd?i:"number"==typeof i?e.assets.get(i)||null:"string"==typeof i&&e.assets.get(parseInt(i,10))||null;case"entity":return i instanceof go?i:"string"==typeof i?e.getEntityFromIndex(i):null;case"rgb":case"rgba":if(i instanceof ue)return n instanceof ue?(n.copy(i),n):i.clone();if(i instanceof Array&&i.length>=3&&i.length<=4){for(var u=0;u<i.length;u++)if("number"!=typeof i[u])return null;return n||(n=new ue),n.r=i[0],n.g=i[1],n.b=i[2],n.a=3===i.length?1:i[3],n}return"string"==typeof i&&/#([0-9abcdef]{2}){3,4}/i.test(i)?(n||(n=new ue),n.fromString(i),n):null;case"vec2":case"vec3":case"vec4":var d=parseInt(t.type.slice(3),10),f=Vv[d];if(i instanceof f)return n instanceof f?(n.copy(i),n):i.clone();if(i instanceof Array&&i.length===d){for(var p=0;p<i.length;p++)if("number"!=typeof i[p])return null;n||(n=new f);for(var m=0;m<d;m++)n[zv[m]]=i[m];return n}return null;case"curve":if(i){var _;if(i instanceof fe||i instanceof pe)_=i.clone();else(_=new(i.keys[0]instanceof Array?pe:fe)(i.keys)).type=i.type;return _}}return i}var Hv=function(){function e(e){this.scriptType=e,this.index={}}var t=e.prototype;return t.add=function(t,i){this.index[t]||e.reservedNames.has(t)||(this.index[t]=i,Object.defineProperty(this.scriptType.prototype,t,{get:function(){return this.__attributes[t]},set:function(e){var n="attr",s="attr:"+t,r=this.__attributes[t],a=r;if(r&&"json"!==i.type&&"entity"!==i.type&&r.clone&&(this._callbacks[n]||this._callbacks[s])&&(a=r.clone()),i.array){if(this.__attributes[t]=[],e)for(var o=0,h=e.length;o<h;o++)this.__attributes[t].push(Gv(this.app,i,e[o],r?r[o]:null))}else this.__attributes[t]=Gv(this.app,i,e,r);this.fire(n,t,this.__attributes[t],a),this.fire(s,this.__attributes[t],a)}}))},t.remove=function(e){return!!this.index[e]&&(delete this.index[e],delete this.scriptType.prototype[e],!0)},t.has=function(e){return!!this.index[e]},t.get=function(e){return this.index[e]||null},e}();Hv.reservedNames=new Set(["app","entity","enabled","_enabled","_enabledOld","_destroyed","__attributes","__attributesRaw","__scriptType","__executionOrder","_callbacks","has","get","on","off","fire","once","hasEvent"]);var Wv="initialize",Xv="postInitialize",jv=function(e){function t(t,i){var n;return(n=e.call(this,t,i)||this)._scripts=[],n._updateList=new re({sortBy:"__executionOrder"}),n._postUpdateList=new re({sortBy:"__executionOrder"}),n._scriptsIndex={},n._destroyedScripts=[],n._destroyed=!1,n._scriptsData=null,n._oldState=!0,n._enabled=!0,n._beingEnabled=!1,n._isLoopingThroughScripts=!1,n._executionOrder=-1,n.on("set_enabled",n._onSetEnabled,ee(n)),n}Q(t,e);var i=t.prototype;return i.onEnable=function(){this._beingEnabled=!0,this._checkState(),this.entity._beingEnabled||this.onPostStateChange(),this._beingEnabled=!1},i.onDisable=function(){this._checkState()},i.onPostStateChange=function(){for(var e=this._beginLooping(),t=0,i=this.scripts.length;t<i;t++){var n=this.scripts[t];n._initialized&&!n._postInitialized&&n.enabled&&(n._postInitialized=!0,n.postInitialize&&this._scriptMethod(n,Xv))}this._endLooping(e)},i._beginLooping=function(){var e=this._isLoopingThroughScripts;return this._isLoopingThroughScripts=!0,e},i._endLooping=function(e){this._isLoopingThroughScripts=e,this._isLoopingThroughScripts||this._removeDestroyedScripts()},i._onSetEnabled=function(e,t,i){this._beingEnabled=!0,this._checkState(),this._beingEnabled=!1},i._checkState=function(){var e=this.enabled&&this.entity.enabled;if(e!==this._oldState){this._oldState=e,this.fire(e?"enable":"disable"),this.fire("state",e),e?this.system._addComponentToEnabled(this):this.system._removeComponentFromEnabled(this);for(var t=this._beginLooping(),i=0,n=this.scripts.length;i<n;i++){var s=this.scripts[i];s.enabled=s._enabled}this._endLooping(t)}},i._onBeforeRemove=function(){this.fire("remove");for(var e=this._beginLooping(),t=0;t<this.scripts.length;t++){var i=this.scripts[t];i&&this.destroy(i.__scriptType.__name)}this._endLooping(e)},i._removeDestroyedScripts=function(){var e=this._destroyedScripts.length;if(e){for(var t=0;t<e;t++){var i=this._destroyedScripts[t];this._removeScriptInstance(i)}this._destroyedScripts.length=0,this._resetExecutionOrder(0,this._scripts.length)}},i._onInitializeAttributes=function(){for(var e=0,t=this.scripts.length;e<t;e++)this.scripts[e].__initializeAttributes()},i._scriptMethod=function(e,t,i){e[t](i)},i._onInitialize=function(){for(var e=this._scripts,t=this._beginLooping(),i=0,n=e.length;i<n;i++){var s=e[i];!s._initialized&&s.enabled&&(s._initialized=!0,s.initialize&&this._scriptMethod(s,Wv))}this._endLooping(t)},i._onPostInitialize=function(){this.onPostStateChange()},i._onUpdate=function(e){var t=this._updateList;if(t.length){var i=this._beginLooping();for(t.loopIndex=0;t.loopIndex<t.length;t.loopIndex++){var n=t.items[t.loopIndex];n.enabled&&this._scriptMethod(n,"update",e)}this._endLooping(i)}},i._onPostUpdate=function(e){var t=this._postUpdateList;if(t.length){var i=this._beginLooping();for(t.loopIndex=0;t.loopIndex<t.length;t.loopIndex++){var n=t.items[t.loopIndex];n.enabled&&this._scriptMethod(n,"postUpdate",e)}this._endLooping(i)}},i._insertScriptInstance=function(e,t,i){-1===t?(this._scripts.push(e),e.__executionOrder=i,e.update&&this._updateList.append(e),e.postUpdate&&this._postUpdateList.append(e)):(this._scripts.splice(t,0,e),e.__executionOrder=t,this._resetExecutionOrder(t+1,i+1),e.update&&this._updateList.insert(e),e.postUpdate&&this._postUpdateList.insert(e))},i._removeScriptInstance=function(e){var t=this._scripts.indexOf(e);return-1===t||(this._scripts.splice(t,1),e.update&&this._updateList.remove(e),e.postUpdate&&this._postUpdateList.remove(e)),t},i._resetExecutionOrder=function(e,t){for(var i=e;i<t;i++)this._scripts[i].__executionOrder=i},i._resolveEntityScriptAttribute=function(e,t,i,n,s,r){if(e.array){var a=i.length;if(!a)return;for(var o=i.slice(),h=0;h<a;h++){var l=o[h]instanceof Zd?o[h].getGuid():o[h];r[l]&&(o[h]=n?r[l].getGuid():r[l])}s[t]=o}else{if(i instanceof Zd)i=i.getGuid();else if("string"!=typeof i)return;r[i]&&(s[t]=r[i])}},i.has=function(e){if("string"==typeof e)return!!this._scriptsIndex[e];if(!e)return!1;var t=e,i=t.__name,n=this._scriptsIndex[i];return(n&&n.instance)instanceof t},i.get=function(e){if("string"==typeof e){var t=this._scriptsIndex[e];return t?t.instance:null}if(!e)return null;var i=e,n=i.__name,s=this._scriptsIndex[n],r=s&&s.instance;return r instanceof i?r:null},i.create=function(e,t){void 0===t&&(t={});var i=this,n=e,s=e;if("string"==typeof n?n=this.system.app.scripts.get(n):n&&(s=n.__name),n){if(!this._scriptsIndex[s]||!this._scriptsIndex[s].instance){var r=new n({app:this.system.app,entity:this.entity,enabled:!t.hasOwnProperty("enabled")||t.enabled,attributes:t.attributes}),a=this._scripts.length,o=-1;return"number"==typeof t.ind&&-1!==t.ind&&a>t.ind&&(o=t.ind),this._insertScriptInstance(r,o,a),this._scriptsIndex[s]={instance:r,onSwap:function(){i.swap(s)}},this[s]=r,t.preloading||r.__initializeAttributes(),this.fire("create",s,r),this.fire("create:"+s,r),this.system.app.scripts.on("swap:"+s,this._scriptsIndex[s].onSwap),t.preloading||(r.enabled&&!r._initialized&&(r._initialized=!0,r.initialize&&this._scriptMethod(r,Wv)),r.enabled&&!r._postInitialized&&(r._postInitialized=!0,r.postInitialize&&this._scriptMethod(r,Xv))),r}}else this._scriptsIndex[s]={awaiting:!0,ind:this._scripts.length};return null},i.destroy=function(e){var t=e,i=e;"string"==typeof i?i=this.system.app.scripts.get(i):i&&(t=i.__name);var n=this._scriptsIndex[t];if(delete this._scriptsIndex[t],!n)return!1;var s=n.instance;if(s&&!s._destroyed)if(s.enabled=!1,s._destroyed=!0,this._isLoopingThroughScripts)this._destroyedScripts.push(s);else{var r=this._removeScriptInstance(s);r>=0&&this._resetExecutionOrder(r,this._scripts.length)}return this.system.app.scripts.off("swap:"+t,n.onSwap),delete this[t],this.fire("destroy",t,s||null),this.fire("destroy:"+t,s||null),s&&s.fire("destroy"),!0},i.swap=function(e){var t=e,i=e;"string"==typeof i?i=this.system.app.scripts.get(i):i&&(t=i.__name);var n=this._scriptsIndex[t];if(!n||!n.instance)return!1;var s=n.instance,r=this._scripts.indexOf(s),a=new i({app:this.system.app,entity:this.entity,enabled:s.enabled,attributes:s.__attributes});return!!a.swap&&(a.__initializeAttributes(),this._scripts[r]=a,this._scriptsIndex[t].instance=a,this[t]=a,a.__executionOrder=r,s.update&&this._updateList.remove(s),s.postUpdate&&this._postUpdateList.remove(s),a.update&&this._updateList.insert(a),a.postUpdate&&this._postUpdateList.insert(a),this._scriptMethod(a,"swap",s),this.fire("swap",t,a),this.fire("swap:"+t,a),!0)},i.resolveDuplicatedEntityReferenceProperties=function(e,t){var i=this.entity.script;for(var n in e._scriptsIndex){var s=this.system.app.scripts.get(n);if(s){var r=e._scriptsIndex[n];if(r&&r.instance){var a=i[n].__attributesRaw,o=i[n].__attributes;if(a||o){var h=!!a,l=r.instance.__attributes;for(var c in l)if(l[c]){var u=s.attributes.get(c);if(u)if("entity"===u.type)this._resolveEntityScriptAttribute(u,c,l[c],h,a||o,t);else if("json"===u.type&&Array.isArray(u.schema))for(var d=l[c],f=a?a[c]:o[c],p=0;p<u.schema.length;p++){var m=u.schema[p];if("entity"===m.type)if(u.array)for(var _=0;_<d.length;_++)this._resolveEntityScriptAttribute(m,m.name,d[_][m.name],h,f[_],t);else this._resolveEntityScriptAttribute(m,m.name,d[m.name],h,f,t)}}}}}}},i.move=function(e,t){var i=this._scripts.length;if(t>=i||t<0)return!1;var n=e,s=e;"string"!=typeof s?s=e.__name:n=null;var r=this._scriptsIndex[s];if(!r||!r.instance)return!1;var a=r.instance;if(n&&!(a instanceof n))return!1;var o=this._scripts.indexOf(a);return-1!==o&&o!==t&&(this._scripts.splice(t,0,this._scripts.splice(o,1)[0]),this._resetExecutionOrder(0,i),this._updateList.sort(),this._postUpdateList.sort(),this.fire("move",s,a,t,o),this.fire("move:"+s,a,t,o),!0)},Z(t,[{key:"scripts",get:function(){return this._scripts},set:function(e){for(var t in this._scriptsData=e,e)if(e.hasOwnProperty(t)){var i=this._scriptsIndex[t];if(i){if("boolean"==typeof e[t].enabled&&(i.enabled=!!e[t].enabled),"object"==typeof e[t].attributes)for(var n in e[t].attributes)if(!Hv.reservedNames.has(n)){if(!i.__attributes.hasOwnProperty(n)){var s=this.system.app.scripts.get(t);s&&s.attributes.add(n,{})}i[n]=e[t].attributes[n]}}else console.log(this.order)}}},{key:"enabled",get:function(){return this._enabled},set:function(e){var t=this._enabled;this._enabled=e,this.fire("set","enabled",t,e)}}]),t}(gf),qv=function(){this.enabled=!0},Yv=0,Kv=function(e){function t(t){var i;return(i=e.call(this,t)||this).id="script",i.ComponentType=jv,i.DataType=qv,i._components=new re({sortBy:"_executionOrder"}),i._enabledComponents=new re({sortBy:"_executionOrder"}),i.preloading=!0,i.on("beforeremove",i._onBeforeRemove,ee(i)),i.app.systems.on("initialize",i._onInitialize,ee(i)),i.app.systems.on("postInitialize",i._onPostInitialize,ee(i)),i.app.systems.on("update",i._onUpdate,ee(i)),i.app.systems.on("postUpdate",i._onPostUpdate,ee(i)),i}Q(t,e);var i=t.prototype;return i.initializeComponentData=function(e,t){if(e._executionOrder=Yv++,this._components.append(e),Yv>Number.MAX_SAFE_INTEGER&&this._resetExecutionOrder(),e.enabled=!t.hasOwnProperty("enabled")||!!t.enabled,e.enabled&&e.entity.enabled&&this._enabledComponents.append(e),t.hasOwnProperty("order")&&t.hasOwnProperty("scripts")){e._scriptsData=t.scripts;for(var i=0;i<t.order.length;i++)e.create(t.order[i],{enabled:t.scripts[t.order[i]].enabled,attributes:t.scripts[t.order[i]].attributes,preloading:this.preloading})}},i.cloneComponent=function(e,t){for(var i=[],n={},s=0;s<e.script._scripts.length;s++){var r=e.script._scripts[s],a=r.__scriptType.__name;i.push(a);var o={};for(var h in r.__attributes)o[h]=r.__attributes[h];n[a]={enabled:r._enabled,attributes:o}}for(var l in e.script._scriptsIndex)l.awaiting&&i.splice(l.ind,0,l);var c={enabled:e.script.enabled,order:i,scripts:n};return this.addComponent(t,c)},i._resetExecutionOrder=function(){Yv=0;for(var e=0,t=this._components.length;e<t;e++)this._components.items[e]._executionOrder=Yv++},i._callComponentMethod=function(e,t,i){for(e.loopIndex=0;e.loopIndex<e.length;e.loopIndex++)e.items[e.loopIndex][t](i)},i._onInitialize=function(){this.preloading=!1,this._callComponentMethod(this._components,"_onInitializeAttributes"),this._callComponentMethod(this._enabledComponents,"_onInitialize")},i._onPostInitialize=function(){this._callComponentMethod(this._enabledComponents,"_onPostInitialize")},i._onUpdate=function(e){this._callComponentMethod(this._enabledComponents,"_onUpdate",e)},i._onPostUpdate=function(e){this._callComponentMethod(this._enabledComponents,"_onPostUpdate",e)},i._addComponentToEnabled=function(e){this._enabledComponents.insert(e)},i._removeComponentFromEnabled=function(e){this._enabledComponents.remove(e)},i._onBeforeRemove=function(e,t){this._components.items.indexOf(t)>=0&&t._onBeforeRemove(),this._removeComponentFromEnabled(t),this._components.remove(t)},i.destroy=function(){e.prototype.destroy.call(this),this.app.systems.off("initialize",this._onInitialize,this),this.app.systems.off("postInitialize",this._onPostInitialize,this),this.app.systems.off("update",this._onUpdate,this),this.app.systems.off("postUpdate",this._onPostUpdate,this)},t}(vf),Zv=function(e){function t(){var t;return(t=e.call(this)||this)._meshes=null,t}Q(t,e);var i=t.prototype;return i.destroy=function(){this.meshes=null},i.decRefMeshes=function(){if(this._meshes)for(var e=this._meshes.length,t=0;t<e;t++){var i=this._meshes[t];i&&(i.decRefCount(),i.refCount<1&&(i.destroy(),this._meshes[t]=null))}},i.incRefMeshes=function(){if(this._meshes)for(var e=this._meshes.length,t=0;t<e;t++)this._meshes[t]&&this._meshes[t].incRefCount()},Z(t,[{key:"meshes",get:function(){return this._meshes},set:function(e){this.decRefMeshes(),this._meshes=e,this.incRefMeshes(),this.fire("set:meshes",e)}}]),t}(p);function $v(e){var t=this;if(t.resource){var i=e.resource,n=i.renders&&i.renders[t.data.renderIndex];n&&(t.resource.meshes=n.resource.meshes)}}function Qv(e){var t=this;t.registry.off("load:"+e.id,$v,t),t.registry.on("load:"+e.id,$v,t),t.registry.off("remove:"+e.id,Jv,t),t.registry.once("remove:"+e.id,Jv,t),e.resource?$v.call(t,e):t.registry.load(e)}function Jv(e){var t=this;t.registry.off("load:"+e.id,$v,t),t.resource&&t.resource.destroy()}var ey=function(){function e(e){this.handlerType="render",this._registry=e.assets}var t=e.prototype;return t.load=function(e,t,i){},t.open=function(e,t){return new Zv},t.patch=function(e,t){if(e.data.containerAsset){var i=t.get(e.data.containerAsset);i?Qv.call(e,i):t.once("add:"+e.data.containerAsset,Qv,e)}},e}(),ty=function(){function e(e,t,i,n){this._paths=e,this._input=t,this._output=i,this._interpolation=n}return Z(e,[{key:"paths",get:function(){return this._paths}},{key:"input",get:function(){return this._input}},{key:"output",get:function(){return this._output}},{key:"interpolation",get:function(){return this._interpolation}}]),e}(),iy=function(){function e(e,t){this._components=e,this._data=t}return Z(e,[{key:"components",get:function(){return this._components}},{key:"data",get:function(){return this._data}}]),e}();function ny(e,t){var i,n=function(e,t){switch(t){case i.DT_INT8:return new Int8Array(e.buffer,e.byteOffset,e.byteLength);case i.DT_INT16:return new Int16Array(e.buffer,e.byteOffset,e.byteLength/2);case i.DT_INT32:return new Int32Array(e.buffer,e.byteOffset,e.byteLength/4);case i.DT_UINT8:return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);case i.DT_UINT16:return new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2);case i.DT_UINT32:return new Uint32Array(e.buffer,e.byteOffset,e.byteLength/4);case i.DT_FLOAT32:return new Float32Array(e.buffer,e.byteOffset,e.byteLength/4)}return null},s=function(e){return e.num_components()*function(e){switch(e){case i.DT_INT8:return 1;case i.DT_INT16:return 2;case i.DT_INT32:return 4;case i.DT_UINT8:return 1;case i.DT_UINT16:return 2;case i.DT_UINT32:case i.DT_FLOAT32:return 4}return 1}(e.data_type())},r={0:0,1:1,5:2,2:3,7:4,8:5,4:6,3:7},a=function(e,t){for(var i=function(e,t,i){e[0]=t[0]-i[0],e[1]=t[1]-i[1],e[2]=t[2]-i[2]},n=function(e,t,i){e[0]=t[1]*i[2]-i[1]*t[2],e[1]=t[2]*i[0]-i[2]*t[0],e[2]=t[0]*i[1]-i[0]*t[1]},s=function(e,t){var i=e[t+0],n=e[t+1],s=e[t+2],r=1/Math.sqrt(i*i+n*n+s*s);e[t+0]*=r,e[t+1]*=r,e[t+2]*=r},r=function(e,t,i){for(var n=0;n<3;++n)e[n]=t[i+n]},a=t.length/3,o=e.length/3,h=new Float32Array(e.length),l=[0,0,0],c=[0,0,0],u=[0,0,0],d=[0,0,0],f=[0,0,0],p=[0,0,0],m=0;m<a;++m){var _=3*t[3*m+0],g=3*t[3*m+1],v=3*t[3*m+2];r(l,e,_),r(c,e,g),r(u,e,v),i(d,c,l),i(f,u,l),n(p,d,f),s(p,0);for(var y=0;y<3;++y)h[_+y]+=p[y],h[g+y]+=p[y],h[v+y]+=p[y]}for(var x=0;x<o;++x)s(h,3*x);return new Uint8Array(h.buffer)},o=function(e){var t=function(e){var t={},o=new i.DecoderBuffer;o.Init(e,e.length);var h=new i.Decoder;if(h.GetEncodedGeometryType(o)!==i.TRIANGULAR_MESH)return t.error="Failed to decode draco mesh: not a mesh",t;var l=new i.Mesh,c=h.DecodeBufferToMesh(o,l);if(!c||!c.ok()||0===l.ptr)return t.error="Failed to decode draco asset",t;var u=3*l.num_faces(),d=l.num_points()<=65535,f=u*(d?2:4),p=i._malloc(f);d?(h.GetTrianglesUInt16Array(l,f,p),t.indices=new Uint16Array(i.HEAPU16.buffer,p,u).slice().buffer):(h.GetTrianglesUInt32Array(l,f,p),t.indices=new Uint32Array(i.HEAPU32.buffer,p,u).slice().buffer),i._free(p);for(var m=[],_=0;_<l.num_attributes();++_)m.push(h.GetAttribute(l,_));m.sort((function(e,t){var i,n;return(null!=(i=r[e.attribute_type()])?i:r.length)-(null!=(n=r[t.attribute_type()])?n:r.length)})),t.attributes=m.map((function(e){return e.unique_id()}));var g=0,v=m.map((function(e){var t=g;return g+=4*Math.ceil(s(e)/4),t})),y=m.some((function(e){return 1===e.attribute_type()})),x=v[1];if(!y){for(var S=1;S<v.length;++S)v[S]+=12;g+=12}t.vertices=new ArrayBuffer(l.num_points()*g);for(var b=new Uint8Array(t.vertices),w=0;w<l.num_attributes();++w){var T=m[w],A=s(T),C=l.num_points()*A,E=i._malloc(C);h.GetAttributeDataArrayForAllPoints(l,T,T.data_type(),C,E);for(var M=new Uint8Array(i.HEAPU8.buffer,E,C),P=0;P<l.num_points();++P)for(var R=0;R<A;++R)b[P*g+v[w]+R]=M[P*A+R];if(!y&&0===T.attribute_type())for(var I=a(n(M,T.data_type()),d?new Uint16Array(t.indices):new Uint32Array(t.indices)),L=0;L<l.num_points();++L)for(var D=0;D<12;++D)b[L*g+x+D]=I[12*L+D];i._free(E)}return i.destroy(l),i.destroy(h),i.destroy(o),t}(new Uint8Array(e.buffer));self.postMessage({jobId:e.jobId,error:t.error,indices:t.indices,vertices:t.vertices,attributes:t.attributes},[t.indices,t.vertices].filter((function(e){return null!=e})))},h=[];self.onmessage=function(e){var t=e.data;switch(t.type){case"init":self.DracoDecoderModule({instantiateWasm:function(e,i){return WebAssembly.instantiate(t.module,e).then((function(e){return i(e)})).catch((function(e){return console.error("instantiate failed + "+e)})),{}}}).then((function(e){i=e,h.forEach((function(e){return o(e)}))}));break;case"decodeMesh":i?o(t):h.push(t)}}}var sy,ry,ay,oy,hy=function(){function e(){this.workers=[[],[],[]],this.jobId=0,this.jobQueue=[],this.jobCallbacks=new Map,this.run=function(e,t){e.postMessage({type:"decodeMesh",jobId:t.jobId,buffer:t.buffer},[t.buffer])}}var t=e.prototype;return t.init=function(e){var t=this;for(e.forEach((function(e){e.addEventListener("message",(function(i){var n=i.data,s=t.jobCallbacks.get(n.jobId);if(s&&s(n.error,{indices:n.indices,vertices:n.vertices,attributes:n.attributes}),t.jobCallbacks.delete(n.jobId),t.jobQueue.length>0){var r=t.jobQueue.shift();t.run(e,r)}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 i=this.jobQueue.shift();if(this.workers[0].length>0){var n=this.workers[0].shift();this.workers[1].push(n),this.run(n,i)}else{var s=this.workers[1].shift();this.workers[2].push(s),this.run(s,i)}}},t.enqueueJob=function(e,t){var i={jobId:this.jobId++,buffer:e};if(this.jobCallbacks.set(i.jobId,t),this.workers[0].length>0){var n=this.workers[0].shift();this.workers[1].push(n),this.run(n,i)}else if(this.workers[1].length>0){var s=this.workers[1].shift();this.workers[2].push(s),this.run(s,i)}else this.jobQueue.push(i)},e}(),ly=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()},cy=function(e){if(sy)return!0;if(!e)if(ry)e=ry;else{var t=X.getConfig("DracoDecoderModule");e=t?{jsUrl:t.glueUrl,wasmUrl:t.wasmUrl,numWorkers:t.numWorkers}:{jsUrl:"draco.wasm.js",wasmUrl:"draco.wasm.wasm",numWorkers:1}}return!(!e.jsUrl||!e.wasmUrl)&&(sy=new hy,Promise.all([(i=e.jsUrl,new Promise((function(e,t){var n={cache:!0,responseType:"text",retry:!0,maxRetries:3};Tr.get(i,n,(function(i,n){i?t(i):e(n)}))}))),ly(e.wasmUrl)]).then((function(t){for(var i=t[0],n=t[1],s=["/* draco */",i,"/* worker */","(\n"+ny.toString()+"\n)()\n\n"].join("\n"),r=new Blob([s],{type:"application/javascript"}),a=URL.createObjectURL(r),o=Math.max(1,Math.min(16,e.numWorkers||1)),h=[],l=0;l<o;++l){var c=new Worker(a);c.postMessage({type:"init",module:n}),h.push(c)}sy.init(h)})),!0);var i},uy=function(){function e(){this.gltf=void 0,this.nodes=void 0,this.scenes=void 0,this.animations=void 0,this.textures=void 0,this.materials=void 0,this.variants=void 0,this.meshVariants=void 0,this.meshDefaultMaterials=void 0,this.renders=void 0,this.skins=void 0,this.lights=void 0,this.cameras=void 0}return e.prototype.destroy=function(){this.renders&&this.renders.forEach((function(e){e.meshes=null}))},e}(),dy=function(e){return/^data:.*,.*$/i.test(e)},fy=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}},py=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}},my=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}},_y={POSITION:lt,NORMAL:ct,TANGENT:ut,COLOR_0:pt,JOINTS_0:ft,WEIGHTS_0:dt,TEXCOORD_0:_t,TEXCOORD_1:gt,TEXCOORD_2:vt,TEXCOORD_3:yt,TEXCOORD_4:xt,TEXCOORD_5:St,TEXCOORD_6:bt,TEXCOORD_7:wt},gy=((ay={})[lt]=0,ay[ct]=1,ay[ut]=2,ay[pt]=3,ay[ft]=4,ay[dt]=5,ay[_t]=6,ay[gt]=7,ay[vt]=8,ay[yt]=9,ay[xt]=10,ay[St]=11,ay[bt]=12,ay[wt]=13,ay),vy=function(e,t,i){for(var n=function(e){switch(e){case 0:return function(e){return Math.max(e/127,-1)};case 1:return function(e){return e/255};case 2:return function(e){return Math.max(e/32767,-1)};case 3:return function(e){return e/65535};default:return function(e){return e}}}(i),s=t.length,r=0;r<s;++r)e[r]=n(t[r]);return e},yy=function e(t,i,n){void 0===n&&(n=!1);var s,r=fy(t.type),a=function(e){switch(e){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5124:return Int32Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:return null}}(t.componentType);if(!a)return null;if(t.sparse){var o=t.sparse,h={count:o.count,type:"SCALAR"},l=e(Object.assign(h,o.indices),i,!0),c={count:o.count,type:t.type,componentType:t.componentType},u=e(Object.assign(c,o.values),i,!0);if(t.hasOwnProperty("bufferView"))s=e({bufferView:t.bufferView,byteOffset:t.byteOffset,componentType:t.componentType,count:t.count,type:t.type},i,!0).slice();else s=new a(t.count*r);for(var d=0;d<o.count;++d)for(var f=l[d],p=0;p<r;++p)s[f*r+p]=u[d*r+p]}else if(t.hasOwnProperty("bufferView")){var m=i[t.bufferView];if(n&&m.hasOwnProperty("byteStride")){for(var _=r*a.BYTES_PER_ELEMENT,g=new ArrayBuffer(t.count*_),v=new Uint8Array(g),y=0,x=0;x<t.count;++x)for(var S=(t.byteOffset||0)+x*m.byteStride,b=0;b<_;++b)v[y++]=m[S++];s=new a(g)}else s=new a(m.buffer,m.byteOffset+(t.byteOffset||0),t.count*r)}else s=new a(t.count*r);return s},xy=function(e,t){var i=yy(e,t,!0);if(i instanceof Float32Array||!e.normalized)return i;var n=new Float32Array(i.length);return vy(n,i,py(e.componentType)),n},Sy=function(e){var t=e.min,i=e.max;if(!t||!i)return null;if(e.normalized){var n=py(e.componentType);t=vy([],t,n),i=vy([],i,n)}return new Ie(new me(.5*(i[0]+t[0]),.5*(i[1]+t[1]),.5*(i[2]+t[2])),new me(.5*(i[0]-t[0]),.5*(i[1]-t[1]),.5*(i[2]-t[2])))},by=function(e){if(!e.hasOwnProperty("mode"))return 4;switch(e.mode){case 0:return 0;case 1:return 1;case 2:return 2;case 3:return 3;case 4:default:return 4;case 5:return 5;case 6:return 6}},wy=function(e,t){var i=e[lt];if(i&&3===i.components){var n;if(i.size!==i.stride){var s=i.stride/li[i.type],r=new hi[i.type](i.buffer,i.offset,i.count*s);n=new hi[i.type](3*i.count);for(var a=0;a<i.count;++a)n[3*a+0]=r[a*s+0],n[3*a+1]=r[a*s+1],n[3*a+2]=r[a*s+2]}else n=new hi[i.type](i.buffer,i.offset,3*i.count);var o=i.count;t||(t=function(e){for(var t=new Uint16Array(e),i=0;i<e;i++)t[i]=i;return t}(o));var h=na(n,t),l=new Float32Array(h.length);l.set(h),e[ct]={buffer:l.buffer,size:12,offset:0,stride:12,count:o,components:3,type:6}}},Ty=function(e){var t=new kd(e.name+"_clone",e.type,e.file,e.data,e.options);return t.loaded=!0,t.resource=function(e){var t=new Yn(e.device,e);return t._levels=function(e){for(var t=[],i=0;i<e._levels.length;++i){var n=[];if(e.cubemap)for(var s=0;s<6;++s)n.push(e._levels[i][s]);else n=e._levels[i];t.push(n)}return t}(e),t}(e.resource),e.registry.add(t),t},Ay=function(e,t,i){var n=t[lt];if(!n)return null;var s,r,a,o,h,l,c=n.count,u=[];for(var d in t)t.hasOwnProperty(d)&&u.push({semantic:d,components:t[d].components,type:t[d].type,normalize:!!t[d].normalize});u.sort((function(e,t){return gy[e.semantic]-gy[t.semantic]}));var f=new Pi(e,u),p=!0;for(s=0;s<f.elements.length;++s)if(l=(o=t[(h=f.elements[s]).name]).offset-n.offset,o.buffer!==n.buffer||o.stride!==h.stride||o.size!==h.size||l!==h.offset){p=!1;break}var m,_,g,v=new Ei(e,f,c,0),y=v.lock(),x=new Uint32Array(y);if(p)m=new Uint32Array(n.buffer,n.offset,c*v.format.size/4),x.set(m);else for(s=0;s<v.format.elements.length;++s){_=(h=v.format.elements[s]).stride/4,g=(o=t[h.name]).stride/4,m=new Uint32Array(o.buffer,o.offset,(o.count-1)*g+(o.size+3)/4);var S=0,b=h.offset/4,w=Math.floor((o.size+3)/4);for(r=0;r<c;++r){for(a=0;a<w;++a)x[b+a]=m[S+a];S+=g,b+=_}}return i&&function(e){var t,i,n=[],s=[],r=[];for(t=0;t<e.format.elements.length;++t){var a=e.format.elements[t];if(a.name===_t||a.name===gt)switch(a.dataType){case 6:n.push({offset:a.offset/4+1,stride:a.stride/4});break;case 3:s.push({offset:a.offset/2+1,stride:a.stride/2});break;case 1:r.push({offset:a.offset+1,stride:a.stride})}}var o=function(n,s,r){var a=new s(e.storage);for(t=0;t<n.length;++t){var o=n[t].offset,h=n[t].stride;for(i=0;i<e.numVertices;++i)a[o]=r-a[o],o+=h}};n.length>0&&o(n,Float32Array,1),s.length>0&&o(s,Uint16Array,65535),r.length>0&&o(r,Uint8Array,255)}(v),v.unlock(),v},Cy=function(e,t,i,n,s,r,a){var o,h=new Jr(e);h.aabb=Sy(i[t.attributes.POSITION]);for(var l=[],c=0,u=Object.entries(t.attributes);c<u.length;c++){var d,f=u[c],p=f[0],m=i[f[1]],_=_y[p],g=py(m.componentType);l.push({semantic:_,components:fy(m.type),type:g,normalize:null!=(d=m.normalized)?d:_===pt&&(1===g||3===g)})}if(a.push(new Promise((function(i,s){var r,a,o=t.extensions.KHR_draco_mesh_compression;r=n[o.bufferView].slice().buffer,a=function(n,r){if(n)console.log(n),s(n);else{for(var a,c={},u=0,d=Object.entries(o.attributes);u<d.length;u++){var f=d[u],p=f[0],m=f[1];c[_y[p]]=r.attributes.indexOf(m)}l.sort((function(e,t){return c[e.semantic]-c[t.semantic]})),null!=(a=t.attributes)&&a.NORMAL||l.splice(1,0,{semantic:"NORMAL",components:3,type:6});var _=new Pi(e,l),g=r.vertices.byteLength/_.size,v=g<=65535?1:2,y=r.indices.byteLength/(g<=65535?2:4),x=new Ei(e,_,g,0,r.vertices),S=new As(e,v,y,0,r.indices);h.vertexBuffer=x,h.indexBuffer[0]=S,h.primitive[0].type=by(t),h.primitive[0].base=0,h.primitive[0].count=S?y:g,h.primitive[0].indexed=!!S,i()}},cy()&&sy.enqueueJob(r,a)}))),null!=t&&null!=(o=t.extensions)&&o.KHR_materials_variants){var v=t.extensions.KHR_materials_variants,y={};v.mappings.forEach((function(e){e.variants.forEach((function(t){y[t]=e.material}))})),s[h.id]=y}return r[h.id]=t.material,h},Ey=function(e,t,i,n,s,r,a,o,h,l){var c=[];return t.primitives.forEach((function(u){var d;if(null!=(d=u.extensions)&&d.KHR_draco_mesh_compression)c.push(Cy(e,u,i,n,a,o,l));else{var f=u.hasOwnProperty("indices")?yy(i[u.indices],n,!0):null,p=function(e,t,i,n,s,r,a){var o={},h=[];for(var l in t)t.hasOwnProperty(l)&&_y.hasOwnProperty(l)&&(o[l]=t[l],h.push(l+":"+t[l]));h.sort();var c=h.join(),u=a[c];if(!u){var d={};for(var f in o){var p=n[t[f]],m=yy(p,s),_=s[p.bufferView],g=_y[f],v=fy(p.type)*my(p.componentType),y=_&&_.hasOwnProperty("byteStride")?_.byteStride:v;d[g]={buffer:m.buffer,size:v,offset:m.byteOffset,stride:y,count:p.count,components:fy(p.type),type:py(p.componentType),normalize:p.normalized}}d.hasOwnProperty(ct)||wy(d,i),u=Ay(e,d,r),a[c]=u}return u}(e,u.attributes,f,i,n,s,r),m=by(u),_=new Jr(e);if(_.vertexBuffer=p,_.primitive[0].type=m,_.primitive[0].base=0,_.primitive[0].indexed=null!==f,null!==f){var g;2!==(g=f instanceof Uint8Array?0:f instanceof Uint16Array?1:2)||e.extUintElement||(g=1,f=new Uint16Array(f)),0===g&&e.isWebGPU&&(g=1,f=new Uint16Array(f));var v=new As(e,g,f.length,0,f);_.indexBuffer[0]=v,_.primitive[0].count=f.length}else _.primitive[0].count=p.numVertices;if(u.hasOwnProperty("extensions")&&u.extensions.hasOwnProperty("KHR_materials_variants")){var y=u.extensions.KHR_materials_variants,x={};y.mappings.forEach((function(e){e.variants.forEach((function(t){x[t]=e.material}))})),a[_.id]=x}o[_.id]=u.material;var S=i[u.attributes.POSITION];if(_.aabb=Sy(S),u.hasOwnProperty("targets")){var b=[];u.targets.forEach((function(e,s){var r={};e.hasOwnProperty("POSITION")&&(S=i[e.POSITION],r.deltaPositions=xy(S,n),r.deltaPositionsType=6,r.aabb=Sy(S)),e.hasOwnProperty("NORMAL")&&(S=i[e.NORMAL],r.deltaNormals=xy(S,n),r.deltaNormalsType=6),t.hasOwnProperty("extras")&&t.extras.hasOwnProperty("targetNames")?r.name=t.extras.targetNames[s]:r.name=s.toString(10),t.hasOwnProperty("weights")&&(r.defaultWeight=t.weights[s]),r.preserveData=h.morphPreserveData,b.push(new Vc(r))})),_.morph=new zc(b,e,{preferHighPrecision:h.morphPreferHighPrecision})}c.push(_)}})),c},My=function(e,t,i){var n,s,r=e.texCoord;if(r)for(s=0;s<i.length;++s)t[i[s]+"MapUv"]=r;var a=null==(n=e.extensions)?void 0:n.KHR_texture_transform;if(a){var o=a.offset||[0,0],h=a.scale||[1,1],l=a.rotation?-a.rotation*ce.RAD_TO_DEG:0,c=new ge(h[0],h[1]),u=new ge(o[0],1-h[1]-o[1]);for(s=0;s<i.length;++s)t[i[s]+"MapTiling"]=c,t[i[s]+"MapOffset"]=u,t[i[s]+"MapRotation"]=l}},Py=function(e,t,i){var n,s;if(e.hasOwnProperty("diffuseFactor")?(n=e.diffuseFactor,t.diffuse.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2)),t.opacity=n[3]):(t.diffuse.set(1,1,1),t.opacity=1),e.hasOwnProperty("diffuseTexture")){var r=e.diffuseTexture;s=i[r.index],t.diffuseMap=s,t.diffuseMapChannel="rgb",t.opacityMap=s,t.opacityMapChannel="a",My(r,t,["diffuse","opacity"])}if(t.useMetalness=!1,e.hasOwnProperty("specularFactor")?(n=e.specularFactor,t.specular.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2))):t.specular.set(1,1,1),e.hasOwnProperty("glossinessFactor")?t.gloss=e.glossinessFactor:t.gloss=1,e.hasOwnProperty("specularGlossinessTexture")){var a=e.specularGlossinessTexture;t.specularEncoding="srgb",t.specularMap=t.glossMap=i[a.index],t.specularMapChannel="rgb",t.glossMapChannel="a",My(a,t,["gloss","metalness"])}},Ry=function(e,t,i){if(e.hasOwnProperty("clearcoatFactor")?t.clearCoat=.25*e.clearcoatFactor:t.clearCoat=0,e.hasOwnProperty("clearcoatTexture")){var n=e.clearcoatTexture;t.clearCoatMap=i[n.index],t.clearCoatMapChannel="r",My(n,t,["clearCoat"])}if(e.hasOwnProperty("clearcoatRoughnessFactor")?t.clearCoatGloss=e.clearcoatRoughnessFactor:t.clearCoatGloss=0,e.hasOwnProperty("clearcoatRoughnessTexture")){var s=e.clearcoatRoughnessTexture;t.clearCoatGlossMap=i[s.index],t.clearCoatGlossMapChannel="g",My(s,t,["clearCoatGloss"])}if(e.hasOwnProperty("clearcoatNormalTexture")){var r=e.clearcoatNormalTexture;t.clearCoatNormalMap=i[r.index],My(r,t,["clearCoatNormal"]),r.hasOwnProperty("scale")&&(t.clearCoatBumpiness=r.scale)}t.clearCoatGlossInvert=!0},Iy=function(e,t,i){t.useLighting=!1,t.emissive.copy(t.diffuse),t.emissiveTint=t.diffuseTint,t.emissiveMap=t.diffuseMap,t.emissiveMapUv=t.diffuseMapUv,t.emissiveMapTiling.copy(t.diffuseMapTiling),t.emissiveMapOffset.copy(t.diffuseMapOffset),t.emissiveMapRotation=t.diffuseMapRotation,t.emissiveMapChannel=t.diffuseMapChannel,t.emissiveVertexColor=t.diffuseVertexColor,t.emissiveVertexColorChannel=t.diffuseVertexColorChannel,t.useLighting=!1,t.useSkybox=!1,t.diffuse.set(0,0,0),t.diffuseTint=!1,t.diffuseMap=null,t.diffuseVertexColor=!1},Ly=function(e,t,i){if(t.useMetalnessSpecularColor=!0,e.hasOwnProperty("specularColorTexture")&&(t.specularEncoding="srgb",t.specularMap=i[e.specularColorTexture.index],t.specularMapChannel="rgb",My(e.specularColorTexture,t,["specular"])),e.hasOwnProperty("specularColorFactor")){var n=e.specularColorFactor;t.specular.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2))}else t.specular.set(1,1,1);e.hasOwnProperty("specularFactor")?t.specularityFactor=e.specularFactor:t.specularityFactor=1,e.hasOwnProperty("specularTexture")&&(t.specularityFactorMapChannel="a",t.specularityFactorMap=i[e.specularTexture.index],My(e.specularTexture,t,["specularityFactor"]))},Dy=function(e,t,i){e.hasOwnProperty("ior")&&(t.refractionIndex=1/e.ior)},Oy=function(e,t,i){t.blendType=2,t.useDynamicRefraction=!0,e.hasOwnProperty("transmissionFactor")&&(t.refraction=e.transmissionFactor),e.hasOwnProperty("transmissionTexture")&&(t.refractionMapChannel="r",t.refractionMap=i[e.transmissionTexture.index],My(e.transmissionTexture,t,["refraction"]))},ky=function(e,t,i){if(t.useSheen=!0,e.hasOwnProperty("sheenColorFactor")){var n=e.sheenColorFactor;t.sheen.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2))}else t.sheen.set(1,1,1);e.hasOwnProperty("sheenColorTexture")&&(t.sheenMap=i[e.sheenColorTexture.index],t.sheenEncoding="srgb",My(e.sheenColorTexture,t,["sheen"])),e.hasOwnProperty("sheenRoughnessFactor")?t.sheenGloss=e.sheenRoughnessFactor:t.sheenGloss=0,e.hasOwnProperty("sheenRoughnessTexture")&&(t.sheenGlossMap=i[e.sheenRoughnessTexture.index],t.sheenGlossMapChannel="a",My(e.sheenRoughnessTexture,t,["sheenGloss"])),t.sheenGlossInvert=!0},Fy=function(e,t,i){if(t.blendType=2,t.useDynamicRefraction=!0,e.hasOwnProperty("thicknessFactor")&&(t.thickness=e.thicknessFactor),e.hasOwnProperty("thicknessTexture")&&(t.thicknessMap=i[e.thicknessTexture.index],t.thicknessMapChannel="g",My(e.thicknessTexture,t,["thickness"])),e.hasOwnProperty("attenuationDistance")&&(t.attenuationDistance=e.attenuationDistance),e.hasOwnProperty("attenuationColor")){var n=e.attenuationColor;t.attenuation.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2))}},By=function(e,t,i){e.hasOwnProperty("emissiveStrength")&&(t.emissiveIntensity=e.emissiveStrength)},Ny=function(e,t,i){t.useIridescence=!0,e.hasOwnProperty("iridescenceFactor")&&(t.iridescence=e.iridescenceFactor),e.hasOwnProperty("iridescenceTexture")&&(t.iridescenceMapChannel="r",t.iridescenceMap=i[e.iridescenceTexture.index],My(e.iridescenceTexture,t,["iridescence"])),e.hasOwnProperty("iridescenceIor")&&(t.iridescenceRefractionIndex=e.iridescenceIor),e.hasOwnProperty("iridescenceThicknessMinimum")&&(t.iridescenceThicknessMin=e.iridescenceThicknessMinimum),e.hasOwnProperty("iridescenceThicknessMaximum")&&(t.iridescenceThicknessMax=e.iridescenceThicknessMaximum),e.hasOwnProperty("iridescenceThicknessTexture")&&(t.iridescenceThicknessMapChannel="g",t.iridescenceThicknessMap=i[e.iridescenceThicknessTexture.index],My(e.iridescenceThicknessTexture,t,["iridescenceThickness"]))},Uy=function(e,t,i){var n,s,r=new Yl;if(r.occludeSpecular=1,r.diffuseTint=!0,r.diffuseVertexColor=!0,r.specularTint=!0,r.specularVertexColor=!0,e.hasOwnProperty("name")&&(r.name=e.name),e.hasOwnProperty("pbrMetallicRoughness")){var a=e.pbrMetallicRoughness;if(a.hasOwnProperty("baseColorFactor")?(n=a.baseColorFactor,r.diffuse.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2)),r.opacity=n[3]):(r.diffuse.set(1,1,1),r.opacity=1),a.hasOwnProperty("baseColorTexture")){var o=a.baseColorTexture;s=t[o.index],r.diffuseMap=s,r.diffuseMapChannel="rgb",r.opacityMap=s,r.opacityMapChannel="a",My(o,r,["diffuse","opacity"])}if(r.useMetalness=!0,r.specular.set(1,1,1),a.hasOwnProperty("metallicFactor")?r.metalness=a.metallicFactor:r.metalness=1,a.hasOwnProperty("roughnessFactor")?r.gloss=a.roughnessFactor:r.gloss=1,r.glossInvert=!0,a.hasOwnProperty("metallicRoughnessTexture")){var h=a.metallicRoughnessTexture;r.metalnessMap=r.glossMap=t[h.index],r.metalnessMapChannel="b",r.glossMapChannel="g",My(h,r,["gloss","metalness"])}}if(e.hasOwnProperty("normalTexture")){var l=e.normalTexture;r.normalMap=t[l.index],My(l,r,["normal"]),l.hasOwnProperty("scale")&&(r.bumpiness=l.scale)}if(e.hasOwnProperty("occlusionTexture")){var c=e.occlusionTexture;r.aoMap=t[c.index],r.aoMapChannel="r",My(c,r,["ao"])}if(e.hasOwnProperty("emissiveFactor")?(n=e.emissiveFactor,r.emissive.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2)),r.emissiveTint=!0):(r.emissive.set(0,0,0),r.emissiveTint=!1),e.hasOwnProperty("emissiveTexture")){var u=e.emissiveTexture;r.emissiveMap=t[u.index],My(u,r,["emissive"])}if(e.hasOwnProperty("alphaMode"))switch(e.alphaMode){case"MASK":r.blendType=3,e.hasOwnProperty("alphaCutoff")?r.alphaTest=e.alphaCutoff:r.alphaTest=.5;break;case"BLEND":r.blendType=2,r.depthWrite=!1;break;default:r.blendType=3}else r.blendType=3;e.hasOwnProperty("doubleSided")?(r.twoSidedLighting=e.doubleSided,r.cull=e.doubleSided?0:1):(r.twoSidedLighting=!1,r.cull=1);var d={KHR_materials_clearcoat:Ry,KHR_materials_emissive_strength:By,KHR_materials_ior:Dy,KHR_materials_iridescence:Ny,KHR_materials_pbrSpecularGlossiness:Py,KHR_materials_sheen:ky,KHR_materials_specular:Ly,KHR_materials_transmission:Oy,KHR_materials_unlit:Iy,KHR_materials_volume:Fy};if(e.hasOwnProperty("extensions"))for(var f in e.extensions){var p=d[f];void 0!==p&&p(e.extensions[f],r,t)}return r.update(),r},zy=new Te,Vy=new me,Gy=function(e,t){var i=new go;if(e.hasOwnProperty("name")&&e.name.length>0?i.name=e.name:i.name="node_"+t,e.hasOwnProperty("matrix")&&(zy.data.set(e.matrix),zy.getTranslation(Vy),i.setLocalPosition(Vy),zy.getEulerAngles(Vy),i.setLocalEulerAngles(Vy),zy.getScale(Vy),i.setLocalScale(Vy)),e.hasOwnProperty("rotation")){var n=e.rotation;i.setLocalRotation(n[0],n[1],n[2],n[3])}if(e.hasOwnProperty("translation")){var s=e.translation;i.setLocalPosition(s[0],s[1],s[2])}if(e.hasOwnProperty("scale")){var r=e.scale;i.setLocalScale(r[0],r[1],r[2])}return i},Hy=function(e,t){var i="orthographic"===e.type?1:0,n=1===i?e.orthographic:e.perspective,s={enabled:!1,projection:i,nearClip:n.znear,aspectRatioMode:0};n.zfar&&(s.farClip=n.zfar),1===i?(s.orthoHeight=.5*n.ymag,n.ymag&&(s.aspectRatioMode=1,s.aspectRatio=n.xmag/n.ymag)):(s.fov=n.yfov*ce.RAD_TO_DEG,n.aspectRatio&&(s.aspectRatioMode=1,s.aspectRatio=n.aspectRatio));var r=new Zd(e.name);return r.addComponent("camera",s),r},Wy=function(e,t){var i={enabled:!1,type:"point"===e.type?"omni":e.type,color:e.hasOwnProperty("color")?new ue(e.color):ue.WHITE,range:e.hasOwnProperty("range")?e.range:9999,falloffMode:1,intensity:e.hasOwnProperty("intensity")?ce.clamp(e.intensity,0,2):1};e.hasOwnProperty("spot")&&(i.innerConeAngle=e.spot.hasOwnProperty("innerConeAngle")?e.spot.innerConeAngle*ce.RAD_TO_DEG:0,i.outerConeAngle=e.spot.hasOwnProperty("outerConeAngle")?e.spot.outerConeAngle*ce.RAD_TO_DEG:Math.PI/4),e.hasOwnProperty("intensity")&&(i.luminance=e.intensity*kc.getLightUnitConversion(Ic[i.type],i.outerConeAngle,i.innerConeAngle));var n=new Zd(t.name);return n.rotateLocal(90,0,0),n.addComponent("light",i),n},Xy=function(e,t,i,n){if(!t.hasOwnProperty("skins")||0===t.skins.length)return[];var s=new Map;return t.skins.map((function(r){return function(e,t,i,n,s,r){var a,o,h,l=t.joints,c=l.length,u=[];if(t.hasOwnProperty("inverseBindMatrices")){var d=t.inverseBindMatrices,f=yy(i[d],n,!0),p=[];for(a=0;a<c;a++){for(o=0;o<16;o++)p[o]=f[16*a+o];(h=new Te).set(p),u.push(h)}}else for(a=0;a<c;a++)h=new Te,u.push(h);var m=[];for(a=0;a<c;a++)m[a]=s[l[a]].name;var _=m.join("#"),g=r.get(_);return g||(g=new Wu(e,u,m),r.set(_,g)),g}(e,r,t.accessors,n,i,s)}))},jy=function(e,t,i,n,s){var r,a,o,h={},l={},c={},u=[];return{meshes:!s.skipMeshes&&(null==t||null==(r=t.meshes)?void 0:r.length)&&(null==t||null==(a=t.accessors)?void 0:a.length)&&(null==t||null==(o=t.bufferViews)?void 0:o.length)?t.meshes.map((function(r){return Ey(e,r,t.accessors,i,n,h,l,c,s,u)})):[],meshVariants:l,meshDefaultMaterials:c,promises:u}},qy=function(e,t,i,n){var s,r,a,o;if(!e.hasOwnProperty("materials")||0===e.materials.length)return[];var h=null==i||null==(s=i.material)?void 0:s.preprocess,l=null!=(r=null==i||null==(a=i.material)?void 0:a.process)?r:Uy,c=null==i||null==(o=i.material)?void 0:o.postprocess;return e.materials.map((function(e){h&&h(e);var i=l(e,t,n);return c&&c(e,i),i}))},Yy=function(e){if(!e.hasOwnProperty("extensions")||!e.extensions.hasOwnProperty("KHR_materials_variants"))return null;for(var t=e.extensions.KHR_materials_variants.variants,i={},n=0;n<t.length;n++)i[t[n].name]=n;return i},Ky=function(e,t,i,n){var s,r;if(!e.hasOwnProperty("animations")||0===e.animations.length)return[];var a=null==n||null==(s=n.animation)?void 0:s.preprocess,o=null==n||null==(r=n.animation)?void 0:r.postprocess;return e.animations.map((function(n,s){a&&a(n);var r=function(e,t,i,n,s,r,a){var o,h=function(e){return new iy(fy(e.type),xy(e,n))},l={STEP:0,LINEAR:1,CUBICSPLINE:2},c={},u={},d={},f=1;for(o=0;o<e.samplers.length;++o){var p=e.samplers[o];c.hasOwnProperty(p.input)||(c[p.input]=h(i[p.input])),u.hasOwnProperty(p.output)||(u[p.output]=h(i[p.output]));var m=p.hasOwnProperty("interpolation")&&l.hasOwnProperty(p.interpolation)?l[p.interpolation]:1,_={paths:[],input:p.input,output:p.output,interpolation:m};d[o]=_}var g=[],v={translation:"localPosition",rotation:"localRotation",scale:"localScale"},y=function(e){for(var t=[];e;)t.unshift(e.name),e=e.parent;return t},x=function(e,t,i){var n=u[e.output];if(n){var s;if(r&&r[t.mesh]){var a=r[t.mesh];a.hasOwnProperty("extras")&&a.extras.hasOwnProperty("targetNames")&&(s=a.extras.targetNames)}for(var h=n.data,l=h.length/c[e.input].data.length,p=h.length/l,m=4*p,_=new ArrayBuffer(m*l),g=0;g<l;g++){for(var v,y=new Float32Array(_,m*g,p),x=0;x<p;x++)y[x]=h[x*l+g];var S=new iy(1,y),b=null!=(v=s)&&v[g]?"name."+s[g]:g;u[-f]=S;var w={paths:[{entityPath:i,component:"graph",propertyPath:["weight."+b]}],input:e.input,output:-f,interpolation:e.interpolation};f++,d["morphCurve-"+o+"-"+g]=w}}};for(o=0;o<e.channels.length;++o){var S=e.channels[o],b=S.target,w=d[S.sampler],T=s[b.node],A=a[b.node],C=y(T);b.path.startsWith("weights")?(x(w,A,C),d[S.sampler].morphCurve=!0):w.paths.push({entityPath:C,component:"graph",propertyPath:[v[b.path]]})}var E=[],M=[],P=[];for(var R in c)E.push(c[R]),c[R]=E.length-1;for(var I in u)M.push(u[I]),u[I]=M.length-1;for(var L in d){var D=d[L];D.morphCurve||(P.push(new ty(D.paths,c[D.input],u[D.output],D.interpolation)),D.paths.length>0&&"localRotation"===D.paths[0].propertyPath[0]&&2!==D.interpolation&&g.push(P[P.length-1].output))}g.sort();var O,k=null;for(o=0;o<g.length;++o){var F=g[o];if(0===o||F!==k){if(4===(O=M[F]).components)for(var B=O.data,N=B.length-4,U=0;U<N;U+=4)B[U+0]*B[U+4]+B[U+1]*B[U+5]+B[U+2]*B[U+6]+B[U+3]*B[U+7]<0&&(B[U+4]*=-1,B[U+5]*=-1,B[U+6]*=-1,B[U+7]*=-1);k=F}}var z=0;for(o=0;o<E.length;o++)O=E[o]._data,z=Math.max(z,0===O.length?0:O[O.length-1]);return new $f(e.hasOwnProperty("name")?e.name:"animation_"+t,z,E,M,P)}(n,s,e.accessors,i,t,e.meshes,e.nodes);return o&&o(n,r),r}))},Zy=function(e,t){var i,n,s,r;if(!e.hasOwnProperty("nodes")||0===e.nodes.length)return[];for(var a=null==t||null==(i=t.node)?void 0:i.preprocess,o=null!=(n=null==t||null==(s=t.node)?void 0:s.process)?n:Gy,h=null==t||null==(r=t.node)?void 0:r.postprocess,l=e.nodes.map((function(e,t){a&&a(e);var i=o(e,t);return h&&h(e,i),i})),c=0;c<e.nodes.length;++c){var u=e.nodes[c];if(u.hasOwnProperty("children"))for(var d=l[c],f={},p=0;p<u.children.length;++p){var m=l[u.children[p]];m.parent||(f.hasOwnProperty(m.name)?m.name+=f[m.name]++:f[m.name]=1,d.addChild(m))}}return l},$y=function(e,t){var i,n=[],s=e.scenes.length;if(1===s&&1===(null==(i=e.scenes[0].nodes)?void 0:i.length)){var r=e.scenes[0].nodes[0];n.push(t[r])}else for(var a=0;a<s;a++){var o=e.scenes[a];if(o.nodes){for(var h=new go(o.name),l=0;l<o.nodes.length;l++){var c=t[o.nodes[l]];h.addChild(c)}n.push(h)}}return n},Qy=function(e,t,i){var n=null;if(e.hasOwnProperty("nodes")&&e.hasOwnProperty("cameras")&&e.cameras.length>0){var s,r,a,o,h=null==i||null==(s=i.camera)?void 0:s.preprocess,l=null!=(r=null==i||null==(a=i.camera)?void 0:a.process)?r:Hy,c=null==i||null==(o=i.camera)?void 0:o.postprocess;e.nodes.forEach((function(i,s){if(i.hasOwnProperty("camera")){var r=e.cameras[i.camera];if(r){h&&h(r);var a=l(r,t[s]);c&&c(r,a),a&&(n||(n=new Map),n.set(i,a))}}}))}return n},Jy=function(e,t,i){var n=null;if(e.hasOwnProperty("nodes")&&e.hasOwnProperty("extensions")&&e.extensions.hasOwnProperty("KHR_lights_punctual")&&e.extensions.KHR_lights_punctual.hasOwnProperty("lights")){var s=e.extensions.KHR_lights_punctual.lights;if(s.length){var r,a,o,h,l=null==i||null==(r=i.light)?void 0:r.preprocess,c=null!=(a=null==i||null==(o=i.light)?void 0:o.process)?a:Wy,u=null==i||null==(h=i.light)?void 0:h.postprocess;e.nodes.forEach((function(e,i){if(e.hasOwnProperty("extensions")&&e.extensions.hasOwnProperty("KHR_lights_punctual")&&e.extensions.KHR_lights_punctual.hasOwnProperty("light")){var r=e.extensions.KHR_lights_punctual.light,a=s[r];if(a){l&&l(a);var o=c(a,t[i]);u&&u(a,o),o&&(n||(n=new Map),n.set(e,o))}}}))}}return n},ex=function(e,t,i){e.nodes.forEach((function(e){e.hasOwnProperty("mesh")&&e.hasOwnProperty("skin")&&t[e.mesh].meshes.forEach((function(t){t.skin=i[e.skin]}))}))},tx=(oy=Y(j().mark((function e(t,i,n,s,r){var a,o,h,l,c,u,d,f,p,m,_,g,v,y,x,S,b,w,T,A,C,E,M,P;return j().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return h=null==r||null==(a=r.global)?void 0:a.preprocess,l=null==r||null==(o=r.global)?void 0:o.postprocess,h&&h(i),c=i.asset&&"PlayCanvas"===i.asset.generator,u=Zy(i,r),d=$y(i,u),f=Jy(i,u,r),p=Qy(i,u,r),m=Yy(i),e.next=12,Promise.all(n);case 12:return _=e.sent,g=jy(t,i,_,c,r),v=g.meshes,y=g.meshVariants,x=g.meshDefaultMaterials,S=g.promises,b=Ky(i,u,_,r),e.next=17,Promise.all(s);case 17:for(w=e.sent,T=w.map((function(e){return e.resource})),A=qy(i,T,r,c),C=Xy(t,i,u,_),E=[],M=0;M<v.length;M++)E[M]=new Zv,E[M].meshes=v[M];return ex(i,E,C),(P=new uy).gltf=i,P.nodes=u,P.scenes=d,P.animations=b,P.textures=w,P.materials=A,P.variants=m,P.meshVariants=y,P.meshDefaultMaterials=x,P.renders=E,P.skins=C,P.lights=f,P.cameras=p,l&&l(i,P),e.next=41,Promise.all(S);case 41:return e.abrupt("return",P);case 42:case"end":return e.stop()}}),e)}))),function(e,t,i,n,s){return oy.apply(this,arguments)}),ix=0,nx=function(e,t,i){var n;e&&e.toLowerCase().endsWith(".glb")||103===(n=new Uint8Array(t))[0]&&108===n[1]&&84===n[2]&&70===n[3]?function(e,t){var i=e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),n=i.getUint32(0,!0),s=i.getUint32(4,!0),r=i.getUint32(8,!0);if(1179937895===n)if(2===s)if(r<=0||r>i.byteLength)t("Invalid length found in glb header. Found "+r);else{for(var a=[],o=12;o<r;){var h=i.getUint32(o,!0);o+h+8>i.byteLength&&t("Invalid chunk length found in glb. Found "+h);var l=i.getUint32(o+4,!0),c=new Uint8Array(i.buffer,i.byteOffset+o+8,h);a.push({length:h,type:l,data:c}),o+=h+8}1===a.length||2===a.length?1313821514===a[0].type?a.length>1&&5130562!==a[1].type?t("Invalid chunk type found in glb file. Expected 0x004E4942, found 0x"+a[1].type.toString(16)):t(null,{gltfChunk:a[0].data,binaryChunk:2===a.length?a[1].data:null}):t("Invalid chunk type found in glb file. Expected 0x4E4F534A, found 0x"+a[0].type.toString(16)):t("Invalid number of chunks found in glb file.")}else t("Invalid version number found in glb header. Expected 2, found "+s);else t("Invalid magic number found in glb header. Expected 0x46546C67, found 0x"+n.toString(16))}(t,i):i(null,{gltfChunk:t,binaryChunk:null})},sx=function(){function e(){}return e.parse=function(e,t,i,n,s,r,a){nx(e,i,(function(e,i){e?a(e):function(e,t){var i=JSON.parse(function(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);for(var t="",i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return decodeURIComponent(escape(t))}(e));i.asset&&i.asset.version&&parseFloat(i.asset.version)<2?t("Invalid gltf version. Expected version 2.0 or above but found version '"+i.asset.version+"'."):t(null,i)}(i.gltfChunk,(function(e,o){if(e)a(e);else{var h=function(e,t,i,n){var s,r,a;if(!e.buffers||0===e.buffers.length)return[];var o=null==n||null==(s=n.buffer)?void 0:s.preprocess,h=null==n||null==(r=n.buffer)?void 0:r.processAsync,l=null==n||null==(a=n.buffer)?void 0:a.postprocess;return e.buffers.map((function(n,s){var r;return o&&o(n),r=(r=new Promise(h?function(e,t){h(n,(function(i,n){i?t(i):e(n)}))}:function(e){e(null)})).then((function(e){if(e)return e;if(n.hasOwnProperty("uri")){if(dy(n.uri)){for(var s=atob(n.uri.split(",")[1]),r=new Uint8Array(s.length),a=0;a<s.length;a++)r[a]=s.charCodeAt(a);return r}return new Promise((function(e,t){Tr.get(Rd.test(n.uri)?n.uri:v.join(i,n.uri),{cache:!0,responseType:"arraybuffer",retry:!1},(function(i,n){i?t(i):e(new Uint8Array(n))}))}))}return t})),l&&(r=r.then((function(t){return l(e.buffers[s],t),t}))),r}))}(o,i.binaryChunk,t,r),l=function(e,t,i){var n,s,r,a,o=[],h=null==i||null==(n=i.bufferView)?void 0:n.preprocess,l=null==i||null==(s=i.bufferView)?void 0:s.processAsync,c=null==i||null==(r=i.bufferView)?void 0:r.postprocess;if(null==(a=e.bufferViews)||!a.length)return o;for(var u=function(){var i,n=e.bufferViews[d];h&&h(n),i=new Promise(l?function(e,i){l(n,t,(function(t,n){t?i(t):e(n)}))}:function(e){e(null)}),i=i.then((function(e){return e||t[n.buffer].then((function(e){return new Uint8Array(e.buffer,e.byteOffset+(n.byteOffset||0),n.byteLength)}))})),n.hasOwnProperty("byteStride")&&(i=i.then((function(e){return e.byteStride=n.byteStride,e}))),c&&(i=i.then((function(e){return c(n,e),e}))),o.push(i)},d=0;d<e.bufferViews.length;++d)u();return o}(o,h,r),c=function(e,t,i,n,s){var r,a,o;if(!e.images||0===e.images.length)return[];var h=null==s||null==(r=s.image)?void 0:r.preprocess,l=null==s||null==(a=s.image)?void 0:a.processAsync,c=null==s||null==(o=s.image)?void 0:o.postprocess,u={"image/png":"png","image/jpeg":"jpg","image/basis":"basis","image/ktx":"ktx","image/ktx2":"ktx2","image/vnd-ms.dds":"dds"},d=function(e,t,i,s,r){return new Promise((function(a,o){var h=function(i){var h=(e.name||"gltf-texture")+"-"+ix++,l={url:t||h};if(i&&(l.contents=i.slice(0).buffer),s){var c=u[s];c&&(l.filename=l.url+"."+c)}var d=new kd(h,"texture",l,null,r);d.on("load",(function(e){return a(e)})),d.on("error",(function(e){return o(e)})),n.add(d),n.load(d)};i?i.then((function(e){return h(e)})):h(null)}))};return e.images.map((function(e,n){var s;return h&&h(e),s=(s=new Promise(l?function(t,i){l(e,(function(e,n){e?i(e):t(n)}))}:function(e){e(null)})).then((function(s){return s||(e.hasOwnProperty("uri")?dy(e.uri)?d(e,e.uri,null,(r=e.uri).substring(r.indexOf(":")+1,r.indexOf(";")),null):d(e,Rd.test(e.uri)?e.uri:v.join(i,e.uri),null,null,{crossOrigin:"anonymous"}):e.hasOwnProperty("bufferView")&&e.hasOwnProperty("mimeType")?d(e,null,t[e.bufferView],e.mimeType,null):Promise.reject(new Error("Invalid image found in gltf (neither uri or bufferView found). index="+n)));var r})),c&&(s=s.then((function(t){return c(e,t),t}))),s}))}(o,l,t,s,r),u=function(e,t,i){var n,s,r,a,o;if(null==e||null==(n=e.images)||!n.length||null==e||null==(s=e.textures)||!s.length)return[];var h=null==i||null==(r=i.texture)?void 0:r.preprocess,l=null==i||null==(a=i.texture)?void 0:a.processAsync,c=null==i||null==(o=i.texture)?void 0:o.postprocess,u=new Set;return e.textures.map((function(i){var n;return h&&h(i),n=(n=new Promise(l?function(t,n){l(i,e.images,(function(e,i){e?n(e):t(i)}))}:function(e){e(null)})).then((function(n){var s,r,a,o,h,l,c;n=null!=(s=null!=(r=null!=(a=n)?a:null==i||null==(o=i.extensions)||null==(h=o.KHR_texture_basisu)?void 0:h.source)?r:null==i||null==(l=i.extensions)||null==(c=l.EXT_texture_webp)?void 0:c.source)?s:i.source;var d=u.has(n);return u.add(n),t[n].then((function(t){var n,s,r,a,o,h,l=d?Ty(t):t;return s=l.resource,r=(null!=(n=e.samplers)?n:[])[i.sampler],o=function(e,t){switch(e){case 9728:return 0;case 9729:return 1;case 9984:return 2;case 9985:return 4;case 9986:return 3;case 9987:return 5;default:return t}},h=function(e,t){switch(e){case 33071:return 1;case 33648:return 2;case 10497:return 0;default:return t}},s&&(r=null!=(a=r)?a:{},s.minFilter=o(r.minFilter,5),s.magFilter=o(r.magFilter,1),s.addressU=h(r.wrapS,0),s.addressV=h(r.wrapT,0)),l}))})),c&&(n=n.then((function(e){return c(i,e),e}))),n}))}(o,c,r);tx(n,o,l,u,r).then((function(e){return a(null,e)})).catch((function(e){return a(e)}))}}))}))},e.createDefaultMaterial=function(){return Uy({name:"defaultGlbMaterial"},[])},e}(),rx=function(){function e(e){this.handlerType="animation",this.device=e.graphicsDevice,this.assets=e.assets,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t,i){var n=this;"string"==typeof e&&(e={load:e,original:e});var s={retry:this.maxRetries>0,maxRetries:this.maxRetries};(e.load.startsWith("blob:")||e.load.startsWith("data:"))&&(".glb"===v.getExtension(e.original).toLowerCase()?s.responseType=wr.ResponseType.ARRAY_BUFFER:s.responseType=wr.ResponseType.JSON),Tr.get(e.load,s,(function(s,r){var a;s?t("Error loading animation resource: "+e.original+" ["+s+"]"):".glb"===v.getExtension(e.original).toLowerCase()?sx.parse("filename.glb","",r,n.device,n.assets,null!=(a=null==i?void 0:i.options)?a:{},(function(e,n){if(e)t(e);else{var s,r=n.animations;if(null!=i&&null!=(s=i.data)&&s.events)for(var a=0;a<r.length;a++)r[a].events=new Zf(Object.values(i.data.events));n.destroy(),t(null,r)}})):t(null,n["_parseAnimationV"+r.animation.version](r))}))},t.open=function(e,t,i){return t},t.patch=function(e,t){},t._parseAnimationV3=function(e){var t=e.animation,i=new $u;i.name=t.name,i.duration=t.duration;for(var n=0;n<t.nodes.length;n++){var s=new Zu,r=t.nodes[n];s._name=r.name;for(var a=0;a<r.keys.length;a++){var o=r.keys[a],h=o.time,l=o.pos,c=o.rot,u=o.scale,d=new me(l[0],l[1],l[2]),f=(new Ae).setFromEulerAngles(c[0],c[1],c[2]),p=new me(u[0],u[1],u[2]),m=new Ku(h,d,f,p);s._keys.push(m)}i.addNode(s)}return i},t._parseAnimationV4=function(e){var t=e.animation,i=new $u;i.name=t.name,i.duration=t.duration;for(var n=0;n<t.nodes.length;n++){var s=new Zu,r=t.nodes[n];s._name=r.name;for(var a=r.defaults.p,o=r.defaults.r,h=r.defaults.s,l=0;l<r.keys.length;l++){var c=r.keys[l],u=c.t,d=a||c.p,f=o||c.r,p=h||c.s,m=new me(d[0],d[1],d[2]),_=(new Ae).setFromEulerAngles(f[0],f[1],f[2]),g=new me(p[0],p[1],p[2]),v=new Ku(u,m,_,g);s._keys.push(v)}i.addNode(s)}return i},e}(),ax=function(){function e(e){this.handlerType="animclip",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=wr.ResponseType.JSON),Tr.get(e.load,i,(function(i,n){i?t("Error loading animation clip resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){var i=t.name,n=t.duration,s=t.inputs.map((function(e){return new iy(1,e)})),r=t.outputs.map((function(e){return new iy(e.components,e.data)})),a=t.curves.map((function(e){return new ty([e.path],e.inputIndex,e.outputIndex,e.interpolation)}));return new $f(i,n,s,r,a)},t.patch=function(e,t){},e}(),ox=function(){function e(e){this.handlerType="animstategraph",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=wr.ResponseType.JSON),Tr.get(e.load,i,(function(i,n){i?t("Error loading animation state graph resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return new Sp(t)},t.patch=function(e,t){},e}(),hx=function(){if("undefined"==typeof window)return!1;var e=window.navigator.userAgent,t=e.indexOf("MSIE ");if(t>0)return parseInt(e.substring(t+5,e.indexOf(".",t)),10);if(e.indexOf("Trident/")>0){var i=e.indexOf("rv:");return parseInt(e.substring(i+3,e.indexOf(".",i)),10)}return!1}(),lx=[".ogg",".mp3",".wav",".mp4a",".m4a",".mp4",".aac",".opus"],cx=function(){function e(e){this.handlerType="audio",this.manager=e.soundManager,this.maxRetries=0}var t=e.prototype;return t._isSupported=function(e){var t=v.getExtension(e);return lx.indexOf(t)>-1},t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i=function(i){var n="Error loading audio url: "+e.original;i&&(n+=": "+(i.message||i)),console.warn(n),t(n)};if(this._createSound){if(!this._isSupported(e.original))return void i("Audio format for "+e.original+" not supported");this._createSound(e.load,(function(e){t(null,new Dr(e))}),i)}else i(null)},t.open=function(e,t){return t},t.patch=function(e,t){},t._createSound=function(e,t,i){if(Ar()){var n=this.manager;if(!n.context)return void i("Audio manager has no audio context");var s={retry:this.maxRetries>0,maxRetries:this.maxRetries};(e.startsWith("blob:")||e.startsWith("data:"))&&(s.responseType=wr.ResponseType.ARRAY_BUFFER),Tr.get(e,s,(function(e,s){e?i(e):n.context.decodeAudioData(s,t,i)}))}else{var r=null;try{r=new Audio}catch(e){return void i("No support for Audio element")}hx&&document.body.appendChild(r);r.onerror=function(){r.onerror=null,hx&&document.body.removeChild(r),i()},r.addEventListener("canplaythrough",(function e(){r.removeEventListener("canplaythrough",e),hx&&document.body.removeChild(r),t(r)})),r.src=e}},e}(),ux=function(){function e(e){this.handlerType="binary",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),Tr.get(e.load,{responseType:wr.ResponseType.ARRAY_BUFFER,retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?t("Error loading binary resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}(),dx=function(){function e(t,i,n,s){for(var r=function(t,s,r){var a=e.createAsset(i.name,t,s,r);return n.add(a),a},a=[],o=0;o<t.renders.length;++o)a.push(r("render",t.renders[o],o));for(var h=[],l=0;l<t.materials.length;++l)h.push(r("material",t.materials[l],l));for(var c=[],u=0;u<t.animations.length;++u)c.push(r("animation",t.animations[u],u));this.data=t,this._model=null,this._assetName=i.name,this._assets=n,this._defaultMaterial=s,this.renders=a,this.materials=h,this.textures=t.textures,this.animations=c}e.createAsset=function(e,t,i,n){var s=new kd(e+"/"+t+"/"+n,t,{url:""});return s.resource=i,s.loaded=!0,s};var t=e.prototype;return t.instantiateModelEntity=function(e){var t=new Zd;return t.addComponent("model",Object.assign({type:"asset",asset:this.model},e)),t},t.instantiateRenderEntity=function(t){for(var i,n=this,s=this._defaultMaterial,r=[],a=function(e,t,i,n,a,o,h){var l=a[i.id],c=void 0===l?s:n[l],u=new Co(i,c);return i.morph&&(u.morphInstance=new Nc(i.morph)),h.hasOwnProperty("skin")&&r.push({meshInstance:u,rootBone:e,entity:t}),u},o=function e(i,s,r){var o=new Zd;s._cloneInternal(o),i||(i=o);for(var h=null,l=null,c=0;c<r.nodes.length;c++){if(r.nodes[c]===s){var u=r.gltf.nodes[c];if(u.hasOwnProperty("mesh")){var d=r.renders[u.mesh].meshes;l=n.renders[u.mesh];for(var f=0;f<d.length;f++){var p=d[f];if(p){var m=a(i,o,p,r.materials,r.meshDefaultMaterials,r.skins,u);h||(h=[]),h.push(m)}}}if(r.lights){var _=r.lights.get(u);_&&o.addChild(_.clone())}if(r.cameras){var g=r.cameras.get(u);g&&g.camera.system.cloneComponent(g,o)}}}h&&(o.addComponent("render",Object.assign({type:"asset",meshInstances:h,rootBone:i},t)),o.render.assignAsset(l));for(var v=s.children,y=0;y<v.length;y++){var x=e(i,v[y],r);o.addChild(x)}return o},h=[],l=ie(this.data.scenes);!(i=l()).done;){var c=i.value;h.push(o(null,c,this.data))}return r.forEach((function(e){e.meshInstance.skinInstance=tg.createCachedSkinInstance(e.meshInstance.mesh.skin,e.rootBone,e.entity)})),e.createSceneHierarchy(h,"Entity")},t.getMaterialVariants=function(){return this.data.variants?Object.keys(this.data.variants):[]},t.applyMaterialVariant=function(e,t){var i=t?this.data.variants[t]:null;if(void 0!==i)for(var n=e.findComponents("render"),s=0;s<n.length;s++){var r=n[s];this._applyMaterialVariant(i,r.meshInstances)}},t.applyMaterialVariantInstances=function(e,t){var i=t?this.data.variants[t]:null;void 0!==i&&this._applyMaterialVariant(i,e)},t._applyMaterialVariant=function(e,t){var i=this;t.forEach((function(t){if(null===e)t.material=i._defaultMaterial;else{var n=i.data.meshVariants[t.mesh.id];n&&(t.material=i.data.materials[n[e]])}}))},e.createSceneHierarchy=function(e,t){var i=null;if(1===e.length)i=e[0];else{i=new t("SceneGroup");for(var n,s=ie(e);!(n=s()).done;){var r=n.value;i.addChild(r)}}return i},e.createModel=function(t,i){for(var n,s=function(e,n,s,r,a,o,h){var l=t.meshDefaultMaterials[n.id],c=void 0===l?i:a[l],u=new Co(n,c,o);if(n.morph){var d=new Nc(n.morph);u.morphInstance=d,e.morphInstances.push(d)}if(h.hasOwnProperty("skin")){var f=h.skin,p=s[f];n.skin=p;var m=r[f];u.skinInstance=m,e.skinInstances.push(m)}e.meshInstances.push(u)},r=new Uc,a=[],o=ie(t.skins);!(n=o()).done;){var h=n.value,l=new Ja(h);l.bones=h.bones,a.push(l)}r.graph=e.createSceneHierarchy(t.scenes,"GraphNode");for(var c=0;c<t.nodes.length;c++){var u=t.nodes[c];if(u.root===r.graph){var d=t.gltf.nodes[c];if(d.hasOwnProperty("mesh"))for(var f=t.renders[d.mesh].meshes,p=0;p<f.length;p++){var m=f[p];m&&s(r,m,t.skins,a,t.materials,u,d)}}}return r},t.destroy=function(){var e=this._assets,t=function(t){e.remove(t),t.unload()},i=function(e){e.forEach((function(e){t(e)}))};this.animations&&(i(this.animations),this.animations=null),this.textures&&(i(this.textures),this.textures=null),this.materials&&(i(this.materials),this.materials=null),this.renders&&(i(this.renders),this.renders=null),this._model&&(t(this._model),this._model=null),this.data=null,this.assets=null},Z(e,[{key:"model",get:function(){if(!this._model){var t=e.createModel(this.data,this._defaultMaterial),i=e.createAsset(this._assetName,"model",t,0);this._assets.add(i),this._model=i}return this._model}}]),e}(),fx=function(){function e(e,t,i){this._device=e,this._assets=t,this._defaultMaterial=sx.createDefaultMaterial(),this.maxRetries=i}var t=e.prototype;return t._getUrlWithoutParams=function(e){return e.indexOf("?")>=0?e.split("?")[0]:e},t.load=function(e,t,i){var n=this;kd.fetchArrayBuffer(e.load,(function(s,r){s?t(s):sx.parse(n._getUrlWithoutParams(e.original),v.extractPath(e.load),r,n._device,i.registry,i.options,(function(e,s){e?t(e):t(null,new dx(s,i,n._assets,n._defaultMaterial))}))}),i,this.maxRetries)},t.open=function(e,t,i){return t},t.patch=function(e,t){},e}(),px=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}(),mx=function(){function e(e){this.handlerType="container",this.glbContainerParser=new fx(e.graphicsDevice,e.assets,0),this.parsers={}}var t=e.prototype;return t._getUrlWithoutParams=function(e){return e.indexOf("?")>=0?e.split("?")[0]:e},t._getParser=function(e){var t=e?v.getExtension(this._getUrlWithoutParams(e)).toLowerCase().replace(".",""):null;return this.parsers[t]||this.glbContainerParser},t.load=function(e,t,i){"string"==typeof e&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,i)},t.open=function(e,t,i){return this._getParser(e).open(e,t,i)},t.patch=function(e,t){},Z(e,[{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)}}]),e}(),_x=function(){function e(e){this.handlerType="css",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),Tr.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?t("Error loading css resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}(),gx=function(){function e(e){this.handlerType="cubemap",this._device=e.graphicsDevice,this._registry=e.assets,this._loader=e.loader}var t=e.prototype;return t.load=function(e,t,i){this.loadAssets(i,t)},t.open=function(e,t,i){return i?i.resource:null},t.patch=function(e,t){this.loadAssets(e,(function(i,n){i&&(t.fire("error",e),t.fire("error:"+e.id,i,e),e.fire("error",e))}))},t.getAssetIds=function(e){var t=[];if(t[0]=e.file,(e.loadFaces||!e.file)&&e.data&&e.data.textures)for(var i=0;i<6;++i)t[i+1]=e.data.textures[i];else t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=null;return t},t.compareAssetIds=function(e,t){return e&&t?parseInt(e,10)===e||"string"==typeof e?e===t:e.url===t.url:null!==e==(null!==t)},t.update=function(e,t,i){var n,s,r,a=e.data||{},o=e._handlerState.assets,h=e._resources,l=[null,null,null,null,null,null,null],c=function(){return a.hasOwnProperty("type")?a.type:a.hasOwnProperty("rgbm")?a.rgbm?Gt:Vt:null};if(e.loaded&&i[0]===o[0])l[1]=h[1]||null,l[2]=h[2]||null,l[3]=h[3]||null,l[4]=h[4]||null,l[5]=h[5]||null,l[6]=h[6]||null;else if(i[0])if((n=i[0].resource).cubemap)for(r=0;r<6;++r)l[r+1]=new Yn(this._device,{name:e.name+"_prelitCubemap"+(n.width>>r),cubemap:!0,type:c()||n.type,width:n.width>>r,height:n.height>>r,format:n.format,levels:[n._levels[r]],fixCubemapSeams:!0,addressU:1,addressV:1,mipmaps:0===r});else n.type=Wt,l[1]=n;var u=i.slice(1);if(e.loaded&&this.cmpArrays(u,o.slice(1)))l[0]=h[0]||null;else if(-1===u.indexOf(null)){var d,f=u.map((function(e){return e.resource})),p=[];for(s=0;s<f[0]._levels.length;++s)p.push(f.map((function(e){return e._levels[s]})));var m=f[0].format,_=new Yn(this._device,{name:e.name+"_faces",cubemap:!0,type:c()||f[0].type,width:f[0].width,height:f[0].height,format:6===m?7:m,mipmaps:null==(d=a.mipmaps)||d,levels:p,minFilter:a.hasOwnProperty("minFilter")?a.minFilter:f[0].minFilter,magFilter:a.hasOwnProperty("magFilter")?a.magFilter:f[0].magFilter,anisotropy:a.hasOwnProperty("anisotropy")?a.anisotropy:1,addressU:1,addressV:1,fixCubemapSeams:!!i[0]});l[0]=_}if(!this.cmpArrays(l,h))for(e.resources=l,e._handlerState.assetIds=t,e._handlerState.assets=i,r=0;r<h.length;++r)null!==h[r]&&-1===l.indexOf(h[r])&&h[r].destroy();for(r=0;r<o.length;++r)null!==o[r]&&-1===i.indexOf(o[r])&&o[r].unload()},t.cmpArrays=function(e,t){if(e.length!==t.length)return!1;for(var i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0},t.resolveId=function(e){var t=parseInt(e,10);return t===e||t.toString()===e?t:e},t.loadAssets=function(e,t){e.hasOwnProperty("_handlerState")||(e._handlerState={assetIds:[null,null,null,null,null,null,null],assets:[null,null,null,null,null,null,null]});for(var i,n=this,s=n.getAssetIds(e),r=[null,null,null,null,null,null,null],a=e._handlerState.assetIds,o=e._handlerState.assets,h=n._registry,l=7,c=function(i,a){r[i]=a,0===--l&&(n.update(e,s,r),t(null,e.resources))},u=function(e,i,n){t(i)},d=function(e,t){t.loaded?c(e,t):(h.once("load:"+t.id,c.bind(n,e)),h.once("error:"+t.id,u.bind(n,e)),t.loading||h.load(t))},f=0;f<7;++f){var p=this.resolveId(s[f]);if(p)if(n.compareAssetIds(p,a[f]))c(f,o[f]);else if(parseInt(p,10)===p)(i=h.get(p))?d(f,i):setTimeout(function(e,t){var i=h.get(t);i?d(e,i):u(0,"failed to find dependent cubemap asset="+t)}.bind(null,f,p));else{var m="string"==typeof p?{url:p,filename:p}:p;i=new kd(e.name+"_part_"+f,"texture",m),h.add(i),h.once("load:"+i.id,c.bind(n,f)),h.once("error:"+i.id,u.bind(n,f)),h.load(i)}else c(f,null)}},e}(),vx=function(){function e(){this.handlerType="folder"}var t=e.prototype;return t.load=function(e,t){t(null,null)},t.open=function(e,t){return t},e}(),yx=function(){function e(e,t){this.type=t&&t.type||Im,this.em=1,this.textures=e,this.intensity=0,this._data=null,this.data=t}return Z(e,[{key:"data",get:function(){return this._data},set:function(e){if(this._data=e,e&&(void 0!==this._data.intensity&&(this.intensity=this._data.intensity),this._data.info||(this._data.info={}),(!this._data.version||this._data.version<2)&&(this._data.info.maps=[{width:this._data.info.width,height:this._data.info.height}],this._data.chars)))for(var t in this._data.chars)this._data.chars[t].map=0}}]),e}();function xx(e){return e.version<3&&(e.version<2&&(e.info.maps=e.info.maps||[{width:e.info.width,height:e.info.height}]),e.chars=Object.keys(e.chars||{}).reduce((function(t,i){var n=e.chars[i],s=void 0!==n.letter?n.letter:G.fromCodePoint(i);return e.version<2&&(n.map=n.map||0),t[s]=n,t}),{}),e.version=3),e}var Sx=function(){function e(e){this.handlerType="font",this._loader=e.loader,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t,i){"string"==typeof e&&(e={load:e,original:e});var n=this;".json"===v.getExtension(e.original)?Tr.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,s){if(i)t("Error loading font resource: "+e.original+" ["+i+"]");else{var r=xx(s);n._loadTextures(e.load.replace(".json",".png"),r,(function(e,i){if(e)return t(e);t(null,{data:r,textures:i})}))}})):(i&&i.data&&(i.data=xx(i.data)),this._loadTextures(e.load,i&&i.data,t))},t._loadTextures=function(e,t,i){for(var n=t.info.maps.length,s=0,r=null,a=new Array(n),o=this._loader,h=function(t){var h=function(e,o){if(!r){if(e)return r=e,i(e);o.upload(),a[t]=o,++s===n&&i(null,a)}};0===t?o.load(e,"texture",h):o.load(e.replace(".png",t+".png"),"texture",h)},l=0;l<n;l++)h(l)},t.open=function(e,t,i){return t.textures?new yx(t.textures,t.data):new yx(t,null)},t.patch=function(e,t){var i=e.resource;!i.data&&e.data?i.data=e.data:!e.data&&i.data&&(e.data=i.data),e.data&&(e.data=xx(e.data))},e}(),bx=function(e,t,i){var n,s,r=i.singleVecs,a=t.___1;a||(n=i.tripleVecs,s=t.___2);var o=a?a[0]:n[s];e.setLocalPosition(r[o],r[o+1],r[o+2]),o=a?a[1]:n[s+1],e.setLocalEulerAngles(r[o],r[o+1],r[o+2]),o=a?a[2]:n[s+2],e.setLocalScale(r[o],r[o+1],r[o+2])},wx=function(e,t){var i=e.charCodeAt(0)-t.fieldFirstCode;return t.fieldArray[i]},Tx=function(e,t){for(var i=0,n=0;n<e.length;n++)i=i*t.fieldCodeBase+e.charCodeAt(n)-t.fieldFirstCode;return t.fieldArray[i]},Ax=function(){function e(e,t){this._node=e,this._data=t}var t=e.prototype;return t.run=function(){var e=Object.prototype.toString.call(this._node);return"[object Object]"===e?this._handleMap():"[object Array]"===e?this._handleArray():this._result=this._node,this._result},t._handleMap=function(){this._result={},Object.keys(this._node).forEach(this._handleKey,this)},t._handleKey=function(t){var i=t,n=t.length;1===n?i=wx(t,this._data):2===n&&(i=Tx(t,this._data)),this._result[i]=new e(this._node[t],this._data).run()},t._handleArray=function(){this._result=[],this._node.forEach(this._handleArElt,this)},t._handleArElt=function(t){var i=new e(t,this._data).run();this._result.push(i)},e}(),Cx=function(){function e(e,t){this._app=e,this._isTemplate=t}var t=e.prototype;return t.parse=function(e){var t={},i=null,n=e.compressedFormat;for(var s in n&&!e.entDecompressed&&(e.entDecompressed=!0,e.entities=new Ax(e.entities,n).run()),e.entities){var r=e.entities[s],a=this._createEntity(r,n);t[s]=a,null===r.parent&&(i=a)}for(var o in e.entities)for(var h=t[o],l=e.entities[o].children,c=l.length,u=0;u<c;u++){var d=t[l[u]];d&&h.addChild(d)}return this._openComponentData(i,e.entities),i},t._createEntity=function(e,t){var i,n=new Zd(e.name,this._app);if(n.setGuid(e.resource_id),this._setPosRotScale(n,e,t),n._enabled=null==(i=e.enabled)||i,this._isTemplate?n._template=!0:n._enabledInHierarchy=n._enabled,n.template=e.template,e.tags)for(var s=0;s<e.tags.length;s++)n.tags.add(e.tags[s]);return e.labels&&e.labels.forEach((function(e){n.addLabel(e)})),n},t._setPosRotScale=function(e,t,i){if(i)bx(e,t,i);else{var n=t.position,s=t.rotation,r=t.scale;e.setLocalPosition(n[0],n[1],n[2]),e.setLocalEulerAngles(s[0],s[1],s[2]),e.setLocalScale(r[0],r[1],r[2])}},t._openComponentData=function(e,t){for(var i=this._app.systems.list,n=i.length,s=t[e.getGuid()],r=0;r<n;r++){var a=i[r],o=s.components[a.id];o&&a.addComponent(e,o)}n=s.children.length;for(var h=e._children,l=0;l<n;l++)h[l]&&(h[l]=this._openComponentData(h[l],t));return e},e}(),Ex=function(e,t,i){"string"==typeof e&&(e={load:e,original:e}),Tr.get(e.load,{retry:t>0,maxRetries:t},(function(t,n){if(t){var s="Error while loading scene JSON "+e.original;t.message?(s+=": "+t.message,t.stack&&(s+="\n"+t.stack)):s+=": "+t,i(s)}else i(t,n)}))},Mx=function(){function e(e){this.handlerType="hierarchy",this._app=e,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){Ex(e,this.maxRetries,t)},t.open=function(e,t){this._app.systems.script.preloading=!0;var i=new Cx(this._app,!1).parse(t);return this._app.systems.script.preloading=!1,i},e}(),Px=function(){function e(e){this.handlerType="html",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),Tr.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?t("Error loading html resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}(),Rx=function(){function e(e){this.handlerType="json",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=wr.ResponseType.JSON),Tr.get(e.load,i,(function(i,n){i?t("Error loading JSON resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}(),Ix=function(){function e(){this.removeInvalid=!0,this.valid=!0,this.enumValidators={occludeSpecular:this._createEnumValidator([0,1,2]),cull:this._createEnumValidator([0,1,2,3]),blendType:this._createEnumValidator([0,1,2,3,4,5,6,7,8,9,10]),depthFunc:this._createEnumValidator([0,1,2,3,4,5,6,7]),shadingModel:this._createEnumValidator([0,1])}}var t=e.prototype;return t.setInvalid=function(e,t){this.valid=!1,this.removeInvalid&&delete t[e]},t.validate=function(e){var t=Ul,i=Wl,n="path"===e.mappingFormat;for(var s in e){var r=t[s];if(r)if(r.startsWith("enum")){var a=r.split(":")[1];this.enumValidators[a]&&(this.enumValidators[a](e[s])||this.setInvalid(s,e))}else if("number"===r)"number"!=typeof e[s]&&this.setInvalid(s,e);else if("boolean"===r)"boolean"!=typeof e[s]&&this.setInvalid(s,e);else if("string"===r)"string"!=typeof e[s]&&this.setInvalid(s,e);else if("vec2"===r)e[s]instanceof Array&&2===e[s].length||this.setInvalid(s,e);else if("rgb"===r)e[s]instanceof Array&&3===e[s].length||this.setInvalid(s,e);else if("texture"===r)n?"string"!=typeof e[s]&&null!==e[s]&&(e[s]instanceof Yn||this.setInvalid(s,e)):"number"!=typeof e[s]&&null!==e[s]&&(e[s]instanceof Yn||this.setInvalid(s,e));else if("boundingbox"===r)e[s].center&&e[s].center instanceof Array&&3===e[s].center.length||this.setInvalid(s,e),e[s].halfExtents&&e[s].halfExtents instanceof Array&&3===e[s].halfExtents.length||this.setInvalid(s,e);else if("cubemap"===r)"number"!=typeof e[s]&&null!==e[s]&&void 0!==e[s]&&(e[s]instanceof Yn&&e[s].cubemap||this.setInvalid(s,e));else if("chunks"===r)for(var o=Object.keys(e[s]),h=0;h<o.length;h++)"string"!=typeof e[s][o[h]]&&this.setInvalid(o[h],e[s]);else console.error("Unknown material type: "+r);else i[s]?delete e[s]:this.valid=!1}return e.validated=!0,this.valid},t._createEnumValidator=function(e){return function(t){return e.indexOf(t)>=0}},e}(),Lx=function(){function e(){this._validator=null}var t=e.prototype;return t.parse=function(e){var t=this.migrate(e),i=this._validate(t),n=new Yl;return this.initialize(n,i),n},t.initialize=function(e,t){for(var i in t.validated||(t=this._validate(t)),t.chunks&&(e.chunks=$({},t.chunks)),t){var n=Ul[i],s=t[i];if("vec2"===n)e[i]=new ge(s[0],s[1]);else if("rgb"===n)e[i]=new ue(s[0],s[1],s[2]);else if("texture"===n)s instanceof Yn?e[i]=s:e[i]instanceof Yn&&"number"==typeof s&&s>0||(e[i]=null);else if("cubemap"===n)s instanceof Yn?e[i]=s:e[i]instanceof Yn&&"number"==typeof s&&s>0||(e[i]=null),"cubeMap"!==i||s||(e.prefilteredCubemaps=null);else if("boundingbox"===n){var r=new me(s.center[0],s.center[1],s.center[2]),a=new me(s.halfExtents[0],s.halfExtents[1],s.halfExtents[2]);e[i]=new Ie(r,a)}else e[i]=t[i]}e.update()},t.migrate=function(e){var t;void 0===e.shadingModel&&("blinn"===e.shader?e.shadingModel=1:e.shadingModel=0),e.shader&&delete e.shader,e.mapping_format&&(e.mappingFormat=e.mapping_format,delete e.mapping_format);var i=[["bumpMapFactor","bumpiness"],["aoUvSet","aoMapUv"],["aoMapVertexColor","aoVertexColor"],["diffuseMapVertexColor","diffuseVertexColor"],["emissiveMapVertexColor","emissiveVertexColor"],["specularMapVertexColor","specularVertexColor"],["metalnessMapVertexColor","metalnessVertexColor"],["opacityMapVertexColor","opacityVertexColor"],["glossMapVertexColor","glossVertexColor"],["lightMapVertexColor","lightVertexColor"],["diffuseMapTint","diffuseTint"],["specularMapTint","specularTint"],["emissiveMapTint","emissiveTint"],["metalnessMapTint","metalnessTint"],["clearCoatGlossiness","clearCoatGloss"]];for(t=0;t<i.length;t++){var n=i[t][0],s=i[t][1];void 0!==e[n]&&(void 0===e[s]&&(e[s]=e[n]),delete e[n])}var r=["fresnelFactor","shadowSampleType"];for(t=0;t<r.length;t++){var a=r[t];e.hasOwnProperty(a)&&delete e[a]}return e},t._validate=function(e){return e.validated||(this._validator||(this._validator=new Ix),this._validator.validate(e)),e},e}(),Dx={aoMap:"white",diffuseMap:"gray",specularMap:"gray",specularityFactorMap:"white",metalnessMap:"black",glossMap:"gray",sheenMap:"black",sheenGlossinessMap:"gray",clearCoatMap:"black",clearCoatGlossMap:"gray",clearCoatNormalMap:"normal",refractionMap:"white",emissiveMap:"gray",normalMap:"normal",heightMap:"gray",opacityMap:"gray",sphereMap:"gray",lightMap:"white"},Ox=function(){function e(e){this.handlerType="material",this._assets=e.assets,this._device=e.graphicsDevice,this._placeholderTextures=null,this._parser=new Lx,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),Tr.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?t&&t("Error loading material: "+e.original+" ["+i+"]"):t&&(n._engine=!0,t(null,n))}))},t.open=function(e,t){var i=this._parser.parse(t);return t._engine&&(i._data=t,delete t._engine),i},t._createPlaceholders=function(){this._placeholderTextures={};var e={white:[255,255,255,255],gray:[128,128,128,255],black:[0,0,0,255],normal:[128,128,255,255]};for(var t in e)if(e.hasOwnProperty(t)){this._placeholderTextures[t]=new Yn(this._device,{width:2,height:2,format:7,name:"material_placeholder"});for(var i=this._placeholderTextures[t].lock(),n=0;n<4;n++)for(var s=0;s<4;s++)i[4*n+s]=e[t][s];this._placeholderTextures[t].unlock()}},t.patch=function(e,t){e.resource._data&&(e._data=e.resource._data,delete e.resource._data),e.data.name=e.name,e.resource.name=e.name,this._bindAndAssignAssets(e,t),e.off("unload",this._onAssetUnload,this),e.on("unload",this._onAssetUnload,this)},t._onAssetUnload=function(e){delete e.data.parameters,delete e.data.chunks,delete e.data.name},t._assignTexture=function(e,t,i){t.resource[e]=i},t._getPlaceholderTexture=function(e){this._placeholderTextures||this._createPlaceholders();var t=Dx[e];return this._placeholderTextures[t]},t._assignPlaceholderTexture=function(e,t){t.resource[e]=this._getPlaceholderTexture(e)},t._onTextureLoad=function(e,t,i){this._assignTexture(e,t,i.resource),t.resource.update()},t._onTextureAdd=function(e,t,i){this._assets.load(i)},t._onTextureRemoveOrUnload=function(e,t,i){var n=t.resource;n&&t.resource[e]===i.resource&&(this._assignPlaceholderTexture(e,t),n.update())},t._assignCubemap=function(e,t,i){t.resource[e]=i[0],"cubeMap"===e&&(t.resource.prefilteredCubemaps=i.slice(1))},t._onCubemapLoad=function(e,t,i){this._assignCubemap(e,t,i.resources),this._parser.initialize(t.resource,t.data)},t._onCubemapAdd=function(e,t,i){0===t.data.shadingModel&&(t.loadFaces=!0),this._assets.load(i)},t._onCubemapRemoveOrUnload=function(e,t,i){var n=t.resource;t.data.prefilteredCubeMap128===i.resources[1]&&(this._assignCubemap(e,t,[null,null,null,null,null,null,null]),n.update())},t._bindAndAssignAssets=function(e,t){var i,n,s,r=this._parser.migrate(e.data),a=e.resource,o="path"===r.mappingFormat,h=zl;for(i=0;i<h.length;i++){n=h[i],s=a._assetReferences[n];var l=r[n],c=a[n],u=c===this._getPlaceholderTexture(n),d=r.validated;!l||c&&d&&!u?s&&(o?s.url=null:s.id=null):(s||(s=new ig(n,e,t,{load:this._onTextureLoad,add:this._onTextureAdd,remove:this._onTextureRemoveOrUnload,unload:this._onTextureRemoveOrUnload},this),a._assetReferences[n]=s),o?s.url=e.getAbsoluteUrl(l):s.id=l,s.asset&&(s.asset.resource?this._assignTexture(n,e,s.asset.resource):this._assignPlaceholderTexture(n,e),t.load(s.asset)))}var f=Gl;for(i=0;i<f.length;i++)n=f[i],s=a._assetReferences[n],r[n]&&!e.data.prefilteredCubeMap128&&(s||(s=new ig(n,e,t,{load:this._onCubemapLoad,add:this._onCubemapAdd,remove:this._onCubemapRemoveOrUnload,unload:this._onCubemapRemoveOrUnload},this),a._assetReferences[n]=s),o?s.url=r[n]:s.id=r[n],s.asset&&(s.asset.loaded&&this._assignCubemap(n,e,s.asset.resources),t.load(s.asset)));this._parser.initialize(a,r)},e}(),kx=function(){function e(e){this._device=e.device,this._defaultMaterial=e.defaultMaterial,this._assets=e.assets}return e.prototype.parse=function(e,t,i){var n,s=this;sx.parse("filename.glb","",e,this._device,this._assets,null!=(n=null==i?void 0:i.options)?n:{},(function(e,i){if(e)t(e);else{var n=dx.createModel(i,s._defaultMaterial);i.destroy(),t(null,n)}}))},e}(),Fx=function(){this.index=0,this.boneIndices=[0,0,0,0]},Bx=function(){function e(){this.partition=0,this.vertexStart=0,this.vertexCount=0,this.indexStart=0,this.indexCount=0,this.boneIndices=[],this.vertices=[],this.indices=[],this.indexMap={},this.originalMesh=null}var t=e.prototype;return t.addVertex=function(e,t,i){var n=-1;if(void 0!==this.indexMap[t])n=this.indexMap[t],this.indices.push(n);else{for(var s=0;s<4;s++)if(0!==i.blendWeight.data[4*t+s]){var r=i.blendIndices.data[4*e.index+s];e.boneIndices[s]=this.getBoneRemap(r)}n=this.vertices.length,this.indices.push(n),this.vertices.push(e),this.indexMap[t]=n}},t.addPrimitive=function(e,t,i,n){for(var s=[],r=0,a=e.length,o=0;o<a;o++)for(var h=e[o].index,l=0;l<4;l++)if(i.blendWeight.data[4*h+l]>0){for(var c=i.blendIndices.data[4*h+l],u=!0,d=0;d<r;d++)if(s[d]===c){u=!1;break}if(u)s[r]=c,r+=-1===this.getBoneRemap(c)?1:0}if(this.boneIndices.length+r>n)return!1;for(var f=0;f<r;f++)this.boneIndices.push(s[f]);for(var p=0;p<a;p++)this.addVertex(e[p],t[p],i);return!0},t.getBoneRemap=function(e){for(var t=0;t<this.boneIndices.length;t++)if(this.boneIndices[t]===e)return t;return-1},e}();function Nx(e,t,i){var n,s,r,a;!function(e){for(var t=e.vertices,i=e.skins,n=e.meshes,s=e.meshInstances,r=0;r<n.length;r++)n[r].vertices=t[n[r].vertices],void 0!==n[r].skin&&(n[r].skin=i[n[r].skin]);for(var a=0;a<s.length;a++)s[a].mesh=n[s[a].mesh]}(e);var o,h=e.vertices,l=e.skins,c=e.meshes,u=e.meshInstances,d=function(e){var t=new Fx;return t.index=e,t};for(n=l.length-1;n>=0;n--)if(l[n].boneNames.length>i){var f=l.splice(n,1)[0],p=[];for(s=0;s<c.length;s++)c[s].skin===f&&p.push(c[s]);for(s=0;s<p.length;s++)-1!==(a=c.indexOf(p[s]))&&c.splice(a,1);if(0===p.length)throw new Error("partitionSkin: There should be at least one mesh that references a skin");var m=p[0].vertices;for(s=1;s<p.length;s++)if(p[s].vertices!==m)throw new Error("partitionSkin: All meshes that share a skin should also share the same vertex buffer");var _=void 0,g=[],v=[],y=[],x=0;for(s=0;s<p.length;s++){for(var S=(o=p[s]).indices,b=o.base;b<o.base+o.count;){a=S[b++],v[0]=d(a),y[0]=a,a=S[b++],v[1]=d(a),y[1]=a,a=S[b++],v[2]=d(a),y[2]=a;for(var w=!1,T=x;T<g.length;T++)if((_=g[T]).addPrimitive(v,y,m,i)){w=!0;break}w||((_=new Bx).originalMesh=o,_.addPrimitive(v,y,m,i),g.push(_))}x=g.length}var A=[],C=[];for(s=0;s<g.length;s++)if((_=g[s]).vertices.length&&_.indices.length){var E=A.length,M=_.vertices.length,P=C.length,R=_.indices.length;_.partition=s,_.vertexStart=E,_.vertexCount=M,_.indexStart=P,_.indexCount=R;var I=void 0,L=void 0;for(I=0,L=E;I<M;)A[L++]=_.vertices[I++];for(I=0,L=P;I<R;)C[L++]=_.indices[I++]+E}var D=[];for(s=0;s<g.length;s++){_=g[s];var O=[],k=[];for(r=0;r<_.boneIndices.length;r++)O.push(f.inverseBindMatrices[_.boneIndices[r]]),k.push(f.boneNames[_.boneIndices[r]]);var F={inverseBindMatrices:O,boneNames:k};D.push(F),l.push(F)}var B=void 0,N=void 0,U=void 0,z=void 0,V={};for(N in m)V[N]={components:m[N].components,data:[],type:m[N].type};for(N in m)if("blendIndices"===N){var G=V[N].data;for(s=0;s<A.length;s++){var H=A[s].boneIndices;G.push(H[0],H[1],H[2],H[3])}}else for(U=(B=m[N]).data,z=B.components,s=0;s<A.length;s++)for(a=A[s].index,r=0;r<z;r++)V[N].data.push(U[a*z+r]);for(h[h.indexOf(m)]=V,s=0;s<g.length;s++)for(_=g[s],o={aabb:{min:[0,0,0],max:[0,0,0]},vertices:V,skin:D[s],indices:C.splice(0,_.indexCount),type:"triangles",base:0,count:_.indexCount},c.push(o),r=u.length-1;r>=0;r--)u[r].mesh===_.originalMesh&&(u.push({mesh:o,node:u[r].node}),t&&t.push({material:t[r].material,path:t[r].path}));for(s=0;s<g.length;s++)for(_=g[s],r=u.length-1;r>=0;r--)u[r].mesh===_.originalMesh&&(u.splice(r,1),t&&t.splice(r,1))}!function(e){for(var t=e.vertices,i=e.skins,n=e.meshes,s=e.meshInstances,r=0;r<n.length;r++)n[r].vertices=t.indexOf(n[r].vertices),void 0!==n[r].skin&&(n[r].skin=i.indexOf(n[r].skin));for(var a=0;a<s.length;a++)s[a].mesh=n.indexOf(s[a].mesh)}(e)}var Ux={points:0,lines:1,lineloop:2,linestrip:3,triangles:4,trianglestrip:5,trianglefan:6},zx={int8:0,uint8:1,int16:2,uint16:3,int32:4,uint32:5,float32:6},Vx=function(){function e(e){this._device=e.device,this._defaultMaterial=e.defaultMaterial}var t=e.prototype;return t.parse=function(e,t){var i=e.model;if(i)if(i.version<=1)t("JsonModelParser#parse: Trying to parse unsupported model format.");else{var n=this._parseNodes(e),s=this._parseSkins(e,n),r=this._parseVertexBuffers(e),a=this._parseIndexBuffers(e,r),o=this._parseMorphs(e,n,r),h=this._parseMeshes(e,s.skins,o.morphs,r,a.buffer,a.data),l=this._parseMeshInstances(e,n,h,s.skins,s.instances,o.morphs,o.instances),c=new Uc;c.graph=n[0],c.meshInstances=l,c.skinInstances=s.instances,c.morphInstances=o.instances,c.getGraph().syncHierarchy(),t(null,c)}else t(null,null)},t._parseNodes=function(e){var t,i=e.model,n=[];for(t=0;t<i.nodes.length;t++){var s=i.nodes[t],r=new go(s.name);r.setLocalPosition(s.position[0],s.position[1],s.position[2]),r.setLocalEulerAngles(s.rotation[0],s.rotation[1],s.rotation[2]),r.setLocalScale(s.scale[0],s.scale[1],s.scale[2]),r.scaleCompensation=!!s.scaleCompensation,n.push(r)}for(t=1;t<i.parents.length;t++)n[i.parents[t]].addChild(n[t]);return n},t._parseSkins=function(e,t){var i,n,s=e.model,r=[],a=[];!this._device.supportsBoneTextures&&s.skins.length>0&&Nx(s,null,this._device.getBoneLimit());for(i=0;i<s.skins.length;i++){var o=s.skins[i],h=[];for(n=0;n<o.inverseBindMatrices.length;n++){var l=o.inverseBindMatrices[n];h[n]=(new Te).set(l)}var c=new Wu(this._device,h,o.boneNames);r.push(c);var u=new Ja(c),d=[];for(n=0;n<c.boneNames.length;n++){var f=c.boneNames[n],p=t[0].findByName(f);d.push(p)}u.bones=d,a.push(u)}return{skins:r,instances:a}},t._getMorphVertexCount=function(e,t,i){for(var n=0;n<e.meshes.length;n++){var s=e.meshes[n];if(s.morph===t)return i[s.vertices].numVertices}},t._parseMorphs=function(e,t,i){var n,s,r,a,o,h,l=e.model,c=[],u=[];if(l.morphs){var d=function(e,t,i){for(var n=new Float32Array(3*i),s=0;s<t.length;s++){var r=3*t[s];n[r]=e[3*s],n[r+1]=e[3*s+1],n[r+2]=e[3*s+2]}return n};for(n=0;n<l.morphs.length;n++){for(a=l.morphs[n].targets,h=[],r=this._getMorphVertexCount(l,n,i),s=0;s<a.length;s++){var f=a[s].aabb,p=f.min,m=f.max,_=new Ie(new me(.5*(m[0]+p[0]),.5*(m[1]+p[1]),.5*(m[2]+p[2])),new me(.5*(m[0]-p[0]),.5*(m[1]-p[1]),.5*(m[2]-p[2]))),g=a[s].indices,v=a[s].deltaPositions,y=a[s].deltaNormals;g&&(v=d(v,g,r),y=d(y,g,r)),o=new Vc({deltaPositions:v,deltaNormals:y,name:a[s].name,aabb:_}),h.push(o)}var x=new zc(h,this._device);c.push(x);var S=new Nc(x);u.push(S)}}return{morphs:c,instances:u}},t._parseVertexBuffers=function(e){for(var t=e.model,i=[],n={position:lt,normal:ct,tangent:ut,blendWeight:dt,blendIndices:ft,color:pt,texCoord0:_t,texCoord1:gt,texCoord2:vt,texCoord3:yt,texCoord4:xt,texCoord5:St,texCoord6:bt,texCoord7:wt},s=0;s<t.vertices.length;s++){var r=t.vertices[s],a=[];for(var o in r){var h=r[o];a.push({semantic:n[o],components:h.components,type:zx[h.type],normalize:n[o]===pt})}for(var l=new Pi(this._device,a),c=r.position.data.length/r.position.components,u=new Ei(this._device,l,c),d=new zs(u),f=0;f<c;f++){for(var p in r){var m=r[p];switch(m.components){case 1:d.element[n[p]].set(m.data[f]);break;case 2:d.element[n[p]].set(m.data[2*f],1-m.data[2*f+1]);break;case 3:d.element[n[p]].set(m.data[3*f],m.data[3*f+1],m.data[3*f+2]);break;case 4:d.element[n[p]].set(m.data[4*f],m.data[4*f+1],m.data[4*f+2],m.data[4*f+3])}}d.next()}d.end(),i.push(u)}return i},t._parseIndexBuffers=function(e,t){var i,n=e.model,s=null,r=null,a=0;for(i=0;i<n.meshes.length;i++){var o=n.meshes[i];void 0!==o.indices&&(a+=o.indices.length)}var h=0;for(i=0;i<t.length;i++)h=Math.max(h,t[i].numVertices);return a>0&&(h>65535&&this._device.extUintElement?(s=new As(this._device,2,a),r=new Uint32Array(s.lock())):(s=new As(this._device,1,a),r=new Uint16Array(s.lock()))),{buffer:s,data:r}},t._parseMeshes=function(e,t,i,n,s,r){for(var a=e.model,o=[],h=0,l=0;l<a.meshes.length;l++){var c=a.meshes[l],u=c.aabb,d=u.min,f=u.max,p=new Ie(new me(.5*(f[0]+d[0]),.5*(f[1]+d[1]),.5*(f[2]+d[2])),new me(.5*(f[0]-d[0]),.5*(f[1]-d[1]),.5*(f[2]-d[2]))),m=void 0!==c.indices,_=new Jr(this._device);_.vertexBuffer=n[c.vertices],_.indexBuffer[0]=m?s:null,_.primitive[0].type=Ux[c.type],_.primitive[0].base=m?c.base+h:c.base,_.primitive[0].count=c.count,_.primitive[0].indexed=m,_.skin=void 0!==c.skin?t[c.skin]:null,_.morph=void 0!==c.morph?i[c.morph]:null,_.aabb=p,m&&(r.set(c.indices,h),h+=c.indices.length),o.push(_)}return null!==s&&s.unlock(),o},t._parseMeshInstances=function(e,t,i,n,s,r,a){var o,h=e.model,l=[];for(o=0;o<h.meshInstances.length;o++){var c=h.meshInstances[o],u=t[c.node],d=i[c.mesh],f=new Co(d,this._defaultMaterial,u);if(d.skin){var p=n.indexOf(d.skin);f.skinInstance=s[p]}if(d.morph){var m=r.indexOf(d.morph);f.morphInstance=a[m]}l.push(f)}return l},e}(),Gx=function(){function e(e){this.handlerType="model",this._parsers=[],this.device=e.graphicsDevice,this.assets=e.assets,this.defaultMaterial=Xa(this.device),this.maxRetries=0,this.addParser(new Vx(this),(function(e,t){return".json"===v.getExtension(e)})),this.addParser(new kx(this),(function(e,t){return".glb"===v.getExtension(e)}))}var t=e.prototype;return t.load=function(e,t,i){var n=this;"string"==typeof e&&(e={load:e,original:e});var s={retry:this.maxRetries>0,maxRetries:this.maxRetries};(e.load.startsWith("blob:")||e.load.startsWith("data:"))&&(".glb"===v.getExtension(e.original).toLowerCase()?s.responseType=wr.ResponseType.ARRAY_BUFFER:s.responseType=wr.ResponseType.JSON),Tr.get(e.load,s,(function(s,r){if(t)if(s)t("Error loading model: "+e.original+" ["+s+"]");else{for(var a=0;a<n._parsers.length;a++){var o=n._parsers[a];if(o.decider(e.original,r))return void o.parser.parse(r,(function(e,i){e?t(e):t(null,i)}),i)}t("No parsers found")}}))},t.open=function(e,t){return t},t.patch=function(e,t){if(e.resource){var i=e.data,n=this;e.resource.meshInstances.forEach((function(s,r){if(i.mapping){var a=function e(i){i.resource?s.material=i.resource:(i.once("load",e),t.load(i)),i.once("remove",(function(e){s.material===e.resource&&(s.material=n.defaultMaterial)}))};if(!i.mapping[r])return void(s.material=n.defaultMaterial);var o,h=i.mapping[r].material,l=i.mapping[r].path;if(void 0!==h)h?(o=t.get(h))?a(o):t.once("add:"+h,a):s.material=n.defaultMaterial;else if(l){var c=e.getAbsoluteUrl(i.mapping[r].path);(o=t.getByUrl(c))?a(o):t.once("add:url:"+c,a)}}}))}},t.addParser=function(e,t){this._parsers.push({parser:e,decider:t})},e}(),Hx=function(){function e(e){this.handlerType="scene",this._app=e,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){Ex(e,this.maxRetries,t)},t.open=function(e,t){this._app.systems.script.preloading=!0;var i=new Cx(this._app,!1).parse(t),n=this._app.scene;return n.root=i,this._app.applySceneSettings(t.settings),this._app.systems.script.preloading=!1,n},t.patch=function(e,t){},e}(),Wx=function(){function e(e){this.handlerType="script",this._app=e,this._scripts={},this._cache={}}var t=e.prototype;return t.load=function(e,t){var i=this;"string"==typeof e&&(e={load:e,original:e});var n=this;_d.app=this._app,this._loadScript(e.load,(function(e,s,r){if(e)t(e);else if(_d.legacy){var a=null;fd._types.length&&(a=fd._types.pop()),a?i._scripts[s]=a:a=null,t(null,a,r)}else{for(var o={},h=0;h<fd._types.length;h++)o[fd._types[h].name]=fd._types[h];fd._types.length=0,t(null,o,r),delete n._loader._cache[Xd.makeKey(s,"script")]}}))},t.open=function(e,t){return t},t.patch=function(e,t){},t._loadScript=function(e,t){var i=document.head,n=document.createElement("script");this._cache[e]=n,n.async=!1,n.addEventListener("error",(function(e){t("Script: "+e.target.src+" failed to load")}),!1);var s=!1;n.onload=n.onreadystatechange=function(){s||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState||(s=!0,t(null,e,n))},n.src=e,i.appendChild(n)},e}(),Xx=function(){function e(e){this.handlerType="shader",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),Tr.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?t("Error loading shader resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}();function jx(e){this.resource&&(this.resource.atlas=e.resource)}function qx(e){this.registry.load(e)}var Yx=function(){function e(e){this.handlerType="sprite",this._assets=e.assets,this._device=e.graphicsDevice,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),".json"===v.getExtension(e.original)&&Tr.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(e,i){e?t(e):t(null,i)}))},t.open=function(e,t){var i=new qu(this._device);return e&&(i.__data=t),i},t.patch=function(e,t){var i=e.resource;if(i.__data&&(e.data.pixelsPerUnit=i.__data.pixelsPerUnit,e.data.renderMode=i.__data.renderMode,e.data.frameKeys=i.__data.frameKeys,i.__data.textureAtlasAsset)){var n=t.getByUrl(i.__data.textureAtlasAsset);n?e.data.textureAtlasAsset=n.id:console.warn("Could not find textureatlas with url: "+i.__data.textureAtlasAsset)}i.startUpdate(),i.renderMode=e.data.renderMode,i.pixelsPerUnit=e.data.pixelsPerUnit,i.frameKeys=e.data.frameKeys,this._updateAtlas(e),i.endUpdate(),e.off("change",this._onAssetChange,this),e.on("change",this._onAssetChange,this)},t._updateAtlas=function(e){var t=e.resource;if(e.data.textureAtlasAsset){this._assets.off("load:"+e.data.textureAtlasAsset,jx,e),this._assets.on("load:"+e.data.textureAtlasAsset,jx,e);var i=this._assets.get(e.data.textureAtlasAsset);i&&i.resource?t.atlas=i.resource:i?this._assets.load(i):(this._assets.off("add:"+e.data.textureAtlasAsset,qx,e),this._assets.on("add:"+e.data.textureAtlasAsset,qx,e))}else t.atlas=null},t._onAssetChange=function(e,t,i,n){"data"===t&&i&&i.textureAtlasAsset&&n&&i.textureAtlasAsset!==n.textureAtlasAsset&&(this._assets.off("load:"+n.textureAtlasAsset,jx,e),this._assets.off("add:"+n.textureAtlasAsset,qx,e))},e}(),Kx=function(){function e(e,t){this._app=e,this._data=t,this._templateRoot=null}var t=e.prototype;return t.instantiate=function(){return this._templateRoot||this._parseTemplate(),this._templateRoot.clone()},t._parseTemplate=function(){var e=new Cx(this._app,!0);this._templateRoot=e.parse(this._data)},e}(),Zx=function(){function e(e){this.handlerType="template",this._app=e,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i={retry:this.maxRetries>0,maxRetries:this.maxRetries};Tr.get(e.load,i,(function(i,n){i?t("Error requesting template: "+e.original):t(i,n)}))},t.open=function(e,t){return new Kx(this._app,t)},e}(),$x=function(){function e(e){this.handlerType="text",this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e}),Tr.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(i,n){i?t("Error loading text resource: "+e.original+" ["+i+"]"):t(null,n)}))},t.open=function(e,t){return t},t.patch=function(e,t){},e}(),Qx={repeat:0,clamp:1,mirror:2},Jx={nearest:0,linear:1,nearest_mip_nearest:2,linear_mip_nearest:4,nearest_mip_linear:3,linear_mip_linear:5},eS=/^data\.frames\.(\d+)$/,tS=function(){function e(e){this.handlerType="textureatlas",this._loader=e.loader,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){"string"==typeof e&&(e={load:e,original:e});var i=this,n=this._loader.getHandler("texture");if(".json"!==v.getExtension(e.original))return n.load(e,t);Tr.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(function(n,s){if(n)t(n);else{var r=e.original.replace(".json",".png");i._loader.load(r,"texture",(function(e,i){e?t(e):t(null,{data:s,texture:i})}))}}))},t.open=function(e,t){var i=new Yu;if(t.texture&&t.data)i.texture=t.texture,i.__data=t.data;else{var n=this._loader.getHandler("texture").open(e,t);if(!n)return null;i.texture=n}return i},t.patch=function(e,t){if(e.resource){e.resource.__data&&(void 0!==e.resource.__data.minfilter&&(e.data.minfilter=e.resource.__data.minfilter),void 0!==e.resource.__data.magfilter&&(e.data.magfilter=e.resource.__data.magfilter),void 0!==e.resource.__data.addressu&&(e.data.addressu=e.resource.__data.addressu),void 0!==e.resource.__data.addressv&&(e.data.addressv=e.resource.__data.addressv),void 0!==e.resource.__data.mipmaps&&(e.data.mipmaps=e.resource.__data.mipmaps),void 0!==e.resource.__data.anisotropy&&(e.data.anisotropy=e.resource.__data.anisotropy),void 0!==e.resource.__data.rgbm&&(e.data.rgbm=!!e.resource.__data.rgbm),e.data.frames=e.resource.__data.frames,delete e.resource.__data);var i=e.resource.texture;if(i&&(i.name=e.name,e.data.hasOwnProperty("minfilter")&&i.minFilter!==Jx[e.data.minfilter]&&(i.minFilter=Jx[e.data.minfilter]),e.data.hasOwnProperty("magfilter")&&i.magFilter!==Jx[e.data.magfilter]&&(i.magFilter=Jx[e.data.magfilter]),e.data.hasOwnProperty("addressu")&&i.addressU!==Qx[e.data.addressu]&&(i.addressU=Qx[e.data.addressu]),e.data.hasOwnProperty("addressv")&&i.addressV!==Qx[e.data.addressv]&&(i.addressV=Qx[e.data.addressv]),e.data.hasOwnProperty("mipmaps")&&i.mipmaps!==e.data.mipmaps&&(i.mipmaps=e.data.mipmaps),e.data.hasOwnProperty("anisotropy")&&i.anisotropy!==e.data.anisotropy&&(i.anisotropy=e.data.anisotropy),e.data.hasOwnProperty("rgbm"))){var n=e.data.rgbm?Gt:Vt;i.type!==n&&(i.type=n)}e.resource.texture=i;var s={};for(var r in e.data.frames){var a=e.data.frames[r];s[r]={rect:new ve(a.rect),pivot:new ge(a.pivot),border:new ve(a.border)}}e.resource.frames=s,e.off("change",this._onAssetChange,this),e.on("change",this._onAssetChange,this)}},t._onAssetChange=function(e,t,i){var n;if("data"===t||"data.frames"===t){var s={};for(var r in i.frames)n=i.frames[r],s[r]={rect:new ve(n.rect),pivot:new ge(n.pivot),border:new ve(n.border)};e.resource.frames=s}else{var a=t.match(eS);if(a){var o=a[1];i?(e.resource.frames[o]?((n=e.resource.frames[o]).rect.set(i.rect[0],i.rect[1],i.rect[2],i.rect[3]),n.pivot.set(i.pivot[0],i.pivot[1]),n.border.set(i.border[0],i.border[1],i.border[2],i.border[3])):e.resource.frames[o]={rect:new ve(i.rect),pivot:new ge(i.pivot),border:new ve(i.border)},e.resource.fire("set:frame",o,e.resource.frames[o])):e.resource.frames[o]&&(delete e.resource.frames[o],e.resource.fire("remove:frame",o))}}},e}();function iS(){var e,t,i,n=0,s=1,r=2,a=3,o=8,h=9,l=10,c=11,u=12,d=13,f=14,p=16,m={astc:l,dxt:r,etc1:n,etc2:n,pvr:o,atc:c,none:f},_={astc:l,dxt:a,etc1:p,etc2:s,pvr:h,atc:u,none:p},g=21,v=22,y=23,x=8,S=10,b=26,w=27,T=28,A=29,C=30,E=7,M=3,P=5,R=function(e,t){switch(e){case n:return t.formats.etc1?g:v;case s:return y;case r:return x;case a:return S;case o:return b;case h:return w;case l:return T;case c:return A;case u:return C;case d:return E;case f:return M;case p:return P}},I=function(e){for(var t=function(e,t){var i=e*(2/255)-1,n=t*(2/255)-1,s=Math.sqrt(1-Math.min(1,i*i+n*n));return Math.max(0,Math.min(255,Math.floor(.5*(s+1)*255)))},i=0;i<e.length;i+=4){var n=e[i+3],s=e[i+1];e[i+0]=n,e[i+2]=t(n,s),e[i+3]=255}return e},L=function(e){for(var t=new Uint16Array(e.length/4),i=0;i<e.length;i+=4){var n=e[i+0],s=e[i+1],r=e[i+2];t[i/4]=(248&n)<<8|(252&s)<<3|r>>3}return t},D=function(){return"undefined"!=typeof performance?performance.now():0},O=function(e,n,s){if(s){if(e.formats.astc)return"astc"}else if(n){if(e.formats.etc2)return"etc2"}else if(e.formats.etc1||e.formats.etc2)return"etc1";return function(t){for(var i=0;i<t.length;++i){var n=t[i];if(e.formats[n])return n}return"none"}(n?i:t)},k=function(e,t,i,d){switch(i){case n:case s:return!0;case r:case a:return 0==(3&e)&&0==(3&t);case o:case h:return function(e,t){return 0==(e&e-1)&&0==(t&t-1)}(e,t)&&(e===t||d);case l:case c:case u:return!0}},F=function(t,i,n){return n.isKTX2?function(t,i,n){if(!e.KTX2File)throw new Error("Basis transcoder module does not include support for KTX2.");var s=D(),r=new e.KTX2File(new Uint8Array(i)),a=r.getWidth(),o=r.getHeight(),h=r.getLevels(),l=!!r.getHasAlpha(),c=r.isUASTC&&r.isUASTC();if(!a||!o||!h)throw r.close(),r.delete(),new Error("Invalid image dimensions url="+t+" width="+a+" height="+o+" levels="+h);var u,g,v=O(n.deviceDetails,l,c),y=!!n.isGGGR&&"pvr"===v;if(y?u=d:k(a,o,u=l?_[v]:m[v],n.deviceDetails.webgl2)||(u=l?d:f),!r.startTranscoding())throw r.close(),r.delete(),new Error("Failed to start transcoding url="+t);for(var x=[],S=0;S<h;++S){var b=r.getImageTranscodedSizeInBytes(S,0,0,u),w=new Uint8Array(b);if(!r.transcodeImage(w,S,0,0,u,0,-1,-1))throw r.close(),r.delete(),new Error("Failed to transcode image url="+t);var T=u===f||u===p;x.push(T?new Uint16Array(w.buffer):w)}if(r.close(),r.delete(),y)for(u=f,g=0;g<x.length;++g)x[g]=L(I(x[g]));return{format:R(u,n.deviceDetails),width:a,height:o,levels:x,cubemap:!1,transcodeTime:D()-s,url:t,unswizzledGGGR:y}}(t,i,n):function(t,i,n){var s=D(),r=new e.BasisFile(new Uint8Array(i)),a=r.getImageWidth(0,0),o=r.getImageHeight(0,0),h=r.getNumImages(),l=r.getNumLevels(0),c=!!r.getHasAlpha(),u=r.isUASTC&&r.isUASTC();if(!(a&&o&&h&&l))throw r.close(),r.delete(),new Error("Invalid image dimensions url="+t+" width="+a+" height="+o+" images="+h+" levels="+l);var g,v,y=O(n.deviceDetails,c,u),x=!!n.isGGGR&&"pvr"===y;if(x?g=d:k(a,o,g=c?_[y]:m[y],n.deviceDetails.webgl2)||(g=c?d:f),!r.startTranscoding())throw r.close(),r.delete(),new Error("Failed to start transcoding url="+t);for(var S=[],b=0;b<l;++b){var w=r.getImageTranscodedSizeInBytes(0,b,g),T=new Uint8Array(w);if(!r.transcodeImage(T,0,b,g,0,0))throw r.close(),r.delete(),new Error("Failed to transcode image url="+t);var A=g===f||g===p;S.push(A?new Uint16Array(T.buffer):T)}if(r.close(),r.delete(),x)for(g=f,v=0;v<S.length;++v)S[v]=L(I(S[v]));return{format:R(g,n.deviceDetails),width:a,height:o,levels:S,cubemap:!1,transcodeTime:D()-s,url:t,unswizzledGGGR:x}}(t,i,n)},B=function(e,t,i){try{var n=F(e,t,i);n.levels=n.levels.map((function(e){return e.buffer})),self.postMessage({url:e,data:n},n.levels)}catch(t){self.postMessage({url:e,err:t},null)}},N=[];self.onmessage=function(n){var s=n.data;switch(s.type){case"init":!function(n,s){self.BASIS(n.module?{instantiateWasm:function(e,t){return WebAssembly.instantiate(n.module,e).then((function(e){t(e)})).catch((function(e){console.error("instantiate failed + "+e)})),{}}}:null).then((function(r){r.initializeBasis(),e=r,t=n.rgbPriority,i=n.rgbaPriority,s(null)}))}(s.config,(function(){for(var e=0;e<N.length;++e)B(N[e].url,N[e].data,N[e].options);N.length=0}));break;case"transcode":e?B(s.url,s.data,s.options):N.push(s)}}}var nS=function(e){return{astc:!!e.extCompressedTextureASTC,atc:!!e.extCompressedTextureATC,dxt:!!e.extCompressedTextureS3TC,etc1:!!e.extCompressedTextureETC1,etc2:!!e.extCompressedTextureETC,pvr:!!e.extCompressedTexturePVRTC}},sS=function(){function e(){this.callbacks={},this.queue=[],this.clients=[]}var t=e.prototype;return t.enqueueJob=function(e,t,i,n){if(this.callbacks.hasOwnProperty(e))this.callbacks[e].push(i);else{this.callbacks[e]=[i];var s={url:e,data:t,options:n};this.clients.length>0?this.clients.shift().run(s):this.queue.push(s)}},t.enqueueClient=function(e){this.queue.length>0?e.run(this.queue.shift()):this.clients.push(e)},t.handleResponse=function(e,t,i){var n=this.callbacks[e];if(t)for(var s=0;s<n.length;++s)n[s](t);else{3===i.format||5===i.format?i.levels=i.levels.map((function(e){return new Uint16Array(e)})):i.levels=i.levels.map((function(e){return new Uint8Array(e)}));for(var r=0;r<n.length;++r)n[r](null,i)}delete this.callbacks[e]},e}(),rS=function(){function e(e,t,i){var n=this;this.queue=e,this.worker=new Worker(t.workerUrl),this.worker.addEventListener("message",(function(e){var t=e.data;n.queue.handleResponse(t.url,t.err,t.data),n.eager||n.queue.enqueueClient(n)})),this.worker.postMessage({type:"init",config:t}),this.eager=i}return e.prototype.run=function(e){var t=[];e.data instanceof ArrayBuffer&&t.push(e.data),this.worker.postMessage({type:"transcode",url:e.url,format:e.format,data:e.data,options:e.options},t),this.eager&&this.queue.enqueueClient(this)},e}(),aS=["etc1","etc2","astc","dxt","pvr","atc"],oS=["astc","dxt","etc2","pvr","atc"],hS=new sS,lS=null,cS=!1;function uS(e){if(!cS){if(e){if(e.lazyInit)return void(lS=e)}else e=lS||{};if(!e.glueUrl||!e.wasmUrl||!e.fallbackUrl){var t=((window.config?window.config.wasmModules:window.PRELOAD_MODULES)||[]).find((function(e){return"BASIS"===e.moduleName}));if(t){var i=window.ASSET_PREFIX||"";e.glueUrl||(e.glueUrl=i+t.glueUrl),e.wasmUrl||(e.wasmUrl=i+t.wasmUrl),e.fallbackUrl||(e.fallbackUrl=i+t.fallbackUrl)}}if(e.glueUrl||e.wasmUrl||e.fallbackUrl){cS=!0;var n=Math.max(1,Math.min(16,e.numWorkers||1)),s=1===e.numWorkers||!e.hasOwnProperty("eagerWorkers")||e.eagerWorkers;e.rgbPriority=e.rgbPriority||aS,e.rgbaPriority=e.rgbaPriority||oS,e.maxRetries=e.hasOwnProperty("maxRetries")?e.maxRetries:5,function(e,t){var i=function(e){var t=["/* basis */",e,"","("+iS.toString()+")()\n\n"].join("\n");return new Blob([t],{type:"application/javascript"})},n=function(n,s){t(null,{workerUrl:URL.createObjectURL(i(n)),module:s,rgbPriority:e.rgbPriority,rgbaPriority:e.rgbaPriority})},s={cache:!0,responseType:"text",retry:e.maxRetries>0,maxRetries:e.maxRetries};if(e.glueUrl&&e.wasmUrl&&function(){try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){var e=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(e instanceof WebAssembly.Module)return new WebAssembly.Instance(e)instanceof WebAssembly.Instance}}catch(e){}return!1}()){var r=null,a=null;Tr.get(e.glueUrl,s,(function(e,i){e?t(e):a?n(i,a):r=i}));var o=fetch(e.wasmUrl),h=function(){o.then((function(e){return e.arrayBuffer()})).then((function(e){return WebAssembly.compile(e)})).then((function(e){r?n(r,e):a=e})).catch((function(e){t(e,null)}))};WebAssembly.compileStreaming?WebAssembly.compileStreaming(o).then((function(e){r?n(r,e):a=e})).catch((function(e){h()})):h()}else Tr.get(e.fallbackUrl,s,(function(e,i){e?t(e,null):n(i,null)}))}(e,(function(e,t){if(e)console.error("failed to initialize basis worker: "+e);else for(var i=0;i<n;++i)hS.enqueueClient(new rS(hS,t,s))}))}}}var dS=null;function fS(e,t,i,n,s){return uS(),dS||(dS={webgl2:e.webgl2,formats:nS(e)}),hS.enqueueJob(t,i,n,{deviceDetails:dS,isGGGR:!(null==s||!s.isGGGR),isKTX2:!(null==s||!s.isKTX2)}),cS}var pS=function(){function e(e,t){this.device=t,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t,i){var n=this.device;kd.fetchArrayBuffer(e.load,(function(s,r){s?t(s):function(s){var r,a,o;fS(n,e.load,s,t,{isGGGR:0!=(8&(null==i||null==(r=i.file)||null==(a=r.variants)||null==(o=a.basis)?void 0:o.opt))})||t("Basis module not found. Asset '"+i.name+"' basis texture variant will not be loaded.")}(r)}),i,this.maxRetries)},t.open=function(e,t,i,n){void 0===n&&(n={});var s=new Yn(i,$({name:e,addressU:t.cubemap?1:0,addressV:t.cubemap?1:0,width:t.width,height:t.height,format:t.format,cubemap:t.cubemap,levels:t.levels},n));return s.upload(),s},e}(),mS=function(){function e(e,t){this.crossOrigin=e.prefix?"anonymous":null,this.maxRetries=0,this.device=t}var t=e.prototype;return t.load=function(e,t,i){var n,s=!(null==i||null==(n=i.file)||!n.contents);if(s){if(this.device.supportsImageBitmap)return void this._loadImageBitmapFromBlob(new Blob([i.file.contents]),t);e={load:URL.createObjectURL(new Blob([i.file.contents])),original:e.original}}var r,a=function(i,n){s&&URL.revokeObjectURL(e.load),t(i,n)};i&&i.options&&i.options.hasOwnProperty("crossOrigin")?r=i.options.crossOrigin:Rd.test(e.load)&&(r=this.crossOrigin),this.device.supportsImageBitmap?this._loadImageBitmap(e.load,e.original,r,a):this._loadImage(e.load,e.original,r,a)},t.open=function(e,t,i,n){void 0===n&&(n={});var s=new Yn(i,$({name:e,width:t.width,height:t.height,format:7},n));return s.setSource(t),s},t._loadImage=function(e,t,i,n){var s=new Image;i&&(s.crossOrigin=i);var r,a=0,o=this.maxRetries;s.onload=function(){n(null,s)},s.onerror=function(){if(!r)if(o>0&&++a<=o){var i=100*Math.pow(2,a);console.log("Error loading Texture from: '"+t+"' - Retrying in "+i+"ms...");var h=e.indexOf("?")>=0?"&":"?";r=setTimeout((function(){s.src=e+h+"retry="+Date.now(),r=null}),i)}else n("Error loading Texture from: '"+t+"'")},s.src=e},t._loadImageBitmap=function(e,t,i,n){var s=this,r={cache:!0,responseType:"blob",retry:this.maxRetries>0,maxRetries:this.maxRetries};Tr.get(e,r,(function(e,t){e?n(e):s._loadImageBitmapFromBlob(t,n)}))},t._loadImageBitmapFromBlob=function(e,t){createImageBitmap(e,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then((function(e){return t(null,e)})).catch((function(e){return t(e)}))},e}(),_S=[1481919403,3140563232,169478669],gS={33776:8,33778:9,33779:je,36196:tt,37492:22,37496:23,35840:st,35841:it,35842:rt,35843:nt,32849:6,32856:7,35905:19,35907:20,35898:et,34843:qe,34842:Ye};for(var vS=function(){function e(e){this.maxRetries=0}var t=e.prototype;return t.load=function(e,t,i){kd.fetchArrayBuffer(e.load,t,i,this.maxRetries)},t.open=function(e,t,i,n){void 0===n&&(n={});var s=this.parse(t);if(!s)return null;var r=new Yn(i,$({name:e,addressU:s.cubemap?1:0,addressV:s.cubemap?1:0,width:s.width,height:s.height,format:s.format,cubemap:s.cubemap,levels:s.levels},n));return r.upload(),r},t.parse=function(e){var t=new Uint32Array(e);if(_S[0]!==t[0]||_S[1]!==t[1]||_S[2]!==t[2])return null;var i={endianness:t[3],glType:t[4],glTypeSize:t[5],glFormat:t[6],glInternalFormat:t[7],glBaseInternalFormat:t[8],pixelWidth:t[9],pixelHeight:t[10],pixelDepth:t[11],numberOfArrayElements:t[12],numberOfFaces:t[13],numberOfMipmapLevels:t[14],bytesOfKeyValueData:t[15]};if(i.pixelDepth>1)return null;if(0!==i.numberOfArrayElements)return null;var n=gS[i.glInternalFormat];if(void 0===n)return null;for(var s,r,a,o=16+i.bytesOfKeyValueData/4,h=i.numberOfFaces>1,l=[],c=0;c<(i.numberOfMipmapLevels||1);c++){var u=t[o++];h&&l.push([]);for(var d=h?l[c]:l,f=0;f<(h?6:1);++f)d.push((s=e,r=4*o,a=u,n===et?new Uint32Array(s,r,a/4):new Uint8Array(s,r,a))),o+=u+3>>2}return{format:n,width:i.pixelWidth,height:i.pixelHeight,levels:l,cubemap:h}},e}(),yS=166,xS=function(){function e(e,t){this.maxRetries=0,this.device=t}var t=e.prototype;return t.load=function(e,t,i){var n=this;kd.fetchArrayBuffer(e.load,(function(s,r){s?t(s,r):n.parse(r,e,t,i)}),i,this.maxRetries)},t.open=function(e,t,i,n){void 0===n&&(n={});var s=new Yn(i,$({name:e,addressU:t.cubemap?1:0,addressV:t.cubemap?1:0,width:t.width,height:t.height,format:t.format,cubemap:t.cubemap,levels:t.levels},n));return s.upload(),s},t.parse=function(e,t,i,n){var s=new se(e),r=[s.readU32be(),s.readU32be(),s.readU32be()];if(2873840728!==r[0]||540160187!==r[1]||218765834!==r[2])return null;for(var a={vkFormat:s.readU32(),typeSize:s.readU32(),pixelWidth:s.readU32(),pixelHeight:s.readU32(),pixelDepth:s.readU32(),layerCount:s.readU32(),faceCount:s.readU32(),levelCount:s.readU32(),supercompressionScheme:s.readU32()},o={dfdByteOffset:s.readU32(),dfdByteLength:s.readU32(),kvdByteOffset:s.readU32(),kvdByteLength:s.readU32(),sgdByteOffset:s.readU64(),sgdByteLength:s.readU64()},h=[],l=0;l<Math.max(1,a.levelCount);++l)h.push({byteOffset:s.readU64(),byteLength:s.readU64(),uncompressedByteLength:s.readU64()});if(s.readU32()!==o.kvdByteOffset-o.dfdByteOffset)return null;s.skip(8);var c,u,d,f=s.readU8();(s.skip(o.dfdByteLength-9),s.skip(o.kvdByteLength),1===a.supercompressionScheme||f===yS)?fS(this.device,t.load,e,i,{isGGGR:0!=(8&(null==n||null==(c=n.file)||null==(u=c.variants)||null==(d=u.basis)?void 0:d.opt)),isKTX2:!0})||i('Basis module not found. Asset "'+n.name+'" basis texture variant will not be loaded.'):i("unsupported KTX2 pixel format")},e}(),SS=function(){function e(e){this.maxRetries=0}var t=e.prototype;return t.load=function(e,t,i){kd.fetchArrayBuffer(e.load,t,i,this.maxRetries)},t.open=function(e,t,i,n){void 0===n&&(n={});var s,r=new Uint32Array(t,0,32),a=r[4],o=r[3],h=Math.max(r[7],1),l=4===r[20],c=r[21],u=r[22],d=65024===r[28],f=827611204,p=825438800,m=825439312,_=!1,g=!1,v=!1,y=!1,x=null,S=1;if(l?c===f?(x=8,_=!0):894720068===c?(x=je,_=!0):113===c?(x=Ye,S=2):116===c?(x=Ze,S=4):826496069===c?(x=tt,_=!0,g=!0):c===p||825504336===c?(x=c===p?it:nt,_=!0,v=!0):c!==m&&825504848!==c||(x=c===m?st:rt,_=!0,y=!0):32===u&&(x=7),!x)return s=new Yn(i,{width:4,height:4,format:6,name:"dds-legacy-empty"});s=new Yn(i,$({name:e,addressU:d?1:0,addressV:d?1:0,width:a,height:o,format:x,cubemap:d,mipmaps:h>1},n));for(var b,w=128,T=d?6:1,A=c===f?8:16,C=0;C<T;C++)for(var E=a,M=o,P=0;P<h;P++){b=_?g?Math.floor((E+3)/4)*Math.floor((M+3)/4)*8:v?Math.max(E,16)*Math.max(M,8)/4:y?Math.max(E,8)*Math.max(M,8)/2:Math.floor((E+4-1)/4)*Math.floor((M+4-1)/4)*A:E*M*4;var R=x===Ze?new Float32Array(t,w,b):x===Ye?new Uint16Array(t,w,b):new Uint8Array(t,w,b);d?(s._levels[P]||(s._levels[P]=[]),s._levels[P][C]=R):s._levels[P]=R,w+=b*S,E=Math.max(.5*E,1),M=Math.max(.5*M,1)}return s.upload(),s},e}(),bS=function(){function e(e){this.maxRetries=0}var t=e.prototype;return t.load=function(e,t,i){kd.fetchArrayBuffer(e.load,t,i,this.maxRetries)},t.open=function(e,t,i,n){void 0===n&&(n={});var s=this.parse(t);if(!s)return null;var r=new Yn(i,$({name:e,addressU:0,addressV:1,minFilter:0,magFilter:0,width:s.width,height:s.height,levels:s.levels,format:7,type:Ht,mipmaps:!1},n));return r.upload(),r},t.parse=function(e){var t=new se(e);if(!t.readLine().startsWith("#?RADIANCE"))return null;for(var i={};;){var n=t.readLine();if(0===n.length)break;var s=n.split("=");2===s.length&&(i[s[0]]=s[1])}if(!i.hasOwnProperty("FORMAT"))return null;var r=t.readLine().split(" ");if(4!==r.length)return null;var a=parseInt(r[1],10),o=parseInt(r[3],10),h=this._readPixels(t,o,a,"-Y"===r[0]);return h?{width:o,height:a,levels:[h]}:null},t._readPixels=function(e,t,i,n){if(t<8||t>32767)return this._readPixelsFlat(e,t,i);var s=[0,0,0,0];if(e.readArray(s),2!==s[0]||2!==s[1]||0!=(128&s[2]))return e.skip(-4),this._readPixelsFlat(e,t,i);var r,a,o,h,l,c,u=new ArrayBuffer(t*i*4),d=new Uint8Array(u),f=n?0:4*t*(i-1);for(a=0;a<i;++a){if(a&&e.readArray(s),(s[2]<<8)+s[3]!==t)return null;for(h=0;h<4;++h)for(r=0;r<t;)if((l=e.readU8())>128){if(r+(l-=128)>t)return null;for(c=e.readU8(),o=0;o<l;++o)d[f+h+4*r++]=c}else{if(0===l||r+l>t)return null;for(o=0;o<l;++o)d[f+h+4*r++]=e.readU8()}f+=4*t*(n?1:-1)}return d},t._readPixelsFlat=function(e,t,i){return e.remainingBytes===t*i*4?new Uint8Array(e.arraybuffer,e.offset):null},e}(),wS={repeat:0,clamp:1,mirror:2},TS={nearest:0,linear:1,nearest_mip_nearest:2,linear_mip_nearest:4,nearest_mip_linear:3,linear_mip_linear:5},AS={default:Vt,rgbm:Gt,rgbe:Ht,rgbp:Wt,swizzleGGGR:Xt},CS=function(){function e(){}var t=e.prototype;return t.load=function(e,t,i){throw new Error("not implemented")},t.open=function(e,t,i){throw new Error("not implemented")},e}(),ES=function(){function e(e){this.handlerType="texture";var t=e.assets,i=e.graphicsDevice;this._device=i,this._assets=t,this.imgParser=new mS(t,i),this.parsers={dds:new SS(t),ktx:new vS(t),ktx2:new xS(t,i),basis:new pS(t,i),hdr:new bS(t)}}var t=e.prototype;return t._getUrlWithoutParams=function(e){return e.indexOf("?")>=0?e.split("?")[0]:e},t._getParser=function(e){var t=v.getExtension(this._getUrlWithoutParams(e)).toLowerCase().replace(".","");return this.parsers[t]||this.imgParser},t._getTextureOptions=function(e){var t={};if(e){var i;(null==(i=e.name)?void 0:i.length)>0&&(t.name=e.name);var n=e.data;n.hasOwnProperty("minfilter")&&(t.minFilter=TS[n.minfilter]),n.hasOwnProperty("magfilter")&&(t.magFilter=TS[n.magfilter]),n.hasOwnProperty("addressu")&&(t.addressU=wS[n.addressu]),n.hasOwnProperty("addressv")&&(t.addressV=wS[n.addressv]),n.hasOwnProperty("mipmaps")&&(t.mipmaps=n.mipmaps),n.hasOwnProperty("anisotropy")&&(t.anisotropy=n.anisotropy),n.hasOwnProperty("flipY")&&(t.flipY=!!n.flipY),n.hasOwnProperty("type")?t.type=AS[n.type]:n.hasOwnProperty("rgbm")&&n.rgbm?t.type=Gt:e.file&&0!=(8&e.file.opt)&&(t.type=Xt)}return t},t.load=function(e,t,i){"string"==typeof e&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,i)},t.open=function(e,t,i){if(e){var n=this._getTextureOptions(i),s=this._getParser(e).open(e,t,this._device,n);return null===s?s=new Yn(this._device,{width:4,height:4,format:6}):(!function(e){var t=Math.log2(Math.max(e._width,e._height))+1;if(!(7!==e._format&&e._format!==Ze||e._volume||e._compressed||1===e._levels.length||e._levels.length===t||(i=e._cubemap?e._levels[0][0]:e._levels[0],i instanceof HTMLCanvasElement||i instanceof HTMLImageElement||i instanceof HTMLVideoElement))){for(var i,n=function(e,t,i){for(var n=Math.max(1,e>>1),s=Math.max(1,t>>1),r=new i.constructor(n*s*4),a=Math.floor(e/n),o=Math.floor(t/s),h=a*o,l=0;l<s;++l)for(var c=0;c<n;++c)for(var u=0;u<4;++u){for(var d=0,f=0;f<o;++f)for(var p=0;p<a;++p)d+=i[4*(c*a+p+(l*o+f)*e)+u];r[4*(c+l*n)+u]=d/h}return r},s=e._levels.length;s<t;++s){var r=Math.max(1,e._width>>s-1),a=Math.max(1,e._height>>s-1);if(e._cubemap){for(var o=[],h=0;h<6;++h)o.push(n(r,a,e._levels[s-1][h]));e._levels.push(o)}else e._levels.push(n(r,a,e._levels[s-1]))}e._levelsUpdated=e._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0]}}(s),t.unswizzledGGGR&&(i.file.variants.basis.opt&=-9)),s}},t.patch=function(e,t){var i=e.resource;if(i)for(var n=this._getTextureOptions(e),s=0,r=Object.keys(n);s<r.length;s++){var a=r[s];i[a]=n[a]}},Z(e,[{key:"crossOrigin",get:function(){return this.imgParser.crossOrigin},set:function(e){this.imgParser.crossOrigin=e}},{key:"maxRetries",get:function(){return this.imgParser.maxRetries},set:function(e){for(var t in this.imgParser.maxRetries=e,this.parsers)this.parsers.hasOwnProperty(t)&&(this.parsers[t].maxRetries=e)}}]),e}(),MS="inline",PS="immersive-vr",RS="immersive-ar",IS="viewer",LS="left",DS="cpu-optimized",OS="gpu-optimized",kS="luminance-alpha",FS=function(e){function t(t){var i;return(i=e.call(this)||this)._manager=void 0,i._available=!1,i._depthInfoCpu=null,i._depthInfoGpu=null,i._usage=null,i._dataFormat=null,i._matrixDirty=!1,i._matrix=new Te,i._emptyBuffer=new Uint8Array(32),i._depthBuffer=null,i._texture=void 0,i._manager=t,i._texture=new Yn(i._manager.app.graphicsDevice,{format:2,mipmaps:!1,addressU:1,addressV:1,minFilter:1,magFilter:1,name:"XRDepthSensing"}),i.supported&&(i._manager.on("start",i._onSessionStart,ee(i)),i._manager.on("end",i._onSessionEnd,ee(i))),i}Q(t,e);var i=t.prototype;return i.destroy=function(){this._texture.destroy(),this._texture=null},i._onSessionStart=function(){var e=this._manager.session;try{this._usage=e.depthUsage,this._dataFormat=e.depthDataFormat}catch(e){this._usage=null,this._dataFormat=null,this._available=!1,this.fire("error",e)}},i._onSessionEnd=function(){this._depthInfoCpu=null,this._depthInfoGpu=null,this._usage=null,this._dataFormat=null,this._available&&(this._available=!1,this.fire("unavailable")),this._depthBuffer=null,this._texture._width=4,this._texture._height=4,this._texture._levels[0]=this._emptyBuffer,this._texture.upload()},i._updateTexture=function(){var e=this._depthInfoCpu||this._depthInfoGpu;if(e){var t=!1;if(e.width===this._texture.width&&e.height===this._texture.height||(this._texture._width=e.width,this._texture._height=e.height,this._matrixDirty=!0,t=!0),this._depthInfoCpu){var i=this._depthInfoCpu.data;this._depthBuffer=new Uint8Array(i),this._texture._levels[0]=this._depthBuffer,this._texture.upload()}else this._depthInfoGpu&&(this._texture._levels[0]=this._depthInfoGpu.texture,this._texture.upload());t&&this.fire("resize",e.width,e.height)}else this._depthBuffer&&(this._depthBuffer=null,this._texture._width=4,this._texture._height=4,this._texture._levels[0]=this._emptyBuffer,this._texture.upload())},i.update=function(e,t){if(this._usage){var i=null,n=null;if(this._usage===DS&&t?i=e.getDepthInformation(t):this._usage===OS&&t&&(n=e.getDepthInformation(t)),(this._depthInfoCpu&&!i||!this._depthInfoCpu&&i||this.depthInfoGpu&&!n||!this._depthInfoGpu&&n)&&(this._matrixDirty=!0),this._depthInfoCpu=i,this._depthInfoGpu=n,this._updateTexture(),this._matrixDirty){this._matrixDirty=!1;var s=this._depthInfoCpu||this._depthInfoGpu;s?this._matrix.data.set(s.normDepthBufferFromNormView.matrix):this._matrix.setIdentity()}!this._depthInfoCpu&&!this._depthInfoGpu||this._available?this._depthInfoCpu||this._depthInfoGpu||!this._available||(this._available=!1,this.fire("unavailable")):(this._available=!0,this.fire("available"))}},i.getDepth=function(e,t){return this._depthInfoCpu?this._depthInfoCpu.getDepthInMeters(e,t):null},Z(t,[{key:"supported",get:function(){return M.browser&&!!window.XRDepthInformation}},{key:"available",get:function(){return this._available}},{key:"usage",get:function(){return this._usage}},{key:"dataFormat",get:function(){return this._dataFormat}},{key:"width",get:function(){var e=this._depthInfoCpu||this._depthInfoGpu;return e&&e.width||0}},{key:"height",get:function(){var e=this._depthInfoCpu||this._depthInfoGpu;return e&&e.height||0}},{key:"texture",get:function(){return this._texture}},{key:"uvMatrix",get:function(){return this._matrix}},{key:"rawValueToMeters",get:function(){var e=this._depthInfoCpu||this._depthInfoGpu;return e&&e.rawValueToMeters||0}}]),t}(p),BS=function(){function e(e){this._manager=void 0,this._supported=M.browser&&!!window.XRDOMOverlayState,this._root=null,this._manager=e}return Z(e,[{key:"supported",get:function(){return this._supported}},{key:"available",get:function(){return this._supported&&this._manager.active&&null!==this._manager._session.domOverlayState}},{key:"state",get:function(){return this._supported&&this._manager.active&&this._manager._session.domOverlayState?this._manager._session.domOverlayState.type:null}},{key:"root",get:function(){return this._root},set:function(e){this._supported&&!this._manager.active&&(this._root=e)}}]),e}(),NS=[],US=[],zS=function(e){function t(t,i,n){var s;return(s=e.call(this)||this).manager=void 0,s._xrHitTestSource=void 0,s._transient=void 0,s.manager=t,s._xrHitTestSource=i,s._transient=n,s}Q(t,e);var i=t.prototype;return i.remove=function(){if(this._xrHitTestSource){var e=this.manager.hitTest.sources,t=e.indexOf(this);-1!==t&&e.splice(t,1),this.onStop()}},i.onStop=function(){this._xrHitTestSource.cancel(),this._xrHitTestSource=null,this.fire("remove"),this.manager.hitTest.fire("remove",this)},i.update=function(e){if(this._transient)for(var t=e.getHitTestResultsForTransientInput(this._xrHitTestSource),i=0;i<t.length;i++){var n=t[i],s=void 0;n.inputSource&&(s=this.manager.input._getByInputSource(n.inputSource)),this.updateHitResults(n.results,s)}else this.updateHitResults(e.getHitTestResults(this._xrHitTestSource))},i.updateHitResults=function(e,t){for(var i=0;i<e.length;i++){var n=e[i].getPose(this.manager._referenceSpace),s=NS.pop();s||(s=new me),s.copy(n.transform.position);var r=US.pop();r||(r=new Ae),r.copy(n.transform.orientation),this.fire("result",s,r,t),this.manager.hitTest.fire("result",this,s,r,t),NS.push(s),US.push(r)}},t}(p),VS=function(e){function t(t){var i;return(i=e.call(this)||this).manager=void 0,i._supported=M.browser&&!(!window.XRSession||!window.XRSession.prototype.requestHitTestSource),i._session=null,i.sources=[],i.manager=t,i._supported&&(i.manager.on("start",i._onSessionStart,ee(i)),i.manager.on("end",i._onSessionEnd,ee(i))),i}Q(t,e);var i=t.prototype;return i._onSessionStart=function(){this.manager.type===RS&&(this._session=this.manager.session)},i._onSessionEnd=function(){if(this._session){this._session=null;for(var e=0;e<this.sources.length;e++)this.sources[e].onStop();this.sources=[]}},i.isAvailable=function(e,t){var i;return this._supported||(i=new Error("XR HitTest is not supported")),this._session||(i=new Error("XR Session is not started (1)")),this.manager.type!==RS&&(i=new Error("XR HitTest is available only for AR")),!i||(e&&e(i),t&&t.fire("error",i),!1)},i.start=function(e){var t=this;if(void 0===e&&(e={}),this.isAvailable(e.callback,this)){var i;e.profile||e.spaceType||(e.spaceType=IS);var n=e.offsetRay;if(n){var s=new DOMPoint(n.origin.x,n.origin.y,n.origin.z,1),r=new DOMPoint(n.direction.x,n.direction.y,n.direction.z,0);i=new XRRay(s,r)}var a=e.callback;e.spaceType?this._session.requestReferenceSpace(e.spaceType).then((function(n){if(!t._session){var s=new Error("XR Session is not started (2)");return a&&a(s),void t.fire("error",s)}t._session.requestHitTestSource({space:n,entityTypes:e.entityTypes||void 0,offsetRay:i}).then((function(e){t._onHitTestSource(e,!1,a)})).catch((function(e){a&&a(e),t.fire("error",e)}))})).catch((function(e){a&&a(e),t.fire("error",e)})):this._session.requestHitTestSourceForTransientInput({profile:e.profile,entityTypes:e.entityTypes||void 0,offsetRay:i}).then((function(e){t._onHitTestSource(e,!0,a)})).catch((function(e){a&&a(e),t.fire("error",e)}))}},i._onHitTestSource=function(e,t,i){if(!this._session){e.cancel();var n=new Error("XR Session is not started (3)");return i&&i(n),void this.fire("error",n)}var s=new zS(this.manager,e,t);this.sources.push(s),i&&i(null,s),this.fire("add",s)},i.update=function(e){for(var t=0;t<this.sources.length;t++)this.sources[t].update(e)},Z(t,[{key:"supported",get:function(){return this._supported}}]),t}(p),GS=function(e){function t(t,i){var n;return(n=e.call(this)||this)._image=void 0,n._width=void 0,n._bitmap=null,n._measuredWidth=0,n._trackable=!1,n._tracking=!1,n._emulated=!1,n._pose=null,n._position=new me,n._rotation=new Ae,n._image=t,n._width=i,n}Q(t,e);var i=t.prototype;return i.prepare=function(){var e=this;return this._bitmap?{image:this._bitmap,widthInMeters:this._width}:createImageBitmap(this._image).then((function(t){return e._bitmap=t,{image:e._bitmap,widthInMeters:e._width}}))},i.destroy=function(){this._image=null,this._pose=null,this._bitmap&&(this._bitmap.close(),this._bitmap=null)},i.getPosition=function(){return this._pose&&this._position.copy(this._pose.transform.position),this._position},i.getRotation=function(){return this._pose&&this._rotation.copy(this._pose.transform.orientation),this._rotation},Z(t,[{key:"image",get:function(){return this._image}},{key:"width",get:function(){return this._width},set:function(e){this._width=e}},{key:"trackable",get:function(){return this._trackable}},{key:"tracking",get:function(){return this._tracking}},{key:"emulated",get:function(){return this._emulated}}]),t}(p),HS=function(e){function t(t){var i;return(i=e.call(this)||this)._manager=void 0,i._supported=M.browser&&!!window.XRImageTrackingResult,i._available=!1,i._images=[],i._manager=t,i._supported&&(i._manager.on("start",i._onSessionStart,ee(i)),i._manager.on("end",i._onSessionEnd,ee(i))),i}Q(t,e);var i=t.prototype;return i.add=function(e,t){if(!this._supported||this._manager.active)return null;var i=new GS(e,t);return this._images.push(i),i},i.remove=function(e){if(!this._manager.active){var t=this._images.indexOf(e);-1!==t&&(e.destroy(),this._images.splice(t,1))}},i._onSessionStart=function(){var e=this;this._manager.session.getTrackedImageScores().then((function(t){e._available=!0;for(var i=0;i<t.length;i++)e._images[i]._trackable="trackable"===t[i]})).catch((function(t){e._available=!1,e.fire("error",t)}))},i._onSessionEnd=function(){this._available=!1;for(var e=0;e<this._images.length;e++){var t=this._images[e];t._pose=null,t._measuredWidth=0,t._tracking&&(t._tracking=!1,t.fire("untracked"))}},i.prepareImages=function(e){this._images.length?Promise.all(this._images.map((function(e){return e.prepare()}))).then((function(t){e(null,t)})).catch((function(t){e(t,null)})):e(null,null)},i.update=function(e){if(this._available){for(var t=e.getImageTrackingResults(),i={},n=0;n<t.length;n++){i[t[n].index]=t[n];var s=this._images[t[n].index];s._emulated="emulated"===t[n].trackingState,s._measuredWidth=t[n].measuredWidthInMeters,s._pose=e.getPose(t[n].imageSpace,this._manager._referenceSpace)}for(var r=0;r<this._images.length;r++)this._images[r]._tracking&&!i[r]?(this._images[r]._tracking=!1,this._images[r].fire("untracked")):!this._images[r]._tracking&&i[r]&&(this._images[r]._tracking=!0,this._images[r].fire("tracked"))}},Z(t,[{key:"supported",get:function(){return this._supported}},{key:"available",get:function(){return this._available}},{key:"images",get:function(){return this._images}}]),t}(p),WS=function(){function e(e,t){this._index=void 0,this._hand=void 0,this._joints=[],this._tip=null,this._index=e,this._hand=t,this._hand._fingers.push(this)}return Z(e,[{key:"index",get:function(){return this._index}},{key:"hand",get:function(){return this._hand}},{key:"joints",get:function(){return this._joints}},{key:"tip",get:function(){return this._tip}}]),e}(),XS=M.browser&&window.XRHand?["thumb-tip","index-finger-tip","middle-finger-tip","ring-finger-tip","pinky-finger-tip"]:[],jS={},qS=0;qS<XS.length;qS++)jS[XS[qS]]=!0;var YS=function(){function e(e,t,i,n){void 0===n&&(n=null),this._index=void 0,this._id=void 0,this._hand=void 0,this._finger=void 0,this._wrist=void 0,this._tip=void 0,this._radius=null,this._localTransform=new Te,this._worldTransform=new Te,this._localPosition=new me,this._localRotation=new Ae,this._position=new me,this._rotation=new Ae,this._dirtyLocal=!0,this._index=e,this._id=t,this._hand=i,this._finger=n,this._wrist="wrist"===t,this._tip=this._finger&&!!jS[t]}var t=e.prototype;return t.update=function(e){this._dirtyLocal=!0,this._radius=e.radius,this._localPosition.copy(e.transform.position),this._localRotation.copy(e.transform.orientation)},t._updateTransforms=function(){this._dirtyLocal&&(this._dirtyLocal=!1,this._localTransform.setTRS(this._localPosition,this._localRotation,me.ONE));var e=this._hand._manager.camera.parent;e?this._worldTransform.mul2(e.getWorldTransform(),this._localTransform):this._worldTransform.copy(this._localTransform)},t.getPosition=function(){return this._updateTransforms(),this._worldTransform.getTranslation(this._position),this._position},t.getRotation=function(){return this._updateTransforms(),this._rotation.setFromMat4(this._worldTransform),this._rotation},Z(e,[{key:"index",get:function(){return this._index}},{key:"hand",get:function(){return this._hand}},{key:"finger",get:function(){return this._finger}},{key:"wrist",get:function(){return this._wrist}},{key:"tip",get:function(){return this._tip}},{key:"radius",get:function(){return this._radius||.005}}]),e}(),KS=[],ZS=new me,$S=new me,QS=new me;M.browser&&window.XRHand&&(KS=[["thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip"],["index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip"],["middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip"],["ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip"],["pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"]]);var JS,eb,tb=function(e){function t(t){var i;(i=e.call(this)||this)._manager=void 0,i._inputSource=void 0,i._tracking=!1,i._fingers=[],i._joints=[],i._jointsById={},i._tips=[],i._wrist=null;var n=t._xrInputSource.hand;if(i._manager=t._manager,i._inputSource=t,n.get("wrist")){var s=new YS(0,"wrist",ee(i),null);i._wrist=s,i._joints.push(s),i._jointsById.wrist=s}for(var r=0;r<KS.length;r++)for(var a=new WS(r,ee(i)),o=0;o<KS[r].length;o++){var h=KS[r][o];if(n.get(h)){var l=new YS(o,h,ee(i),a);i._joints.push(l),i._jointsById[h]=l,l.tip&&(i._tips.push(l),a._tip=l),a._joints.push(l)}}return i}Q(t,e);var i=t.prototype;return i.update=function(e){for(var t=this._inputSource._xrInputSource,i=0;i<this._joints.length;i++){var n=this._joints[i],s=t.hand.get(n._id);if(s){var r=void 0;if("hidden"!==e.session.visibilityState&&(r=e.getJointPose(s,this._manager._referenceSpace)),r)n.update(r),n.wrist&&!this._tracking&&(this._tracking=!0,this.fire("tracking"));else if(n.wrist){this._tracking&&(this._tracking=!1,this.fire("trackinglost"));break}}}var a=this._jointsById["thumb-metacarpal"],o=this._jointsById["thumb-tip"],h=this._jointsById["index-finger-phalanx-proximal"],l=this._jointsById["index-finger-tip"],c=this._jointsById["ring-finger-phalanx-proximal"],u=this._jointsById["pinky-finger-phalanx-proximal"];if(a&&o&&h&&l&&c&&u){this._inputSource._dirtyRay=!0,this._inputSource._rayLocal.origin.lerp(o._localPosition,l._localPosition,.5);var d=a,f=u;if(this._inputSource.handedness===LS){var p=d;d=f,f=p}ZS.sub2(d._localPosition,this._wrist._localPosition),$S.sub2(f._localPosition,this._wrist._localPosition),QS.cross(ZS,$S).normalize(),ZS.lerp(h._localPosition,c._localPosition,.5),ZS.sub(this._wrist._localPosition).normalize(),this._inputSource._rayLocal.direction.lerp(QS,ZS,.5).normalize()}this._fingerIsClosed(1)&&this._fingerIsClosed(2)&&this._fingerIsClosed(3)&&this._fingerIsClosed(4)?this._inputSource._squeezing||(this._inputSource._squeezing=!0,this._inputSource.fire("squeezestart"),this._manager.input.fire("squeezestart",this._inputSource)):this._inputSource._squeezing&&(this._inputSource._squeezing=!1,this._inputSource.fire("squeeze"),this._manager.input.fire("squeeze",this._inputSource),this._inputSource.fire("squeezeend"),this._manager.input.fire("squeezeend",this._inputSource))},i._fingerIsClosed=function(e){var t=this._fingers[e];return ZS.sub2(t.joints[0]._localPosition,t.joints[1]._localPosition).normalize(),$S.sub2(t.joints[2]._localPosition,t.joints[3]._localPosition).normalize(),ZS.dot($S)<-.8},i.getJointById=function(e){return this._jointsById[e]||null},Z(t,[{key:"fingers",get:function(){return this._fingers}},{key:"joints",get:function(){return this._joints}},{key:"tips",get:function(){return this._tips}},{key:"wrist",get:function(){return this._wrist}},{key:"tracking",get:function(){return this._tracking}}]),t}(p),ib=new Ae,nb=0,sb=function(e){function t(t,i){var n;return(n=e.call(this)||this)._id=void 0,n._manager=void 0,n._xrInputSource=void 0,n._ray=new Fe,n._rayLocal=new Fe,n._grip=!1,n._hand=null,n._localTransform=null,n._worldTransform=null,n._position=new me,n._rotation=new Ae,n._localPosition=null,n._localRotation=null,n._dirtyLocal=!0,n._dirtyRay=!1,n._selecting=!1,n._squeezing=!1,n._elementInput=!0,n._elementEntity=null,n._hitTestSources=[],n._id=++nb,n._manager=t,n._xrInputSource=i,i.hand&&(n._hand=new tb(ee(n))),n}Q(t,e);var i=t.prototype;return i.update=function(e){if(this._hand)this._hand.update(e);else{if(this._xrInputSource.gripSpace){var t=e.getPose(this._xrInputSource.gripSpace,this._manager._referenceSpace);t&&(this._grip||(this._grip=!0,this._localTransform=new Te,this._worldTransform=new Te,this._localPosition=new me,this._localRotation=new Ae),this._dirtyLocal=!0,this._localPosition.copy(t.transform.position),this._localRotation.copy(t.transform.orientation))}var i=e.getPose(this._xrInputSource.targetRaySpace,this._manager._referenceSpace);i&&(this._dirtyRay=!0,this._rayLocal.origin.copy(i.transform.position),this._rayLocal.direction.set(0,0,-1),ib.copy(i.transform.orientation),ib.transformVector(this._rayLocal.direction,this._rayLocal.direction))}},i._updateTransforms=function(){this._dirtyLocal&&(this._dirtyLocal=!1,this._localTransform.setTRS(this._localPosition,this._localRotation,me.ONE));var e=this._manager.camera.parent;e?this._worldTransform.mul2(e.getWorldTransform(),this._localTransform):this._worldTransform.copy(this._localTransform)},i._updateRayTransforms=function(){var e=this._dirtyRay;if(this._dirtyRay=!1,this._manager.camera.parent){var t=this._manager.camera.parent.getWorldTransform();t.getTranslation(this._position),this._rotation.setFromMat4(t),this._rotation.transformVector(this._rayLocal.origin,this._ray.origin),this._ray.origin.add(this._position),this._rotation.transformVector(this._rayLocal.direction,this._ray.direction)}else e&&(this._ray.origin.copy(this._rayLocal.origin),this._ray.direction.copy(this._rayLocal.direction))},i.getPosition=function(){return this._position?(this._updateTransforms(),this._worldTransform.getTranslation(this._position),this._position):null},i.getLocalPosition=function(){return this._localPosition},i.getRotation=function(){return this._rotation?(this._updateTransforms(),this._rotation.setFromMat4(this._worldTransform),this._rotation):null},i.getLocalRotation=function(){return this._localRotation},i.getOrigin=function(){return this._updateRayTransforms(),this._ray.origin},i.getDirection=function(){return this._updateRayTransforms(),this._ray.direction},i.hitTestStart=function(e){var t=this;void 0===e&&(e={}),e.profile=this._xrInputSource.profiles[0];var i=e.callback;e.callback=function(e,n){n&&t.onHitTestSourceAdd(n),i&&i(e,n)},this._manager.hitTest.start(e)},i.onHitTestSourceAdd=function(e){this._hitTestSources.push(e),this.fire("hittest:add",e),e.on("result",(function(t,i,n){n===this&&this.fire("hittest:result",e,t,i)}),this),e.once("remove",(function(){this.onHitTestSourceRemove(e),this.fire("hittest:remove",e)}),this)},i.onHitTestSourceRemove=function(e){var t=this._hitTestSources.indexOf(e);-1!==t&&this._hitTestSources.splice(t,1)},Z(t,[{key:"id",get:function(){return this._id}},{key:"inputSource",get:function(){return this._xrInputSource}},{key:"targetRayMode",get:function(){return this._xrInputSource.targetRayMode}},{key:"handedness",get:function(){return this._xrInputSource.handedness}},{key:"profiles",get:function(){return this._xrInputSource.profiles}},{key:"grip",get:function(){return this._grip}},{key:"hand",get:function(){return this._hand}},{key:"gamepad",get:function(){return this._xrInputSource.gamepad||null}},{key:"selecting",get:function(){return this._selecting}},{key:"squeezing",get:function(){return this._squeezing}},{key:"elementInput",get:function(){return this._elementInput},set:function(e){this._elementInput!==e&&(this._elementInput=e,this._elementInput||(this._elementEntity=null))}},{key:"elementEntity",get:function(){return this._elementEntity}},{key:"hitTestSources",get:function(){return this._hitTestSources}}]),t}(p),rb=function(e){function t(t){var i;return(i=e.call(this)||this).manager=void 0,i._inputSources=[],i._onInputSourcesChangeEvt=void 0,i.manager=t,i._onInputSourcesChangeEvt=function(e){i._onInputSourcesChange(e)},i.manager.on("start",i._onSessionStart,ee(i)),i.manager.on("end",i._onSessionEnd,ee(i)),i}Q(t,e);var i=t.prototype;return i._onSessionStart=function(){var e=this,t=this.manager.session;t.addEventListener("inputsourceschange",this._onInputSourcesChangeEvt),t.addEventListener("select",(function(t){var i=e._getByInputSource(t.inputSource);i.update(t.frame),i.fire("select",t),e.fire("select",i,t)})),t.addEventListener("selectstart",(function(t){var i=e._getByInputSource(t.inputSource);i.update(t.frame),i._selecting=!0,i.fire("selectstart",t),e.fire("selectstart",i,t)})),t.addEventListener("selectend",(function(t){var i=e._getByInputSource(t.inputSource);i.update(t.frame),i._selecting=!1,i.fire("selectend",t),e.fire("selectend",i,t)})),t.addEventListener("squeeze",(function(t){var i=e._getByInputSource(t.inputSource);i.update(t.frame),i.fire("squeeze",t),e.fire("squeeze",i,t)})),t.addEventListener("squeezestart",(function(t){var i=e._getByInputSource(t.inputSource);i.update(t.frame),i._squeezing=!0,i.fire("squeezestart",t),e.fire("squeezestart",i,t)})),t.addEventListener("squeezeend",(function(t){var i=e._getByInputSource(t.inputSource);i.update(t.frame),i._squeezing=!1,i.fire("squeezeend",t),e.fire("squeezeend",i,t)}));for(var i=t.inputSources,n=0;n<i.length;n++)this._addInputSource(i[n])},i._onSessionEnd=function(){for(var e=this._inputSources.length;e--;){var t=this._inputSources[e];this._inputSources.splice(e,1),t.fire("remove"),this.fire("remove",t)}this.manager.session.removeEventListener("inputsourceschange",this._onInputSourcesChangeEvt)},i._onInputSourcesChange=function(e){for(var t=0;t<e.removed.length;t++)this._removeInputSource(e.removed[t]);for(var i=0;i<e.added.length;i++)this._addInputSource(e.added[i])},i._getByInputSource=function(e){for(var t=0;t<this._inputSources.length;t++)if(this._inputSources[t].inputSource===e)return this._inputSources[t];return null},i._addInputSource=function(e){if(!this._getByInputSource(e)){var t=new sb(this.manager,e);this._inputSources.push(t),this.fire("add",t)}},i._removeInputSource=function(e){for(var t=0;t<this._inputSources.length;t++)if(this._inputSources[t].inputSource===e){var i=this._inputSources[t];this._inputSources.splice(t,1);for(var n=i.hitTestSources.length;n--;)i.hitTestSources[n].remove();return i.fire("remove"),void this.fire("remove",i)}},i.update=function(e){for(var t=0;t<this._inputSources.length;t++)this._inputSources[t].update(e)},Z(t,[{key:"inputSources",get:function(){return this._inputSources}}]),t}(p),ab=new me,ob=new me,hb=new Te,lb=new Te,cb=function(e){function t(t){var i;return(i=e.call(this)||this)._manager=void 0,i._supported=!1,i._available=!1,i._lightProbeRequested=!1,i._lightProbe=null,i._intensity=0,i._rotation=new Ae,i._color=new ue,i._sphericalHarmonics=new Float32Array(27),i._manager=t,i._manager.on("start",i._onSessionStart,ee(i)),i._manager.on("end",i._onSessionEnd,ee(i)),i}Q(t,e);var i=t.prototype;return i._onSessionStart=function(){!!this._manager.session.requestLightProbe&&(this._supported=!0)},i._onSessionEnd=function(){this._supported=!1,this._available=!1,this._lightProbeRequested=!1,this._lightProbe=null},i.start=function(){var e,t=this;this._manager.session||(e=new Error("XR session is not running")),e||this._manager.type===RS||(e=new Error("XR session type is not AR")),e||this._supported||(e=new Error("light-estimation is not supported")),(!e&&this._lightProbe||this._lightProbeRequested)&&(e=new Error("light estimation is already requested")),e?this.fire("error",e):(this._lightProbeRequested=!0,this._manager.session.requestLightProbe().then((function(e){var i=t._lightProbeRequested;t._lightProbeRequested=!1,t._manager.active?i&&(t._lightProbe=e):t.fire("error",new Error("XR session is not active"))})).catch((function(e){t._lightProbeRequested=!1,t.fire("error",e)})))},i.end=function(){this._lightProbeRequested=!1,this._lightProbe=null,this._available=!1},i.update=function(e){if(this._lightProbe){var t=e.getLightEstimate(this._lightProbe);if(t){this._available||(this._available=!0,this.fire("available"));var i=t.primaryLightIntensity;this._intensity=Math.max(1,Math.max(i.x,Math.max(i.y,i.z))),ab.copy(i).mulScalar(1/this._intensity),this._color.set(ab.x,ab.y,ab.z),ab.set(0,0,0),ob.copy(t.primaryLightDirection),hb.setLookAt(ob,ab,me.UP),lb.setFromAxisAngle(me.RIGHT,90),hb.mul(lb),this._rotation.setFromMat4(hb),this._sphericalHarmonics.set(t.sphericalHarmonicsCoefficients)}}},Z(t,[{key:"supported",get:function(){return this._supported}},{key:"available",get:function(){return this._available}},{key:"intensity",get:function(){return this._available?this._intensity:null}},{key:"color",get:function(){return this._available?this._color:null}},{key:"rotation",get:function(){return this._available?this._rotation:null}},{key:"sphericalHarmonics",get:function(){return this._available?this._sphericalHarmonics:null}}]),t}(p),ub=0,db=function(e){function t(t,i){var n;return(n=e.call(this)||this)._id=void 0,n._planeDetection=void 0,n._xrPlane=void 0,n._lastChangedTime=void 0,n._orientation=void 0,n._position=new me,n._rotation=new Ae,n._id=++ub,n._planeDetection=t,n._xrPlane=i,n._lastChangedTime=i.lastChangedTime,n._orientation=i.orientation,n}Q(t,e);var i=t.prototype;return i.destroy=function(){this.fire("remove")},i.update=function(e){var t=this._planeDetection._manager,i=e.getPose(this._xrPlane.planeSpace,t._referenceSpace);i&&(this._position.copy(i.transform.position),this._rotation.copy(i.transform.orientation)),this._lastChangedTime!==this._xrPlane.lastChangedTime&&(this._lastChangedTime=this._xrPlane.lastChangedTime,this.fire("change"))},i.getPosition=function(){return this._position},i.getRotation=function(){return this._rotation},Z(t,[{key:"id",get:function(){return this._id}},{key:"orientation",get:function(){return this._orientation}},{key:"points",get:function(){return this._xrPlane.polygon}}]),t}(p),fb=function(e){function t(t){var i;return(i=e.call(this)||this)._manager=void 0,i._supported=M.browser&&!!window.XRPlane,i._available=!1,i._planesIndex=new Map,i._planes=null,i._manager=t,i._supported&&i._manager.on("end",i._onSessionEnd,ee(i)),i}Q(t,e);var i=t.prototype;return i._onSessionEnd=function(){if(this._planes)for(var e=0;e<this._planes.length;e++)this._planes[e].destroy();this._planesIndex.clear(),this._planes=null,this._available&&(this._available=!1,this.fire("unavailable"))},i.update=function(e){var t;if(this._available)t=e.detectedPlanes;else try{t=e.detectedPlanes,this._planes=[],this._available=!0,this.fire("available")}catch(e){return}for(var i,n=ie(this._planesIndex);!(i=n()).done;){var s=i.value,r=s[0],a=s[1];t.has(r)||(this._planesIndex.delete(r),this._planes.splice(this._planes.indexOf(a),1),a.destroy(),this.fire("remove",a))}for(var o,h=ie(t);!(o=h()).done;){var l=o.value,c=this._planesIndex.get(l);c?c.update(e):(c=new db(this,l),this._planesIndex.set(l,c),this._planes.push(c),c.update(e),this.fire("add",c))}},Z(t,[{key:"supported",get:function(){return this._supported}},{key:"available",get:function(){return this._available}},{key:"planes",get:function(){return this._planes}}]),t}(p),pb=function(e){function t(t){var i;return(i=e.call(this)||this).app=void 0,i._supported=M.browser&&!!navigator.xr,i._available={},i._type=null,i._spaceType=null,i._session=null,i._baseLayer=null,i._referenceSpace=null,i.depthSensing=void 0,i.domOverlay=void 0,i.hitTest=void 0,i.imageTracking=void 0,i.planeDetection=void 0,i.input=void 0,i.lightEstimation=void 0,i._camera=null,i.views=[],i.viewsPool=[],i._localPosition=new me,i._localRotation=new Ae,i._depthNear=.1,i._depthFar=1e3,i._width=0,i._height=0,i.app=t,i._available[MS]=!1,i._available[PS]=!1,i._available[RS]=!1,i.depthSensing=new FS(ee(i)),i.domOverlay=new BS(ee(i)),i.hitTest=new VS(ee(i)),i.imageTracking=new HS(ee(i)),i.planeDetection=new fb(ee(i)),i.input=new rb(ee(i)),i.lightEstimation=new cb(ee(i)),i._supported&&(navigator.xr.addEventListener("devicechange",(function(){i._deviceAvailabilityCheck()})),i._deviceAvailabilityCheck()),i}Q(t,e);var i=t.prototype;return i.destroy=function(){this.depthSensing.destroy(),this.depthSensing=null},i.start=function(e,t,i,n){var s=this,r=n;if("object"==typeof n&&(r=n.callback),this._available[t])if(this._session)r&&r(new Error("XR session is already started"));else{this._camera=e,this._camera.camera.xr=this,this._type=t,this._spaceType=i,this._setClipPlanes(e.nearClip,e.farClip);var a={requiredFeatures:[i],optionalFeatures:[]};if(t===RS){if(a.optionalFeatures.push("light-estimation"),a.optionalFeatures.push("hit-test"),n&&(n.imageTracking&&this.imageTracking.supported&&a.optionalFeatures.push("image-tracking"),n.planeDetection&&a.optionalFeatures.push("plane-detection")),this.domOverlay.supported&&this.domOverlay.root&&(a.optionalFeatures.push("dom-overlay"),a.domOverlay={root:this.domOverlay.root}),n&&n.depthSensing&&this.depthSensing.supported){a.optionalFeatures.push("depth-sensing");var o=[DS],h=[kS];if(n.depthSensing.usagePreference){var l=o.indexOf(n.depthSensing.usagePreference);-1!==l&&o.splice(l,1),o.unshift(n.depthSensing.usagePreference)}if(n.depthSensing.dataFormatPreference){var c=h.indexOf(n.depthSensing.dataFormatPreference);-1!==c&&h.splice(c,1),h.unshift(n.depthSensing.dataFormatPreference)}a.depthSensing={usagePreference:o,dataFormatPreference:h}}}else t===PS&&a.optionalFeatures.push("hand-tracking");n&&n.optionalFeatures&&(a.optionalFeatures=a.optionalFeatures.concat(n.optionalFeatures)),this.imageTracking.supported&&this.imageTracking.images.length?this.imageTracking.prepareImages((function(e,n){if(e)return r&&r(e),void s.fire("error",e);null!==n&&(a.trackedImages=n),s._onStartOptionsReady(t,i,a,r)})):this._onStartOptionsReady(t,i,a,r)}else r&&r(new Error("XR is not available"))},i._onStartOptionsReady=function(e,t,i,n){var s=this;navigator.xr.requestSession(e,i).then((function(e){s._onSessionStart(e,t,n)})).catch((function(e){s._camera.camera.xr=null,s._camera=null,s._type=null,s._spaceType=null,n&&n(e),s.fire("error",e)}))},i.end=function(e){this._session?(e&&this.once("end",e),this._session.end()):e&&e(new Error("XR Session is not initialized"))},i.isAvailable=function(e){return this._available[e]},i._deviceAvailabilityCheck=function(){for(var e in this._available)this._sessionSupportCheck(e)},i._sessionSupportCheck=function(e){var t=this;navigator.xr.isSessionSupported(e).then((function(i){t._available[e]!==i&&(t._available[e]=i,t.fire("available",e,i),t.fire("available:"+e,i))})).catch((function(e){t.fire("error",e)}))},i._onSessionStart=function(e,t,i){var n=this,s=!1;this._session=e;var r=function(){n.fire("visibility:change",e.visibilityState)},a=function(){n._setClipPlanes(n._camera.nearClip,n._camera.farClip)};e.addEventListener("end",(function t(){n._camera&&(n._camera.off("set_nearClip",a),n._camera.off("set_farClip",a),n._camera.camera.xr=null,n._camera=null),e.removeEventListener("end",t),e.removeEventListener("visibilitychange",r),s||n.fire("end"),n._session=null,n._referenceSpace=null,n.views=[],n._width=0,n._height=0,n._type=null,n._spaceType=null,n.app.tick()})),e.addEventListener("visibilitychange",r),this._camera.on("set_nearClip",a),this._camera.on("set_farClip",a);var o=this.app.graphicsDevice.maxPixelRatio/window.devicePixelRatio;this._baseLayer=new XRWebGLLayer(e,this.app.graphicsDevice.gl,{alpha:!0,depth:!0,stencil:!0,framebufferScaleFactor:o}),e.updateRenderState({baseLayer:this._baseLayer,depthNear:this._depthNear,depthFar:this._depthFar}),e.requestReferenceSpace(t).then((function(e){n._referenceSpace=e,n.app.tick(),i&&i(null),n.fire("start")})).catch((function(t){s=!0,e.end(),i&&i(t),n.fire("error",t)}))},i._setClipPlanes=function(e,t){this._depthNear===e&&this._depthFar===t||(this._depthNear=e,this._depthFar=t,this._session&&this._session.updateRenderState({depthNear:this._depthNear,depthFar:this._depthFar}))},i.update=function(e){if(!this._session)return!1;var t=e.session.renderState.baseLayer.framebufferWidth,i=e.session.renderState.baseLayer.framebufferHeight;this._width===t&&this._height===i||(this._width=t,this._height=i,this.app.graphicsDevice.setResolution(t,i));var n=e.getViewerPose(this._referenceSpace);if(!n)return!1;for(var s=this.views.length,r=n.views.length;r>this.views.length;){var a=this.viewsPool.pop();a||(a={viewport:new ve,projMat:new Te,viewMat:new Te,viewOffMat:new Te,viewInvMat:new Te,viewInvOffMat:new Te,projViewOffMat:new Te,viewMat3:new _e,position:new Float32Array(3),rotation:new Ae}),this.views.push(a)}for(;r<this.views.length;)this.viewsPool.push(this.views.pop());var o=n.transform.position,h=n.transform.orientation;this._localPosition.set(o.x,o.y,o.z),this._localRotation.set(h.x,h.y,h.z,h.w);for(var l=e.session.renderState.baseLayer,c=0;c<n.views.length;c++){var u=n.views[c],d=this.views[c],f=l.getViewport(u);d.viewport.x=f.x,d.viewport.y=f.y,d.viewport.z=f.width,d.viewport.w=f.height,d.projMat.set(u.projectionMatrix),d.viewMat.set(u.transform.inverse.matrix),d.viewInvMat.set(u.transform.matrix)}if(0===s&&this.views.length>0){var p=new Te,m=this.views[0];p.copy(m.projMat);var _=p.data,g=2*Math.atan(1/_[5])*180/Math.PI,v=_[5]/_[0],y=_[14]/(_[10]+1),x=_[14]/(_[10]-1);this._camera.camera.setXrProperties({aspectRatio:v,farClip:y,fov:g,horizontalFov:!1,nearClip:x})}return this._camera.camera._node.setLocalPosition(this._localPosition),this._camera.camera._node.setLocalRotation(this._localRotation),this.input.update(e),this._type===RS&&(this.hitTest.supported&&this.hitTest.update(e),this.lightEstimation.supported&&this.lightEstimation.update(e),this.depthSensing.supported&&this.depthSensing.update(e,n&&n.views[0]),this.imageTracking.supported&&this.imageTracking.update(e),this.planeDetection.supported&&this.planeDetection.update(e)),this.fire("update",e),!0},Z(t,[{key:"supported",get:function(){return this._supported}},{key:"active",get:function(){return!!this._session}},{key:"type",get:function(){return this._type}},{key:"spaceType",get:function(){return this._spaceType}},{key:"session",get:function(){return this._session}},{key:"camera",get:function(){return this._camera?this._camera.entity:null}},{key:"visibilityState",get:function(){return this._session?this._session.visibilityState:null}}]),t}(p),mb=function(e){function t(t,i){var n;void 0===i&&(i={}),n=e.call(this,t)||this;var s=new af;return s.graphicsDevice=n.createDevice(t,i),n.addComponentSystems(s),n.addResourceHandles(s),s.elementInput=i.elementInput,s.keyboard=i.keyboard,s.mouse=i.mouse,s.touch=i.touch,s.gamepads=i.gamepads,s.scriptPrefix=i.scriptPrefix,s.assetPrefix=i.assetPrefix,s.scriptsOrder=i.scriptsOrder,s.soundManager=new Lr,s.lightmapper=_f,s.batchManager=ko,s.xr=pb,n.init(s),n}Q(t,e);var i=t.prototype;return i.createDevice=function(e,t){return t.graphicsDeviceOptions||(t.graphicsDeviceOptions={}),M.browser&&navigator.xr&&(t.graphicsDeviceOptions.xrCompatible=!0),t.graphicsDeviceOptions.alpha=t.graphicsDeviceOptions.alpha||!1,new ws(e,t.graphicsDeviceOptions)},i.addComponentSystems=function(e){e.componentSystems=[Ag,Cm,x_,sp,Ap,W_,og,Dv,Uv,_d.legacy?Gg:Kv,Dp,dv,Pp,J_,Lg,u_,Qp,iv,av,wv,z_,T_,Ev]},i.addResourceHandles=function(e){e.resourceHandlers=[ey,rx,ax,ox,Gx,Ox,ES,$x,Rx,cx,Wx,Hx,gx,Px,_x,Xx,Mx,vx,Sx,ux,tS,Yx,Zx,mx]},t}(nf),_b=function(e){function t(t,i){var n;return(n=e.call(this)||this)._assets=new Set,n._loadingAssets=new Set,n._waitingAssets=new Set,n._registry=i,n._loading=!1,n._loaded=!1,n._failed=[],t.forEach((function(e){if(e instanceof kd)e.registry||(e.registry=i),n._assets.add(e);else{var t=i.get(e);t?n._assets.add(t):n._waitForAsset(e)}})),n}Q(t,e);var i=t.prototype;return i.destroy=function(){var e=this;this._registry.off("load",this._onLoad),this._registry.off("error",this._onError),this._waitingAssets.forEach((function(t){e._registry.off("add:"+t,this._onAddAsset)})),this.off("progress"),this.off("load")},i._assetHasDependencies=function(e){var t;return"model"===e.type&&(null==(t=e.file)?void 0:t.url)&&e.file.url&&e.file.url.match(/.json$/g)},i.load=function(e,t){var i=this;if(!this._loading){this._loading=!0,this._callback=e,this._scope=t,this._registry.on("load",this._onLoad,this),this._registry.on("error",this._onError,this);var n=!1;this._assets.forEach((function(e){e.loaded||(n=!0,i._assetHasDependencies(e)&&i._registry.loadFromUrl(e.file.url,e.type,(function(t,n){t?i._onError(t,e):i._onLoad(e)})),i._loadingAssets.add(e),i._registry.add(e))})),this._loadingAssets.forEach((function(e){i._assetHasDependencies(e)||i._registry.load(e)})),n||0!==this._waitingAssets.size||this._loadingComplete()}},i.ready=function(e,t){void 0===t&&(t=this),this._loaded?e.call(t,Array.from(this._assets)):this.once("load",(function(i){e.call(t,i)}))},i._loadingComplete=function(){this._loaded||(this._loaded=!0,this._registry.off("load",this._onLoad,this),this._registry.off("error",this._onError,this),this._failed.length?(this._callback&&this._callback.call(this._scope,"Failed to load some assets",this._failed),this.fire("error",this._failed)):(this._callback&&this._callback.call(this._scope),this.fire("load",Array.from(this._assets))))},i._onLoad=function(e){var t=this;this._loadingAssets.has(e)&&(this.fire("progress",e),this._loadingAssets.delete(e)),0===this._loadingAssets.size&&setTimeout((function(){t._loadingComplete(t._failed)}),0)},i._onError=function(e,t){var i=this;this._loadingAssets.has(t)&&(this._failed.push(t),this._loadingAssets.delete(t)),0===this._loadingAssets.size&&setTimeout((function(){i._loadingComplete(i._failed)}),0)},i._onAddAsset=function(e){this._waitingAssets.delete(e),this._assets.add(e),e.loaded||(this._loadingAssets.add(e),this._registry.load(e))},i._waitForAsset=function(e){this._waitingAssets.add(e),this._registry.once("add:"+e,this._onAddAsset,this)},t}(p),gb=4096,vb=function(e){function t(t,i){var n;void 0===i&&(i={}),(n=e.call(this)||this).type="bitmap",n.app=t,n.intensity=0,n.fontWeight=i.fontWeight||"normal",n.fontSize=parseInt(i.fontSize,10),n.glyphSize=n.fontSize,n.fontName=i.fontName||"Arial",n.color=i.color||new ue(1,1,1),n.padding=i.padding||0;var s=i.width>gb?gb:i.width||512,r=i.height>gb?gb:i.height||512,a=document.createElement("canvas");a.height=r,a.width=s;var o=new Yn(n.app.graphicsDevice,{name:"font",format:7,minFilter:5,magFilter:1,addressU:1,addressV:1,mipmaps:!0});return o.setSource(a),n.textures=[o],n.chars="",n.data={},n}Q(t,e);var i=t.prototype;return i.createTextures=function(e){var t=this._normalizeCharsSet(e);if(t.length===this.chars.length){for(var i=0;i<t.length;i++)if(t[i]!==this.chars[i])return void this._renderAtlas(t)}else this._renderAtlas(t)},i.updateTextures=function(e){for(var t=this._normalizeCharsSet(e),i=[],n=0;n<t.length;n++){var s=t[n];this.data.chars[s]||i.push(s)}i.length>0&&this._renderAtlas(this.chars.concat(i))},i.destroy=function(){for(var e=0;e<this.textures.length;e++)this.textures[e].destroy();this.chars=null,this.color=null,this.data=null,this.fontName=null,this.fontSize=null,this.glyphSize=null,this.intensity=null,this.textures=null,this.type=null,this.fontWeight=null},i._getAndClearContext=function(e,t){var i=e.width,n=e.height,s=e.getContext("2d",{alpha:!0});return s.clearRect(0,0,i,n),s.fillStyle=t,s.fillRect(0,0,i,n),s},i._colorToRgbString=function(e,t){var i=Math.round(255*e.r),n=Math.round(255*e.g),s=Math.round(255*e.b);return t?"rgba("+i+", "+n+", "+s+", "+e.a+")":"rgb("+i+", "+n+", "+s+")"},i.renderCharacter=function(e,t,i,n,s){e.fillStyle=s,e.fillText(t,i,n)},i._renderAtlas=function(e){this.chars=e;var t=1,i=this.textures[t-1].getSource(),n=i.width,s=i.height,r=this._colorToRgbString(this.color,!1),a=this.color.a;this.color.a=1/255;var o=this._colorToRgbString(this.color,!0);this.color.a=a;var h="center",l="alphabetic",c=this._getAndClearContext(i,o);c.font=this.fontWeight+" "+this.fontSize.toString()+"px "+this.fontName,c.textAlign=h,c.textBaseline=l,this.data=this._createJson(this.chars,this.fontName,n,s);for(var u=G.getSymbols(this.chars.join("")),d=this.textures.length,f=0,p=0,m={},_=0;_<u.length;_++){var g=u[_];m[g]=this._getTextMetrics(g),f=Math.max(f,m[g].height),p=Math.max(p,m[g].descent)}this.glyphSize=Math.max(this.glyphSize,f);for(var v=this.glyphSize+2*this.padding,y=this.glyphSize+2*this.padding,x=this.glyphSize/2+this.padding,S=y-p-this.padding,b=0,w=0,T=0;T<u.length;T++){var A=u[T],C=G.getCodePoint(u[T]),E=this.fontSize;c.font=this.fontWeight+" "+E.toString()+"px "+this.fontName,c.textAlign=h,c.textBaseline=l;var M=c.measureText(A).width;M>E&&(E=this.fontSize*this.fontSize/M,c.font=this.fontWeight+" "+E.toString()+"px "+this.fontName,M=this.fontSize),this.renderCharacter(c,A,b+x,w+S,r);var P=this.padding+(this.glyphSize-M)/2,R=-this.padding+m[A].descent-p,I=M;if(this._addChar(this.data,A,C,b,w,v,y,P,R,I,t-1,n,s),(b+=v)+v>n&&(b=0,(w+=y)+y>s))if(this.textures[t-1].upload(),w=0,++t>d){(i=document.createElement("canvas")).height=s,i.width=n,c=this._getAndClearContext(i,o);var L=new Yn(this.app.graphicsDevice,{format:7,mipmaps:!0,name:"font-atlas"});L.setSource(i),L.minFilter=5,L.magFilter=1,L.addressU=1,L.addressV=1,this.textures.push(L)}else i=this.textures[t-1].getSource(),c=this._getAndClearContext(i,o)}if(this.textures[t-1].upload(),t<d){for(var D=t;D<d;D++)this.textures[D].destroy();this.textures.splice(t)}this.fire("render")},i._createJson=function(e,t,i,n){return{version:3,intensity:this.intensity,info:{face:t,width:i,height:n,maps:[{width:i,height:n}]},chars:{}}},i._addChar=function(e,t,i,n,s,r,a,o,h,l,c,u,d){e.info.maps.length<c+1&&e.info.maps.push({width:u,height:d});var f=this.fontSize/32;e.chars[t]={id:i,letter:t,x:n,y:s,width:r,height:a,xadvance:l/f,xoffset:o/f,yoffset:(h+this.padding)/f,scale:f,range:1,map:c,bounds:[0,0,r/f,a/f]}},i._normalizeCharsSet=function(e){var t=this.app.systems.element.getUnicodeConverter();t&&(e=t(e));for(var i={},n=G.getSymbols(e),s=0;s<n.length;s++){var r=n[s];i[r]||(i[r]=r)}return Object.keys(i).sort()},i._getTextMetrics=function(e){var t=document.createElement("span");t.id="content-span",t.innerHTML=e;var i=document.createElement("div");i.id="content-block",i.style.display="inline-block",i.style.width="1px",i.style.height="0px";var n=document.createElement("div");n.appendChild(t),n.appendChild(i),n.style.font=this.fontSize+"px "+this.fontName,document.body.appendChild(n);var s=-1,r=-1,a=-1;try{i.style["vertical-align"]="baseline",s=i.offsetTop-t.offsetTop,i.style["vertical-align"]="bottom",r=(a=i.offsetTop-t.offsetTop)-s}finally{document.body.removeChild(n)}return{ascent:s,descent:r,height:a}},t}(p),yb=new Set,xb={depth:1,flags:2},Sb=function(){function e(e,t,i){this.renderTarget=null,e instanceof Ii&&(e=ud()),this.app=e,this.device=e.graphicsDevice,this.pickColor=new Float32Array(4),this.pickColor[3]=1,this.mapping=[],this.cameraEntity=null,this.layer=null,this.layerComp=null,this.initLayerComposition();var n=this.device;this.clearDepthCommand=new Ao(0,0,(function(){n.clear(xb)})),this.width=0,this.height=0,this.resize(t,i)}var t=e.prototype;return t.getSelection=function(e,t,i,n){var s=this.device;if("object"==typeof e){var r=e;e=r.x,t=r.y,i=r.width,n=r.height}else t=this.renderTarget.height-(t+(n||1));e=Math.floor(e),t=Math.floor(t),i=Math.floor(Math.max(i||1,1)),n=Math.floor(Math.max(n||1,1));var a=s.renderTarget;s.setRenderTarget(this.renderTarget),s.updateBegin();var o=new Uint8Array(4*i*n);s.readPixels(e,t,i,n,o),s.updateEnd(),s.setRenderTarget(a);for(var h=this.mapping,l=0;l<i*n;l++){var c=o[4*l+0]<<16|o[4*l+1]<<8|o[4*l+2];16777215!==c&&yb.add(h[c])}var u=[];return yb.forEach((function(e){return u.push(e)})),yb.clear(),u},t.allocateRenderTarget=function(){var e=new Yn(this.device,{format:7,width:this.width,height:this.height,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1,name:"pick"});this.renderTarget=new Di({colorBuffer:e,depth:!0})},t.releaseRenderTarget=function(){this.cameraEntity.camera.renderTarget=null,this.renderTarget&&(this.renderTarget.destroyTextureBuffers(),this.renderTarget.destroy(),this.renderTarget=null)},t.initLayerComposition=function(){var e=this.device,t=this,i=e.scope.resolve("uColor");this.cameraEntity=new Zd,this.cameraEntity.addComponent("camera"),this.layer=new dc({name:"Picker",shaderPass:3,opaqueSortMode:0,onDrawCall:function(n,s){t.pickColor[0]=(s>>16&255)/255,t.pickColor[1]=(s>>8&255)/255,t.pickColor[2]=(255&s)/255,i.setValue(t.pickColor),e.setBlendState(yi.NOBLEND),t.mapping[s]=n}}),this.layer.addCamera(this.cameraEntity.camera),this.layerComp=new Ec("picker"),this.layerComp.pushOpaque(this.layer)},t.prepare=function(e,t,i){e instanceof Vo&&(e=e.node.camera),i instanceof dc&&(i=[i]),this.layer.clearMeshInstances();for(var n=this.layer.opaqueMeshInstances,s=t.layers.layerList,r=t.layers.subLayerEnabled,a=t.layers.subLayerList,o=0;o<s.length;o++){var h=s[o];if(!(i&&i.indexOf(h)<0))if(h.enabled&&r[o])if(h.cameras.indexOf(e)>=0){h._clearDepthBuffer&&n.push(this.clearDepthCommand);for(var l=a[o]?h.instances.transparentMeshInstances:h.instances.opaqueMeshInstances,c=0;c<l.length;c++){var u=l[c];u.pick&&n.push(u)}}}this.renderTarget&&this.width===this.renderTarget.width&&this.height===this.renderTarget.height||(this.releaseRenderTarget(),this.allocateRenderTarget()),this.updateCamera(e),this.mapping.length=0,this.app.renderComposition(this.layerComp)},t.updateCamera=function(e){this.cameraEntity.copy(e.entity),this.cameraEntity.name="PickerCamera";var t=this.cameraEntity.camera;t.copy(e),t.clearColorBuffer=!0,t.clearDepthBuffer=!0,t.clearStencilBuffer=!0,t.clearColor=ue.WHITE,t.renderTarget=this.renderTarget,this.layer.clearCameras(),this.layer.addCamera(t),t.layers=[this.layer.id]},t.resize=function(e,t){this.width=Math.floor(e),this.height=Math.floor(t)},e}(),bb=function(){function e(){}var t=e.prototype;return t.load=function(e,t,i){throw new Error("not implemented")},t.open=function(e,t,i){throw new Error("not implemented")},t.patch=function(e,t){},e}(),wb=function(){function e(e){this._app=e,this.maxRetries=0}var t=e.prototype;return t.load=function(e,t){Ex(e,this.maxRetries,t)},t.open=function(e,t){return t.settings},e}(),Tb=new me,Ab=new me,Cb=new Fe,Eb=new Fe,Mb=new Fe;Cb.end=new me,Eb.end=new me,Mb.end=new me;var Pb=new me,Rb=new me,Ib=new me,Lb=new me,Db=new me,Ob=new me,kb=new me,Fb=new me,Bb=new me,Nb=new me,Ub=new me,zb=new me,Vb=new me,Gb=new me,Hb=new me,Wb=new me,Xb=new me,jb=new me,qb=new me,Yb=new me,Kb=new ve;function Zb(e,t,i){return Ub.cross(e,t).dot(i)}var $b=function(){function e(e,t,i){this.event=e,this.element=t,this.camera=i,this._stopPropagation=!1}return e.prototype.stopPropagation=function(){this._stopPropagation=!0,this.event&&(this.event.stopImmediatePropagation(),this.event.stopPropagation())},e}(),Qb=function(e){function t(t,i,n,s,r,a,o){var h;return(h=e.call(this,t,i,n)||this).x=s,h.y=r,h.ctrlKey=t.ctrlKey||!1,h.altKey=t.altKey||!1,h.shiftKey=t.shiftKey||!1,h.metaKey=t.metaKey||!1,h.button=t.button,sr.isPointerLocked()?(h.dx=t.movementX||t.webkitMovementX||t.mozMovementX||0,h.dy=t.movementY||t.webkitMovementY||t.mozMovementY||0):(h.dx=s-a,h.dy=r-o),h.wheelDelta=0,"wheel"===t.type&&(t.deltaY>0?h.wheelDelta=1:t.deltaY<0&&(h.wheelDelta=-1)),h}return Q(t,e),t}($b),Jb=function(e){function t(t,i,n,s,r,a){var o;return(o=e.call(this,t,i,n)||this).touches=t.touches,o.changedTouches=t.changedTouches,o.x=s,o.y=r,o.touch=a,o}return Q(t,e),t}($b),ew=function(e){function t(t,i,n,s){var r;return(r=e.call(this,t,i,n)||this).inputSource=s,r}return Q(t,e),t}($b),tw=function(){function e(e,t){this._app=null,this._attached=!1,this._target=null,this._enabled=!0,this._lastX=0,this._lastY=0,this._upHandler=this._handleUp.bind(this),this._downHandler=this._handleDown.bind(this),this._moveHandler=this._handleMove.bind(this),this._wheelHandler=this._handleWheel.bind(this),this._touchstartHandler=this._handleTouchStart.bind(this),this._touchendHandler=this._handleTouchEnd.bind(this),this._touchcancelHandler=this._touchendHandler,this._touchmoveHandler=this._handleTouchMove.bind(this),this._sortHandler=this._sortElements.bind(this),this._elements=[],this._hoveredElement=null,this._pressedElement=null,this._touchedElements={},this._touchesForWhichTouchLeaveHasFired={},this._selectedElements={},this._selectedPressedElements={},this._useMouse=!t||!1!==t.useMouse,this._useTouch=!t||!1!==t.useTouch,this._useXr=!t||!1!==t.useXr,this._selectEventsAttached=!1,M.touch&&(this._clickedEntities={}),this.attach(e)}var t=e.prototype;return t.attach=function(e){this._attached&&(this._attached=!1,this.detach()),this._target=e,this._attached=!0;var t=!!M.passiveEvents&&{passive:!0};this._useMouse&&(window.addEventListener("mouseup",this._upHandler,t),window.addEventListener("mousedown",this._downHandler,t),window.addEventListener("mousemove",this._moveHandler,t),window.addEventListener("wheel",this._wheelHandler,t)),this._useTouch&&M.touch&&(this._target.addEventListener("touchstart",this._touchstartHandler,t),this._target.addEventListener("touchend",this._touchendHandler,!1),this._target.addEventListener("touchmove",this._touchmoveHandler,!1),this._target.addEventListener("touchcancel",this._touchcancelHandler,!1)),this.attachSelectEvents()},t.attachSelectEvents=function(){!this._selectEventsAttached&&this._useXr&&this.app&&this.app.xr&&this.app.xr.supported&&(this._clickedEntities||(this._clickedEntities={}),this._selectEventsAttached=!0,this.app.xr.on("start",this._onXrStart,this))},t.detach=function(){if(this._attached){this._attached=!1;var e=!!M.passiveEvents&&{passive:!0};this._useMouse&&(window.removeEventListener("mouseup",this._upHandler,e),window.removeEventListener("mousedown",this._downHandler,e),window.removeEventListener("mousemove",this._moveHandler,e),window.removeEventListener("wheel",this._wheelHandler,e)),this._useTouch&&(this._target.removeEventListener("touchstart",this._touchstartHandler,e),this._target.removeEventListener("touchend",this._touchendHandler,!1),this._target.removeEventListener("touchmove",this._touchmoveHandler,!1),this._target.removeEventListener("touchcancel",this._touchcancelHandler,!1)),this._selectEventsAttached&&(this._selectEventsAttached=!1,this.app.xr.off("start",this._onXrStart,this),this.app.xr.off("end",this._onXrEnd,this),this.app.xr.off("update",this._onXrUpdate,this),this.app.xr.input.off("selectstart",this._onSelectStart,this),this.app.xr.input.off("selectend",this._onSelectEnd,this),this.app.xr.input.off("remove",this._onXrInputRemove,this)),this._target=null}},t.addElement=function(e){-1===this._elements.indexOf(e)&&this._elements.push(e)},t.removeElement=function(e){var t=this._elements.indexOf(e);-1!==t&&this._elements.splice(t,1)},t._handleUp=function(e){this._enabled&&(sr.isPointerLocked()||(this._calcMouseCoords(e),this._onElementMouseEvent("mouseup",e)))},t._handleDown=function(e){this._enabled&&(sr.isPointerLocked()||(this._calcMouseCoords(e),this._onElementMouseEvent("mousedown",e)))},t._handleMove=function(e){this._enabled&&(this._calcMouseCoords(e),this._onElementMouseEvent("mousemove",e),this._lastX=JS,this._lastY=eb)},t._handleWheel=function(e){this._enabled&&(this._calcMouseCoords(e),this._onElementMouseEvent("mousewheel",e))},t._determineTouchedElements=function(e){for(var t={},i=this.app.systems.camera.cameras,n=i.length-1;n>=0;n--){for(var s=i[n],r=0,a=e.changedTouches.length,o=0;o<a;o++)if(t[e.changedTouches[o].identifier])r++;else{var h=this._calcTouchCoords(e.changedTouches[o]),l=this._getTargetElementByCoords(s,h.x,h.y);l&&(r++,t[e.changedTouches[o].identifier]={element:l,camera:s,x:h.x,y:h.y})}if(r===a)break}return t},t._handleTouchStart=function(e){if(this._enabled){for(var t=this._determineTouchedElements(e),i=0,n=e.changedTouches.length;i<n;i++){var s=e.changedTouches[i],r=t[s.identifier],a=this._touchedElements[s.identifier];!r||a&&r.element===a.element||(this._fireEvent(e.type,new Jb(e,r.element,r.camera,r.x,r.y,s)),this._touchesForWhichTouchLeaveHasFired[s.identifier]=!1)}for(var o in t)this._touchedElements[o]=t[o]}},t._handleTouchEnd=function(e){if(this._enabled){var t=this.app.systems.camera.cameras;for(var i in this._clickedEntities)delete this._clickedEntities[i];for(var n=0,s=e.changedTouches.length;n<s;n++){var r=e.changedTouches[n],a=this._touchedElements[r.identifier];if(a){var o=a.element,h=a.camera,l=a.x,c=a.y;delete this._touchedElements[r.identifier],delete this._touchesForWhichTouchLeaveHasFired[r.identifier],this._fireEvent(e.type,new Jb(e,o,h,l,c,r));for(var u=this._calcTouchCoords(r),d=t.length-1;d>=0;d--){this._getTargetElementByCoords(t[d],u.x,u.y)===o&&(this._clickedEntities[o.entity.getGuid()]||(this._fireEvent("click",new Jb(e,o,h,l,c,r)),this._clickedEntities[o.entity.getGuid()]=Date.now()))}}}}},t._handleTouchMove=function(e){if(e.preventDefault(),this._enabled)for(var t=this._determineTouchedElements(e),i=0,n=e.changedTouches.length;i<n;i++){var s=e.changedTouches[i],r=t[s.identifier],a=this._touchedElements[s.identifier];if(a){var o=this._calcTouchCoords(s);r&&r.element===a.element||this._touchesForWhichTouchLeaveHasFired[s.identifier]||(this._fireEvent("touchleave",new Jb(e,a.element,a.camera,o.x,o.y,s)),this._touchesForWhichTouchLeaveHasFired[s.identifier]=!0),this._fireEvent("touchmove",new Jb(e,a.element,a.camera,o.x,o.y,s))}}},t._onElementMouseEvent=function(e,t){var i=null,n=this._hoveredElement;this._hoveredElement=null;for(var s,r=this.app.systems.camera.cameras,a=r.length-1;a>=0&&(s=r[a],!(i=this._getTargetElementByCoords(s,JS,eb)));a--);if(this._hoveredElement=i,"mousemove"!==e&&"mouseup"!==e||!this._pressedElement?i&&(this._fireEvent(e,new Qb(t,i,s,JS,eb,this._lastX,this._lastY)),"mousedown"===e&&(this._pressedElement=i)):this._fireEvent(e,new Qb(t,this._pressedElement,s,JS,eb,this._lastX,this._lastY)),n!==this._hoveredElement&&(n&&this._fireEvent("mouseleave",new Qb(t,n,s,JS,eb,this._lastX,this._lastY)),this._hoveredElement&&this._fireEvent("mouseenter",new Qb(t,this._hoveredElement,s,JS,eb,this._lastX,this._lastY))),"mouseup"===e&&this._pressedElement){if(this._pressedElement===this._hoveredElement){var o=this._hoveredElement.entity.getGuid(),h=!this._clickedEntities;if(this._clickedEntities){var l=this._clickedEntities[o]||0;h=Date.now()-l>300,delete this._clickedEntities[o]}h&&this._fireEvent("click",new Qb(t,this._hoveredElement,s,JS,eb,this._lastX,this._lastY))}this._pressedElement=null}},t._onXrStart=function(){this.app.xr.on("end",this._onXrEnd,this),this.app.xr.on("update",this._onXrUpdate,this),this.app.xr.input.on("selectstart",this._onSelectStart,this),this.app.xr.input.on("selectend",this._onSelectEnd,this),this.app.xr.input.on("remove",this._onXrInputRemove,this)},t._onXrEnd=function(){this.app.xr.off("update",this._onXrUpdate,this),this.app.xr.input.off("selectstart",this._onSelectStart,this),this.app.xr.input.off("selectend",this._onSelectEnd,this),this.app.xr.input.off("remove",this._onXrInputRemove,this)},t._onXrUpdate=function(){if(this._enabled)for(var e=this.app.xr.input.inputSources,t=0;t<e.length;t++)this._onElementSelectEvent("selectmove",e[t],null)},t._onXrInputRemove=function(e){var t=this._selectedElements[e.id];t&&(e._elementEntity=null,this._fireEvent("selectleave",new ew(null,t,null,e))),delete this._selectedElements[e.id],delete this._selectedPressedElements[e.id]},t._onSelectStart=function(e,t){this._enabled&&this._onElementSelectEvent("selectstart",e,t)},t._onSelectEnd=function(e,t){this._enabled&&this._onElementSelectEvent("selectend",e,t)},t._onElementSelectEvent=function(e,t,i){var n,s,r,a=this._selectedElements[t.id],o=this.app.systems.camera.cameras;if(t.elementInput){Mb.set(t.getOrigin(),t.getDirection());for(var h=o.length-1;h>=0&&(r=o[h],!(n=this._getTargetElementByRay(Mb,r)));h--);}t._elementEntity=n||null,n?(this._selectedElements[t.id]=n,s=n):delete this._selectedElements[t.id],a!==s&&(a&&this._fireEvent("selectleave",new ew(i,a,r,t)),s&&this._fireEvent("selectenter",new ew(i,s,r,t)));var l=this._selectedPressedElements[t.id];"selectmove"===e&&l&&this._fireEvent("selectmove",new ew(i,l,r,t)),"selectstart"===e&&(this._selectedPressedElements[t.id]=s,s&&this._fireEvent("selectstart",new ew(i,s,r,t))),!t.elementInput&&l&&(delete this._selectedPressedElements[t.id],a&&this._fireEvent("selectend",new ew(i,l,r,t))),"selectend"===e&&t.elementInput&&(delete this._selectedPressedElements[t.id],l&&this._fireEvent("selectend",new ew(i,l,r,t)),l&&l===a&&this._fireEvent("click",new ew(i,l,r,t)))},t._fireEvent=function(e,t){for(var i=t.element;i.fire(e,t),!t._stopPropagation&&i.entity.parent&&(i=i.entity.parent.element););},t._calcMouseCoords=function(e){var t=this._target.getBoundingClientRect(),i=Math.floor(t.left),n=Math.floor(t.top);JS=e.clientX-i,eb=e.clientY-n},t._calcTouchCoords=function(e){for(var t=0,i=0,n=e.target;!(n instanceof HTMLElement);)n=n.parentNode;var s=n;do{t+=s.offsetLeft-s.scrollLeft,i+=s.offsetTop-s.scrollTop,s=s.offsetParent}while(s);return{x:e.pageX-t,y:e.pageY-i}},t._sortElements=function(e,t){var i=this.app.scene.layers.sortTransparentLayers(e.layers,t.layers);return 0!==i?i:e.screen&&!t.screen?-1:!e.screen&&t.screen?1:e.screen||t.screen?e.screen.screen.screenSpace&&!t.screen.screen.screenSpace?-1:t.screen.screen.screenSpace&&!e.screen.screen.screenSpace?1:t.drawOrder-e.drawOrder:0},t._getTargetElementByCoords=function(e,t,i){var n=this._calculateRayScreen(t,i,e,Cb)?Cb:null,s=this._calculateRay3d(t,i,e,Eb)?Eb:null;return this._getTargetElement(e,n,s)},t._getTargetElementByRay=function(e,t){Cb.origin.copy(e.origin),Cb.direction.copy(e.direction),Cb.end.copy(Cb.direction).mulScalar(2*t.farClip).add(Cb.origin);var i=Cb,n=t.worldToScreen(i.origin,Tb),s=this._calculateRayScreen(n.x,n.y,t,Eb)?Eb:null;return this._getTargetElement(t,s,i)},t._getTargetElement=function(e,t,i){var n=null,s=1/0;this._elements.sort(this._sortHandler);for(var r=0,a=this._elements.length;r<a;r++){var o=this._elements[r];if(o.layers.some((function(t){return e.layersSet.has(t)})))if(o.screen&&o.screen.screen.screenSpace){if(!t)continue;if(this._checkElement(t,o,!0)>=0){n=o;break}}else{if(!i)continue;var h=this._checkElement(i,o,!1);if(h>=0&&(h<s&&(n=o,s=h),o.screen)){n=o;break}}}return n},t._calculateRayScreen=function(e,t,i,n){var s=this.app.graphicsDevice.width,r=this.app.graphicsDevice.height,a=i.rect.z*s,o=i.rect.w*r,h=i.rect.x*s,l=h+a,c=(1-i.rect.y)*r,u=c-o,d=e*s/this._target.clientWidth,f=t*r/this._target.clientHeight;return d>=h&&d<=l&&f<=c&&f>=u&&(d=s*(d-h)/a,f=r-(f=r*(f-u)/o),n.origin.set(d,f,1),n.direction.set(0,0,-1),n.end.copy(n.direction).mulScalar(2).add(n.origin),!0)},t._calculateRay3d=function(e,t,i,n){var s=this._target.clientWidth,r=this._target.clientHeight,a=i.rect.z*s,o=i.rect.w*r,h=i.rect.x*s,l=h+a,c=(1-i.rect.y)*r,u=c-o,d=e,f=t;return e>=h&&e<=l&&t<=c&&f>=u&&(d=s*(d-h)/a,f=r*(f-u)/o,i.screenToWorld(d,f,i.nearClip,Tb),i.screenToWorld(d,f,i.farClip,Ab),n.origin.copy(Tb),n.direction.set(0,0,-1),n.end.copy(Ab),!0)},t._checkElement=function(t,i,n){if(i.maskedBy&&this._checkElement(t,i.maskedBy.element,n)<0)return-1;var s;s=n?e.calculateScaleToScreen(i):e.calculateScaleToWorld(i);var r=e.buildHitCorners(i,n?i.screenCorners:i.worldCorners,s);return function(e,t,i){Pb.sub2(t,e),Rb.sub2(i[0],e),Ib.sub2(i[1],e),Lb.sub2(i[2],e),Ob.cross(Lb,Pb);var n,s,r=Rb.dot(Ob);if(r>=0){if((n=-Ib.dot(Ob))<0)return-1;if((s=Zb(Pb,Ib,Rb))<0)return-1;var a=1/(n+r+s);kb.copy(i[0]).mulScalar(n*a),Fb.copy(i[1]).mulScalar(r*a),Bb.copy(i[2]).mulScalar(s*a),Nb.copy(kb).add(Fb).add(Bb)}else{if(Db.sub2(i[3],e),(n=Db.dot(Ob))<0)return-1;if((s=Zb(Pb,Rb,Db))<0)return-1;var o=1/(n+(r=-r)+s);kb.copy(i[0]).mulScalar(n*o),Fb.copy(i[3]).mulScalar(r*o),Bb.copy(i[2]).mulScalar(s*o),Nb.copy(kb).add(Fb).add(Bb)}return Pb.sub2(i[0],i[2]).lengthSq()<1e-8||Pb.sub2(i[1],i[3]).lengthSq()<1e-8?-1:Nb.sub(e).lengthSq()}(t.origin,t.end,r)},e.buildHitCorners=function(e,t,i){var n=t;if(e.entity&&e.entity.button){var s=e.entity.button.hitPadding||Kb;Vb.copy(e.entity.up),Gb.copy(Vb).mulScalar(-1),Wb.copy(e.entity.right),Hb.copy(Wb).mulScalar(-1),Vb.mulScalar(s.w*i.y),Gb.mulScalar(s.y*i.y),Wb.mulScalar(s.z*i.x),Hb.mulScalar(s.x*i.x),Xb.copy(n[0]).add(Gb).add(Hb),jb.copy(n[1]).add(Gb).add(Wb),qb.copy(n[2]).add(Vb).add(Wb),Yb.copy(n[3]).add(Vb).add(Hb),n=[Xb,jb,qb,Yb]}if(i.x<0){var r=n[2].x,a=n[0].x;n[0].x=r,n[1].x=a,n[2].x=a,n[3].x=r}if(i.y<0){var o=n[2].y,h=n[0].y;n[0].y=o,n[1].y=o,n[2].y=h,n[3].y=h}if(i.z<0){var l=n[2].x,c=n[2].y,u=n[2].z;n[2].x=n[0].x,n[2].y=n[0].y,n[2].z=n[0].z,n[0].x=l,n[0].y=c,n[0].z=u}return n},e.calculateScaleToScreen=function(e){var t=e.entity,i=e.screen.screen.scale;for(zb.set(i,i,i);t&&!t.screen;)zb.mul(t.getLocalScale()),t=t.parent;return zb},e.calculateScaleToWorld=function(e){var t=e.entity;for(zb.set(1,1,1);t;)zb.mul(t.getLocalScale()),t=t.parent;return zb},Z(e,[{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"app",get:function(){return this._app||ud()},set:function(e){this._app=e}}]),e}(),iw=new RegExp("^\\s*function(?:\\s|\\s*\\/\\*.*\\*\\/\\s*)+([^\\(\\s\\/]*)\\s*"),nw=function(e){function t(t){var i;return(i=e.call(this)||this).app=void 0,i.entity=void 0,i._enabled=void 0,i._enabledOld=void 0,i._initialized=void 0,i._postInitialized=void 0,i.__destroyed=void 0,i.__attributes=void 0,i.__attributesRaw=void 0,i.__scriptType=void 0,i.__executionOrder=void 0,i.initScriptType(t),i}Q(t,e);var i=t.prototype;return i.initScriptType=function(e){var t=this.constructor;this.app=e.app,this.entity=e.entity,this._enabled="boolean"!=typeof e.enabled||e.enabled,this._enabledOld=this.enabled,this.__destroyed=!1,this.__attributes={},this.__attributesRaw=e.attributes||{},this.__scriptType=t,this.__executionOrder=-1},t.__getScriptName=function(e){if("function"==typeof e){if("name"in Function.prototype)return e.name;if(e===Function||e===Function.prototype.constructor)return"Function";var t=(""+e).match(iw);return t?t[1]:void 0}},i.__initializeAttributes=function(e){if(e||this.__attributesRaw){for(var t in this.__scriptType.attributes.index)this.__attributesRaw&&this.__attributesRaw.hasOwnProperty(t)?this[t]=this.__attributesRaw[t]:this.__attributes.hasOwnProperty(t)||(this.__scriptType.attributes.index[t].hasOwnProperty("default")?this[t]=this.__scriptType.attributes.index[t].default:this[t]=null);this.__attributesRaw=null}},t.extend=function(e){for(var t in e)e.hasOwnProperty(t)&&(this.prototype[t]=e[t])},Z(t,[{key:"enabled",get:function(){return this._enabled&&!this._destroyed&&this.entity.script.enabled&&this.entity.enabled},set:function(e){this._enabled=!!e,this.enabled!==this._enabledOld&&(this._enabledOld=this.enabled,this.fire(this.enabled?"enable":"disable"),this.fire("state",this.enabled),!this._initialized&&this.enabled&&(this._initialized=!0,this.__initializeAttributes(!0),this.initialize&&this.entity.script._scriptMethod(this,Wv)),this._initialized&&!this._postInitialized&&this.enabled&&!this.entity.script._beingEnabled&&(this._postInitialized=!0,this.postInitialize&&this.entity.script._scriptMethod(this,Xv)))}}],[{key:"scriptName",get:function(){return this.__name}},{key:"attributes",get:function(){return this.hasOwnProperty("__attributes")||(this.__attributes=new Hv(this)),this.__attributes}}]),t}(p);nw.__name=null;var sw=new Set(["system","entity","create","destroy","swap","move","data","scripts","_scripts","_scriptsIndex","_scriptsData","enabled","_oldState","onEnable","onDisable","onPostStateChange","_onSetEnabled","_checkState","_onBeforeRemove","_onInitializeAttributes","_onInitialize","_onPostInitialize","_onUpdate","_onPostUpdate","_callbacks","has","get","on","off","fire","once","hasEvent"]);function rw(e,t){if(_d.legacy)return null;if(sw.has(e))throw new Error("Script name '"+e+"' is reserved, please rename the script");var i=function(e){p.prototype.initEventHandler.call(this),nw.prototype.initScriptType.call(this,e)};return(i.prototype=Object.create(nw.prototype)).constructor=i,i.extend=nw.extend,i.attributes=new Hv(i),ow(i,e,t),i}var aw={};function ow(e,t,i){if(!e.legacy){if("function"!=typeof e)throw new Error("script class: '"+e+"' must be a constructor function (i.e. class).");if(!(e.prototype instanceof nw))throw new Error("script class: '"+nw.__getScriptName(e)+"' does not extend pc.ScriptType.");if(t=t||e.__name||nw.__getScriptName(e),sw.has(t))throw new Error("script name: '"+t+"' is reserved, please change script name");e.__name=t,(i?i.scripts:nf.getApplication().scripts).add(e),fd.push(e,e.legacy)}}Hv.reservedNames.forEach((function(e,t,i){aw[e]=1})),rw.reservedAttributes=aw;var hw={write:function(e){console.log(e)},open:function(){hw.write("Powered by PlayCanvas "+l+" "+c)},info:function(e){console.info("INFO: "+e)},debug:function(e){console.debug("DEBUG: "+e)},error:function(e){console.error("ERROR: "+e)},warning:function(e){console.warn("WARNING: "+e)},alert:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){hw.write("ALERT: "+e),alert(e)})),assert:function(e,t){!1===e&&hw.write("ASSERT: "+t)}};G.endsWith=function(e,t){return e.endsWith(t)},G.startsWith=function(e,t){return e.startsWith(t)};var lw=function(){function e(){this._isRunning=!1,this._a=0,this._b=0}var t=e.prototype;return t.start=function(){this._isRunning=!0,this._a=oe()},t.stop=function(){this._isRunning=!1,this._b=oe()},t.getMilliseconds=function(){return this._b-this._a},e}(),cw={now:oe,Timer:lw};Object.defineProperty(ue.prototype,"data",{get:function(){return this._data||(this._data=new Float32Array(4)),this._data[0]=this.r,this._data[1]=this.g,this._data[2]=this.b,this._data[3]=this.a,this._data}}),Object.defineProperty(ue.prototype,"data3",{get:function(){return this._data3||(this._data3=new Float32Array(3)),this._data3[0]=this.r,this._data3[1]=this.g,this._data3[2]=this.b,this._data3}}),ce.INV_LOG2=Math.LOG2E,ce.intToBytes=ce.intToBytes32,ce.bytesToInt=ce.bytesToInt32,Object.defineProperty(ge.prototype,"data",{get:function(){return this._data||(this._data=new Float32Array(2)),this._data[0]=this.x,this._data[1]=this.y,this._data}}),ge.prototype.scale=ge.prototype.mulScalar,Object.defineProperty(me.prototype,"data",{get:function(){return this._data||(this._data=new Float32Array(3)),this._data[0]=this.x,this._data[1]=this.y,this._data[2]=this.z,this._data}}),me.prototype.scale=me.prototype.mulScalar,Object.defineProperty(ve.prototype,"data",{get:function(){return this._data||(this._data=new Float32Array(4)),this._data[0]=this.x,this._data[1]=this.y,this._data[2]=this.z,this._data[3]=this.w,this._data}}),ve.prototype.scale=ve.prototype.mulScalar;var uw={Aabb:Ie,Sphere:Oe,Plane:Ge};Oe.prototype.intersectRay=Oe.prototype.intersectsRay,ke.prototype.update=function(e,t){var i=new Te;i.mul2(e,t),this.setFromMat4(i)};function dw(e){this.name="UnsupportedBrowserError",this.message=e||""}function fw(e){this.name="ContextCreationError",this.message=e||""}dw.prototype=Error.prototype,fw.prototype=Error.prototype;var pw={begin:Va,dummyFragmentCode:vs.dummyFragmentCode,end:Ga,fogCode:Ua,gammaCode:Ba,precisionCode:vs.precisionCode,skinCode:za,tonemapCode:Na,versionCode:vs.versionCode},mw={ADDRESS_CLAMP_TO_EDGE:1,ADDRESS_MIRRORED_REPEAT:2,ADDRESS_REPEAT:0,BLENDMODE_ZERO:0,BLENDMODE_ONE:1,BLENDMODE_SRC_COLOR:2,BLENDMODE_ONE_MINUS_SRC_COLOR:3,BLENDMODE_DST_COLOR:4,BLENDMODE_ONE_MINUS_DST_COLOR:5,BLENDMODE_SRC_ALPHA:6,BLENDMODE_SRC_ALPHA_SATURATE:7,BLENDMODE_ONE_MINUS_SRC_ALPHA:8,BLENDMODE_DST_ALPHA:9,BLENDMODE_ONE_MINUS_DST_ALPHA:10,BUFFER_STATIC:0,BUFFER_DYNAMIC:1,BUFFER_STREAM:2,CULLFACE_NONE:0,CULLFACE_BACK:1,CULLFACE_FRONT:2,CULLFACE_FRONTANDBACK:3,ELEMENTTYPE_INT8:0,ELEMENTTYPE_UINT8:1,ELEMENTTYPE_INT16:2,ELEMENTTYPE_UINT16:3,ELEMENTTYPE_INT32:4,ELEMENTTYPE_UINT32:5,ELEMENTTYPE_FLOAT32:6,FILTER_NEAREST:0,FILTER_LINEAR:1,FILTER_NEAREST_MIPMAP_NEAREST:2,FILTER_NEAREST_MIPMAP_LINEAR:3,FILTER_LINEAR_MIPMAP_NEAREST:4,FILTER_LINEAR_MIPMAP_LINEAR:5,INDEXFORMAT_UINT8:0,INDEXFORMAT_UINT16:1,INDEXFORMAT_UINT32:2,PIXELFORMAT_RGB565:3,PIXELFORMAT_RGB8:6,PIXELFORMAT_RGBA8:7,PRIMITIVE_POINTS:0,PRIMITIVE_LINES:1,PRIMITIVE_LINELOOP:2,PRIMITIVE_LINESTRIP:3,PRIMITIVE_TRIANGLES:4,PRIMITIVE_TRISTRIP:5,PRIMITIVE_TRIFAN:6,SEMANTIC_POSITION:lt,SEMANTIC_NORMAL:ct,SEMANTIC_COLOR:pt,SEMANTIC_TEXCOORD:mt,SEMANTIC_TEXCOORD0:_t,SEMANTIC_TEXCOORD1:gt,SEMANTIC_ATTR0:At,SEMANTIC_ATTR1:Ct,SEMANTIC_ATTR2:Et,SEMANTIC_ATTR3:Mt,TEXTURELOCK_READ:1,TEXTURELOCK_WRITE:2,drawQuadWithShader:Da,programlib:pw,shaderChunks:Sa,ContextCreationError:fw,Device:Ii,IndexBuffer:As,ProgramLibrary:rd,RenderTarget:Di,ScopeId:Ti,Shader:Nn,ShaderInput:Qn,Texture:Yn,UnsupportedBrowserError:dw,VertexBuffer:Ei,VertexFormat:Pi,VertexIterator:zs},_w=new ve;function gw(e,t,i,n,s){var r;if(s){var a=t?t.width:e.width,o=t?t.height:e.height;r=_w.set(s.x*a,s.y*o,s.z*a,s.w*o)}Da(e,t,n,r)}var vw={createFullscreenQuad:function(e){return e.quadVertexBuffer},drawFullscreenQuad:gw,PostEffect:td,PostEffectQueue:Pv};Object.defineProperty(Sa,"transformSkinnedVS",{get:function(){return"#define SKIN\n"+Sa.transformVS}});Object.keys({"ambientPrefilteredCube.frag":"ambientEnv.frag","ambientPrefilteredCubeLod.frag":"ambientEnv.frag","dpAtlasQuad.frag":null,"genParaboloid.frag":null,"prefilterCubemap.frag":null,"reflectionDpAtlas.frag":"reflectionEnv.frag","reflectionPrefilteredCube.frag":"reflectionEnv.frag","reflectionPrefilteredCubeLod.frag":"reflectionEnv.frag"}).forEach((function(e){Object.defineProperty(Sa,e,{get:function(){return null},set:function(){}})})),Object.defineProperties(Di.prototype,{_glFrameBuffer:{get:function(){return this.impl._glFrameBuffer},set:function(e){}}}),Object.defineProperty(Pi,"defaultInstancingFormat",{get:function(){return Pi.getDefaultInstancingFormat(Kr.get())}}),Object.defineProperties(Yn.prototype,{rgbm:{get:function(){return this.type===Gt},set:function(e){this.type=e?Gt:Vt}},swizzleGGGR:{get:function(){return this.type===Xt},set:function(e){this.type=e?Xt:Vt}},_glTexture:{get:function(){return this.impl._glTexture}},autoMipmap:{get:function(){return this._mipmaps},set:function(e){this._mipmaps=e}}}),Ii.prototype.getProgramLibrary=function(){return wa(this)},Ii.prototype.setProgramLibrary=function(e){Ta(this,e)},Ii.prototype.removeShaderFromCache=function(e){wa(this).removeFromCache(e)},yi.DEFAULT=Object.freeze(new yi);var yw=new yi,xw=new xi;Ii.prototype.setBlendFunction=function(e,t){var i=this.blendState;yw.copy(i),yw.setColorBlend(i.colorOp,e,t),yw.setAlphaBlend(i.alphaOp,e,t),this.setBlendState(yw)},Ii.prototype.setBlendFunctionSeparate=function(e,t,i,n){var s=this.blendState;yw.copy(s),yw.setColorBlend(s.colorOp,e,t),yw.setAlphaBlend(s.alphaOp,i,n),this.setBlendState(yw)},Ii.prototype.setBlendEquation=function(e){var t=this.blendState;yw.copy(t),yw.setColorBlend(e,t.colorSrcFactor,t.colorDstFactor),yw.setAlphaBlend(e,t.alphaSrcFactor,t.alphaDstFactor),this.setBlendState(yw)},Ii.prototype.setBlendEquationSeparate=function(e,t){var i=this.blendState;yw.copy(i),yw.setColorBlend(e,i.colorSrcFactor,i.colorDstFactor),yw.setAlphaBlend(t,i.alphaSrcFactor,i.alphaDstFactor),this.setBlendState(yw)},Ii.prototype.setColorWrite=function(e,t,i,n){var s=this.blendState;yw.copy(s),yw.setColorWrite(e,t,i,n),this.setBlendState(yw)},Ii.prototype.getBlending=function(){return this.blendState.blend},Ii.prototype.setBlending=function(e){yw.copy(this.blendState),yw.blend=e,this.setBlendState(yw)},Ii.prototype.setDepthWrite=function(e){xw.copy(this.depthState),xw.write=e,this.setDepthState(xw)},Ii.prototype.setDepthFunc=function(e){xw.copy(this.depthState),xw.func=e,this.setDepthState(xw)},Ii.prototype.setDepthTest=function(e){xw.copy(this.depthState),xw.test=e,this.setDepthState(xw)},Ii.prototype.getCullMode=function(){return this.cullMode};var Sw=Yl,bw={partitionSkin:Nx,procedural:{calculateTangents:sa,createMesh:ra,createTorus:aa,createCylinder:ha,createCapsule:la,createCone:ca,createSphere:ua,createPlane:da,createBox:fa},BasicMaterial:Ka,Command:Ao,ForwardRenderer:yc,GraphNode:go,Material:Ya,Mesh:Jr,MeshInstance:Co,Model:Uc,ParticleEmitter:ku,PhongMaterial:Yl,Picker:Sb,Projection:{ORTHOGRAPHIC:1,PERSPECTIVE:0},Scene:Hu,Skin:Wu,SkinInstance:Ja};function ww(e,t){Object.defineProperty(Yl.prototype,t,{get:function(){return this[e]},set:function(t){this[e]=t}})}function Tw(e,t){"chunks"!==e&&"_pass"!==e&&"_isForwardPass"!==e&&Object.defineProperty(Ll.prototype,e,{get:function(){return this.litOptions[t||e]},set:function(i){this.litOptions[t||e]=i}})}Object.defineProperty(Hu.prototype,"defaultMaterial",{get:function(){return Xa(ud().graphicsDevice)}}),["128","64","32","16","8","4"].forEach((function(e,t){Object.defineProperty(Hu.prototype,"skyboxPrefiltered"+e,{get:function(){return this._prefilteredCubemaps[t]},set:function(e){this._prefilteredCubemaps[t]=e,this.updateShaders=!0}})})),Object.defineProperty(Hu.prototype,"models",{get:function(){return this._models||(this._models=[]),this._models}}),Object.defineProperty(dc.prototype,"renderTarget",{set:function(e){this._renderTarget=e,this._dirtyCameras=!0},get:function(){return this._renderTarget}}),Hu.prototype._updateSkybox=function(e){this._updateSky(e)},Hu.prototype.addModel=function(e){if(!this.containsModel(e)){var t=this.layers.getLayerById(0);t&&(t.addMeshInstances(e.meshInstances),this.models.push(e))}},Hu.prototype.addShadowCaster=function(e){var t=this.layers.getLayerById(0);t&&t.addShadowCasters(e.meshInstances)},Hu.prototype.removeModel=function(e){var t=this.models.indexOf(e);if(-1!==t){var i=this.layers.getLayerById(0);if(!i)return;i.removeMeshInstances(e.meshInstances),this.models.splice(t,1)}},Hu.prototype.removeShadowCasters=function(e){var t=this.layers.getLayerById(0);t&&t.removeShadowCasters(e.meshInstances)},Hu.prototype.containsModel=function(e){return this.models.indexOf(e)>=0},Hu.prototype.getModels=function(e){return this.models},Object.defineProperty(Za.prototype,"model",{get:function(){return null}}),yc.prototype.renderComposition=function(e){ud().renderComposition(e)},yc.prototype.updateShader=function(e,t,i,n,s){var r=e.material._scene||ud().scene;return e.updatePassShader(r,n,i,s)},Co.prototype.syncAabb=function(){},zc.prototype.getTarget=function(e){return this.targets[e]},go.prototype._dirtify=function(e){e?this._dirtifyLocal():this._dirtifyWorld()},go.prototype.addLabel=function(e){this._labels[e]=!0},go.prototype.getLabels=function(){return Object.keys(this._labels)},go.prototype.hasLabel=function(e){return!!this._labels[e]},go.prototype.removeLabel=function(e){delete this._labels[e]},go.prototype.findByLabel=function(e,t){void 0===t&&(t=[]),this.hasLabel(e)&&t.push(this);for(var i=0;i<this._children.length;++i)t=this._children[i].findByLabel(e,t);return t},go.prototype.getChildren=function(){return this.children},go.prototype.getName=function(){return this.name},go.prototype.getPath=function(){return this.path},go.prototype.getRoot=function(){return this.root},go.prototype.getParent=function(){return this.parent},go.prototype.setName=function(e){this.name=e},Ya.prototype.getName=function(){return this.name},Ya.prototype.setName=function(e){this.name=e},Ya.prototype.getShader=function(){return this.shader},Ya.prototype.setShader=function(e){this.shader=e},Object.defineProperty(Ya.prototype,"blend",{set:function(e){this.blendState.blend=e},get:function(){return this.blendState.blend}}),Object.defineProperty(Ya.prototype,"blendSrc",{set:function(e){var t=this.blendState;yw.copy(t),yw.setColorBlend(t.colorOp,e,t.colorDstFactor),yw.setAlphaBlend(t.alphaOp,e,t.alphaDstFactor),this.blendState=yw},get:function(){return this.blendState.colorSrcFactor}}),Object.defineProperty(Ya.prototype,"blendDst",{set:function(e){var t=this.blendState;yw.copy(t),yw.setColorBlend(t.colorOp,t.colorSrcFactor,e),yw.setAlphaBlend(t.alphaOp,t.alphaSrcFactor,e),this.blendState=yw},get:function(){return this.blendState.colorDstFactor}}),Object.defineProperty(Yl.prototype,"shininess",{get:function(){return 100*this.gloss},set:function(e){this.gloss=.01*e}}),ww("diffuseTint","diffuseMapTint"),ww("specularTint","specularMapTint"),ww("emissiveTint","emissiveMapTint"),ww("aoVertexColor","aoMapVertexColor"),ww("diffuseVertexColor","diffuseMapVertexColor"),ww("specularVertexColor","specularMapVertexColor"),ww("emissiveVertexColor","emissiveMapVertexColor"),ww("metalnessVertexColor","metalnessMapVertexColor"),ww("glossVertexColor","glossMapVertexColor"),ww("opacityVertexColor","opacityMapVertexColor"),ww("lightVertexColor","lightMapVertexColor"),ww("sheenGloss","sheenGlossiess"),ww("clearCoatGloss","clearCostGlossiness"),Tw("refraction","useRefraction");var Aw=new Il,Cw=Object.getOwnPropertyNames(Aw);for(var Ew in Cw)Tw(Cw[Ew]);var Mw={Animation:$u,Key:Ku,Node:Zu,Skeleton:Ju};$u.prototype.getDuration=function(){return this.duration},$u.prototype.getName=function(){return this.name},$u.prototype.getNodes=function(){return this.nodes},$u.prototype.setDuration=function(e){this.duration=e},$u.prototype.setName=function(e){this.name=e},Ju.prototype.getAnimation=function(){return this.animation},Ju.prototype.getCurrentTime=function(){return this.currentTime},Ju.prototype.getLooping=function(){return this.looping},Ju.prototype.getNumNodes=function(){return this.numNodes},Ju.prototype.setAnimation=function(e){this.animation=e},Ju.prototype.setCurrentTime=function(e){this.currentTime=e},Ju.prototype.setLooping=function(e){this.looping=e};var Pw={AudioManager:Lr,Channel:Cr,Channel3d:Er,Listener:Pr,Sound:Dr};Lr.prototype.getListener=function(){return this.listener},Lr.prototype.getVolume=function(){return this.volume},Lr.prototype.setVolume=function(e){this.volume=e};Bd.prototype.getAssetById=function(e){return this.get(e)},Object.defineProperty(sb.prototype,"ray",{get:function(){return this._rayLocal}}),Object.defineProperty(sb.prototype,"position",{get:function(){return this._localPosition}}),Object.defineProperty(sb.prototype,"rotation",{get:function(){return this._localRotation}});var Rw={getTouchTargetCoords:yr,Controller:rr,GamePads:vr,Keyboard:tr,KeyboardEvent:Zs,Mouse:sr,MouseEvent:nr,Touch:xr,TouchDevice:br,TouchEvent:Sr};Object.defineProperty(tw.prototype,"wheel",{get:function(){return-2*this.wheelDelta}}),Object.defineProperty(nr.prototype,"wheel",{get:function(){return-2*this.wheelDelta}});var Iw=am,Lw=om,Dw=hm;nf.prototype.isFullscreen=function(){return!!document.fullscreenElement},nf.prototype.enableFullscreen=function(e,t,i){e=e||this.graphicsDevice.canvas;t&&document.addEventListener("fullscreenchange",(function e(){t(),document.removeEventListener("fullscreenchange",e)}),!1),i&&document.addEventListener("fullscreenerror",(function e(){i(),document.removeEventListener("fullscreenerror",e)}),!1),e.requestFullscreen?e.requestFullscreen(Element.ALLOW_KEYBOARD_INPUT):i()},nf.prototype.disableFullscreen=function(e){e&&document.addEventListener("fullscreenchange",(function t(){e(),document.removeEventListener("fullscreenchange",t)}),!1),document.exitFullscreen()},nf.prototype.getSceneUrl=function(e){var t=this.scenes.find(e);return t?t.url:null},nf.prototype.loadScene=function(e,t){this.scenes.loadScene(e,t)},nf.prototype.loadSceneHierarchy=function(e,t){this.scenes.loadSceneHierarchy(e,t)},nf.prototype.loadSceneSettings=function(e,t){this.scenes.loadSceneSettings(e,t)},nf.prototype.renderMeshInstance=function(e,t){var i=null!=t&&t.layer?t.layer:this.scene.defaultDrawLayer;this.scene.immediate.drawMesh(null,null,null,e,i)},nf.prototype.renderMesh=function(e,t,i,n){var s=null!=n&&n.layer?n.layer:this.scene.defaultDrawLayer;this.scene.immediate.drawMesh(t,i,e,null,s)},nf.prototype._addLines=function(e,t,i){var n=i&&i.layer?i.layer:this.scene.layers.getLayerById(3),s=!i||void 0===i.depthTest||i.depthTest;this.scene.immediate.getBatch(n,s).addLines(e,t)},nf.prototype.renderLine=function(e,t,i){var n,s=i,r=arguments[3],a=arguments[4];r instanceof ue?(s=r,n="number"==typeof a?1===a?{layer:this.scene.layers.getLayerById(3),depthTest:!1}:{layer:this.scene.layers.getLayerById(3),depthTest:!0}:a):"number"==typeof r?(s=i,n=1===r?{layer:this.scene.layers.getLayerById(3),depthTest:!1}:{layer:this.scene.layers.getLayerById(3),depthTest:!0}):r&&(n=r),this._addLines([e,t],[i,s],n)},nf.prototype.renderLines=function(e,t,i){i?"number"==typeof i&&(i=1===i?{layer:this.scene.layers.getLayerById(3),depthTest:!1}:{layer:this.scene.layers.getLayerById(3),depthTest:!0}):i={layer:this.scene.layers.getLayerById(3),depthTest:!0},!t.length||e.length===t.length?e.length%2==0?this._addLines(e,t,i):console.error("renderLines: array length is not divisible by 2"):console.error("renderLines: position/color arrays have different lengths")},nf.prototype.enableVr=function(){},Object.defineProperty(Rv.prototype,"node",{get:function(){return this.entity}}),Object.defineProperty(Fv.prototype,"enable",{get:function(){return this.enabled},set:function(e){this.enabled=e}}),V_.prototype.setVisible=function(e){this.enabled=e},Object.defineProperty(V_.prototype,"aabb",{get:function(){return null},set:function(e){}}),Object.defineProperty(ng.prototype,"aabb",{get:function(){return null},set:function(e){}}),Object.defineProperty(vg.prototype,"bodyType",{get:function(){return this.type},set:function(e){this.type=e}}),vg.prototype.syncBodyToEntity=function(){this._updateDynamic()},Ag.prototype.setGravity=function(){1===arguments.length?this.gravity.copy(arguments[0]):this.gravity.set(arguments[0],arguments[1],arguments[2])},e.ABSOLUTE_URL=Rd,e.ACTION_GAMEPAD=Hs,e.ACTION_KEYBOARD=Gs,e.ACTION_MOUSE=Vs,e.ADDRESS_CLAMP_TO_EDGE=1,e.ADDRESS_MIRRORED_REPEAT=2,e.ADDRESS_REPEAT=0,e.ANIM_BLEND_1D="1D",e.ANIM_BLEND_2D_CARTESIAN=Uf,e.ANIM_BLEND_2D_DIRECTIONAL=Nf,e.ANIM_BLEND_DIRECT=zf,e.ANIM_CONTROL_STATES=Wf,e.ANIM_EQUAL_TO=Lf,e.ANIM_GREATER_THAN=Mf,e.ANIM_GREATER_THAN_EQUAL_TO=Rf,e.ANIM_INTERRUPTION_NEXT=Af,e.ANIM_INTERRUPTION_NEXT_PREV=Ef,e.ANIM_INTERRUPTION_NONE=wf,e.ANIM_INTERRUPTION_PREV=Tf,e.ANIM_INTERRUPTION_PREV_NEXT=Cf,e.ANIM_LAYER_ADDITIVE=jf,e.ANIM_LAYER_OVERWRITE=Xf,e.ANIM_LESS_THAN=Pf,e.ANIM_LESS_THAN_EQUAL_TO=If,e.ANIM_NOT_EQUAL_TO=Df,e.ANIM_PARAMETER_BOOLEAN=Ff,e.ANIM_PARAMETER_FLOAT=kf,e.ANIM_PARAMETER_INTEGER=Of,e.ANIM_PARAMETER_TRIGGER=Bf,e.ANIM_STATE_ANY=Hf,e.ANIM_STATE_END=Gf,e.ANIM_STATE_START=Vf,e.ASPECT_AUTO=0,e.ASPECT_MANUAL=1,e.ASSET_ANIMATION="animation",e.ASSET_AUDIO="audio",e.ASSET_CONTAINER="container",e.ASSET_CSS="css",e.ASSET_CUBEMAP="cubemap",e.ASSET_HTML="html",e.ASSET_IMAGE="image",e.ASSET_JSON="json",e.ASSET_MATERIAL="material",e.ASSET_MODEL="model",e.ASSET_SCRIPT="script",e.ASSET_SHADER="shader",e.ASSET_TEXT="text",e.ASSET_TEXTURE="texture",e.ASSET_TEXTUREATLAS="textureatlas",e.AXIS_KEY="key",e.AXIS_MOUSE_X="mousex",e.AXIS_MOUSE_Y="mousey",e.AXIS_PAD_L_X="padlx",e.AXIS_PAD_L_Y="padly",e.AXIS_PAD_R_X="padrx",e.AXIS_PAD_R_Y="padry",e.AnimBinder=Qf,e.AnimClip=bf,e.AnimClipHandler=ax,e.AnimComponent=bp,e.AnimComponentLayer=xp,e.AnimComponentSystem=Ap,e.AnimController=fp,e.AnimCurve=ty,e.AnimData=iy,e.AnimEvaluator=Kf,e.AnimEvents=Zf,e.AnimSnapshot=Sf,e.AnimStateGraph=Sp,e.AnimStateGraphHandler=ox,e.AnimTarget=Jf,e.AnimTrack=$f,e.Animation=$u,e.AnimationComponent=tp,e.AnimationComponentSystem=sp,e.AnimationHandler=rx,e.AppBase=nf,e.AppOptions=af,e.Application=mb,e.Asset=kd,e.AssetListLoader=_b,e.AssetReference=ig,e.AssetRegistry=Bd,e.AudioHandler=cx,e.AudioListenerComponent=Cp,e.AudioListenerComponentSystem=Pp,e.AudioSourceComponent=Rp,e.AudioSourceComponentSystem=Dp,e.BAKE_COLOR=0,e.BAKE_COLORDIR=1,e.BINDGROUP_MESH=0,e.BINDGROUP_VIEW=1,e.BLENDEQUATION_ADD=0,e.BLENDEQUATION_MAX=4,e.BLENDEQUATION_MIN=3,e.BLENDEQUATION_REVERSE_SUBTRACT=2,e.BLENDEQUATION_SUBTRACT=1,e.BLENDMODE_CONSTANT=11,e.BLENDMODE_CONSTANT_ALPHA=11,e.BLENDMODE_CONSTANT_COLOR=11,e.BLENDMODE_DST_ALPHA=9,e.BLENDMODE_DST_COLOR=4,e.BLENDMODE_ONE=1,e.BLENDMODE_ONE_MINUS_CONSTANT=12,e.BLENDMODE_ONE_MINUS_CONSTANT_ALPHA=12,e.BLENDMODE_ONE_MINUS_CONSTANT_COLOR=12,e.BLENDMODE_ONE_MINUS_DST_ALPHA=10,e.BLENDMODE_ONE_MINUS_DST_COLOR=5,e.BLENDMODE_ONE_MINUS_SRC_ALPHA=8,e.BLENDMODE_ONE_MINUS_SRC_COLOR=3,e.BLENDMODE_SRC_ALPHA=6,e.BLENDMODE_SRC_ALPHA_SATURATE=7,e.BLENDMODE_SRC_COLOR=2,e.BLENDMODE_ZERO=0,e.BLEND_ADDITIVE=1,e.BLEND_ADDITIVEALPHA=6,e.BLEND_MAX=10,e.BLEND_MIN=9,e.BLEND_MULTIPLICATIVE=5,e.BLEND_MULTIPLICATIVE2X=7,e.BLEND_NONE=3,e.BLEND_NORMAL=2,e.BLEND_PREMULTIPLIED=4,e.BLEND_SCREEN=8,e.BLEND_SUBTRACTIVE=0,e.BLUR_BOX=0,e.BLUR_GAUSSIAN=1,e.BODYFLAG_KINEMATIC_OBJECT=2,e.BODYFLAG_NORESPONSE_OBJECT=4,e.BODYFLAG_STATIC_OBJECT=1,e.BODYGROUP_DEFAULT=1,e.BODYGROUP_DYNAMIC=1,e.BODYGROUP_ENGINE_1=8,e.BODYGROUP_ENGINE_2=32,e.BODYGROUP_ENGINE_3=64,e.BODYGROUP_KINEMATIC=4,e.BODYGROUP_NONE=0,e.BODYGROUP_STATIC=2,e.BODYGROUP_TRIGGER=16,e.BODYGROUP_USER_1=128,e.BODYGROUP_USER_2=256,e.BODYGROUP_USER_3=512,e.BODYGROUP_USER_4=1024,e.BODYGROUP_USER_5=2048,e.BODYGROUP_USER_6=4096,e.BODYGROUP_USER_7=8192,e.BODYGROUP_USER_8=16384,e.BODYMASK_ALL=lm,e.BODYMASK_NONE=0,e.BODYMASK_NOT_STATIC=cm,e.BODYMASK_NOT_STATIC_KINEMATIC=65529,e.BODYMASK_STATIC=2,e.BODYSTATE_ACTIVE_TAG=1,e.BODYSTATE_DISABLE_DEACTIVATION=4,e.BODYSTATE_DISABLE_SIMULATION=5,e.BODYSTATE_ISLAND_SLEEPING=2,e.BODYSTATE_WANTS_DEACTIVATION=3,e.BODYTYPE_DYNAMIC=om,e.BODYTYPE_KINEMATIC=hm,e.BODYTYPE_STATIC=am,e.BUFFER_DYNAMIC=1,e.BUFFER_GPUDYNAMIC=3,e.BUFFER_STATIC=0,e.BUFFER_STREAM=2,e.BUTTON_TRANSITION_MODE_SPRITE_CHANGE=1,e.BUTTON_TRANSITION_MODE_TINT=0,e.BasicMaterial=Ka,e.Batch=Za,e.BatchGroup=$a,e.BatchManager=ko,e.BinaryHandler=ux,e.BlendState=yi,e.BoundingBox=Ie,e.BoundingSphere=Oe,e.Bundle=zd,e.BundleHandler=Wd,e.BundleRegistry=Nd,e.ButtonComponent=Yp,e.ButtonComponentSystem=Qp,e.CHUNKAPI_1_51="1.51",e.CHUNKAPI_1_55="1.55",e.CHUNKAPI_1_56="1.56",e.CHUNKAPI_1_57="1.57",e.CHUNKAPI_1_58="1.58",e.CHUNKAPI_1_60="1.60",e.CHUNKAPI_1_62=pi,e.CLEARFLAG_COLOR=1,e.CLEARFLAG_DEPTH=2,e.CLEARFLAG_STENCIL=4,e.COMPUPDATED_BLEND=8,e.COMPUPDATED_CAMERAS=4,e.COMPUPDATED_INSTANCES=1,e.COMPUPDATED_LIGHTS=2,e.CUBEFACE_NEGX=1,e.CUBEFACE_NEGY=3,e.CUBEFACE_NEGZ=5,e.CUBEFACE_POSX=0,e.CUBEFACE_POSY=2,e.CUBEFACE_POSZ=4,e.CUBEPROJ_BOX=1,e.CUBEPROJ_NONE=0,e.CULLFACE_BACK=1,e.CULLFACE_FRONT=2,e.CULLFACE_FRONTANDBACK=3,e.CULLFACE_NONE=0,e.CURVE_CARDINAL=3,e.CURVE_CATMULL=2,e.CURVE_LINEAR=0,e.CURVE_SMOOTHSTEP=1,e.CURVE_SPLINE=4,e.CURVE_STEP=5,e.Camera=Vo,e.CameraComponent=Rv,e.CameraComponentSystem=Dv,e.CanvasFont=vb,e.CollisionComponent=sm,e.CollisionComponentSystem=Cm,e.Color=ue,e.Command=Ao,e.Component=gf,e.ComponentSystem=vf,e.ComponentSystemRegistry=Ud,e.ContactPoint=bg,e.ContactResult=wg,e.ContainerHandler=mx,e.ContainerResource=px,e.ContextCreationError=fw,e.Controller=rr,e.CssHandler=_x,e.CubemapHandler=gx,e.Curve=fe,e.CurveSet=pe,e.DETAILMODE_ADD="add",e.DETAILMODE_MAX="max",e.DETAILMODE_MIN="min",e.DETAILMODE_MUL=Vr,e.DETAILMODE_OVERLAY="overlay",e.DETAILMODE_SCREEN="screen",e.DEVICETYPE_WEBGL1=ni,e.DEVICETYPE_WEBGL2=si,e.DEVICETYPE_WEBGPU=ri,e.DISTANCE_EXPONENTIAL=Xe,e.DISTANCE_INVERSE=We,e.DISTANCE_LINEAR=He,e.DefaultAnimBinder=ep,e.DepthState=xi,e.ELEMENTTYPE_FLOAT32=6,e.ELEMENTTYPE_GROUP=kp,e.ELEMENTTYPE_IMAGE=Fp,e.ELEMENTTYPE_INT16=2,e.ELEMENTTYPE_INT32=4,e.ELEMENTTYPE_INT8=0,e.ELEMENTTYPE_TEXT=Bp,e.ELEMENTTYPE_UINT16=3,e.ELEMENTTYPE_UINT32=5,e.ELEMENTTYPE_UINT8=1,e.EMITTERSHAPE_BOX=0,e.EMITTERSHAPE_SPHERE=1,e.EVENT_GAMEPADCONNECTED=Ys,e.EVENT_GAMEPADDISCONNECTED=Ks,e.EVENT_KEYDOWN="keydown",e.EVENT_KEYUP="keyup",e.EVENT_MOUSEDOWN=Ws,e.EVENT_MOUSEMOVE=Xs,e.EVENT_MOUSEUP=js,e.EVENT_MOUSEWHEEL=qs,e.EVENT_SELECT="select",e.EVENT_SELECTEND="selectend",e.EVENT_SELECTSTART="selectstart",e.EVENT_TOUCHCANCEL="touchcancel",e.EVENT_TOUCHEND="touchend",e.EVENT_TOUCHMOVE="touchmove",e.EVENT_TOUCHSTART="touchstart",e.ElementComponent=o_,e.ElementComponentSystem=u_,e.ElementDragHelper=$g,e.ElementInput=tw,e.ElementInputEvent=$b,e.ElementMouseEvent=Qb,e.ElementSelectEvent=ew,e.ElementTouchEvent=Jb,e.Entity=Zd,e.EntityReference=Op,e.EnvLighting=Cl,e.EventHandler=p,e.FILLMODE_FILL_WINDOW=od,e.FILLMODE_KEEP_ASPECT=hd,e.FILLMODE_NONE="NONE",e.FILTER_LINEAR=1,e.FILTER_LINEAR_MIPMAP_LINEAR=5,e.FILTER_LINEAR_MIPMAP_NEAREST=4,e.FILTER_NEAREST=0,e.FILTER_NEAREST_MIPMAP_LINEAR=3,e.FILTER_NEAREST_MIPMAP_NEAREST=2,e.FITMODE_CONTAIN=Up,e.FITMODE_COVER=zp,e.FITMODE_STRETCH=Np,e.FITTING_BOTH=3,e.FITTING_NONE=0,e.FITTING_SHRINK=2,e.FITTING_STRETCH=1,e.FOG_EXP="exp",e.FOG_EXP2="exp2",e.FOG_LINEAR=Ur,e.FOG_NONE=Nr,e.FONT_BITMAP=Lm,e.FONT_MSDF=Im,e.FRESNEL_NONE=0,e.FRESNEL_SCHLICK=2,e.FUNC_ALWAYS=7,e.FUNC_EQUAL=2,e.FUNC_GREATER=4,e.FUNC_GREATEREQUAL=6,e.FUNC_LESS=1,e.FUNC_LESSEQUAL=3,e.FUNC_NEVER=0,e.FUNC_NOTEQUAL=5,e.FolderHandler=vx,e.Font=yx,e.FontHandler=Sx,e.ForwardRenderer=yc,e.Frustum=ke,e.GAMMA_NONE=0,e.GAMMA_SRGB=1,e.GAMMA_SRGBFAST=2,e.GAMMA_SRGBHDR=3,e.GamePads=vr,e.GraphNode=go,e.GraphicsDevice=Ii,e.HierarchyHandler=Mx,e.HtmlHandler=Px,e.Http=wr,e.I18n=qd,e.INDEXFORMAT_UINT16=1,e.INDEXFORMAT_UINT32=2,e.INDEXFORMAT_UINT8=0,e.INTERPOLATION_CUBIC=2,e.INTERPOLATION_LINEAR=1,e.INTERPOLATION_STEP=0,e.ImageElement=Pm,e.IndexBuffer=As,e.IndexedList=H,e.JointComponent=__,e.JointComponentSystem=x_,e.JsonHandler=Rx,e.JsonStandardMaterialParser=Lx,e.KEY_0=48,e.KEY_1=49,e.KEY_2=50,e.KEY_3=51,e.KEY_4=52,e.KEY_5=53,e.KEY_6=54,e.KEY_7=55,e.KEY_8=56,e.KEY_9=57,e.KEY_A=65,e.KEY_ADD=107,e.KEY_ALT=18,e.KEY_B=66,e.KEY_BACKSPACE=8,e.KEY_BACK_SLASH=220,e.KEY_C=67,e.KEY_CAPS_LOCK=20,e.KEY_CLOSE_BRACKET=221,e.KEY_COMMA=188,e.KEY_CONTEXT_MENU=93,e.KEY_CONTROL=17,e.KEY_D=68,e.KEY_DECIMAL=110,e.KEY_DELETE=46,e.KEY_DIVIDE=111,e.KEY_DOWN=40,e.KEY_E=69,e.KEY_END=35,e.KEY_ENTER=13,e.KEY_EQUAL=61,e.KEY_ESCAPE=27,e.KEY_F=70,e.KEY_F1=112,e.KEY_F10=121,e.KEY_F11=122,e.KEY_F12=123,e.KEY_F2=113,e.KEY_F3=114,e.KEY_F4=115,e.KEY_F5=116,e.KEY_F6=117,e.KEY_F7=118,e.KEY_F8=119,e.KEY_F9=120,e.KEY_G=71,e.KEY_H=72,e.KEY_HOME=36,e.KEY_I=73,e.KEY_INSERT=45,e.KEY_J=74,e.KEY_K=75,e.KEY_L=76,e.KEY_LEFT=37,e.KEY_M=77,e.KEY_META=224,e.KEY_MULTIPLY=106,e.KEY_N=78,e.KEY_NUMPAD_0=96,e.KEY_NUMPAD_1=97,e.KEY_NUMPAD_2=98,e.KEY_NUMPAD_3=99,e.KEY_NUMPAD_4=100,e.KEY_NUMPAD_5=101,e.KEY_NUMPAD_6=102,e.KEY_NUMPAD_7=103,e.KEY_NUMPAD_8=104,e.KEY_NUMPAD_9=105,e.KEY_O=79,e.KEY_OPEN_BRACKET=219,e.KEY_P=80,e.KEY_PAGE_DOWN=34,e.KEY_PAGE_UP=33,e.KEY_PAUSE=19,e.KEY_PERIOD=190,e.KEY_PRINT_SCREEN=44,e.KEY_Q=81,e.KEY_R=82,e.KEY_RETURN=13,e.KEY_RIGHT=39,e.KEY_S=83,e.KEY_SEMICOLON=59,e.KEY_SEPARATOR=108,e.KEY_SHIFT=16,e.KEY_SLASH=191,e.KEY_SPACE=32,e.KEY_SUBTRACT=109,e.KEY_T=84,e.KEY_TAB=9,e.KEY_U=85,e.KEY_UP=38,e.KEY_V=86,e.KEY_W=87,e.KEY_WINDOWS=91,e.KEY_X=88,e.KEY_Y=89,e.KEY_Z=90,e.Key=Ku,e.Keyboard=tr,e.KeyboardEvent=Zs,e.LAYERID_DEPTH=1,e.LAYERID_IMMEDIATE=3,e.LAYERID_SKYBOX=2,e.LAYERID_UI=4,e.LAYERID_WORLD=0,e.LAYER_FX=2,e.LAYER_GIZMO=1,e.LAYER_HUD=0,e.LAYER_WORLD=15,e.LIGHTFALLOFF_INVERSESQUARED=1,e.LIGHTFALLOFF_LINEAR=0,e.LIGHTSHAPE_DISK=2,e.LIGHTSHAPE_PUNCTUAL=0,e.LIGHTSHAPE_RECT=1,e.LIGHTSHAPE_SPHERE=3,e.LIGHTTYPE_COUNT=3,e.LIGHTTYPE_DIRECTIONAL=0,e.LIGHTTYPE_OMNI=1,e.LIGHTTYPE_POINT=1,e.LIGHTTYPE_SPOT=2,e.LINEBATCH_GIZMO=2,e.LINEBATCH_OVERLAY=1,e.LINEBATCH_WORLD=0,e.Layer=dc,e.LayerComposition=Ec,e.LayoutCalculator=O_,e.LayoutChildComponent=S_,e.LayoutChildComponentSystem=T_,e.LayoutGroupComponent=B_,e.LayoutGroupComponentSystem=z_,e.Light=kc,e.LightComponent=Fv,e.LightComponentSystem=Uv,e.LightingParams=Fc,e.Lightmapper=_f,e.LitOptions=Il,e.LocalizedAsset=Rm,e.MASK_AFFECT_DYNAMIC=1,e.MASK_AFFECT_LIGHTMAPPED=2,e.MASK_BAKE=4,e.MOTION_FREE=d_,e.MOTION_LIMITED=f_,e.MOTION_LOCKED=p_,e.MOUSEBUTTON_LEFT=0,e.MOUSEBUTTON_MIDDLE=1,e.MOUSEBUTTON_NONE=-1,e.MOUSEBUTTON_RIGHT=2,e.Mat3=_e,e.Mat4=Te,e.Material=Ya,e.MaterialHandler=Ox,e.Mesh=Jr,e.MeshInstance=Co,e.Model=Uc,e.ModelComponent=V_,e.ModelComponentSystem=W_,e.ModelHandler=Gx,e.Morph=zc,e.MorphInstance=Nc,e.MorphTarget=Vc,e.Mouse=sr,e.MouseEvent=nr,e.Node=Zu,e.ORIENTATION_HORIZONTAL=0,e.ORIENTATION_VERTICAL=1,e.OrientedBox=Ve,e.PAD_1=0,e.PAD_2=1,e.PAD_3=2,e.PAD_4=3,e.PAD_DOWN=13,e.PAD_FACE_1=0,e.PAD_FACE_2=1,e.PAD_FACE_3=2,e.PAD_FACE_4=3,e.PAD_LEFT=14,e.PAD_L_SHOULDER_1=4,e.PAD_L_SHOULDER_2=6,e.PAD_L_STICK_BUTTON=10,e.PAD_L_STICK_X=0,e.PAD_L_STICK_Y=1,e.PAD_RIGHT=15,e.PAD_R_SHOULDER_1=5,e.PAD_R_SHOULDER_2=7,e.PAD_R_STICK_BUTTON=11,e.PAD_R_STICK_X=2,e.PAD_R_STICK_Y=3,e.PAD_SELECT=8,e.PAD_START=9,e.PAD_UP=12,e.PAD_VENDOR=16,e.PARTICLEMODE_CPU=1,e.PARTICLEMODE_GPU=0,e.PARTICLEORIENTATION_EMITTER=2,e.PARTICLEORIENTATION_SCREEN=0,e.PARTICLEORIENTATION_WORLD=1,e.PARTICLESORT_DISTANCE=1,e.PARTICLESORT_NEWER_FIRST=2,e.PARTICLESORT_NONE=0,e.PARTICLESORT_OLDER_FIRST=3,e.PIXELFORMAT_111110F=et,e.PIXELFORMAT_A8=0,e.PIXELFORMAT_ASTC_4x4=28,e.PIXELFORMAT_ATC_RGB=29,e.PIXELFORMAT_ATC_RGBA=30,e.PIXELFORMAT_BGRA8=31,e.PIXELFORMAT_DEPTH=Qe,e.PIXELFORMAT_DEPTHSTENCIL=Je,e.PIXELFORMAT_DXT1=8,e.PIXELFORMAT_DXT3=9,e.PIXELFORMAT_DXT5=je,e.PIXELFORMAT_ETC1=tt,e.PIXELFORMAT_ETC2_RGB=22,e.PIXELFORMAT_ETC2_RGBA=23,e.PIXELFORMAT_L8=1,e.PIXELFORMAT_L8_A8=2,e.PIXELFORMAT_LA8=2,e.PIXELFORMAT_PVRTC_2BPP_RGBA_1=nt,e.PIXELFORMAT_PVRTC_2BPP_RGB_1=it,e.PIXELFORMAT_PVRTC_4BPP_RGBA_1=rt,e.PIXELFORMAT_PVRTC_4BPP_RGB_1=st,e.PIXELFORMAT_R32F=$e,e.PIXELFORMAT_R4_G4_B4_A4=5,e.PIXELFORMAT_R5_G5_B5_A1=4,e.PIXELFORMAT_R5_G6_B5=3,e.PIXELFORMAT_R8_G8_B8=6,e.PIXELFORMAT_R8_G8_B8_A8=7,e.PIXELFORMAT_RGB16F=qe,e.PIXELFORMAT_RGB32F=Ke,e.PIXELFORMAT_RGB565=3,e.PIXELFORMAT_RGB8=6,e.PIXELFORMAT_RGBA16F=Ye,e.PIXELFORMAT_RGBA32F=Ze,e.PIXELFORMAT_RGBA4=5,e.PIXELFORMAT_RGBA5551=4,e.PIXELFORMAT_RGBA8=7,e.PIXELFORMAT_SRGB=19,e.PIXELFORMAT_SRGBA=20,e.PRIMITIVE_LINELOOP=2,e.PRIMITIVE_LINES=1,e.PRIMITIVE_LINESTRIP=3,e.PRIMITIVE_POINTS=0,e.PRIMITIVE_TRIANGLES=4,e.PRIMITIVE_TRIFAN=6,e.PRIMITIVE_TRISTRIP=5,e.PROJECTION_ORTHOGRAPHIC=1,e.PROJECTION_PERSPECTIVE=0,e.ParticleEmitter=ku,e.ParticleSystemComponent=Z_,e.ParticleSystemComponentSystem=J_,e.PhongMaterial=Sw,e.Picker=Sb,e.Plane=Ge,e.PostEffect=td,e.PostEffectQueue=Pv,e.ProgramLibrary=rd,e.QuadRender=Ia,e.Quat=Ae,e.RENDERSTYLE_POINTS=2,e.RENDERSTYLE_SOLID=0,e.RENDERSTYLE_WIREFRAME=1,e.RESOLUTION_AUTO=ld,e.RESOLUTION_FIXED=cd,e.RIGIDBODY_ACTIVE_TAG=1,e.RIGIDBODY_CF_KINEMATIC_OBJECT=2,e.RIGIDBODY_CF_NORESPONSE_OBJECT=4,e.RIGIDBODY_CF_STATIC_OBJECT=1,e.RIGIDBODY_DISABLE_DEACTIVATION=4,e.RIGIDBODY_DISABLE_SIMULATION=5,e.RIGIDBODY_ISLAND_SLEEPING=2,e.RIGIDBODY_TYPE_DYNAMIC=Lw,e.RIGIDBODY_TYPE_KINEMATIC=Dw,e.RIGIDBODY_TYPE_STATIC=Iw,e.RIGIDBODY_WANTS_DEACTIVATION=3,e.Ray=Fe,e.RaycastResult=xg,e.ReadStream=se,e.RenderComponent=ng,e.RenderComponentSystem=og,e.RenderHandler=ey,e.RenderTarget=Di,e.ResourceHandler=bb,e.ResourceLoader=Xd,e.RigidBodyComponent=vg,e.RigidBodyComponentSystem=Ag,e.SAMPLETYPE_DEPTH=2,e.SAMPLETYPE_FLOAT=0,e.SAMPLETYPE_UNFILTERABLE_FLOAT=1,e.SCALEMODE_BLEND=Eg,e.SCALEMODE_NONE=Cg,e.SCROLLBAR_VISIBILITY_SHOW_ALWAYS=0,e.SCROLLBAR_VISIBILITY_SHOW_WHEN_REQUIRED=1,e.SCROLL_MODE_BOUNCE=1,e.SCROLL_MODE_CLAMP=0,e.SCROLL_MODE_INFINITE=2,e.SEMANTIC_ATTR=Tt,e.SEMANTIC_ATTR0=At,e.SEMANTIC_ATTR1=Ct,e.SEMANTIC_ATTR10=kt,e.SEMANTIC_ATTR11=Ft,e.SEMANTIC_ATTR12=Bt,e.SEMANTIC_ATTR13=Nt,e.SEMANTIC_ATTR14=Ut,e.SEMANTIC_ATTR15=zt,e.SEMANTIC_ATTR2=Et,e.SEMANTIC_ATTR3=Mt,e.SEMANTIC_ATTR4=Pt,e.SEMANTIC_ATTR5=Rt,e.SEMANTIC_ATTR6=It,e.SEMANTIC_ATTR7=Lt,e.SEMANTIC_ATTR8=Dt,e.SEMANTIC_ATTR9=Ot,e.SEMANTIC_BLENDINDICES=ft,e.SEMANTIC_BLENDWEIGHT=dt,e.SEMANTIC_COLOR=pt,e.SEMANTIC_NORMAL=ct,e.SEMANTIC_POSITION=lt,e.SEMANTIC_TANGENT=ut,e.SEMANTIC_TEXCOORD=mt,e.SEMANTIC_TEXCOORD0=_t,e.SEMANTIC_TEXCOORD1=gt,e.SEMANTIC_TEXCOORD2=vt,e.SEMANTIC_TEXCOORD3=yt,e.SEMANTIC_TEXCOORD4=xt,e.SEMANTIC_TEXCOORD5=St,e.SEMANTIC_TEXCOORD6=bt,e.SEMANTIC_TEXCOORD7=wt,e.SHADERDEF_DIRLM=Gr,e.SHADERDEF_INSTANCING=32,e.SHADERDEF_LM=64,e.SHADERDEF_LMAMBIENT=qr,e.SHADERDEF_MORPH_NORMAL=Xr,e.SHADERDEF_MORPH_POSITION=Wr,e.SHADERDEF_MORPH_TEXTURE_BASED=jr,e.SHADERDEF_NOSHADOW=1,e.SHADERDEF_SCREENSPACE=Hr,e.SHADERDEF_SKIN=2,e.SHADERDEF_TANGENTS=512,e.SHADERDEF_UV0=4,e.SHADERDEF_UV1=8,e.SHADERDEF_VCOLOR=16,e.SHADERLANGUAGE_GLSL="glsl",e.SHADERLANGUAGE_WGSL=ei,e.SHADERPASS_ALBEDO="debug_albedo",e.SHADERPASS_AO="debug_ao",e.SHADERPASS_EMISSION="debug_emission",e.SHADERPASS_FORWARD="forward",e.SHADERPASS_GLOSS="debug_gloss",e.SHADERPASS_LIGHTING="debug_lighting",e.SHADERPASS_METALNESS="debug_metalness",e.SHADERPASS_OPACITY="debug_opacity",e.SHADERPASS_SPECULARITY="debug_specularity",e.SHADERPASS_UV0="debug_uv0",e.SHADERPASS_WORLDNORMAL="debug_world_normal",e.SHADERSTAGE_COMPUTE=4,e.SHADERSTAGE_FRAGMENT=2,e.SHADERSTAGE_VERTEX=1,e.SHADERTAG_MATERIAL=1,e.SHADER_DEPTH=2,e.SHADER_FORWARD=0,e.SHADER_FORWARDHDR=1,e.SHADER_PICK=3,e.SHADER_SHADOW=4,e.SHADOWUPDATE_NONE=0,e.SHADOWUPDATE_REALTIME=2,e.SHADOWUPDATE_THISFRAME=1,e.SHADOW_DEPTH=0,e.SHADOW_PCF1=5,e.SHADOW_PCF3=0,e.SHADOW_PCF5=4,e.SHADOW_PCSS=6,e.SHADOW_VSM16=2,e.SHADOW_VSM32=3,e.SHADOW_VSM8=1,e.SORTKEY_DEPTH=1,e.SORTKEY_FORWARD=0,e.SORTMODE_BACK2FRONT=3,e.SORTMODE_CUSTOM=5,e.SORTMODE_FRONT2BACK=4,e.SORTMODE_MANUAL=1,e.SORTMODE_MATERIALMESH=2,e.SORTMODE_NONE=0,e.SPECOCC_AO=1,e.SPECOCC_GLOSSDEPENDENT=2,e.SPECOCC_NONE=0,e.SPECULAR_BLINN=1,e.SPECULAR_PHONG=0,e.SPRITETYPE_ANIMATED=pv,e.SPRITETYPE_SIMPLE=fv,e.SPRITE_RENDERMODE_SIMPLE=0,e.SPRITE_RENDERMODE_SLICED=1,e.SPRITE_RENDERMODE_TILED=2,e.STENCILOP_DECREMENT=5,e.STENCILOP_DECREMENTWRAP=6,e.STENCILOP_INCREMENT=3,e.STENCILOP_INCREMENTWRAP=4,e.STENCILOP_INVERT=7,e.STENCILOP_KEEP=0,e.STENCILOP_REPLACE=2,e.STENCILOP_ZERO=1,e.Scene=Hu,e.SceneHandler=Hx,e.SceneRegistry=Jd,e.SceneRegistryItem=Qd,e.SceneSettingsHandler=wb,e.ScopeId=Ti,e.ScopeSpace=Ai,e.ScreenComponent=Pg,e.ScreenComponentSystem=Lg,e.ScriptAttributes=Hv,e.ScriptComponent=jv,e.ScriptComponentSystem=Kv,e.ScriptHandler=Wx,e.ScriptLegacyComponent=Dg,e.ScriptLegacyComponentSystem=Gg,e.ScriptRegistry=Yd,e.ScriptType=nw,e.ScrollViewComponent=Jg,e.ScrollViewComponentSystem=iv,e.ScrollbarComponent=nv,e.ScrollbarComponentSystem=av,e.Shader=Nn,e.ShaderHandler=Xx,e.ShaderPass=Fa,e.SingleContactResult=Sg,e.Skeleton=Ju,e.Skin=Wu,e.SkinBatchInstance=eo,e.SkinInstance=Ja,e.SortedLoopArray=re,e.Sound=Dr,e.SoundComponent=lv,e.SoundComponentSystem=dv;e.SoundInstance=kr,e.SoundInstance3d=Fr,e.SoundManager=Lr,e.SoundSlot=hv,e.Sprite=qu,e.SpriteAnimationClip=mv,e.SpriteComponent=xv,e.SpriteComponentSystem=wv,e.SpriteHandler=Yx,e.StandardMaterial=Yl,e.StandardMaterialOptions=Ll,e.StencilParameters=Ri,e.TEXHINT_ASSET=2,e.TEXHINT_LIGHTMAP=3,e.TEXHINT_NONE=0,e.TEXHINT_SHADOWMAP=1,e.TEXTUREDIMENSION_1D="1d",e.TEXTUREDIMENSION_2D=jt,e.TEXTUREDIMENSION_2D_ARRAY=qt,e.TEXTUREDIMENSION_3D=Kt,e.TEXTUREDIMENSION_CUBE=Yt,e.TEXTUREDIMENSION_CUBE_ARRAY="cube-array",e.TEXTURELOCK_READ=1,e.TEXTURELOCK_WRITE=2,e.TEXTUREPROJECTION_CUBE=$t,e.TEXTUREPROJECTION_EQUIRECT=Qt,e.TEXTUREPROJECTION_NONE=Zt,e.TEXTUREPROJECTION_OCTAHEDRAL=Jt,e.TEXTURETYPE_DEFAULT=Vt,e.TEXTURETYPE_RGBE=Ht,e.TEXTURETYPE_RGBM=Gt,e.TEXTURETYPE_RGBP=Wt,e.TEXTURETYPE_SWIZZLEGGGR=Xt,e.TONEMAP_ACES=3,e.TONEMAP_ACES2=4,e.TONEMAP_FILMIC=1,e.TONEMAP_HEJL=2,e.TONEMAP_LINEAR=0,e.TRACEID_BINDGROUPFORMAT_ALLOC="BindGroupFormatAlloc",e.TRACEID_BINDGROUP_ALLOC="BindGroupAlloc",e.TRACEID_PIPELINELAYOUT_ALLOC="PipelineLayoutAlloc",e.TRACEID_RENDERPIPELINE_ALLOC="RenderPipelineAlloc",e.TRACEID_RENDER_ACTION="RenderAction",e.TRACEID_RENDER_FRAME="RenderFrame",e.TRACEID_RENDER_FRAME_TIME="RenderFrameTime",e.TRACEID_RENDER_PASS="RenderPass",e.TRACEID_RENDER_PASS_DETAIL="RenderPassDetail",e.TRACEID_RENDER_TARGET_ALLOC="RenderTargetAlloc",e.TRACEID_SHADER_ALLOC="ShaderAlloc",e.TRACEID_SHADER_COMPILE="ShaderCompile",e.TRACEID_TEXTURES="Textures",e.TRACEID_TEXTURE_ALLOC="TextureAlloc",e.TRACEID_VRAM_IB="VRAM.Ib",e.TRACEID_VRAM_TEXTURE="VRAM.Texture",e.TRACEID_VRAM_VB="VRAM.Vb",e.TRACE_ID_ELEMENT="Element",e.TYPE_FLOAT32=6,e.TYPE_INT16=2,e.TYPE_INT32=4,e.TYPE_INT8=0,e.TYPE_UINT16=3,e.TYPE_UINT32=5,e.TYPE_UINT8=1,e.Tags=ae,e.Template=Kx,e.TemplateHandler=Zx,e.TextElement=Qm,e.TextHandler=$x,e.Texture=Yn,e.TextureAtlas=Yu,e.TextureAtlasHandler=tS,e.TextureHandler=ES,e.TextureParser=CS,e.TextureUtils=xn,e.Touch=xr,e.TouchDevice=br,e.TouchEvent=Sr,e.Tracing=g,e.TransformFeedback=Cs,e.UNIFORMTYPE_BOOL=0,e.UNIFORMTYPE_BVEC2=9,e.UNIFORMTYPE_BVEC3=10,e.UNIFORMTYPE_BVEC4=11,e.UNIFORMTYPE_FLOAT=2,e.UNIFORMTYPE_FLOATARRAY=17,e.UNIFORMTYPE_INT=1,e.UNIFORMTYPE_IVEC2=6,e.UNIFORMTYPE_IVEC3=7,e.UNIFORMTYPE_IVEC4=8,e.UNIFORMTYPE_MAT2=12,e.UNIFORMTYPE_MAT3=13,e.UNIFORMTYPE_MAT4=ti,e.UNIFORMTYPE_MAT4ARRAY=24,e.UNIFORMTYPE_TEXTURE2D=15,e.UNIFORMTYPE_TEXTURE2D_SHADOW=18,e.UNIFORMTYPE_TEXTURE3D=20,e.UNIFORMTYPE_TEXTURECUBE=16,e.UNIFORMTYPE_TEXTURECUBE_SHADOW=19,e.UNIFORMTYPE_VEC2=3,e.UNIFORMTYPE_VEC2ARRAY=21,e.UNIFORMTYPE_VEC3=4,e.UNIFORMTYPE_VEC3ARRAY=22,e.UNIFORMTYPE_VEC4=5,e.UNIFORMTYPE_VEC4ARRAY=23,e.UNIFORM_BUFFER_DEFAULT_SLOT_NAME=ai,e.URI=le,e.UnsupportedBrowserError=dw,e.VIEW_CENTER=0,e.VIEW_LEFT=1,e.VIEW_RIGHT=2,e.Vec2=ge,e.Vec3=me,e.Vec4=ve,e.VertexBuffer=Ei,e.VertexFormat=Pi,e.VertexIterator=zs,e.WasmModule=X,e.WebglGraphicsDevice=ws,e.WebgpuGraphicsDevice=jn,e.WorldClusters=lh,e.XRDEPTHSENSINGFORMAT_F32="float32",e.XRDEPTHSENSINGFORMAT_L8A8=kS,e.XRDEPTHSENSINGUSAGE_CPU=DS,e.XRDEPTHSENSINGUSAGE_GPU=OS,e.XRHAND_LEFT=LS,e.XRHAND_NONE="none",e.XRHAND_RIGHT="right",e.XRPAD_A=4,e.XRPAD_B=5,e.XRPAD_SQUEEZE=1,e.XRPAD_STICK_BUTTON=3,e.XRPAD_STICK_X=2,e.XRPAD_STICK_Y=3,e.XRPAD_TOUCHPAD_BUTTON=2,e.XRPAD_TOUCHPAD_X=0,e.XRPAD_TOUCHPAD_Y=1,e.XRPAD_TRIGGER=0,e.XRSPACE_BOUNDEDFLOOR="bounded-floor",e.XRSPACE_LOCAL="local",e.XRSPACE_LOCALFLOOR="local-floor",e.XRSPACE_UNBOUNDED="unbounded",e.XRSPACE_VIEWER=IS,e.XRTARGETRAY_GAZE="gaze",e.XRTARGETRAY_POINTER="tracked-pointer",e.XRTARGETRAY_SCREEN="screen",e.XRTRACKABLE_MESH="mesh",e.XRTRACKABLE_PLANE="plane",e.XRTRACKABLE_POINT="point",e.XRTYPE_AR=RS,e.XRTYPE_INLINE=MS,e.XRTYPE_VR=PS,e.XrDepthSensing=FS,e.XrDomOverlay=BS,e.XrHitTest=VS,e.XrHitTestSource=zS,e.XrImageTracking=HS,e.XrInput=rb,e.XrInputSource=sb,e.XrLightEstimation=cb,e.XrManager=pb,e.XrPlane=db,e.XrPlaneDetection=fb,e.XrTrackedImage=GS,e.ZoneComponent=Tv,e.ZoneComponentSystem=Ev,e.anim=Mw,e.apps={},e.asset={ASSET_ANIMATION:"animation",ASSET_AUDIO:"audio",ASSET_IMAGE:"image",ASSET_JSON:"json",ASSET_MODEL:"model",ASSET_MATERIAL:"material",ASSET_TEXT:"text",ASSET_TEXTURE:"texture",ASSET_CUBEMAP:"cubemap",ASSET_SCRIPT:"script"},e.audio=Pw,e.basisInitialize=uS,e.basisSetDownloadConfig=function(e,t,i){uS({glueUrl:e,wasmUrl:t,fallbackUrl:i,lazyInit:!0})},e.bindGroupNames=oi,e.calculateNormals=na,e.calculateTangents=sa,e.common={},e.config={},e.createBox=fa,e.createCapsule=la,e.createCone=ca,e.createCylinder=ha,e.createGraphicsDevice=function(e,t){var i;void 0===t&&(t={});var n,s,r=null!=(i=t.deviceTypes)?i:[];r.includes(si)||r.push(si),r.includes(ni)||r.push(ni),M.browser&&navigator.xr&&(null!=(n=t).xrCompatible||(n.xrCompatible=!0));for(var a=0;a<r.length;a++){var o,h,l=r[a];if(l===ri&&null!=(o=window)&&null!=(h=o.navigator)&&h.gpu)return(s=new jn(e,t)).initWebGpu(t.glslangUrl,t.twgslUrl);if(l!==ri)return t.preferWebGl2=l===si,s=new ws(e,t),Promise.resolve(s)}return Promise.reject(new Error("Failed to allocate graphics device"))},e.createMesh=ra,e.createPlane=da,e.createScript=rw,e.createShader=Aa,e.createShaderFromCode=Ca,e.createSphere=ua,e.createStyle=function(e){var t=document.createElement("style");return t.type="text/css",t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e)),t},e.createTorus=aa,e.createURI=function(e){var t="";if((e.authority||e.scheme)&&(e.host||e.hostpath))throw new Error("Can't have 'scheme' or 'authority' and 'host' or 'hostpath' option");if(e.host&&e.hostpath)throw new Error("Can't have 'host' and 'hostpath' option");if(e.path&&e.hostpath)throw new Error("Can't have 'path' and 'hostpath' option");return e.scheme&&(t+=e.scheme+":"),e.authority&&(t+="//"+e.authority),e.host&&(t+=e.host),e.path&&(t+=e.path),e.hostpath&&(t+=e.hostpath),e.query&&(t+="?"+e.query),e.fragment&&(t+="#"+e.fragment),t},e.data={},e.dracoInitialize=function(e){null!=e&&e.lazyInit?ry=e:cy(e)},e.drawFullscreenQuad=gw,e.drawQuadWithShader=Da,e.drawTexture=function(e,t,i,n,s,r){n=n||e.getCopyShader(),e.constantTexSource.setValue(t),Da(e,i,n,s,r)},e.events=m,e.extend=f,e.getPixelFormatArrayType=ht,e.getReservedScriptNames=function(){return sw},e.getTouchTargetCoords=yr,e.gfx=mw,e.guid=_,e.http=Tr,e.inherits=function(e,t){var i=function(){},n=function(i,n,s,r,a,o,h,l){t.call(this,i,n,s,r,a,o,h,l),e.call(this,i,n,s,r,a,o,h,l)};return n._super=t.prototype,i.prototype=t.prototype,n.prototype=new i,n},e.input=Rw,e.isCompressedPixelFormat=ot,e.log=hw,e.makeArray=function(e){return Array.prototype.slice.call(e)},e.math=ce,e.now=oe,e.path=v,e.pixelFormatInfo=at,e.platform=M,e.posteffect=vw,e.prefilterCubemap=function(e){},e.programlib=pw,e.registerScript=ow,e.reprojectTexture=Tl,e.revision=c,e.scene=bw,e.script=_d,e.semanticToLocation=fi,e.shFromCubemap=function(e,t,i){if(7!==t.format)return null;if(!t._levels[0]||!t._levels[0][0])return null;var n=t.width;if(!t._levels[0][0].length){if(!(t._levels[0][0]instanceof HTMLImageElement))return null;for(var s=Ca(e,Sa.fullscreenQuadVS,Sa.fullscreenQuadPS,"fsQuadSimple"),r=e.scope.resolve("source"),a=0;a<6;a++){var o=t._levels[0][a],h=new Yn(e,{name:"prefiltered-cube",cubemap:!1,type:Vt,format:t.format,width:n,height:n,mipmaps:!1});h._levels[0]=o,h.upload();var l=new Yn(e,{name:"prefiltered-cube",cubemap:!1,type:Vt,format:t.format,width:n,height:n,mipmaps:!1}),c=new Di({colorBuffer:l,depth:!1});r.setValue(h),e.setBlendState(yi.NOBLEND),Da(e,c,s);var u=e.gl;u.bindFramebuffer(u.FRAMEBUFFER,c.impl._glFrameBuffer);var d=new Uint8Array(n*n*4);u.readPixels(0,0,h.width,h.height,u.RGBA,u.UNSIGNED_BYTE,d),t._levels[0][a]=d}}for(var f=[],p=0;p<n;p++)for(var m=0;m<n;m++){var _=m/(n-1)*2-1,g=p/(n-1)*2-1;f[p*n+m]=new me(_,g,1).normalize()}for(var v=new Float32Array(27),y=0,x=0;x<6;x++)for(var S=0;S<n;S++)for(var b=0;b<n;b++){var w=S*n+b,T=nd(b,S,n),A=4*T/17,C=8*T/17,E=15*T/17,M=5*T/68,P=15*T/68,R=f[w],I=void 0,L=void 0,D=void 0;0===x?(I=R.z,L=-R.y,D=-R.x):1===x?(I=-R.z,L=-R.y,D=R.x):2===x?(I=R.x,L=R.z,D=R.y):3===x?(I=R.x,L=-R.z,D=-R.y):4===x?(I=R.x,L=-R.y,D=R.z):5===x&&(I=-R.x,L=-R.y,D=-R.z),i||(I=-I);for(var O=t._levels[0][x][4*w+3]/255,k=0;k<3;k++){var F=t._levels[0][x][4*w+k]/255;t.type===Gt?(F*=8*O,F*=F):F=Math.pow(F,2.2),v[0+k]+=F*A,v[3+k]+=F*C*I,v[6+k]+=F*C*L,v[9+k]+=F*C*D,v[12+k]+=F*E*I*D,v[15+k]+=F*E*D*L,v[18+k]+=F*E*L*I,v[21+k]+=F*M*(3*D*D-1),v[24+k]+=F*P*(I*I-L*L),y+=T}}for(var B=0;B<v.length;B++)v[B]*=4*Math.PI/y;return v},e.shaderChunks=Sa,e.shaderChunksLightmapper=ad,e.shadowTypeToString=zr,e.shape=uw,e.string=G,e.time=cw,e.type=d,e.typedArrayIndexFormats=ui,e.typedArrayIndexFormatsByteSize=di,e.typedArrayToType=ci,e.typedArrayTypes=hi,e.typedArrayTypesByteSize=li,e.uniformTypeToName=ii,e.version=l,e.vertexTypesNames=["INT8","UINT8","INT16","UINT16","INT32","UINT32","FLOAT32"]}));
| ver. 1.4 |
Github
|
.
| PHP 8.2.29 | Генераци� �траницы: 0.32 |
proxy
|
phpinfo
|
�а�тройка